Search Results

Search found 4129 results on 166 pages for 'models'.

Page 17/166 | < Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >

  • Django loading mysql data into template correctly

    - by user805981
    I'm new to django and I'm trying to get display a list of buildings and sort them alphabetically, then load it into an html document. Is there something that I am not doing correctly? below is models.py class Class(models.Model): building = models.CharField(max_length=20) class Meta: db_table = u'class' def __unicode__(self): return self.building below is views.py views.py def index(request): buildinglist = Class.objects.all().order_by('building') c = {'buildinglist': buildinglist} t = loader.get_template('index.html') return HttpResponse(t.render(c)) below is index.html index.html {% block content%} <h3>Buildings:</h3> <ul> {% for building in buildinglist %} <li> <a href='www.{% building %}.com'> # ex. www.searstower.com </li> {% endfor %} </ul> {% endblock %} Can you guys point me in the right direction? Thank you in advance guys! I appreciate your help very much.

    Read the article

  • django objects.all() method issue

    - by xlione
    after I saved one item using MyModelClass.save() method of django in one view/page , at another view I use MyModelClass.objects.all() to list all items in MyModelClass but the newly added one always is missing at the new page. i am using django 1.1 i am using mysql middleware setting MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.locale.LocaleMiddleware', ) my model: class Company(models.Model): name = models.CharField(max_length=500) description = models.CharField(max_length=500,null=True) addcompany view def addcompany(request): if request.POST: form = AddCompanyForm(request.POST) if form.is_valid(): companyname = form.cleaned_data['companyname'] c = Company(name=companyname,description='description') c.save() return HttpResponseRedirect('/admins/') else: form = AddCompanyForm() return render_to_response('user/addcompany.html',{'form':form},context_instance=RequestContext(request)) after this page in another view i called this form in another view class CompanyForm(forms.Form): companies=((0,' '),) for o in CcicCompany.objects.all(): x=o.id,o.name companies+=(x,) company = forms.ChoiceField(choices=companies,label='Company Name') to list all companies but the recently added one is missing. The transaction should be successful, since after i do a apache server reboot , i can see the newly added company name Thanks for any help...

    Read the article

  • Problem getting started with GeoDjango

    - by akv
    As soon as I add "from django.contrib.gis.db import models" instead of "from django.db import models", Django stops recognizing the app and gives this error: Error: App with label location could not be found. Are you sure your INSTALLED_APPS setting is correct? The error goes away as soon as I comment out "from django.contrib.gis.db import models"... I have added "django.contrib.gis" and the "location" app to the INSTALLED_APPS setting correctly. Any clues why this is happening? I am running using Django v1.1.1 final, on my windows laptop.

    Read the article

  • Processing file uploads before object is saved

    - by Dominic Rodger
    I've got a model like this: class Talk(BaseModel): title = models.CharField(max_length=200) mp3 = models.FileField(upload_to = u'talks/', max_length=200) seconds = models.IntegerField(blank = True, null = True) I want to validate before saving that the uploaded file is an MP3, like this: def is_mp3(path_to_file): from mutagen.mp3 import MP3 audio = MP3(path_to_file) return not audio.info.sketchy Once I'm sure I've got an MP3, I want to save the length of the talk in the seconds attribute, like this: audio = MP3(path_to_file) self.seconds = audio.info.length The problem is, before saving, the uploaded file doesn't have a path (see this ticket, closed as wontfix), so I can't process the MP3. I'd like to raise a nice validation error so that ModelForms can display a helpful error ("You idiot, you didn't upload an MP3" or something). Any idea how I can go about accessing the file before it's saved? p.s. If anyone knows a better way of validating files are MP3s I'm all ears - I also want to be able to mess around with ID3 data (set the artist, album, title and probably album art, so I need it to be processable by mutagen).

    Read the article

  • verbose_name for a model's method

    - by mawimawi
    How can I set a verbose_name for a model's method, so that it might be displayed in the admin's change_view form? example: class Article(models.Model): title = models.CharField(max_length=64) created_date = models.DateTimeField(....) def created_weekday(self): return self.created_date.strftime("%A") in admin.py: class ArticleAdmin(admin.ModelAdmin): readonly_fields = ('created_weekday',) fields = ('title', 'created_weekday') Now the label for created_weekday is "Created Weekday", but I'd like it to have a different label which should be i18nable using ugettext_lazy as well. I've tried created_weekday.verbose_name=... after the method, but that did not show any result. Is there a decorator or something I can use, so I could make my own "verbose_name" / "label" / whateverthename is?

    Read the article

  • (Django) Trim whitespaces from charField

    - by zardon
    How do I strip whitespaces (trim) from the end of a charField in Django? Here is my Model, as you can see I've tried putting in clean methods but these never get run. I've also tried doing name.strip(), models.charField().strip() but these do not work either. Is there a way to force the charField to trim automatically for me? Thanks. class Employee(models.Model): """(Workers, Staff, etc)""" name = models.CharField(blank=True, null=True, max_length=100) # This never gets run def clean_variable(self): data = self.cleaned_data['variable'].strip() return data def __unicode__(self): return self.name class Meta: verbose_name_plural = 'Employees' # This never gets run either class EmployeesForm(forms.ModelForm): class Meta: model = Employee def clean_description(self): #if not self.cleaned_data['description'].strip(): # raise forms.ValidationError('Your error message here') self.cleaned_data['name'].strip()

    Read the article

  • Django model class and custom property

    - by dArignac
    Howdy - today a weird problem occured to me: I have a modle class in Django and added a custom property to it that shall not be saved into the database and therefore is not represent in the models structure: class Category(models.Model): groups = models.ManyToManyField(Group) title = defaultdict() Now, when I'm within the shell or writing a test and I do the following: c1 = Category.objects.create() c1.title['de'] = 'german title' print c1.title['de'] # prints "german title" c2 = Category.objects.create() print c2.title['de'] # prints "german title" <-- WTF? It seems that 'title' is kind of global. If I change title to a simple string it works as expected, so it has to do something with the dict? I also tried setting title as a property: title = property(_title) But that did not work, too. So, how can I solve this? Thank you in advance! enter code here

    Read the article

  • Django: Converting an entire Model into a single dictionary

    - by LarrikJ
    Is there a good way in Django to convert an entire model to a dictionary? I mean, like this: class DictModel(models.Model): key = models.CharField(20) value = models.CharField(200) DictModel.objects.all().to_dict() ... with the result being a dictionary with the key/value pairs made up of records in the Model? Has anyone else seen this as being useful for them? Thanks. Update I just wanted to add is that my ultimate goal is to be able to do a simple variable lookup inside a Template. Something like: {{ DictModel.exampleKey }} With a result of DictModel.objects.get(key__exact=exampleKey).value Overall, though, you guys have really surprised me with how helpful allof your responses are, and how different the ways to approach it can be. Thanks a lot.

    Read the article

  • iPhone HTTP Live Streaming not working on models below 3GS

    - by dreamer
    We are using http live streaming for on demand video from within our iPhone app and on the 3GS models the videos play as they are meant to. However, on the models pre 3GS it gives an error saying this movie format is not supported. I have seen other threads on this however no solutions or insights. Does anyone know if this really is a hardware limitation of the pre 3GS phones or does it have something to do with our code?

    Read the article

  • Should I define models that will be owned by many different models or use controller and views?

    - by jgervin
    I am struggling to figure out how to get a relationship between several models. I have sales_leads which I need to view by company and by event. So if someone looks up the leads by company they can see all leads across all events, but also see all leads by event. Not sure if this is ownership versus a where? Should it be something like Company.sales_leads where("event.event_id = ?", "2356") Or Models: sales_lead belongs_to event belongs_to company

    Read the article

  • ASP.Net MVC - Models and User Controls

    - by cdotlister
    Hi guys, I have a View with a Master Page. The user control makes use of a Model: <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<BudgieMoneySite.Models.SiteUserLoginModel>" %> This user control is shown on all screens (Part of the Master Page). If the user is logged in, it shows a certain text, and if the user isn't logged in, it offers a login box. That is working OK. Now, I am adding my first functional screen. So I created a new view... and, well, i generated the basic view code for me when I selected the controller method, and said 'Create View'. My Controller has this code: public ActionResult Transactions() { List<AccountTransactionDetails> trans = GetTransactions(); return View(trans); } private List<AccountTransactionDetails> GetTransactions() { List<AccountTransactionDto> trans = Services.TransactionServices.GetTransactions(); List<AccountTransactionDetails> reply = new List<AccountTransactionDetails>(); foreach(var t in trans) { AccountTransactionDetails a = new AccountTransactionDetails(); foreach (var line in a.Transactions) { AccountTransactionLine l = new AccountTransactionLine(); l.Amount = line.Amount; l.SubCategory = line.SubCategory; l.SubCategoryId = line.SubCategoryId; a.Transactions.Add(l); } reply.Add(a); } return reply; } So, my view was generated with this: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<System.Collections.Generic.List<BudgieMoneySite.Models.AccountTransactionDetails>>" %> Found <%=Model.Count() % Transactions. All I want to show for now is the number of records I will be displaying. When I run it, I get an error: "The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[BudgieMoneySite.Models.AccountTransactionDetails]', but this dictionary requires a model item of type 'BudgieMoneySite.Models.SiteUserLoginModel'." It looks like the user control is being rendered first, and as the Model from the controller is my List<, it's breaking! What am I doing wrong?

    Read the article

  • Inline editing of ManyToMany relation in Django

    - by vorpyg
    After working through the Django tutorial I'm now trying to build a very simple invoicing application. I want to add several Products to an Invoice, and to specify the quantity of each product in the Invoice form in the Django admin. Now I've to create a new Product object if I've got different quantites of the same Product. Right now my models look like this (Company and Customer models left out): class Product(models.Model): description = models.TextField() quantity = models.IntegerField() price = models.DecimalField(max_digits=10,decimal_places=2) tax = models.ForeignKey(Tax) class Invoice(models.Model): company = models.ForeignKey(Company) customer = models.ForeignKey(Customer) products = models.ManyToManyField(Product) invoice_no = models.IntegerField() invoice_date = models.DateField(auto_now=True) due_date = models.DateField(default=datetime.date.today() + datetime.timedelta(days=14)) I guess the quantity should be left out of the Product model, but how can I make a field for it in the Invoice model?

    Read the article

  • Entity Framework with large systems - how to divide models?

    - by jkohlhepp
    I'm working with a SQL Server database with 1000+ tables, another few hundred views, and several thousand stored procedures. We are looking to start using Entity Framework for our newer projects, and we are working on our strategy for doing so. The thing I'm hung up on is how best to split the tables into different models (EDMX or DbContext if we go code first). I can think of a few strategies right off the bat: Split by schema We have our tables split across probably a dozen schemas. We could do one model per schema. This isn't perfect, though, because dbo still ends up being very large, with 500+ tables / views. Another problem is that certain units of work will end up having to do transactions that span multiple models, which adds to complexity, although I assume EF makes this fairly straightforward. Split by intent Instead of worrying about schemas, split the models by intent. So we'll have different models for each application, or project, or module, or screen, depending on how granular we want to get. The problem I see with this is that there are certain tables that inevitably have to be used in every case, such as User or AuditHistory. Do we add those to every model (violates DRY I think), or are those in a separate model that is used by every project? Don't split at all - one giant model This is obviously simple from a development perspective but from my research and my intuition this seems like it could perform terribly, both at design time, compile time, and possibly run time. What is the best practice for using EF against such a large database? Specifically what strategies do people use in designing models against this volume of DB objects? Are there options that I'm not thinking of that work better than what I have above? Also, is this a problem in other ORMs such as NHibernate? If so have they come up with any better solutions than EF?

    Read the article

  • Rails: Single Table Inheritance and models subdirectories

    - by Chris
    I have a card-game application which makes use of Single Table Inheritance. I have a class Card, and a database table cards with column type, and a number of subclasses of Card (including class Foo < Card and class Bar < Card, for the sake of argument). As it happens, Foo is a card from the original printing of the game, which Bar is a card from an expansion. In an attempt to rationalise my models, I have created a directory structure like so: app/ + models/ + card.rb + base_game/ + foo.rb + expansion/ + bar.rb And modified environment.rb to contain: Rails::Initializer.run do |config| config.load_paths += Dir["#{RAILS_ROOT}/app/models/**"] end However, when my reads a card from the database, Rails throws the following exception: ActiveRecord::SubclassNotFound (The single-table inheritance mechanism failed to locate the subclass: 'Foo'. This error is raised because the column 'type' is reserved for storing the class in case of inheritance. Please rename this column if you didn't intend it to be used for storing the inheritance class or overwrite Card.inheritance_column to use another column for that information.) Is it possible to make this work, or am I doomed to a flat directory structure?

    Read the article

  • Load Ruby on Rails models without loading the entire framework

    - by epochwolf
    I'm looking to create a custom daemon that will run various database tasks such as delaying mailings and user notifications (each notice is a separate row in the notifications table). I don't want to use script/runner or rake to do these tasks because it is possible that some of the tasks only require the create of one or two database rows or thousands of rows depending on the task. I don't want the overhead of launching a ruby process or loading the entire rails framework for each operation. I plan to keep this daemon in memory full time. To create this daemon I would like to use my models from my ruby on rails application. I have a number of rails plugins such as acts_as_tree and AASM that I will need loaded if I where to use the models. Some of the plugins I need to load are custom hacks on ActiveRecord::Base that I've created. (I am willing to accept removing or recoding some of the plugins if they need components from other parts of rails.) My questions are Is this a good idea? And - Is this possible to do in a way that doesn't have me manually including each file in my models and plugins? If not a good idea What is a good alternative? (I am not apposed to doing writing my own SQL queries but I would have to add database constraints and a separate user for the daemon to prevent any stupid accidents. Given my lack of familiarity with configuring a database, I would like to use active record as a crutch.)

    Read the article

  • django views getid

    - by Hulk
    class host(models.Model): emp = models.ForeignKey(getname) def __unicode__(self): return self.topic In views there is the code as, real =[] for emp in my_emp: real.append(host.objects.filter(emp=emp.id)) This above results only the values of emp,My question is that how to get the ids along with emp values. Thanks..

    Read the article

  • django: CheckboxMultiSelect problem with db queries

    - by xiackok
    firstly sorry for my bad english there is a simple model Person. That contains just languages: LANGUAGE_LIS = ( (1, 'English'), (2, 'Turkish'), (3, 'Spanish') ) class Person(models.Model): languages = models.CharField(max_length=100, choices=LANGUAGE_LIST) #languages is multi value (CheckBoxSelectMultiple) and here person_save_form: class person_save_form(forms.ModelForm): languages = forms.CharField(widget=forms.CheckBoxSelectMultiple(choices=LANGUAGE_LIST)) class Meta: model = Person it is ok. but how can i search persons for languages like "get persons who knows turkish and english" in the database (MySQL) record "languages" column seen like "[u'1', u'2']". but i want search persons like this: persons = Person.objects.filter(languages__in=request.POST.getlist('languages'))

    Read the article

  • extending satchmo user profile

    - by z3a
    I'm trying to extend the basic user registration form and profile included in satchmo store, but I'm in problems with that. This what I've done: Create a new app "extendedprofile" Wrote a models.py that extends the satchmo_store.contact.models class and add the custom name fields. wrote an admin.py that unregister the Contact class and register my newapp but this still showing me the default user profile form. Maybe some one can show me the correct way to do this?

    Read the article

  • querying for timestamp field in django

    - by Hulk
    In my views i have the date in the following format s_date=20090106 and e_date=20100106 The model is defined as class Activity(models.Model): timestamp = models.DateTimeField(auto_now_add=True) how to query for the timestamp filed with the above info. Activity.objects.filter(timestamp>=s_date and timestamp<=e_date) Thanks.....

    Read the article

  • Maintaining content type pk integrity in a Django deployment

    - by hekevintran
    When you run syncdb in Django, the primary keys of the content types will be recomputed. If I create new models, the next time I run syncdb, the primary keys of the content types will be different. If I have an application running in production, how can I update the database with the new models and keep the integrity of content type pks?

    Read the article

  • Check if Django model field choices exists

    - by Justin Lucas
    I'm attempting to check if a value exists in the choices tuple set for a model field. For example lets say I have a Model like this: class Vote(models.Model): VOTE_TYPE = ( (1, "Up"), (-1, "Down"), ) value = models.SmallIntegerField(max_length=1, choices=VOTE_TYPES) Now lets say in a view I have a variable new_value = 'Up' that I would like to use as the value field in a new Vote. How can I first check to see if the value of that variable exists in the VOTE_TYPE tuple? Thank you.

    Read the article

  • Django ModelAdmin.save_model() -vs- ModelAdmin.save_formset()

    - by anonymous coward
    I want to ensure that a user editing a particular model is saved in that models updated_by (FK User) field. I'm using mostly ModelForms (not necessarily the built in Admin), and wondering: In what cases would I need to override ModelAdmin.save_model() or ModelAdmin.save_formset()? Or, is that doing it wrong? If it's just the models' save() method that needs to be overridden, is there a proper way to access the request object there?

    Read the article

  • Setting custom SQL in django admin

    - by eugene y
    I'm trying to set up a proxy model in django admin. It will represent a subset of the original model. The code from models.py: class MyManager(models.Manager): def get_query_set(self): return super(MyManager, self).get_query_set().filter(some_column='value') class MyModel(OrigModel): objects = MyManager() class Meta: proxy = True Now instead of filter() I need to use a complex SELECT statement with JOINS. What's the proper way to inject it wholly to the custom manager?

    Read the article

< Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >