Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
issues with python virtual environment
I am facing following 2 issues: python command is not using the virtualenvwrapper python. After activating my virtual environment if I type python then the code still uses the native python libraries. I can easily install libraries etc with pip to my virtual environment but I cannot run any command using python. e.g. if I execute $ ./manage.py runserverthen it is fine and I can run a django server but if I try $ python manage.py runserver or even just $ python then it uses the native python libraries and that should not happen This is while using iterm or terminal in osx. I have never faced this problem in any linux based os While using any os (linux based or osx), the workon command doesn't work inside any shell script, while it works normally in a terminal os: osx -
Django Twitter clone. How to restrict user from liking a tweet only once?
I'm not sure where to start. Right now, the user can press like as many times they want and it'll just add up the total likes for that tweet. models.py class Howl(models.Model): author = models.ForeignKey(User, null=True) content = models.CharField(max_length=150) published_date = models.DateTimeField(default=timezone.now) like_count = models.IntegerField(default=0) rehowl_count = models.IntegerField(default=0) def get_absolute_url(self): return reverse('howl:index') def __str__(self): return self.content views.py class HowlLike(UpdateView): model = Howl fields = [] def form_valid(self, form): instance = form.save(commit=False) instance.like_count += 1 instance.save() return redirect('howl:index') -
I can't expand the template django
I can't expand the template base.html template header.html Content base.html <div id="main-container"> <!-- HEADER --> {% block header %}{% endblock %} <!-- END HEADER --> </div> Content header.html {% extends "blog/base.html" %} {% block header %} <header id="header"> *** </header> {% endblock %} The output in the browser get the code: <div id="main-container"> <!-- HEADER --> <!-- END HEADER --> Why not be able to extend the template? Using {% include "blog/header.html"%} code inserted. using extends no. Use Django 1.10.1 views.py from django.shortcuts import render from django.utils import timezone from .models import Post from django.shortcuts import render, get_object_or_404 def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/index.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404 (Post, pk=pk) return render(request, 'blog/base.html', {'post': post}) def header(request): return render (request, 'blog/header.html') -
NoReverseMatch - How to add url parameter to render?
Is there any method to provide url argument in case of render or any other solution? # view def create_gallery(request, user_url): if request.method == 'POST': extended_form = GalleryExtendedForm(request.POST, prefix="extended_form") basic_form = GalleryForm(request.POST, prefix="basic_form") print(request.POST) if extended_form.is_valid() and basic_form.is_valid(): pass else: extended_form = GalleryExtendedForm(prefix="extended_form") basic_form = GalleryForm(prefix="basic_form") return render(request, 'galleries/gallery_create_n_update.html', {'extended_form': extended_form, 'basic_form': basic_form}) # core.urls urlpatterns = [ url(r'^(?P<user_url>[\w.-]+)/', include('profiles.urls', namespace='profiles_user')), ] # profiles.urls urlpatterns = [ url(r'^gallery/', include('galleries.urls')), # ... lots of others urls ] # galleries.urls urlpatterns = [ url(r'^add/$', views.create_gallery, name='gallery-add'), ] Error: django.urls.exceptions.NoReverseMatch: Reverse for 'gallery-add' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['(?P<user_url>[\\w.-]+)/gallery/add/$'] -
request.user.is_authenticated() consistently returns false (Django)
The problem I'm having I'm currently using Django v1.9 as a back-end for my Angular2 app (I'm not using the Django REST Framework yet, just using Django's authentication system and dumping JSON) I'm trying to authenticate the user, log them in, and then allow them to edit their profile. The first two steps seem to work. However, I'm having some trouble with request.user.is_authenticated() - it consistently returns false, even though I have called the login() function on the user previously. The part that seems to work @csrf_exempt def userlogin(request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) input_u = body['uname'] input_p = body['pword'] worked = False user = authenticate(username=input_u, password=input_p) if user is not None: login(request, user) context = { "login_data" : { "logged_in" : True, "user_id" : user.id } } else: context = { "login_data" : { "logged_in" : False, "user_id" : 0 } } return HttpResponse(json.dumps(context), content_type="application/json") The part I'm struggling with @ensure_csrf_cookie def user(request): is_auth = False if request.user.is_authenticated(): is_auth = True context = { "is_auth" : is_auth } return HttpResponse(json.dumps(context), content_type="application/json") Note: I'm using is_authenticated() (function) and not is_authenticated (property) as I'm on Django v1.9 and not v.1.10 (source). I was previously making the mistake of checking for … -
django specific url/view that wont modify the session expiry date?
As I see each time the session is changed, i.e request.session['last_date'] = datetime.datetime.now() for example, the expiry_date is changed too. Can I create an exception for that? I want to use the expiry_date as a timeout for the session, but I have a JS code in the client which send requests every few minutes, thus always extend the session expiry_date. I want a way (simple, I hope) to write to the session without extending this date. -
Angular2 and Django: CSRF Token Headache
The Issue I'm Having I'm making an Ajax POST request from my Angular2 client to my Django (v1.9) backend (both on localhost, different ports). I'm not yet using the Django REST framework, I'm just dumping the JSON in Django without any add-ons. I have been issued a csrf token by the server, and I'm manually sending it back in the HTTP headers (I can see it there when I make the call). However, I still get the error from django: Forbidden (CSRF cookie not set.) I've read a number of other threads, and tried a few things, but still can't get Django to accept the CSRF token. Client side code: private _editUserUri = "http://127.0.0.1:8000/search/edit/user/"; constructor(private _http: Http){} getCookie(name) { let value = "; " + document.cookie; let parts = value.split("; " + name + "="); if (parts.length == 2) return parts.pop().split(";").shift(); } validateData(userdata) { return true; } editUser(userdata) { console.log("UserService: createUser function called"); console.log(JSON.stringify(userdata)); if(this.validateData(userdata)) { let headers = new Headers({ 'Content-Type': 'application/json', 'X-CSRFToken': this.getCookie('csrftoken') }); let options = new RequestOptions({ headers: headers }); return this._http .post( this._editUserUri, JSON.stringify(userdata), options) .map(res => { console.log(res.json()); return res.json(); }) } } Screenshot of csrf token in header (x-csrftoken). This is exactly how … -
Django: TypeError: 'x' is an invalid keyword argument for this function
The view below works, which is utilising the "update_or_create" feature, brilliantly when something exists and therefore updates a record. However, if it does not exist and has to use the create option to create a new record I get the following error: TypeError at /selectteams/1025/3/ 'soccerseasonid_id' is an invalid keyword argument for this function View Below: if request.method == 'POST': form = SelectTwoTeams(request.POST,user=request.user) if form.is_valid(): teamSelection1, created = UserSelection.objects.update_or_create(user_id=currentUserID, fixturematchday=fixturematchday, soccerseason_id=soccerseason, teamselection1or2=1, defaults={"campaignno":11, "teamselection1or2":1, "teamselectionid_id":request.POST['team1'], "user_id":currentUserID, "fixturematchday":fixturematchday, "soccerseasonid_id":soccerseason}) teamSelection2, created = UserSelection.objects.update_or_create(user_id=currentUserID, fixturematchday=fixturematchday, soccerseason_id=soccerseason, teamselection1or2=2, defaults={"campaignno":11, "teamselection1or2":2, "teamselectionid_id":request.POST['team2'], "user_id":currentUserID, "fixturematchday":fixturematchday, "soccerseasonid_id":soccerseason}) Models Below: class StraightredSeason(models.Model): seasonid = models.IntegerField(primary_key = True) seasonyear = models.CharField(max_length = 4) seasonname = models.CharField(max_length = 36) def __unicode__(self): return self.seasonid class Meta: managed = True db_table = 'straightred_season' class UserSelection(models.Model): userselectionid = models.AutoField(primary_key=True) campaignno = models.CharField(max_length=36,unique=False) user = models.ForeignKey(User, related_name='selectionUser') teamselection1or2 = models.PositiveSmallIntegerField() teamselectionid = models.ForeignKey('straightred.StraightredTeam', db_column='teamselectionid', related_name='teamID') fixturematchday = models.IntegerField(null=True) soccerseason = models.ForeignKey('straightred.StraightredSeason', db_column='soccerseasonid', related_name='fixture_seasonUserSelection') class Meta: managed = True db_table = 'straightred_userselection' Any help would be appreciated, many thanks, Alan. -
How to auto populate updated_by in abstract model that is used by all other models in my app?
I usually use some decorators but this time decided to use the abstract model to have all my common fields. How do I auto populate updated by. I saw some old answers saying it is not possible to do in the model . DRY way to add created/modified by and time Anything changed+ in 5 years? how you usually do it? So far it looks like I will have to use both decorator django-author with Common model for other fields. class CommonInfo(models.Model): created = models.DateTimeField("creation date", auto_now_add=True) modified = models.DateTimeField("modification date", auto_now=True) description = models.TextField() is_active = models.BooleanField(default=True) updated_by= class Meta: and to have more control abstract = True -
Display additional content panel based on boolean block in Wagtail Editor Interface
I want to add a boolean block to my Wagtail model and show a content panel field only if it is checked. I have figured out how to add a boolean block and render content in the template based on its value, but not how to do control the editor interface with it. Here is my model. I want to show the heldover_from, date chooser block, only when heldover boolean is checked. class AgendaPage(Page): author= models.CharField(max_length=255) date = models.DateField('Post date') agenda = StreamField([ ('agenda_item', blocks.StreamBlock([ ('item_title', blocks.TextBlock()), ('item_text', blocks.TextBlock()), ('mtg_doc', blocks.StructBlock([ ('doc_description', blocks.TextBlock()), ('doc_link', blocks.TextBlock()), ('submitted_late', blocks.BooleanBlock(required=False, help_text='Submitted Late')), ('heldover', blocks.BooleanBlock(required=False, help_text='Held Over')), ('heldover_from', blocks.DateBlock(required=False, help_text="Held Over From") ])) ] )) ]) content_panels = Page.content_panels + [ FieldPanel('author'), FieldPanel('date'), StreamFieldPanel('agenda'), ] (And after I figure this out, I want to know if I can make it required, but only if heldover is checked, not for the whole streamblock) -
django with jinja2 using model's get_absolute_url definition in template
I am using jinja2 as my template engine in Django 1.10. I have a model that has a definition as: def get_absolute_url(self): return reverse('apps.web.views.work_detail', kwargs={'year':self.created_at.year, 'month':self.created_at.strftime("%m"), 'day':self.created_at.strftime("%d"), 'slug':self.slug, 'workId':self.id}) and my urls.py has: url(r'^ardiye/çalışmalar/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+),(?P<workId>\d)/$', work_detail, name='work_detail') when i use my model definition to get the absolute url in my template via <a href='{{next_work.get_absolute_url() }}' class='directional-menu-prev'>Önceki</a> i get an error: NoReverseMatch at / Reverse for 'apps.web.views.work_detail' with arguments '()' and keyword arguments '{'year': 2016, 'slug': 'kksjs', 'month': '09', 'day': '10', 'workId': 2}' not found. 0 pattern(s) tried: [] -
Migrating Django 1.3 to 1.10 Unwanted suffix added to admin urls
When I use any link on the admin page a "change/" suffix is added to my url's and they are not found. Things start out OK, but after jquery is loaded RelatedObjectLookups is loaded and subsequent urls have a "/change" appended. I've been looking at this problem for a few hours and have no idea where to go. This is what my test server output looks like: September 10, 2016 - 16:21:49 Django version 1.10.1, using settings 'adsync.settings' Starting development server at http://192.168.56.101:8080/ Quit the server with CONTROL-C. [10/Sep/2016 16:21:55] "GET /admin/ HTTP/1.1" 200 5558 [10/Sep/2016 16:22:05] "GET /admin/auth/user/ HTTP/1.1" 200 6876 [10/Sep/2016 16:22:05] "GET /admin/auth/user/static/admin/css/base.css/ HTTP/1.1" 302 0 [10/Sep/2016 16:22:05] "GET /admin/auth/user/static/admin/css/changelists.css/ HTTP/1.1" 302 0 [10/Sep/2016 16:22:05] "GET /admin/jsi18n/ HTTP/1.1" 200 3217 [10/Sep/2016 16:22:05] "GET /admin/auth/user/static/admin/js/core.js/ HTTP/1.1" 302 0 [10/Sep/2016 16:22:05] "GET /admin/auth/user/static/admin/js/vendor/jquery/jquery.js/ HTTP/1.1" 302 0 [10/Sep/2016 16:22:05] "GET /admin/auth/user/static/admin/js/jquery.init.js/ HTTP/1.1" 302 0 [10/Sep/2016 16:22:05] "GET /admin/auth/user/static/admin/js/admin/RelatedObjectLookups.js/ HTTP/1.1" 302 0 WARNING Not Found: /admin/auth/user/static/admin/css/base.css/change/ Not Found: /admin/auth/user/static/admin/css/base.css/change/ [10/Sep/2016 16:22:05] "GET /admin/auth/user/static/admin/css/base.css/change/ HTTP/1.1" 404 1870 WARNING Not Found: /admin/auth/user/static/admin/css/changelists.css/change/ Not Found: /admin/auth/user/static/admin/css/changelists.css/change/ [10/Sep/2016 16:22:05] "GET /admin/auth/user/static/admin/css/changelists.css/change/ HTTP/1.1" 404 1891 [10/Sep/2016 16:22:05] "GET /admin/auth/user/static/admin/js/actions.js/ HTTP/1.1" 302 0 [10/Sep/2016 16:22:05] "GET /admin/auth/user/static/admin/js/urlify.js/ HTTP/1.1" 302 0 [10/Sep/2016 16:22:05] "GET /admin/auth/user/static/admin/js/prepopulate.js/ HTTP/1.1" 302 0 … -
No Reverse Match with Django Auth Views
I created a custom User model following the example in the Django documentation, now I'm trying to use Django auth views but I keep getting NoReverseMatch at /accounts/login/ Reverse for 'django.contrib.auth.views.login' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] This is the url conf: from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^accounts/login/$', auth_views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}), url(r'^logout/$', auth_views.logout, {'next_page': '/accounts/login'}), url(r'^$', home, name="home"), ] And I have this line in my template: <form method="post" action="{% url 'django.contrib.auth.views.login' %}"> -
Django - How to add a validator to form field (instead of setting it)
In Django, you can specify the validators to a given form field by def SomeForm(forms.Form): field_1 = forms.CharField() field_2 = forms.CharField(validators=[...]) However, what if I only want to add a single validator on? (instead of replacing all potentially inherent/inherited validators? -
How to I relate ManyToMany relationship in a single form with single submit
I have two models which have ManyToMany relationship, Category and Post.I am trying to incorporate two modelforms, post_form and category_form in a same form with one submit button. How do I show the relationship when I save it? Currently, when I add same category_name for two different posts, it gives me warning saying it already exists. I would like to be able to choose the same category_name in dropdown or something similar. Please help. If this is not possible what are my alternatives? Models.py class Category(models.Model): category_name = models.CharField(max_length=250, unique=True) category_slug = models.SlugField(max_length=250, unique=True) class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') categories = models.ManyToManyField(Category) def get_absolute_url(self): return reverse('posts:post_detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) Views.py def post_list(request): queryset = Post.objects.all() return render(request, 'posts/post_list.html', {'post_list': queryset}) def post_detail(request, year, month, day, post): instance = get_object_or_404(Post, slug = post, status = 'published', publish__year = year, publish__month = month, publish__day = day) return render(request, 'posts/post_detail.html', {'post':instance}) def post_create(request): post_form = PostForm(request.POST or None) category_form = CategoryForm(request.POST or None) if post_form.is_valid() and category_form.is_valid(): post_form_instance = post_form.save() category_form_instance = category_form.save() … -
TypeError: int() argument must be a string, a bytes-like object or a number, not datetime
TypeError: int() argument must be a string, a bytes-like object or a number, not datetime.datetime Models.py from django.db import models from django.core.urlresolvers import reverse class Register(models.Model): user_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=50) password = models.CharField(max_length=50) confirm_password = models.CharField(max_length=50) email = models.EmailField(max_length=100) position = models.CharField(max_length=50) def get_absolute_url(self): return reverse('user:register', kwargs={'pk': self.pk}) class Login(models.Model): id = models.OneToOneField(Register, on_delete=models.CASCADE, primary_key=True) username = models.CharField(max_length=50) password = models.CharField(max_length=50) def __str__(self): login = {'username': self.username, 'password': self.password} return login I searched and tried other options but can't still figure out problem and solution. makemigrations doesn't give an error but migrate command gives. -
Django query not considers special characters
I've come across a problem with special characters on a django query (Django 1.9.2). I've created a model that stores a word in it, and I'm feeding that model with words from a Spanish dictionary, using code as follows: MyModel.objects.get_or_create(word=myword) And now I've realized that words containing special characters haven't been added, so, for example, there is only one row of MyModel in the database for año and ano! And when I query the database I retrieve the same object for these two queries: MyModel.objects.get(word='año') MyModel.objects.get(word='ano') ...and no, those words are not the same ;D I would want to create one object for each, of course. -
Strange Behaviour @login_required not working in google chrome django
from django.contrib.auth.decorators import login_required @login_required(login_url='/accounts/login/') def viewfunc(request): <code> I have used login_required to be safe from back button pressing issue but it seems to be failing for GoogleChrome but works like charm on FireFox any issue/bug with this -
Django admin - Inline with choices from database
I need some basic help with the django admin site. What I basically want to do is to be able to populate an inline with choices from the database. For example consider the following models: class Item(models.Model): description = models.CharField(max_length=100) class Category(models.Model): name = models.CharField(max_length=100) item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True, blank=True) And in admin.py I have the following setup: class CategoryAdminForm(forms.ModelForm): name = forms.ChoiceField(choices = category_service.get_all_categories()) class CategoryInline(admin.TabularInline): model = Category form = CategoryAdminForm class ItemAdmin(admin.ModelAdmin): inlines = [CategoryInline] admin.site.register(Item, ItemAdmin) admin.site.register(Category) Want I want to be able to do is to insert categories into db, and when I want to insert an item, the categories inline to be populated with categories from the db. What am I missing here? -
Templates doesnot exist
I just start to learn Django and I stuck with a issue that i Can't solve. Me and My friend want to create a Web site, our project structure is like that Projet --home ----migrations ----static ----templates ------home --------home.html --Projet --manage.py --db.sqlite3 I get this error : TemplateDoesNotExist at / home/home.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.10.1 Exception Type: TemplateDoesNotExist Exception Value: home/home.html Exception Location: C:\Python27\lib\site-packages\django\template\loader.py in get_template, line 25 Python Executable: C:\Python27\python.exe Python Version: 2.7.12 Python Path: ['C:\\Python27\\Lib\\site-packages\\Jobin.git\\trunk', 'C:\\Python27\\lib\\site-packages\\virtualenvwrapper_win-1.2.1-py2.7.egg', 'C:\\Python27\\lib\\site-packages\\virtualenv-15.0.3-py2.7.egg', 'C:\\Python27\\Lib\\site-packages\\Jobin.git\\trunk', 'C:\\Windows\\SYSTEM32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages'] Server time: Sat, 10 Sep 2016 13:19:12 -0400 here is my setting.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['/templates/'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I've tried everything on the field 'DIR' , like 'DIRS': [BASE_DIR+"/templates", ] 'DIRS': [os.path.join(BASE_DIR, "templates")], 'DIRS': [os.path.join(BASE_DIR, 'templates')], still get this error , I don't know what to do anymore anyone has an idea ? -
Foreign key model in Django Admin
I have two user roles in Django: Commercials Sellers I have created two models, Seller Model has a ForeignKey field to Commercials (every seller has a commercial related to). When I register the models in admin I can create Commercials and related sellers using StackedInline, TabularInline etc. The problem I have is I need to associate users to this models in order to authenticate, login, etc. In admin I need to create a user (in an inline way, not dropdown box) This is my code: In models.py: class Commercial(models.Model): name = models.CharField(max_length=255, null=True) user = models.OneToOneField(User, null=True) class Seller(models.Model): name = models.CharField(max_length=255, null=True) commercial = models.ForeignKey('Commercial') user = models.OneToOneField(User, null=True) In admin.py: class SellerAdmin(admin.StackedInline): model = Seller extra = 1 class CommercialAdmin(admin.ModelAdmin): inlines = [SellerAdmin] admin.site.register(Commercial, CommercialAdmin) I need to edit, create, users etc. related to this models inline not in a modal window, ¿is there any way? Thanks in advance. -
Django INSTALLED_APPS not installed and preventing makemigrations
I recently pulled a repo from GitHub to get a local copy on my machine. The backend uses Django, and I was working on updating some models. Since I changed some models I wanted to run ./manage.py makemigrations. At first there was an issue with python2 vs python3, so I changed the #!/usr/bin/env python to #!/usr/bin/env python3. Then when I ran makemigrations, I get this: File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No module named 'autofixture' Looking a bit further, I found out that this is because my settings.py file has autofixture, bootstrap3, and formtools in INSTALLED_APPS, but somehow my machine doesn't have those. I've tried to pip install all of them but the names autofixture, bootstrap3, and formtools aren't found in pip. -
Debugging TemplateNotFound postmortem django 1.9
Been couple days of trying to get my template loaded in view - keep getting error in subj. Here is postmortem http://pastebin.com/JJCtPyYj You can see in there TEMPLATE_DIRS being defined. Tried django 1.10, 1.9.9, 1.8.7. Any clues on how to further debug this annoyance would be greatly appreciated. -
Django model form doesn't populate when instance=object is set
I'm trying to populate a ModelForm with existing data if it exists or create a new instance if not. I've read the django docs and several questions here on Stack Overflow but I can't figure out why my form doesn't populate with the existing data. I'm sure I'm missing something simple, any help would be appreciated. In forms.py: from django.forms import ModelForm, Textarea from .models import Batch class BatchForm(ModelForm): class Meta: model = Batch fields = ('recipe', 'date', 'original_gravity', 'final_gravity', 'gravity_units', 'notes') widgets = {'notes': Textarea(attrs={'cols': 40, 'rows': 10})} in views.py: (notice the instance=batch argument, this should pre-populate the form correct?) def batch_entry(request, batch_id): if int(batch_id) > 0: batch = get_object_or_404(Batch, id=batch_id) form = BatchForm(request.POST, instance=batch) context = {'BatchForm': form, 'batch': batch } else: form = BatchForm() context = {'BatchForm': form, 'batch': None } return render(request, 'logger/batch_entry.html', context) the batch_entry.html template: {% if batch.id > 0 %} <h1>{{batch.date}}</h1> <h3>{{batch.recipe}}</h3> <form action="{% url 'logger:batch_entry' batch.id %}" method="post"> {% csrf_token %} <table> {{BatchForm.as_table}} </table> <input type="submit" value="Submit"> </form> {% else %} <h1>New Batch</h1> <form action="{% url 'logger:batch_entry' 0 %}" method="post"> {% csrf_token %} <table> {{BatchForm.as_table}} </table> <input type="submit" value="Submit"> </form> {% endif %} <form action="{% url 'logger:index' %}" method="post"> {% csrf_token %} … -
How to change a layout of a crispy form by using radio buttons
I am using crispy-forms to render forms. I have model form that I want it to be filled with 2 ways. The first way is users can fill out fields 1 to 6 and leave fields 7 to 15 blank, and fileds 7 to 15 can be filled using a updateview method. The second way is to fill out the 15 fields all by once. I idea is two use tow radio button on the top of the form say 'layout-1' and 'layout-2' and the form layout can be changed by clicking the radio buttons. Can anyone give me some clue on doing this? My code as follows: models.py class test(models.Model): station= models.ForeignKey(station) type = models.CharField(max_length=5, choices=( ('inner', 'inner'), ('outer', 'outer'), )) serialNO = models.CharField(max_length=20) content = models.CharField(max_length=100) person_1 = models.CharField(max_length=10, blank=True) ordering_time = models.DateTimeField(null=True, blank=True) starting_time = models.DateTimeField(null=True, blank=True) ending_time = models.DateTimeField( null=True, blank=True) person_2 = models.CharField(max_length=10) person_3 = models.CharField(max_length=10) person_4 = models.CharField(max_length=10,blank=True) person_5 = models.CharField(max_length=10,blank=True) person_6 = models.CharField(max_length=10,blank=True) steps=models.PositiveIntegerField() status=models.CharField(max_length=20,choices=( ('0', 'canceled'), ('1', 'will do'), ('2', 'done'), ) ) forms.py class testForm(forms.ModelForm): form_type=forms.ChoiceField(required=False,choices=((1,'layout-1'),(2,'layout-2')),widget=forms.RadioSelect(),label='select layouts') form_layout_1=Layout( 'form_type', 'station', 'type', 'serialNO', 'content', 'person_2', 'person_3', 'steps', 'status', ButtonHolder( Submit('submit','Submit') ), ) form_layout_2=Layout( 'form_type', 'station', 'type', 'serialNO', 'content', 'person_1 ' 'ordering_time' 'starting_time' …