Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError at /notify/notify/ 'UserNotifications' object has no attribute 'user'
I am trying to make a notifications app. I have a middle that collects info about the action the user should be notified about and in the view that handles the action it automatically creates an instance in the UserNotification model. This is all working. Now, if a user's post gets liked by another user, that actions needs to be displayed on the notifications page. However, I obviously don't want any one use to be able to see every notification that is being created on the site, but rather only the notifications that are created by their posts. I am running into an issue with the view and filtering the notifications based on the current user. More specifically, I am getting this error: AttributeError at /notify/notify/ 'UserNotifications' object has no attribute 'user' With traceback: Traceback (most recent call last): File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/contrib/auth/mixins.py", line 56, in dispatch return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) … -
Migration urls in app ...has no Migration class
Why when I try to run migration I get "Migration urls in app *** has no Migration class"? I just added new app and thats it. Have no idea what direction to look > C:\Users\PAPA\DEV\liberty\lib\site-packages\django\db\models\__init__.py:55: > RemovedInDjango19Warning: The utilities in django.db.models.loading > are deprecated in favor of the new application loading system. from > . import loading > > Traceback (most recent call last): File "manage.py", line 22, in > <module> > execute_from_command_line(sys.argv) File "C:\Users\PAPA\DEV\liberty\lib\site-packages\django\core\management\__init__.py", > line 338, in execute_from_command_line > utility.execute() File "C:\Users\PAPA\DEV\liberty\lib\site-packages\django\core\management\__init__.py", > line 330, in execute > self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\PAPA\DEV\liberty\lib\site-packages\django\core\management\base.py", > line 390, in run_from_argv > self.execute(*args, **cmd_options) File "C:\Users\PAPA\DEV\liberty\lib\site-packages\django\core\management\base.py", > line 441, in execute > output = self.handle(*args, **options) File "C:\Users\PAPA\DEV\liberty\lib\site-packages\django\core\management\commands\makemigrations.py", > line 63, in handle > loader = MigrationLoader(None, ignore_no_migrations=True) File "C:\Users\PAPA\DEV\liberty\lib\site-packages\django\db\migrations\loader.py", > line 47, in __init__ > self.build_graph() File "C:\Users\PAPA\DEV\liberty\lib\site-packages\django\db\migrations\loader.py", > line 174, in build_graph > self.load_disk() File "C:\Users\PAPA\DEV\liberty\lib\site-packages\django\db\migrations\loader.py", > line 109, in load_disk > "Migration %s in app %s has no Migration class" % (migration_name, app_config.label) django.db.migrations.loader.BadMigrationError: > Migration urls in app expense has no Migration class -
Fixing this "Page not found (404)" error
I am attempting to access a page in my application but I keep getting this error : Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/nesting/Identity-nest/%7B%25%20url%20'nesting:Symptoms_nest_list'%7D Using the URLconf defined in Identity.urls, Django tried these URL patterns, in this order: ^admin/ ^Identity/ ^nesting/ ^$[name='nesting'] ^nesting/ ^Identity-nest/$[name='Identity_nest_list'] ^nesting/ ^Symptoms-document/$[name='Symptoms_nest_list'] ^$ [name='login_redirect'] The current URL, nesting/Identity-nest/{% url 'nesting:Symptoms_nest_list'}, didn't match any of these. This is my main urls.py from django.conf.urls import url, include from django.contrib import admin from Identity import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^Identity/', include('Identities.urls', namespace = 'Identities')), url(r'^nesting/', include('nesting.urls', namespace = 'nesting')), url(r'^$', views.login_redirect, name = 'login_redirect'), ] This is my nesting urls.py from django.conf.urls import url from nesting.views import Identity_view, Identity_nest_list_view, Symptoms_document_view from . import views urlpatterns = [ url(r'^$', Identity_view.as_view(), name = 'nesting'), url(r'^Identity-nest/$', Identity_nest_list_view.as_view(), name = 'Identity_nest_list'), url(r'^Symptoms-document/$', Symptoms_document_view.as_view(), name = 'Symptoms_nest_list') ] This is my views.py class Symptoms_document_view(TemplateView): model = Symptoms template_name = 'nesting/Symptoms_list.html' def get(self, request): form = Symptom_Form() Symptoms_desc = Symptoms.objects.all() var = {'form':form, 'Symptoms_desc':Symptoms_desc} return render(request, self.template_name, var) def post(self, request): form = Symptom_Form(request.POST or None) Symptom_content = None if form.is_valid(): Symptoms_description = form.save(commit = False) Symptoms_description.user = request.user Symptoms_description.save() Symptoms_content = form.cleaned_data['Symptoms_description'] form = Symptom_Form() redirect('nesting:nesting') var = {'form': … -
How to initialize django objects automatically for the first time?
This is my first django application and I looked all over the place to find an answer, to no avail. I created my models and I know need to to initialize the values to one of the classes. I could do it using the admin page, one by one, but I want anyone using my application to be able to just load the application for the first time to have all the correct objects (and associated records in the database) to be created automatically. Please help -
Django: how to create a record that contains one or more items from a different db tables
I want to make a simple ticket system. I have 3 tables : Ticket, Responsible and Services .I also have the views that create, update and delete data to all 3 tables. what I am having problems is creating a view that creates the main ticket. My 3 tables are Ticket, Services and Responsible. my ticket can only have one responsible person and my ticket need to have one or more services. I'm lost on how to select multiple services to a ticket my models looks like this: from django.db import models from django.core.urlresolvers import reverse # Create your models here. class Servicios(models.Model): servicio = models.CharField(max_length=250) precio = models.FloatField() class Doctor(models.Model): nombre = models.CharField(max_length=250) porcentaje = models.FloatField() class Ticket(models.Model): fecha = models.DateTimeField(auto_now_add=True) servicio = models.ForeignKey(Servicios) doctor = models.ForeignKey(Doctor) cantidad = models.IntegerField() p_unitario = models.FloatField() total = models.FloatField() def get_absolute_url(self): return reverse('Main:get-list') -
I can't open manage.py
On the command prompt, (Windows 10) I created a virtual environment, I then created a new project, I installed django in the virtual environment using pip. Then decided to run the command python manage.py runserver To run djangos web server, This returned with "...can't open file 'manage.py': [Errno 2] No such file or directory" I did see a similar question to this on this platform but it seems to only apply to those using linux. Where answers specify to use the ls command, which is not applicable on Windows command prompt. I have tried this multiple times but i just can't open manage.py -
Django creates migration files after each 'makemigrations' because of dictionary?
I've noticed strange things in my Django project. Each time I run python manage.py makemigrations command new migration file for my app called notifications is created. I did zero changes to the model, but the new migration file is created. I can run makemigrations command N number of times and N number of migration files will be created. The model looks as following: from django.db import models from django.db.models.fields import EmailField class EmailLog(models.Model): email = models.EmailField(max_length=70, null=False) subject = models.CharField(max_length=255, null=False) html_body = models.TextField(null=False) sent_choices = { ('OK', 'Sent'), ('KO', 'Not sent'), ('KK', 'Unexpected problems') } status = models.CharField(max_length=2, choices=sent_choices, null=False, default='KO') sent_log = models.TextField(null=True) sent_date = models.DateTimeField(auto_now_add=True, null=False) Each migration just swaps the position of sent_choices field. that's all! Is it because dictionaries in Python have random order? How do I avoid it? -
nginx unix:/webapps/myproject/run/gunicorn.sock failed (13: Permission denied) while connecting to upstream
Want to do work assembly: django, nginx, gunicorn, supervisor, centos 7. Work perfect, but I have one problem and one error in browser - "502 Bad Gateway nginx/1.10.2". nginx-error.log unix:/webapps/myproject/run/gunicorn.sock failed (13: Permission denied) while connecting to upstream, client: 192.168.4.33, server: 192.168.4.39, request: "GET / HTTP/1.1", upstream: "http://unix:/webapps/myproject/run/gunicorn.sock:/", host: "192.168.4.39" Haven`t idia how to fix it. Had tried configure selinux, give permissions, change users and some anything else, but it is did not help, I do not have enough knowledge. /etc/nginx/conf.d/myproject.conf server { listen 80; server_name 192.168.4.39; location = /favicon.ico { access_log off; log_not_found off; } client_max_body_size 2G; access_log /webapps/myproject/logs/nginx-access.log; error_log /webapps/myproject/logs/nginx-error.log; location /static/ { root /webapps/myproject/; } location /media/ { alias /webapps/myproject/media/; } location / { # include proxy_params; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # proxy_pass http://127.0.0.1:8000; proxy_pass http://unix:/webapps/myproject/run/gunicorn.sock; } } gunicorn_start.bash #!/bin/bash NAME="myproject" # Name of the application DJANGODIR=/webapps/myproject/ # Django project directory SOCKFILE=/webapps/myproject/run/gunicorn.sock # we will communicte using this unix socket USER=myproject # the user to run as GROUP=webapps # the group to run as NUM_WORKERS=3 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=myproject.settings # which settings file should Django use DJANGO_WSGI_MODULE=myproject.wsgi # WSGI module name echo "Starting $NAME … -
Django - field of language choices
I want to let user choose from languages they speak. Is there a Django built in list of languages or should I get list of languages from other source? For now: class UserProfile(models.Model): languages = models.ManyToManyField(Language) class Language(models.Model): shortcut ... name ... The languages field should only be able to list all languages user can speak. -
django + gunicorn + nginx: Browser refreshes toggling between PRE/POST dynamic content change
Below are the nginx.conf and gunicorn.start.sh files that I use for the Django application that I'm running (which, by the way, I didn't write). When I make any one-time change to dynamic content, then repeatedly refresh the browser, the rendered content switches/flaps variously between PRE and POST changes made. But it should just update once, and never again. The only thing that momentarily fixes the issue is restarting gunicorn: myapp$ sudo supervisorctl restart gunicorn But this only works until the next change to dynamic content. No good. I've tried numerous browsers, and it happens even when I clear their caches. Makes no difference. I also temporarily tried uWSGI instead of gunicorn (just to see), and the same issue occurs. A tail -f gunicorn.access.log during browser refreshes shows HTTP statuses that vary between 200 (content was downloaded) and 304 (you already have the content; redirecting you to your local cache). But dynamic content shouldn't be cached. Note that when running the application using the development server, like this: myapp$ python manage.py runserver --settings live 0.0.0.0:8080 the issue doesn't occur; but neither does this use nginx nor gunicorn. Any ideas? I've tried everything I know, but don't know what is causing this … -
Django + mod_wsgi Fatal Python Error: Py_Initialize: No module named Encodings
I am attempting to get a website to load within a web browser using Django + mod_wsgi and apache. I have exactly the same problem as in This Question Here, but the solution found there does not work in my case. Here is my httpd-vhosts.conf setup: WSGIDaemonProcess binshellpress.com python-home=/usr/local/docs/binshellpress-production/virtpy/ python-path=/usr/local/docs/binshellpress-production/virtpy/lib/python3.6/ WSGIProcessGroup binshellpress.com WSGIApplicationGroup %{GLOBAL} <VirtualHost *:80> ServerAdmin webmaster@binshellpress.com DocumentRoot "/usr/local/docs/binshellpress-production/root" ServerName binshellpress.com ServerAlias www.binshellpress.com ErrorLog "/var/log/httpd/bsp-error_log" CustomLog "/var/log/httpd/bsp-access_log" common Alias /robots.txt /usr/local/docs/binshellpress-production/static/robots.txt Alias /favicon.ico /usr/local/docs/binshellpress-production/static/favicon.ico Alias /media/ /usr/local/docs/binshellpress-production/media Alias /static/ /usr/local/docs/binshellpress-production/static <Directory /usr/local/docs/binshellpress-production/static> Require all granted </Directory> <Directory /usr/local/docs/binshellpress-production/media> Require all granted </Directory> WSGIScriptAlias / /usr/local/docs/binshellpress-production/binshellpress/wsgi.py process-group=binshellpress.com <Directory /usr/local/docs/binshellpress-production/binshellpress> <Files wsgi.py> Require all granted </Files> </Directory> </Virtualhost> I have a virtual environment set up at /usr/local/docs/binshellpress-production/virtpy. I have rebuilt mod_wsgi to explicitly use that virtual environment. I have performed the permissions modifications as described in the answer to This Question No change. I am desperate. I have been searching up and down. I can't figure out what to do. Please, help me. I beg you. Thank you, for anything, thank, just please, help me, thank you. -
Request google app engine
I do a http request with module requests in django (python 3), import requests url = 'https://www.google.es' r = requests.get(url) str = str(r.content) and It work right in localhost, but when I deploy in Google App Engine, It return a "('Connection aborted.', error(104, 'connection reset by peer'))", I deploy in a flex enviroment. I read than it not necessary change for urlfetch module. -
Unresponsive django-bootstrap3-datetimepicker (not showing calendar)
As a beginner I often struggle with understanding the connections between Python-Django, html, javascript and css. The problem at hand is this: I'm trying to implement DateTimePicker widget from django-bootstrap3-datetimepicker-2. Since this library does not include js/css assets, I started by implementing datetimepicker without backend involvement just to see if I loaded all static files etc. correctly. Thus, I added this example to html template: <div class="container"> <div class="row"> <div class="col-sm-6"> <div class="form-group"> <div class="input-group date" id="datetimepicker1"> <input type="text" class="form-control"> <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div> </div> </div> <script type="text/javascript"> $(function () { $('#datetimepicker1').datetimepicker(); }); </script> </div> </div> Everything worked as intended, so I tried to implement datetimepicker as a widget from django forms: class FooForm(forms.Form): pick_a_date = forms.DateTimeField( widget=DateTimePicker(options={ "format": "YYYY-MM-DD", "pickTime": False} )) I also wanted to benefit from form wizard (namely SessionWizardView from formtools.wizard), so I output the above mentioned form into html like this: <form action="" method="post" role="form">{% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %} {% else %} {{ wizard.form }} {% endif %} </table> However, the widget is not responsive (the calendar window isn't showing, the … -
django can't find my choiceField on fields
I have my class: from django import forms from .models import Donator class DonatorForm(forms.ModelForm): BLOOD_CHOICES = ( ('A-','A-'), ('A+','A+'), ('B-','B-'), ('B+','B+'), ('AB-','AB-'), ('AB+','AB+'), ('O-','O-'), ('O+','O+'), ('TODOS','TODOS') ) SITUATION_CHOICES = ( ('Sem Problemas','Sem Problemas'), ('Problemas Momentâneos','Problemas Momentâneos'), ('Problemas Graves', 'Problemas Graves') ) class Meta: model = Donator fields = ('name', 'age', 'email','phone', forms.ChoiceField(choices = SITUATION_CHOICES, required=True, label = "Situacao do Doador"), 'bloodType', 'observation') I receive: NameError: name 'SITUATION_CHOICES' is not defined How could I correctly mention my fieldCHoices to appear a dropdown on the Form? -
How to use django login_required method
$ class HomePage(TemplateView): template_name = 'obs/homepage.html' I want to make this view accessible to only logged in users. How can i do that? i've seen django documentation but it was for functions. -
Creating / storing a form preview with Django forms and cart
I've never had to do this before and I'm wondering if I'm on the right track / this is the standard way to do something of this nature. I was going to use Django formtools FormPreview but it doesn' handle files (They can upload various images)... So, rolling my own solution or trying to. Currently I'm using a form wizard with model forms and everything validates / saves fine. I now want to add in a form preview, before purchasing the item they create with the form, and I've thought about doing the following: Save it to the database but mark it as not paid / inactive. On the form preview page grab the id (from pk in url) and display it. They have the option to go back and edit (update view) and / or pay. Using this route it's really easy to update and grab the data for viewing whether they wish to go back or forward. Similarly, if they add multiple items in their cart I can just display these items by grabbing the pk's from the DB rather than trying to handle a ton of session data. If they remove the item -> delete the row … -
Django UpdateView - get initial data from many-to-many field and add them when saving form
I'm using Django class based generic view. In my models.py I have a model called MyModel with many-to-many field called m2m. I have multiple groups of users they can edit the m2m field. Each group of users can only see and add their portion to the field - using get_form to set what they can see in the m2m field. The problem I'm having is that when one user enter his record it will delete the initial records in the m2m field. I need to somehow get the initial values from the m2m field save them and then add them to the new ones when the form is submitted. Here is my views.py: class MyModelUpdate(UpdateView): model = MyModel fields = ['m2m'] def get_initial(self): return initials def get_form(self, form_class=None): form = super(MyModelUpdate, self).get_form(form_class) form.fields["m2m"].queryset = DiffModel.objects.filter(user = self.request.user) return form def form_valid(self, form): form.instance.m2m.add( ??? add the initial values) return super(MyModelUpdate, self).form_valid(form) def get_success_url(self): ... -
django app deploy to google app engine
I am trying to deploy my django project on google app engine. When I 'gcloud app deploy' everything looks like it is going well except it takes a really long time. Then I get the message: 'ERROR: (gcloud.app.deploy) Error Response: [4] Your deployment has failed to become healthy in the allotted time and therefore was rolled back. If you believe this was an error, try adjusting the 'app_start_timeout_sec' setting in the 'readiness_check' section.' I checked my acitivity log in google cloud and i have the error: " STATIC_ADDRESSES quota limit reached " This is my first django project and first time on google app engine. How can I get this thing up? -
How to start building a django website with postgres nginx and gunicorn on separate machines?
I searched all over the internet and I guess I'm lost, Please I want a detailed answer here. I know how to make all three of these things(gunicorn, Nginx, and Postgres) work on the same machine but what if I wanna have all of them on the different/individual machine. Let's say I got 3 behemoth powerful machines capable of handling anything but the real question in my mind is where do I start. how can I connect all three of these together? what if I wanna add more storage? How do I connect multiple database machines together I'm sorry but I'm pretty new in networking and it's really crucial for me to understand this because if I don't my mind won't allow me to go ahead with the process. -
Error ! The following packages have unmet dependencies: mysql-server
I tried to install mysql on my ubuntu16.04 for a django project. The installation has some problem with some existing files, getting the error: mysql-server is already the newest version (5.7.19-0ubuntu0.16.04.1). You might want to run 'apt-get -f install' to correct these: The following packages have unmet dependencies: mysql-server : Depends: mysql-server-5.7 but it is not going to be installed E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution) I tried, sudo apt-get -f install which gives error: Preparing to unpack .../mysql-server-5.7_5.7.19-0ubuntu0.16.04.1_amd64.deb ... grep: /etc/mysql/: No such file or directory Aborting downgrade from (at least) 10.2 to 5.7. If are sure you want to downgrade to 5.7, remove the file /var/lib/mysql/debian-*.flag and try installing again. dpkg: error processing archive /var/cache/apt/archives/mysql-server-5.7_5.7.19-0ubuntu0.16.04.1_amd64.deb (--unpack): subprocess new pre-installation script returned error exit status 1 Errors were encountered while processing: /var/cache/apt/archives/mysql-server-5.7_5.7.19-0ubuntu0.16.04.1_amd64.deb E: Sub-process /usr/bin/dpkg returned an error code (1) I have tried installation steps also but gets the first error. -
Django crispy forms - creating a form in home.html and getting an error
I have built a crispy form from a tutorial (https://godjango.com/29-crispy-forms/) and am getting an error that I believe means I need to define a URL in the urls.py. I also get the sense that there may be more than one issue going on - I am still trying to make this work and will continue to research it but I am quite new to Django and Python so struggling on this. Any guidance gratefully received. Here's the error: Failed lookup for key [form] in "[{'True': True, 'False': False, 'None': None}, {}, {}, {'view': <django.views.generic.base.TemplateView object at 0x10faa03c8>, 'home_url': '/'}]" For reference here are the files: forms.py from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Field from crispy_forms.bootstrap import ( PrependedText, PrependedAppendedText, FormActions) class SimpleForm(forms.Form): username = forms.CharField(label="Username", required=True) password = forms.CharField( label="Password", required=True, widget=forms.PasswordInput) remember = forms.BooleanField(label="Remember Me?") helper = FormHelper() helper.form_method = 'POST' helper.add_input(Submit('login', 'login', css_class='btn-primary')) class CartForm(forms.Form): item = forms.CharField() quantity = forms.IntegerField(label="Qty") price = forms.DecimalField() helper = FormHelper() helper.form_method = 'POST' helper.layout = Layout( 'item', PrependedText('quantity', '#'), PrependedAppendedText('price', '$', '.00'), FormActions(Submit('login', 'login', css_class='btn-primary')) ) class CreditCardForm(forms.Form): fullname = forms.CharField(label="Full Name", required=True) card_number = forms.CharField(label="Card", required=True, max_length=16) expire = forms.DateField(label="Expire Date", input_formats=['%m/%y']) ccv … -
Error when running a Django server
I am using Django 1.8 and I get the following error: WARNINGS: ?: (1_7.W001) MIDDLEWARE_CLASSES is not set. HINT: Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES. django.contrib.sessions.middleware.SessionMiddleware, django.contrib.auth.middl eware.AuthenticationMiddleware, and django.contrib.messages.middleware.MessageMi ddleware were removed from the defaults. If your project needs these middleware then you should configure this setting. What do I have to do ? -
django domain setup and routing schema
Can anyone give me a short walkthrough (yes, I know that's asking a lot... I'm completely lost) of how to properly setup different domains using a single django project? Or... point me in the right direction / some insight to my questions below... I've searched around and looked at various app solutions, apache stuff, etc but still don't have a clear understanding. Specifically, each (main) app in my project is on a different domain. I have an app for news, job posts, etc and these would be on (name)news.io, (name)jobs.io, etc. In my settings.py file currently I'm using django-multiple-domains and have the MULTIURL_CONF set to point to each app based upon the domain name. As I understand it.... i can just set up the project on my domains using the same settings file since it will use this routing schema rather than the suggested route of multiple different settings file for each domain based upon the middleware that django-multiple-domains uses. Now, here's where I get confused on the URL routing.... In an app we typically include the urls inside the main urls.py file in the root app folder for our project to creating a routing schema for the entire site … -
How to create instances when there are multiple senders in django signals?
I am getting error order_id must be Order instance user must also be MyUser instance. How do i create instances? @receiver(post_save, sender=MyUser) @receiver(post_save, sender=Order) def create_order_message(sender, **kwargs): user_id = instance.id MyUser.object.filter(id=user_id) if kwargs.get('created', False): Notification.objects.create(order_id = kwargs.get('instance'), user = kwargs.get('instance'), title='Welcome to Django!', message='Thank for signing up!', ) -
Django with unique_together on foreign key and slug=slugify fails
I am building a basic CMS. I have created an organization app, that adds a project ID with foreign key to all my model objects. The form is for creating a basic website object with header and text. I was able to create and save one instance with the following code. Further tries with different titles fail with "(1062, "Duplicate entry '' for key 'cms_page_url_117a950602ffab5c_uniq'") I have now idea where I am going wrong, can somebody point me in the correct direction? I am running on mysql database. Model: class Page(models.Model): title = models.CharField(max_length=100) text = models.TextField(blank=True) slug = models.SlugField() date_created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(default=timezone.now) project = models.ForeignKey(Project) def __unicode__(self): return "Page '%s' @: %s from %s" % (self.title, self.slug, self.project) def __str__(self): return unicode(self).encode('utf-8') def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Page, self).save(*args, **kwargs) class Meta: unique_together = (("project", "slug"),) Form: class PageForm(ModelForm): def __init__(self, *args, **kwargs): super(PageForm, self).__init__(*args, **kwargs) for key, field in six.iteritems(self.fields): field.widget.attrs['placeholder'] = field.label class Meta: model = Page fields = ['title', 'text'] # TODO: ordering title = forms.CharField(max_length=100, label=ugettext_lazy("Add a title")) text = forms.CharField(label=ugettext_lazy("Type your text here"), widget=forms.Textarea) def save(self, project, commit=True): instance = super(PageForm, self).save(commit=False) instance.project = project if commit: instance.save() return …