Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
405 method not allowed, Django + ngrok, only on my local machine
This is a legacy project that I'm working with other guys in my current job. and is doing a very strange behavior that I cannot understand. It's returning 405 http response status, which does not make sense, because this view already accepts POST requests I would share a couple of snippets, I just detected that happens just in the comment that I would mark. this is the view file, that actually accepts both methods GET and POST @csrf_exempt @load_checkout @validate_cart @validate_is_shipping_required @require_http_methods(["GET", "POST"]) def one_step_view(request, checkout): """Display the entire checkout in one step.""" this is the decorator that modifies the response, and returns 405. def load_checkout(view): """Decorate view with checkout session and cart for each request. Any views decorated by this will change their signature from `func(request)` to `func(request, checkout, cart)`.""" @wraps(view) @get_or_empty_db_cart(Cart.objects.for_display()) def func(request, cart): try: session_data = request.session[STORAGE_SESSION_KEY] except KeyError: session_data = '' tracking_code = analytics.get_client_id(request) checkout = Checkout.from_storage( session_data, cart, request.user, tracking_code) response = view(request, checkout, cart) # in this response it returns 405. if checkout.modified: request.session[STORAGE_SESSION_KEY] = checkout.for_storage() return response return func Any idea or clue when I can start to find out the problem?. for the record: I didn't code this, this was working a … -
How to change background color in Django Admin Dashboard
Please tell me how to change background color in django admin dashboard. And maybe all. -
Why is 'heroku run bash' command not keeping the changes after exit?
I've a django project deployed on Heroku, I'm trying to update its database but it requires the migrations to be deleted. I'm trying to delete using heroku run bash and then rm command. But it does not keep the changes after I exit from bash (see screenshot). Please tell what is wrong and is there any other way to delete those migrations?. Thanks. Migration files come back on returning - Screenshot -
form dont save data in django
i am using django's built-in contrib.auth User model and have setup a foreignkey and primary key relationships to a user for a Candidat model class Candidat(models.Model) : sexe = ( ('FEMELLE','FEMELLE'), ('MALE','MALE') ) prenom = models.CharField(max_length=100,null=True) nom = models.CharField(max_length=100 ,null= True) Email = models.EmailField(null= True) Telephone = models.CharField(max_length=100,null= True) age = models.IntegerField(null= True) dateNaissance = models.DateField(null= True) lieuNaissance = models.CharField(max_length=100, null=True) Nationalite = models.CharField(max_length=100,null=True) Addresse = models.CharField(max_length=100,null=True) Image = models.ImageField(max_length=100,null=True,upload_to='media') Telephone = models.CharField(max_length=100,null=True) sexe= models.CharField(max_length=120,null=True,choices=sexe) site = models.CharField(max_length=100,null=True) linkedin = models.CharField(max_length=100,null=True) # user = models.ForeignKey(User, null= True, on_delete=models.SET_NULL) user = models.OneToOneField(User, primary_key=True,on_delete=models.CASCADE,unique=True,related_name="candidat") def __str__(self): return f"candidature: {self.nom}" when i try to Save candidat informations in database that's dont match! forms.py class CandidatForm(ModelForm): class Meta: model=Candidat fields="__all__" exclude = ["user"] class UserForm(ModelForm): model = User fields:'__all__' views.py def create(request): candidat = request.user.candidat # print(request.user) form=CandidatForm(instance = candidat) # if request.method=='POST': # print(request.POST) form=CandidatForm(request.POST,request.FILES) if form.is_valid(): form= form.save(commit=False) formt.user = UserForm.objects.get(id=request.user.id) form.save() return redirect('coordonnées') context={'form':form} return render(request, 'pages/candid_form.html',context) the signals file create for me an instance candidat but it is empty please help help help me signals.py from .models import Candidat from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # @receiver(post_save,sender = User) def post_save_create_candidat(sender, instance, created, **kwargs): … -
How to stop browser redirect from CBV Django
I am in the process of switching everything from plain Django/HTML/CSS to JS with AJAX on some parts of my site. The problem I am running into is that with FBVs I can return an HTTPResponse i.e. return render(request, template, context) and use my JS to update the page; but with CBVs it seems to always redirect to the page when it gets the response. How can I stop it from redirecting? I have tried updating the get method to return the HTTPResponse the way a FBV would: class FilteredList(ListView): model = Item template_name = 'item/filtered_list.html' def get(self, request, *args, **kwargs): queryset = self.get_queryset() context = {'filtered_list': queryset} return render(request, self.template_name, context) def get_ordering(self, *args, **kwargs): ordering = self.request.GET.get('ordering', 'end') return ordering and the JS: function loadResults(e) { e.preventDefault(); $.get({ 'url': resultsURL + id + '/' }).done( function (data) { document.getElementById('resultsContainer').innerHTML = data; }) document.getElementById("resultsContainer").style.display = "block"; } ript> But this does not stop the redirect. how can I handle AJAX in CBV without the redirect? -
django second request in queue until first request complete
I'm new to django, tried to understand how multiple request can handle at the same time. i have app with two html and two different function and i put sleep 40 sec for one function ( one.html) and second function no sleep just render the html (second.html). opened one.html in one browser and second.html in another browser ( shows nothing ), because one.html will wait for 40 sec to complete. Django: 3.2.3 Runserver: python manage.py runserver ip:port Tried uwsgi but multi request not working: uwsgi --http --module app.wsgi --processess 4 --master --threads 2 Appreciated for any ideas/solutions provided. -
Get form values (foreign key field) in django
I'm trying to add the foreign key options to a select input but don't know how to get it. I want to make the same as using the form generated by Django, but with my own HTML. The form is for creating a new "patient". This is are the foreignkeys from my patient model: ubication = models.ForeignKey(Ubication, on_delete=models.CASCADE) supervisor = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) And this is the patient form: class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ['dni', 'first_name', 'last_name', 'birth', 'risk', 'status', 'ubication', 'supervisor'] widgets = { 'dni': forms.NumberInput(attrs={'class': 'form-control'}), 'first_name': forms.TextInput(attrs={'class': 'form-control'}), 'last_name': forms.TextInput(attrs={'class': 'form-control'}), 'birth': forms.DateInput(attrs={'class': 'form-control'}), 'risk': forms.CheckboxInput(attrs={'class': 'form-control'}), 'status': forms.Select(attrs={'class': 'form-select'}), 'ubication': forms.Select(attrs={'class': 'form-select'}), 'supervisor': forms.Select(attrs={'class': 'form-select'}) } For example, here I want to add the supervisors from the supervisor model to vinculate it to the patient model: <select class="form-select" aria-label="Default select example" required name="supervisor" id="id_supervisor"> <option selected>Select supervisor</option> {% for f in form.supervisor %} <option value="{{f.id}}">{{f.first_name}}</option> {% endfor %} </select> -
Django modal bootstrap not displaying
I have been blocked on this problem for several days. I have bootstrap 3.3.7 in the project root folder. I am rendering some buttons in the django template that should open modal windows when clicked. But the modal functionality is not working. I am following the examples shown on this page: https://www.quackit.com/bootstrap/bootstrap_3/tutorial/bootstrap_modal.cfm Here is the template code: <h6> <button type="button" class="btn btn-sm" data-toggle="modal" data-target="#smallShoes"> DCCRP 2102 </button> <!-- The modal --> <div class="modal fade" id="smallShoes" tabindex="-1" role="dialog" aria-labelledby="modalLabelSmall" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title" id="modalLabelSmall">Modal Title</h4> </div> <div class="modal-body"> Modal content... </div> </div> </div> </div> </h6> Inside my base.html ... section, I have the following: {% load static %} <link rel="stylesheet" href="{% static '/boot/css/bootstrap.css' %}"> <!-- Add additional CSS in static file --> {% load static %} <link rel="stylesheet" href="{% static '/custom/custom.css' %}"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> Thanks! -
django: how to use django mathfilters in CSS or style HTML tags
In this question, a user suggested this: For CSS like in your example you could use calc(). <img style="padding-top: calc({{ img.height }} / 2)" src=""/> I haven't been able to find anything similar to this using "calc", but I've tried it and it doesn't work for me. Is this the way to do it? Or is there another way to achieve this using django on CSS? I'm trying to achieve something like the following, to create a "progress bar". So I'll have a total and then other values lower than this total and do a simple calc by the rule of three. <div style="width: calc({{ value1 }} * 100 / {{ total }})"> -
How to create an object of model A out of 2 random objects of model B in Django?
I'm trying to create an app that meets two random users in Django. my question is how to create an object Meeting out of 2 random users from my User model, I want something like a for loop so that every 2 users in my database have a meeting! ps: I have only one day left to submit my work I will be so thankful if u help me this is my code so far: def createMeeting(): user_p = get_user_model() users = user_p.objects.all() all_users = users.exclude(username="Admin") n = all_users.count() for k in range(math.floor(n/2)): for user in all_users: freedate = FreeDate.objects.filter(user=user) starreds = user.userprofile.desired_user.all() matched_user = User if freedate: if starreds: for u in starreds: u_freedate = FreeDate.objects.filter(user=u.user) for dates in freedate: for matchdates in u_freedate: if dates.FreeTime == matchdates.FreeTime and dates.FreeDay == matchdates.FreeDay: matched_user = u.user else: for u in users: u_freedate = FreeDate.objects.filter(user = u) for dates in freedate: for matchdates in u_freedate: if dates.FreeTime == matchdates.FreeTime and dates.FreeDay == matchdates.FreeDay: matched_user = u if matched_user and matched_user != user and not(Meeting.objects.filter(user1=user, user2=matched_user) | Meeting.objects.filter(user1=matched_user, user2=user)): Meeting.objects.create(user1=user, user2=matched_user)` it creates only one Meeting object and i'm getting this error: TypeError: Field 'id' expected a number but got <class 'django.contrib.auth.models.User'>. … -
Importing django modules
I'm doing the django tutorial on the official website and I'm trying to figure out how to import the django modules. I have in VS code: from django.http import HttpResponse I'm getting a problem that says: Import "django.http" could not be response from source Pylance. I looked into this and it seems this is because I'm not running the virtual environment in vs code. How can I fix this? In the terminal I normally activate the venv with something like: source env/bin/activate I think I need to have that path in vs code, but I'm not entirely sure. -
Django says field does not exist when it does exist
So I created a poll model in my Django app. I'm going thorugh the polling app tutorial posted on the Django website, however, I'm using a remote MySQL database rather than a SQLite database. from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField() class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, default='') choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) I then go to terminal and type $ python manage.py makemigrations followed by $ python manage.py migrate. This all runs perfectly fine and outputs the following: Migrations for 'polls': polls/migrations/0001_initial.py - Create model Question - Create model Choice So far so good. But when I try to create a question in the shell, trouble comes $ python manage.py shell >>> from polls.models import Choice, Question >>> from django.utils import timezone >>> q = Question(question_text="What's new?", pub_date=timezone.now()) >>> q.save() Traceback (most recent call last): File "/Users/caineardayfio/Documents/CodingProjects/mysite/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/Users/caineardayfio/Documents/CodingProjects/mysite/venv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/Users/caineardayfio/Documents/CodingProjects/mysite/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/Users/caineardayfio/Documents/CodingProjects/mysite/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/Users/caineardayfio/Documents/CodingProjects/mysite/venv/lib/python3.7/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (1054, "Unknown column 'pub_date' in 'field list'") The above exception was the direct cause of … -
Can't install requirements using pip and python 3.8.5 on a Ubuntu 20.04 server
I'm trying to install python dependencies for a Django project, but I keep getting Non-user install because user site-packages disabled error. It sounds like a permission issue, I just can't figure out what went wrong. My working tools include: Django Python 3.8.5 Ubuntu 20.04 Probably worth mentioning, I am using a virtual environment for this project. Also, I have tried using root to install the packages without any luck. Any ideas on how to solve this issue is more than welcome. -
Django query using case expression to decide where inclusion
I have a query in django which I want to use in mysql and possibly with sqlite during the test stage if some conditions exist then some query would be included in the where part of the query i.e. if name is provided or year is provided the query would be select * from tab1, tab2, tab3 where tab1.name='%s' and tab1.year=%s and tab1.id=tab1.tb2_id and tab3.id=tab1.tb3_id else the query should be select * from tab1, tab2, tab3 where tab1.id=tab1.tb2_id and tab3.id=tab1.tb3_id I have made use of case expression but it was giving me error. This is the query Modelname.objects.raw("select * from tab1, tab2, tab3 where tab1.id=tab1.tb2_id and tab3.id=tab1.tb3_id and CASE '%s' WHEN None THEN '' ELSE tab1.name='%s' END and CASE %s WHEN None THEN '' ELSE tab1.year=%s END", ["user name",2]) error returned TypeError: not all arguments converted during string formatting return self.sql % self.params_type(self.params) -
How can I add a class to the autogenerated form label tag?
I have passed a queryset into a form as a field like so: class CustomCardField(forms.ModelMultipleChoiceField): def label_from_instance(self, cards): return cards class DeckForm(ModelForm): cards = CustomCardField( queryset=Card.objects.all(), widget=forms.CheckboxSelectMultiple ) class Meta: model = Deck fields = ('cards') And this autogenerates the following html: <tr> <th> <label>Cards:</label> </th> <td> <ul id="id_cards"> <li> <label for="id_cards_0"> <input type="checkbox" name="cards" value="1" id="id_cards_0"> Dog - Pas </label> </li> ... </ul> </td> </tr> Finally, my question. How can I either, add a class to the autogenerated label tag where [for="id_cards_0"], or, prevent the autogeneration of the label tag and add my own in the template? Thank you! -
Failed import for Sentry_sdk in Django
I am currently trying to get Sentry to work with my Django project. While initializing Sentry in the settings.py file I get this error: line 301, in module import sentry_sdk ModuleNotFoundError: No module named 'sentry_sdk' unable to load app 0 (mountpoint='') (callable not found or import error) I copied the docs, and I'm wondering why this is happening. Has anyone experienced this issue before? My Django version is 2.2.11 and I'm running python v 3.9.5 Here is the code for the docs if it matters (pip install --upgrade sentry-sdk) import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration sentry_sdk.init( dsn="https://examplePublicKey@o0.ingest.sentry.io/0", integrations=[DjangoIntegration()], # Set traces_sample_rate to 1.0 to capture 100% # of transactions for performance monitoring. # We recommend adjusting this value in production, traces_sample_rate=1.0, # If you wish to associate users to errors (assuming you are using # django.contrib.auth) you may enable sending PII data. send_default_pii=True, # By default the SDK will try to use the SENTRY_RELEASE # environment variable, or infer a git commit # SHA as release, however you may want to set # something more human-readable. # release="myapp@1.0.0", ) -
Django ignoring REQUIRED_FIELDS
I am trying to create a page with a registration and login function, however, I cannot seem to set fields as required. My models.py class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ["first_name", "last_name"] objects = CustomUserManager() def __str__(self): return self.email forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ("first_name", "last_name", "email") And views.py def register(request): if request.method == 'POST': user_form = CustomUserCreationForm(request.POST) if user_form.is_valid(): new_user = user_form.save(commit=False) new_user.save() Profile.objects.create(user=new_user) return render(request, 'account/register_done.html', {'new_user': new_user}) else: user_form = CustomUserCreationForm() return render(request, 'account/register.html', {'user_form': user_form}) As you can see I declared first_name and last_name (I also tried to write them with a space instead of an underscore but it didn't help) as required. However, I am still perfectly able to create a user without these features. -
Whats the proper way to transmit updating data to a client via Django websockets?
Currently, I have an element that when clicked, sets up a global cooldown timer that effects all clients with the use of Django websockets. My issue is that while initially the websocket value is converted to state in my React client via componentDidMount, the websocket doesn't run again when its value changes in real time. Heres how it works in detail. The timer is updated via a django model, which I broadcast via my websocket to my React front-end with: consumer.py async def websocket_connect(self, event): print("connected", event) await self.send({ "type":"websocket.accept", }) @database_sync_to_async def get_timer_val(): val = Timer.objects.order_by('-pk')[0] return val.time await self.send({ "type": "websocket.send", "text": json.dumps({ 'timer':await get_timer_val(), }) }) This works initially, as my React client boots up and converts the value to state, with: component.jsx componentDidMount() { client.onopen = () => { console.log("WebSocket Client Connected"); }; client.onmessage = (message) => { const myObj = JSON.parse(message.data); console.log(myObj.timer); this.setState({ timestamp: myObj.timer }); }; } However, when a user clicks the rigged element and the database model changes, the web socket value doesn't until I refresh the page. I think the issue is that I'm only sending the websocket data during connection, but I don't know how to keep that "connection" open … -
Django messages not working with HttpResponseRedirect
I have the following code in Django. Only showing the relevant part messages.info(request, "Welcome ...") return HttpResponseRedirect('/') Now I dont see the messages in the '/' url How can we do this -
not able to createsuperuser in django
I am not able to createsuperuser, I am getting the following error Django Version 3.1.1 Traceback (most recent call last): File "/Users/napoleon/django-app/mysite/manage.py", line 22, in <module> main() File "/Users/napoleon/django-app/mysite/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/napoleon/django-app/pfs-venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/napoleon/django-app/pfs-venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/napoleon/django-app/pfs-venv/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Users/napoleon/django-app/pfs-venv/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "/Users/napoleon/django-app/pfs-venv/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Users/napoleon/django-app/pfs-venv/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) AttributeError: 'UserManager' object has no attribute 'create_superuser' basically its throwing AttributeError: 'UserManager' object has no attribute 'create_superuser' I read this also[SO-related question][1] I don't get it exactly as conveyed there. Custom User models mainapp/models.py import uuid from django.contrib.auth.models import AbstractUser, UserManager from django.db import models class CustomUserManager(UserManager): def create_user(self, email,date_of_birth, username,password=None,): if not email: msg = 'Users must have an email address' raise ValueError(msg) if not username: msg = 'This username is not valid' raise ValueError(msg) # if not date_of_birth: # msg = 'Please Verify Your DOB' # raise ValueError(msg) # user = self.model( email=UserManager.normalize_email(email), # username=username,date_of_birth=date_of_birth ) user = self.model( email=UserManager.normalize_email(email), username=username ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,username,password,date_of_birth): user = self.create_user(email,password=password,username=username,date_of_birth=date_of_birth) user.is_admin = True user.is_staff = … -
using ListView in django it does not diplay images after looping through image_url in my template but other database obj works
main.html {% include 'base.html' %} {% block title %} Home page {% endblock title %} {% block content %} {% for news in news %} {{ news.title }} {{ news.description | truncatewords:2 }} detail page {% endfor %} {% endblock content %} -
Access many-to-many relations of foreign object as multiple choice in model form
I have model Classroom which relates to an instance of Group of the same name. I do need the Classroom model because I am not comfortable with subsetting Group but I need further fields on Classroom which I will omit below. class Classroom(models.Model): group = models.ForeignKey(to=Group) name = models.CharField() # ... I use a model form to edit instances of Classroom. To this form I would like to add a MultipleChoiceField which allows the user of the form to add users to the classroom's group. I do understand that I could add a field members to the model form like so: class LectureClassForm(forms.ModelForm): members = forms.MultipleChoiceField() class Meta: model = LectureClass fields = ["name", "is_invitation_code_active"] But how can I populate this MultipleChoiceField with all users (User.objects.all()) and mark the ones in the group belonging to classroom (classroom.group.user_set.all()) as selected? -
Should I use Flask or Django?
I am new to web development, but I am proficient in Python. I want to build my first website, where the client can create and print their own book. The website should do a number of things: Select book content from an already existing website. Customize book features, page size, cover etc. Create pdf from the text content scraped from another site. Upload that pdf to dropbox. Connect to lulu to publish the pdf as a printed book. Take payment from the client. How should I go about this? For instance, should I use only Python (that is my best language), or will I need to learn Javascript also? If I go with Python, should I use Flask or Django? I think the former is simpler, so that sounds better. -
How to query from 2 Models in Class based views in django?
I have a model Log and another model Solutions and I am using DetailView to display details of each log Each log can have many solutions. There is a log field in the Solutions model that is Foreign Key to Log model.. Now how do I access both Log model and Solutions of that particular log in the same html template if I want to display all the solutions of that particular log below the details of the log models.py: class Log(models.Model): title = models.CharField(blank=False, max_length=500) content = models.TextField(blank=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=50, null=False, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE,null=True, blank=True) image = models.ImageField( upload_to='images', blank=True) def save(self, *args, **kwargs): super().save() self.slug = self.slug or slugify(self.title + '-' + str(self.id)) super().save(*args, **kwargs) class Meta: verbose_name = ("Log") verbose_name_plural = ("Logs") def __str__(self): return f"{self.title}" def get_absolute_url(self): return reverse("log-detail", kwargs={"question": self.slug}) class Solutions(models.Model): log = models.ForeignKey( Log, on_delete=models.CASCADE, blank=True, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE,null=True, blank=True) solution = models.TextField(null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=50, null=False, blank=True) image = models.ImageField( upload_to='images', blank=True) def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.solution) super().save(*args, **kwargs) class Meta: verbose_name = ("Solution") verbose_name_plural = ("Solutions") def __str__(self): return f" … -
Django unable to save form trying to set user in a field
What I want to make, is to create a record of this class: class Order(models.Model): OPTIONS = [ ('1', 'Option 1'), ('2', 'Option 2'), ('3', 'Option 3'), ('4', 'Option 4'), ] user = models.ForeignKey(User, on_delete=models.CASCADE) choice = models.CharField(choices=OPTIONS, max_length=60) custom = models.CharField(max_length=60) date = models.DateField(default=localdate) Using this form: <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} <div class="input-group mb-3"> <div class="input-group-append"> <span class="input-group-text"><i class="fa fa-cutlery"></i></span> </div> {{form.choice}} </div> <div class="input-group mb-3"> <div class="input-group-append"> <span class="input-group-text"><i class="fa fa-comment"></i></span> </div> {{form.custom}} </div> <div class="d-flex justify-content-center mt-3"> <input class="btn btn-success" type="submit" value="Confirm"> </div> </form> The template is rendered by this view: @login_required def createOrder(request): date = localdate() form = None item = Menu.objects.filter(date=date) if item.exists(): instance = Order.objects.filter(user=request.user,date=date) if instance.exists(): return render(request,'requestMenu.html',{'note': 'We\'re preparing your meal'}) else: user = Order(user=request.user) form = orderForm() if request.method == 'POST': form = orderForm(request.POST) if form.is_valid(): form.save(commit=False) form.user = request.user form.save() return render(request,'requestMenu.html',{'note': 'You\'re order has been saved. We\'re preparing it for you. Be patient.'}) else: return render(request,'requestMenu.html',{'note': 'Choose your meal'}) So... it supossed that Date field will come by default (already checked it, that's working good) and User will be assigned with actual logged user, after the form is completed. But then, when I go to check …