Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using more number of relational database in django
Using more number of ForeignKey's in Django cause any problem in production? Is there any limits of using models. I'm using cache to handle some views.But I'm really worried about my database design. In my project, I'm using 30 FK's to store information about users and activities.right now all working fine on the production server.In future, more FK will present.Using more number DB's cause any problem in future? Thanks in advance. -
SEO for Django CMS
my research on SEO for Django/ Django CMS/ Aldryn Newsblog website yielded dated articles published in 2013, 2014, 2015. I will like to seek your advice on the software/ setup you use in your Django/ Django CMS/ Aldryn Newsblog website for SEO. Thank you. -
Django: how to best separate development and deployment?
I have a remote project on a web server and would like to further develop the project in use. How can I work best without the changes being implemented directly in the application? I have already a settings folder to have separate settings and I can also access the Django testserver remotely, but all changes are implemented directly in the project. A solution would be to duplicate the project and then copy it after editing, but that does not seem to me to be a good solution. -
creating two content blocks on two different files - django
I have a django project that I am working on and I have 3 html files. I have the base html that holds all of the non content specific information like links, header, and over body tags. I have a block called content and a block called header in the the main body tag of the html. Then content comes from html files that are in the templates folder. Right now I have content from one html template. My question is. Can i have the content from the header block and content block come from two different html files within the templates folder. So the header block is its own file because it will be located on every page, while the content block comes from the different files that are specified. Do both content blocks have to come from the same html file. If I can grab the content from both, how do I structure it. is it possible to save the html in a variable within the django views and then pass it to each template. What is the most efficient way to approach this issue. base.html: {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% … -
How to avoid hitting DB everytime a foreign key is required in Django
I am logged in into my application as institute user and I have to save student details. Student Model have a column as FK to Institute Model. institute = models.ForeignKey('institute.InstituteDetailsModel', to_field="sys_id", on_delete = models.SET_NULL, null=True, blank=True) Every-time I register student, I have to hit the DB to get institute instance and use it while saving student details. This DB-hitting situation is arising at many places when doing other things. To avoid hitting DB everytime I tried doing below things: Get the institute instance from DB at login time and 1. convert it to dict using model_to_dict (dates needs to be handled separately because of serialisation issue) and store in session. 2. serialize it using django's serialization framework and store in session. But I am getting below issues in above methods respectively: 1. Using ModelForms to save data. data["institute_id"] = request.session["institute"]["id"] form = StudentForm(data) got error "this field is required" for institute. I tried to deserialized the saved object but it is of type generator and not of type model instance hence got the errors'generator' object has no attribute 'id and 'DeserializedObject' object has no attribute 'id' when tried getting id attribute. What is the best way to retrieve and store … -
Python/Django: Selecting max value of one-to-many relation and displaying it in HTML/View
Good Day SO, I am a beginner in Django and python, just started learning two days ago. This qn is related to this question: Python/Django: How to show both main model and 'foreign-key model' together in HTML I have two models in a one(crisis)-to-many(plans) relationship, with the models shown here: class Plan(models.Model): plan_ID = models.CharField( primary_key=True, max_length=8, validators=[RegexValidator(regex='^\w{8}$', message='Length has to be 8', code='nomatch')] ) plan_crisisID = models.ForeignKey(Crisis, on_delete=models.CASCADE) plan_status = models.CharField(max_length=50) class Crisis(models.Model): crisis_ID = models.CharField( primary_key=True, max_length=4, validators=[RegexValidator(regex='^\w{4}$', message='Length has to be 4', code='nomatch')] ) crisis_name = models.CharField(max_length=50) Currently, the displayed data looks something like this: I am new to django/python in general, and I do not know how to filter the data such that i only display each crisis once, and report ID with the highest value. My desired end result looks like this: Here is my views.py section: def home(request): template = loader.get_template('pmoapp/home.html') planList = Plan.objects.filter(plan_crisisID__crisis_status='Ongoing') context = { #'crisisList': crisisList, 'planList': planList } return HttpResponse(template.render(context, request)) How do I code the loop function to get the max value of the planID for each crisisID? Any help will be greatly appreciated.. Thank you very much SO.. -
queryset vs filter_backends in django rest framework
I am new to DRF. I went through the example of filtering queryset at http://www.django-rest-framework.org/api-guide/filtering/#filtering-and-object-lookups This link contains description about queryset filtering, as well as DjangoFilterBackend. As far as I am able to understand, they are serving the same purpose. But it's not clear when to use any one of them. In some of the cases, both queryset and filter_backends are used :- class UserListView(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer filter_backends = (filters.OrderingFilter,) ordering_fields = ('username', 'email') Can anyone let me know, what's the difference between these two ?which one of these two have to be used, in which situations, we must prefer one over another ? Thanks in advance -
NoReverseMatch in django when trying without harcoding
I have a music app which has the urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<album_id>[0-9]+)/$', views.detail, name='detail'), url(r'^(?P<album_id>[0-9]+)/favorite/$', views.favorite, name='favorite'), ] and in my html code I called this <form action="{% url 'music:favorite' album_id %}" method="post"> Then I am getting NoReverseMatch exception. Reverse for 'favorite' with arguments '('',)' not found. 1 pattern(s) tried: ['music/(?P<album_id>[0-9]+)/favorite/$'] -
Django css and js not loading
I just spent all day deploying a small Django app on cPanel. Python virtual environment set up, Django files are in, dependencies installed... Static css and js files are not being loaded properly. The cPanel host put passenger_wsgi.py inside my Django app directory with .htaccess pointing to the wsgi file, so that's what is handling the requests. The static files are exactly where they were in development, and in settings.py STATIC_URL = "/static/" STATIC_ROOT = "/path/to/public_html/static/" STATICFILES_DIRS = [( "static", "/path/to/myapp/static/" ),] In templates/base/navigation.html (I have also tried {% load static %}) {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %} | SG</title> <script src="{% static 'js/jquery.min.js' %}" type="text/javascript"> </script> <script src="{% static 'js/bootstrap.min.js' %}" type="text/javascript"> </script> <script src="{% static 'js/custom.js' %}" type="text/javascript"></script> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet" type="text/css"> ... ... After running python manage.py collectstatic I get all my static files and the only page that actually loads my static files is the landing page. Any other page (admin, blog, etc.) seems to shove the app/dir name into the link/script tag causing errors. added /blog/ between domain and static url added /admin/ between domain and static url And in my templates/blog/blogs.html {% extends … -
Display detailed info using AJAX
I can get my Django app to display scraped news, but how do I make it show the news content only upon clicking on the news headline using AJAX? I know pretty much nothing about JavaScript (and just started learning Django and REST framework a few days ago). models.py: from django.db import models from datetime import datetime class Headline(models.Model): headline_text = models.CharField(max_length=255) pub_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.headline_text class Article(models.Model): headline = models.OneToOneField(Headline, on_delete=models.CASCADE, blank=True) article_text = models.TextField() def __str__(self): return self.article_text serializers.py: from rest_framework import serializers from .models import Headline, Article class ArticleSerializer(serializers.ModelSerializer): class Meta: fields = ('article_text',) model = Article class HeadlineSerializer(serializers.ModelSerializer): article = serializers.SerializerMethodField() # For flattening nested relationship class Meta: fields = ('pk', 'headline_text', 'pub_date', 'article') model = Headline def get_article(self, obj): if getattr(obj, 'article', None): return obj.article.article_text views.py: from django.http import HttpResponse def index(request): latest_headline_list = Headline.objects.order_by('-pub_date') template = loader.get_template('pyscraper/index.html') context = { 'latest_headline_list': latest_headline_list, } return HttpResponse(template.render(context, request)) index.html: <tbody> {% if latest_headline_list %} {% for headline in latest_headline_list %} <tr class="{% cycle 'row1' 'row2' %}"><th class="field-__str__"><a href="{% url 'detail' headline.id %}">{{ headline.headline_text }}</a></th></tr> <tr class="{% cycle 'row1' 'row2' %}"><td class="field-__str__"><p>{{ headline.article.article_text }}</p></td></tr> {% endfor %} {% endif %} </tbody> Example JSON … -
Drawing dependencies in a sentence in Django
I have a sentence and some words in the sentence are connected. At each time a new connection is made I would like to show the dependency graph. Each time a request is made I will pass a json file which specifies which words are connected. How can I draw arrows between words to show the dependencies? Right now all I have found are packages from nltk, which will do the dependency parsing for you, but I want the arrows to have costume names. -
Creating Polls app form Django
Trying to create a form for my polls app.But I am not able to include choices as well for it.I can only add polls right now through admin. (Its the official django polls app tutorial and i am trying to extend it further by adding a form) Models.py class Question(models.Model): question_text = models.CharField(max_length=200) publish_date = models.DateTimeField('date published',null=True,blank=True) def __str__(self): return self.question_text def get_absolute_url(self): return reverse('polls:index') class Choice(models.Model): question_text = models.ForeignKey(Question,on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text forms.py class QuestionForm(forms.ModelForm): question_text = forms.CharField(required=True) publish_date = forms.CharField(required=False) choice_text = forms.CharField(required=True) class Meta(): model = Question fields = ('question_text','choice_text') View To create Poll class CreatePoll(CreateView): redirect_field_name = 'polls/index.html' template_name = 'polls/poll_form.html' form_class = QuestionForm model = Question This is My Form View But the choice entered doesnt get saved.Saw in the admin view too -
python manage.py migrate make me frustated
Hi guys I got a problem when I used command of django-admin startproject mysite, it couldn't work but python -m django startproject mysite is ok. there has been another problems in my CneOs6.8, when inputed python manage.py migrate, which would : [root@localhost mysite]# python manage.py migrate Traceback (most recent call last): File "/usr/local/python3.5.0/lib/python3.5/site- packages/django/db/backends/sqlite3/base.py", line 31, in from pysqlite2 import dbapi2 as Database ImportError: No module named 'pysqlite2' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/python3.5.0/lib/python3.5/site- packages/django/db/backends/sqlite3/base.py", line 33, in from sqlite3 import dbapi2 as Database File "/usr/local/python3.5.0/lib/python3.5/sqlite3/init.py", line 23, in from sqlite3.dbapi2 import * File "/usr/local/python3.5.0/lib/python3.5/sqlite3/dbapi2.py", line 27, in from _sqlite3 import * ImportError: No module named '_sqlite3' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/usr/local/python3.5.0/lib/python3.5/site- packages/django/core/management/init.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/python3.5.0/lib/python3.5/site- packages/django/core/management/init.py", line 338, in execute django.setup () File "/usr/local/python3.5.0/lib/python3.5/site-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/python3.5.0/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/usr/local/python3.5.0/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/local/python3.5.0/lib/python3.5/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 986, in _gcd_import File " importlib._bootstrap>", line 969, in _find_and_load … -
Why does my aging Django 1.3.1 site say ''TemplateDoesNotExist at /admin/" after migration to a new server?
I have a Django v1.3.1 site on a now-compromised server (used to be on Python v2.7.3). I've been able to reconstruct the bulk of the content via a cache of the old admin site but after re-installing Python and Django on a new server instance (Python v2.7.12), I'm running across the following error: TemplateDoesNotExist at /admin/ admin/login.html Request Method: GET Django Version: 1.3.1 Exception Type: TemplateDoesNotExist Exception Value: admin/login.html Exception Location: /usr/local/lib/python2.7/dist-packages/django/template/loader.py in find_template, line 138 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/var/django/mysite', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] Server time: Sun, 15 Oct 2017 02:31:49 +0100 The relevant info from trying to load the templates: Django tried loading these templates, in this order: Using loader django.template.loaders.filesystem.Loader: /var/django/mysite/templates/admin/login.html (File does not exist) Using loader django.template.loaders.app_directories.Loader: Looking on the new machine for /admin/index.html I get: locate admin/login.html /usr/local/django/contrib/admin/templates/admin/login.html On the old machine I get: locate admin/login.html /root/build/Django/build/lib.linux-x86_64-2.7/django/contrib/admin/templates/admin/login.html /root/build/Django/django/contrib/admin/templates/admin/login.html /root/build/Django/tests/templates/custom_admin/login.html /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/admin/login.html What have I missed in getting this up and running / how do I resolve this before I start upgrading to the latest Django version? -
How to query in django one to many
What I want to do? I have an app have three models:Series,Section and Episode,every one have a one-many query(by ForeignKey). just like this series-> many Section,section-> many Episode Now I will show a section with episodes information in series page, but it make more query. now code views.py series = Series.objects.get(id=series_id) section = Section.objects.filter(series=series) list.html {% for item in sections %} ... {% for episode in item.episode_set.all %} ... {% endfor %} ... {%endfor%} models.py class Section(models.Model): series = models.ForeignKey(Series) .... class Episode(models.Model): section = models.ForeignKey(Section) What I want to get ? an example code tell me how to query in views.py and use just little query. you can guess, in my code, if here are many section and many episode, it will have many query. Some idea. I use Laravel Before, In Laravel , it has a hasMany Function, I can use it to get other models items(Define by belongsTo). Is Django has same function? -
Django view does not redirect to details page
I've created a form and view in Django. I can see the add new post form when I go to http://localhost:8000/post/new/ but after I complete all required fields and click submit the page just refreshes itself and I am not redirected to the post details page. Here's my views.py def post_new(request): if request.method == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.createdAt = timezone.now() post.writer = request.user post.save() return redirect('posts:post_detail', pk=post.pk) else: form = PostForm() context = {'form':form} return render(request,"posts/post_new.html",context) Here's my urls.py: urlpatterns = [ url(r'^$', views.post_list, name="post_list"), url(r'^posts/(?P<post_title_slug>[\w\-]+)/$', views.post_detail, name='post_detail'), url(r'^post/new/$', views.post_new, name='post_new'), ] Here's my html: <div class="col"> <form method='POST' class='post_form' enctype='multipart/form-data'> {% csrf_token %} {{ form.non_field_errors }} <div class="form-row"> <div class="form-group col-md-6"> <label for="{{ form.title.id_for_label }}" class="col-form-label">Title</label> <input type="text" class="form-control" id="{{ form.title.id_for_label }}" name= "{{ form.title.html_name }}" placeholder="Enter post title"> {{ form.title.errors }} </div> </div> <div class="form-group"> <label for="{{ form.comment.id_for_label }}">Description here:</label> <textarea class="form-control" rows="5" id="{{ form.comment.id_for_label }}" name="{{ form.comment.html_name }}" aria-describedby="descriptionHelpBlock"></textarea> <small id="descriptionHelpBlock" class="form-text text-muted"> Describe your post in this text box. </small> {{ form.comment.errors }} </div> <div class="form-group"> <label for="{{ form.image.id_for_label }}">Upload picture here</label> <input type="file" id="{{ form.image.id_for_label }}" name="{{ form.image.html_name }}" class="form-control-file"> {{ form.image.errors }} </div> <br> <button type="submit" class="btn … -
503 error with apache domain when faking domain
I'm attempting to fake domains, on windows, for testing a django application locally that would be spread across domains for the different apps within it. I'm using XAMPP and have resolved loading the mod_wsgi module and set my hosts file to include localhost, jobs, and quotes My apache httpd.conf file looks like this: Listen Listen 80 ServerName ServerName localhost:8000 Virtual hosts NameVirtualHost * <VirtualHost *:80> ServerName jobs ServerAlias jobs.io *.jobs.io DocumentRoot "C:\Users\username\Desktop\VirtualEnviornment\EnvName\Name\" WSGIScriptAlias / "C:\Users\username\Desktop\VirtualEnviornment\EnvName\Name\wsgi.py" <Directory "C:/xampp/apache"> Order deny,allow Allow from all </Directory> </VirtualHost> Shouldn't this be serving my application when I go to jobs.io or quotes.io in my browser? All I get is: Service Unavailable The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later. Apache Server at jobs.io Port 80 -
Why does Django AssertFormError throw a TypeError: argument of type 'property' is not iterable?
I'd like some help or advice on how to test for errors in one of my Django forms. It's responsible for ensuring the user enters a valid session ID which is used as a authentication token for a 3rd party API. Valid IDs are 32 characters long and alphanumerical. I've chosen an approach that validates the field, rather than the model. When I manually test this using the development server it works as expected. I.E. if the user pastes a string of the wrong length or with the special characters, the field's validate method creates errors which are then displayed via a for loop around the form errors in the html template. I don't understand the following error. I've temporarily modified testcases.py to prove that the errors are being passed to it - so why is context[form].errors a 'property' and how did it get there? I'm using Django 1.10 and Python 3.5.1 ====================================================================== ERROR: test_index_sessid_short_strings (poe.tests.TestBannerButtons) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/adam.green/Documents/workspace/poe-client/poetools_project/poe/tests.py", line 105, in test_index_sessid_short_strings self.assertFormError(response, 'form', "new_sessid" , 'The Session ID needs to be exactly 32 characters long') File "/Users/adam.green/.virtualenvs/poe-tools/lib/python3.5/site-packages/django/test/testcases.py", line 421, in assertFormError if field in context[form].errors: TypeError: argument of type 'property' is not iterable … -
Mock keeps calling real function
I'm trying to mock a function. When I try to mock the function core.use_cases.add_owner_to_place the mock doesn't work. It keeps printing "Ouch". I've tried to test mocked_add_owner_to_place.called and it returns False. Does anyone know why it keeps using the real function even if I mock it? views.py: from core.use_cases import add_owner_to_place class CreatePlace(LoginRequiredMixin, FormView): template_name = 'place/create_place.html' form_class = PlaceForm success_url = reverse_lazy('place_list') def form_valid(self, form): place = form.save() add_owner_to_place(place, self.request.user) return super(CreatePlace, self).form_valid(form) tests.py: from unittest.mock import patch, Mock @patch('core.use_cases.add_owner_to_place') @patch('core.forms.PlaceForm.is_valid') @patch('core.forms.PlaceForm.save') def test_save_should_be_called(self, mocked_save, mocked_is_valid, mocked_add_owner_to_place): self.client.post(reverse('place_create'), data={}) self.assertTrue(mocked_save.called) uses_cases.py: def add_owner_to_place(place, user): print('Ouch') -
Django: Returning a template with POST parameters
I have a table with multiple rows, each of which has an 'edit' button. On clicking this button, the user should redirect to a form with his details already prefilled. Now, I have defined data attributes inside the 'edit' button's definition: <a href='#' class="edit-user" data-email="abc@gmail.com">edit</a> Using JQuery, I'm deriving the value of the 'email' data attribute and passing it in a POST request to /add-edit-user, which is also mapped to the page which has my form: $( ".edit-user" ).click(function() { var url = base_url + '/add-edit-user/'; var data = { 'email': $(this).data('email'), 'csrfmiddlewaretoken': csrftoken, }; // $.post(url, data); $.post(url, data).done(function(result) { console.log(result); }).fail(function(error) { console.log(error); }); }); The /add-edit-user URL maps to the following view where I'm trying to define my form object and pass on as a context variable to my template file: def add_edit_users(request): form = AddUpdateForm(request.POST or None) data = {'form': form} return render(request, 'add_edit_users.html', data) Now, my assumption was that if the user clicks on the 'edit' button, I'd set the 'email' parameter in a data attribute and pass it on in my POST request to /add-edit-user URL, after which I'll render my form template with the form object as a context variable which will display … -
How to delete arguments from url
I need to generate keys by clicking button and to show generated ones. Here my view: @user_passes_test(lambda u: u.is_superuser) def get_key(request): if(request.GET.get('create_new_key')): for_whom = request.GET.get('for_whom') create_key(for_whom) created_keys = RegistrationKey.objects.all() return render(request, 'registration/get_key.html', { 'created_keys':created_keys, }) And template: <!DOCTYPE html> <html> {% include "core/header.html" %} <body> <form action="#" method="get"> <input type="text" name="for_whom"/> <input type="submit" class="btn" value="Create" name="create_new_key"> </form> <ul> {% for created_key in created_keys %} <p>{{created_key.key}}</p> <p>{{created_key.for_whom}}</p> {% endfor %} </ul> </body> {% include "core/footer.html" %} </html> Now when I'm clicking the button on page http://127.0.0.1:8000/get_registration_key/ the key is generating but now I'm at http://127.0.0.1:8000/get_registration_key/?for_whom=&create_new_key=Create#, so refreshing this page would generate more keys. I really need to cut this arguments from url but don't understand how. -
ng-show not updating with $timeout function
I'm trying to write my own photo slider so that the image and text I have on my Django homepage will fade from one to the next (and then repeat). I created a timeout function to loop a $scope.current_slide variable from 1-3, and back to 1 at a set interval. I'm using ng-show on each so that when the $scope.current_slide variable is equal to the number of slide, each picture will appear. The problem I'm having: The images aren't cycling through when I use the timeout function. However! I know in theory my code should work because when I make a button, and use ng-click to allow the button to increment a an angular 'click' variable (1, 2, 3, etc.) the correct pictures show up. The pictures just don't scroll correctly with the timeout function. I added $scope.$apply() thinking this would fix it, but nothing changed. I have the JS file within my home.html page so that it can dynamically pull the total number of slides from Django. home.html <script> var myApp = angular.module('myApp', ['ngRoute', 'ui.bootstrap', 'ngAnimate']); myApp.controller('myController', ['$scope', '$timeout', function($scope, $timeout) { $scope.timeInMs = 0; console.log("We are here in CTRL Controller"); $scope.current_slide = 1; // FUNCTION EXECUTES EVERY FEW … -
django different domain url routing using {% url %} and app urls
How would I setup django url routing to reroute to a specific domain for each app's urls? Meaning: Let's say I have an app "Jobs" and I want to route to "jobs/list" to view a lsit of all jobs which is on domain: "(name)jobs.io" whereas my main app is on (name).io. These links are in the navbar. I've ported django-multiple-domains to Django 1.11 and have the setting, used by the middleware, setup to use each apps urls based upon the domain but this doesn't seem to take care of using the {% url %} tag. -
django rest 400 responce when putting date field
I am putting a datetime value to my drf backend. This is my code: models.py class MyModel(models.Model): .... date = models.DateField(blank=true, null=true) ..... serializers.py class MyModelSerializer(ModelSerializer): class Meta: model = MyModel fields = '__all__' views.py class UpdateNRetrieve(RetrieveUpdateAPIView): queryset = MyModel.objects.all() serializer_class = MyModelSerializer lookup_field = 'pk' On my settings.py I have this: REST_FRAMEWORK = [ ..... 'DATE_FORMAT': '%d/%m/%Y', 'DATE_INPUT_FORMATS': '%d/%m/%Y', ..... ] And also this: LANGUAGE_CODE = 'it-IT' TIME_ZONE = 'Europe/Rome' USE_I18N = True USE_L10N = True USE_TZ = True When i make a PUT request from my front-end I am getting a 400 error (bad request) whit this value: date:"04/12/1984" I always get this response: Date has wrong format. Use one of these formats instead: %, d, /, %, m, /, %, Y." I can't realize where is my error! -
Django how to get record id from ModelForm
I've been banging my head on this for weeks but I am determined to get ModelForm to work! When you process a POST with data received from a ModelForm, I understand that you need to get the original record from the database and then create a new form using that original record as the 'instance'. This is documented in the Django docs as follows: >>> from myapp.models import Article >>> from myapp.forms import ArticleForm # Create a form instance from POST data. >>> f = ArticleForm(request.POST) # Save a new Article object from the form's data. >>> new_article = f.save() # Create a form to edit an existing Article, but use # POST data to populate the form. >>> a = Article.objects.get(pk=1) >>> f = ArticleForm(request.POST, instance=a) >>> f.save() In this example they know that the pk of the record they are looking for is 1. BUT, how do you know the pk if you're reading data from request.POST, assuming that the POST is based on data you previously wrote to the screen? ModelForm doesn't store the pk. So, from where do you pick this up? Without it, how do you know which record to pull out of the DB …