Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.IntegrityError: UNIQUE constraint failed: mode_setting.user_id
I am new to Javascript, I am currently learning to debug errors that I am receiving in the Console. In my project I am adding a theme choosing option for each user logged into the website. Currently, it is showing the 2 themes when I click the buttons but it is not saving the theme for each user. I have created an app in my Django Project and everything is as covered in the tutorial I am following except that in the console I am receiving errors every time I select a theme from the buttons: (index):573 POST http://127.0.0.1:8000/update_theme/ 500 (Internal Server Error) and in the Terminal this error: django.db.utils.IntegrityError: UNIQUE constraint failed: mode_setting.user_id Here is the base template: <link id="mystylesheet" href="{% static 'css/app-light.css' %}" type="text/css" rel="stylesheet"> <!-- Mode --> <div id="mode" class="section" style="padding-top: 1rem; padding-bottom: 3rem;text-align: right"> <button onclick="swapStyles('app-light.css')" type="button" class="btn btn-secondary">Light Mode</button> <button onclick="swapStyles('app-dark.css')" type="button" class="btn btn-dark">Dark Mode</button> </div> <!-- Mode --> Javascript <script type="text/javascript"> function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? … -
Error db_table is used by multiple models: Django
Im confused what does this error mean?, when I tried to transfer my project to another pc and runs using python manage.py runserver this error will display. It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance. -
mod_wsgi (pid=*): Target WSGI script '/root/project/wsgi.py' cannot be loaded as Python
getting this error when making website live. When path set in wsgi WSGIDaemonProcess demo python-path=/root/election python-home=/root/venv WSGIProcessGroup demo WSGIScriptAlias / /root/election/election/wsgi.py this is error from my logs mod_wsgi (pid=*): Target WSGI script '/root/election/election/wsgi.py' cannot be loaded as Python m$[time] [wsgi:error] [pid 17712:tid 140454280738560] [remote 43.241.144.192:527] mod_wsgi (pid=*): Exception occurred processing WSGI script '/root/election/election/wsgi.py'. Traceback (most recent call last): File "/root/election/election/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named 'django' I verified that path is correctly specified that is as below path to wsgi /root/election/election/wsgi.py virtual env path /root/venv tried reinstalling wsgi by below command. but still error not solved $ sudo apt-get remove libapache2-mod-python libapache2-mod-wsgi $ sudo apt-get install libapache2-mod-wsgi-py3 I even given persmission of 777 to my project directory and virtualevn still geting this error output of these command ask other peoples so. It is as below. >>> django.__file__ '/root/venv/lib/python3.8/site-packages/django/__init__.py' >>> import sys >>> sys.prefix '/root/venv' followed this and googled other answers but although this question asked many time and duplicated but still it is is not answerd. -
How to create a form in Django from a model with multiple ForeignKey and ManytoManyField fields?
I am a Django newbie. I cannot figure out how to create a form that properly displays my model, which has two ForeignKey fields and three ManytoManyFields. I am familiar with creating forms from more simple models, but I'm stuck on this one. So far, I've tried ModelForm and used ModelChoiceField for ForeignKey relationships, but that did not work. When viewing the form, the fields options did not render. I then tried inlineformset_factory but I could not find helpful examples. Any help is appreciated. models.py class Animal(models.Model): name = models.CharField(max_length=500, blank=False, null=False) **type = models.ForeignKey(Type, on_delete=models.SET_NULL, blank=False, null=True)** **ageGroup = models.ForeignKey(AgeGroup, max_length=300, on_delete=models.SET_NULL, blank=False, null=True)** ageYears = models.PositiveIntegerField(blank=False, null=False) ageMonths = models.PositiveIntegerField(blank=True, null=True) sex = models.CharField(max_length=100, choices=SEX, blank=False, null=False, default='NA') city = models.CharField(max_length=200, blank=True, null=True) state = models.CharField(max_length=200, blank=True, null=True) country = models.CharField(max_length=250, blank=True, null=True) **breedGroup = models.ManyToManyField(BreedGroup, blank=False)** **breed = models.ManyToManyField(Breed, blank=False)** tagLine = models.CharField(max_length=300, blank=False, null=False) goodWithCats = models.BooleanField(blank=False, null=False, default='Not Enough Information') goodWithDogs = models.BooleanField(null=False, blank=False, default='Not Enough Information') goodWKids = models.BooleanField(null=False, blank=False, default='Not Enough Information') profilePic = ResizedImageField(size=[300, 450], quality=100, upload_to='media/', default='', null=True, blank=True, keep_meta=False) **contact = models.ForeignKey(ContactDetails, on_delete=models.SET_NULL, blank=False, null=True)** forms.py class AnimalDetailsForm(ModelForm): type = ModelChoiceField(queryset=Type.objects.all()) #doesn't work ageGroup = ModelChoiceField(queryset=AgeGroup.objects.all()) #doesn't work #breed = … -
Why django ORM .filter() two way binding my data?
Let's say I store my query result temporarily to a variable temp_doc = Document.objects.filter(detail=res) and then I want to insert some data in said model and will be something like this p = Document(detail=res) p.save() note that res are object from other model to make some FK relation. For some reason the temp_doc will contain the new data. Are .filter() supposed to work like that? Because with .get() the data inside temp_doc don't change -
Using multiple filters for django text?
I have a model called article that has a field for the content of the article: content = RichTextField() I am trying to add two filters to it: safe and linebreaks. However when I do this: {{article.content|safe|linebreaks}} Only the first filter works. Does anyone know the syntax to use multiple filters? Thanks y'all! -
Is there a better way to load Django static directories for multiple apps than this? Thank you
I currently have the following in settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') #add app-specific static directory STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'project/static'), os.path.join(BASE_DIR, 'project/apps/blog/static/'), os.path.join(BASE_DIR, 'project/apps/users/static/'), os.path.join(BASE_DIR, 'project/apps/comments/static/'), os.path.join(BASE_DIR, 'project/apps/categories/static/'), ) Should I be doing this in one line? Thanks very much. -
Cannot connect to Websocket after deploying with docker-compose+daphne+nginx
I have an application running in Docker which is using django 2.2 (Django DRF) + channels 3, daphne, nginx. Now I'm trying to deploy the application. DRF APIs are working fine, but supervisord shows that asgi is repeating spawned and exited, and when the frontend app(react) tries to connect to the websocket it shows 500 error. This doesn't occur in my local. I've been looking for the error messages on Google but couldn't find answers. Looks like it comes from my misconfiguration, but I have no idea. This is my docker-compose. version: '2' services: db: build: ../containers/mysql ports: - "3306:3306" env_file: staging.env volumes: - ./mysql:/var/lib/mysql - ../containers/mysql/conf:/etc/mysql/conf.d - ../containers/mysql/init:/docker-entrypoint-initdb.d redis: image: redis ports: - "6379:6379" django: build: ../containers/django command: daphne -b 0.0.0.0 -p 8001 myapp.asgi:application volumes: - ../../myapp:/code - ../../logs/django:/var/log/django - ../../logs/uwsgi:/var/log/uwsgi - ../../logs/supervisor:/var/log/supervisor ports: - "8002:8001" links: - db - redis depends_on: - db - redis entrypoint: ./scripts/wait-for-it.sh db:3306 --strict -- supervisor: build: ../containers/django command: /usr/bin/supervisord -n -c /etc/supervisor/supervisord.conf volumes_from: - django volumes: - ../containers/django/supervisord.conf:/etc/supervisor/supervisord.conf - ../../daphne:/run/daphne ports: - "9999" links: - db - redis depends_on: - django entrypoint: ./scripts/wait-for-it.sh django:8001 -- nginx: image: nginx ports: - "80:80" - "443:443" links: - django depends_on: - django volumes: - ../../myapp:/code … -
Django Error: Reverse for 'like_post' with arguments '('',)' not found
Full error: Reverse for 'like_post' with arguments '('',)' not found. 2 pattern(s) tried: ['like/(?P[0-9]+)$', 'home/like/(?P[0-9]+)$'] views.py: def like_post(request, pk): post = Post.objects.get(id=pk) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) post.dislikes.remove(request.user) liked = True return HttpResponseRedirect(reverse('home-new')) The above code works if i put form action to the url that calls the view but it refreshes the page when i like a post so im trying to call the view through javascript instead so i tried this templates: <script> $(document).on('submit','#like_form',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'{% url 'like_post' item.id %}', success:function(){ } }); }); </script> {% block content %} {% for item in products %} <div class="item_btns_container"> <div class="like_btn_form_container"> <form id="like_form">//was action="{% url 'like_post' item.id %}" {% csrf_token %} {% if user in item.likes.all %} <button type="submit" class="liked_post" name="post_id" value="{{ item.id }}"><div class="liked_btn" >Like</div></button> {% else %} <button type="submit" class="like_btn" name="post_id" value="{{ item.id }}"><div class="liked_btn">Like</div></button> {% endif %} </form> </div> {% endfor %} {% endblock content %} i also tried this with a different view def like_post(request, pk): post = Post.objects.get(id=pk) liked = False if request.method == 'POST': if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) post.dislikes.remove(request.user) liked = True return render(request, 'new.html') -
Should I sent images through JSON
I'm new to Django, and I'm building a REST backend for my iOS app, I figured out encode an Image to it's Base64 data, and I would like to use it together with some texts, is it a good idea to put it into the JSON for the rest of the data or is it better to use another request to download each image data. I'm guessing that separating concerns is the best way, and have two GET request to retrieve the data, but I just want to be sure!. OPTION A { "owner": { "username": "lilysmith", "email": "lily@email.com", "first_name": "Lily", "last_name": "Smith" }, "is_user_page": true, "title": "Lily Smith", "subtitle": "Photographer", "about": [ { "icon": "🇺🇸", "label": "Austin, TX" } ], "photos": [ { "position": 2, "description": "I love hiking", "photo": "/9j/2wCEAAgGBg....CEAAgGBg" <- (The rest of the binary data) } ] } OPTION B (Separating Concern) The same JSON response, but instead of image data, using it's id. Then getting it just the data through another request, but esencially making the front end handle two or more request to server. -
Django Model default call back not adding beyond 10
I was hoping someone can assist with my issue in that when I used a default callback my 'account_number' field gets an Integrity Error when above 10. Without a default callback, I have no issues and it works. My Account Model: def account_number_increment(): last_number = Account.objects.all().order_by("account_number").last() print("I am the last number") start_from = AccountSettings.account_number_startfrom print("I am the start from") acc_number = '1' if last_number is None: print("I am the initiator") return acc_number if start_from != '' or start_from is not None: while Account.objects.all().filter(account_number=start_from).exists(): acc_number_start = int(last_number.account_number) + 1 print("acc # from start from", str(acc_number_start)) return str(acc_number_start) if last_number: # last_number.refresh_from_db(fields="account_number") # last_number.refresh_from_db() while Account.objects.all().filter(account_number=last_number.account_number).exists(): print("BEFORE addition", last_number.account_number) new_acc_number = int(last_number.account_number) + 1 print("acc # new number", str(new_acc_number)) return str(new_acc_number) class Account(models.Model): name = models.CharField(max_length=100, null=True, blank=True) address = models.OneToOneField(Address, on_delete=models.SET_NULL, blank=True, null=True, related_name="account_address") account_number = models.CharField(max_length=20, default=account_number_increment, null=True, blank=True, unique=True) # account_number = models.CharField(max_length=20, default='1def') # works with for loop in views. date_created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.name My Account_Settings Model class AccountSettings(models.Model): account_number_startfrom = models.CharField(max_length=100, default='1', blank=True, null=True) def __str__(self): return f'{self.job_number_startfrom}, {self.account_number_startfrom}, {self.invoice_number_startfrom}' My views def index(request): if request.method == 'POST': form1 = AccountForm(prefix='form1', data=request.POST) form2 = AccountForm(prefix='form2', data=request.POST) if … -
Navbar image not loading in production environment
I am building a website with Django and bootstrap. I added an image to my navbar which is in a 'base.html' which I use as a template for my other html files. The image loads in development but doesn't appear in production. I'm using Heroku to host and deploy my app and google drive storage as my backend file storage for user uploaded-files. The navbar also uses another static file with the resume button and it works fine. base.html header <header> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container py-2"> <a class="navbar-brand" href="{% url 'homepage' %}"> <span class="d-flex align-items-center"> <img class="mx-3" src="{% static 'logo (200px).png' %}" width='70' alt=""> <h4> MAVERON AGUARES </h4> </span> </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs- target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse justify-content-end" id="navbarNavAltMarkup"> <div class="navbar-nav ml-auto"> <h5> <a class="nav-link " aria-current="page" href="{% static 'Sample Resume.pdf' %}">Resume</a> </h5> <h5> <a class="nav-link " aria-current="page" href="{% url 'blogHomePage' %}">Blog</a> </h5> </div> </div> </div> </nav> </header> settings.py STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'personalportfolio/static/') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' GOOGLE_DRIVE_STORAGE_JSON_KEY_FILE = 'Mave-Aguares-Portfolio-55b70982536d.json' GOOGLE_DRIVE_STORAGE_MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', projects.views.homepage, name='homepage'), … -
where does "create()" method comes from in django
I just want to know where create method comes from in django. I checked Model class, BaseManager class and so on. I cannot find where create method is defined. Anyone knows about it ? https://github.com/django/django/blob/2d6179c819010f6a9d00835d5893c4593c0b85a0/django/ -
How to optimize Django DateTimeField for null value lookups in postgres
I have a problem with deeper undestanding of indexing and its positive side. Lets assume such model class SupportTicket(models.Model): content = models.TextField() closed_at = models.DateTimeField(default=None) to keep it clean I do not add is_closed boolean field as it would be redundant (since closed_at == None implies that ticket is open). As you can imagine the open Tickets will be looked up and called more frequently and thats why I would like to optimize it database-wise. I am using postgres and my desired effect is to speed up this filter active_tickets = SupportTicket.objects.filter(closed_at__isnull=True) I know that postgres support DateTime indexing but I have no knowleadge nor experience with null/not null speed ups. My guess looks like this class SupportTicket(models.Model): class Meta: indexes = [models.Index( name='ticket_open_condition', fields=['closed_at'], condition=Q(closed_at__isnull=True)) ] content = models.TextField() closed_at = models.DateTimeField(default=None) but I have no idea if it will speed up the query at all. The db will grow in about 200 Tickets a day and will be queried at around 10 000 a day. I know its not that much but UX (speed) really matters here. I will be grateful for any suggestions on how to improve this model definition. -
Heroku (python) FileNotFoundError on root directory
I uploaded an application to heroku and the status of the webservice appears to be ok, but I'm having an error when I start the POST method that reads a file in the project's root directory. Locally it works. The error log is: FileNotFoundError: [Errno 2] No such file or directory: '/app/.heroku/python/bin/chave_privada_google.json' My Procfile looks like this: web:gunicorn app:app When I run the ls command on my heroku bash the file list looks like this, with the app.py file being the main one: ls comand on heroku bash This is how I'm referencing the chave_privada_google.json file in the app.py file: file calling I still haven't figured out what's going on. Could anyone help? -
Trouble installing Django for first time
I am trying to use Django on mac to develop a website backend using python. I installed Django 3.1.5 and when I try to upgrade (to 3.1.5) it says 'requirement already satisfied' so I can tell 3.1.5 is installed However when I type python -m django --version into terminal, it returns 1.11.29 How do I fix this? -
How can I show list of names of the foreignkey IDs and update on a intermediary table with Django modelform?
I am trying to make a table view of the intermediary table for many to many relationship(managerproject table). And I want to directly update this table with the Django form. I want to have a form to add a row to the managerproject table which contains pid from project table and manid from manager table. But I would like to have a choicefield for all pid shown as pname from project and another choicefield for all manid shown as mname from manager table. When I submit the form, it just adds a row to managerproject table with chosen pname's pid and mname's manid. mproj.html <tbody> {% for mproj in mprojs %} <tr> <td>{{ mproj.pId.pName}}</td> <td>{{ mproj.manId.mName}}</td> <td> <a href="{% url 'mproj:edit_mproj' mproj.pId %}" class="btn btn-primary btn-sm"> Edit </a> </td> </tr> {% endfor %} </tbody> add_mproj.html {% block content %} <h2>Project Manager</h2> <form class = "upload_form" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary">Add</button> </form> {% endblock %} models.py STATUS_CHOICES = [('Active', 'Active'), ('Inactive', 'Inactive')] class Manager(models.Model): manId = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') mName = models.CharField(db_column='name', max_length=100) email = models.CharField(db_column='email', max_length=100, blank=True) status = models.CharField(db_column='status', max_length=16, choices=STATUS_CHOICES) class Project(models.Model): pId = models.AutoField(db_column='pId', primary_key=True) pName = models.CharField(db_column='name', max_length=100) … -
Django unable to access the translated fields of a model in the update_or_create function
I have a model such as below: class MyModel(TranslatableModel): date_created = models.DateField( verbose_name=_('Date Created'), default=timezone.now) source = models.CharField(max_length=100, verbose_name=('Type')) translations = TranslatedFields( name=models.CharField(verbose_name=_('Name'), max_length=200) ) I want to use update_or_create function on this model; I want to fetch a record which has the given id and source; If it exists I want to update its name in 3 different languages. Otherwise I want to create a new record. I used the following code. I tried name_en, name__en, translations__name_en; None of them worked. I also tried get_or_create function, None of them worked with that as well. obj, created = MyModel.objects.update_or_create( id= id, source = 'tmp', defaults={ 'name_en': en_name, 'name_fi': fi_name, 'name_sv': sv_name, }) I don't want to use get function and create function separately. I would like to know how to access the django translated fields via update_or_create function or get_or_create function. Can some one help me with this please? -
Django - Cannot link static CSS to applications
So I am working on a django datascience project tutorial from this guy's youtube channel: https://github.com/pyplane/django_with_data_science and I'm stuck at getting my static CSS file to apply to my html view. here is my file structure: So far, I've been able to get static_project/main.js to work fine but I cannot get the style.css file to work. style.css .test_blue_2 { color:blue; } css_test.html {% load static %} <link rel='stylesheet' type='text/css' href={% static 'style.css' %}> <style type = 'text/css'> .test_blue_1 { color:blue; } </style> {% block content %} <div class ='test_blue_1'>Blue text 1</div> <div class ='test_blue_2'>Blue text 2</div> {% endblock %} This outputs Blue text 1 in blue and Blue text 2 remains black Settings: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static_project'), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "static_root") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "media_root") http://127.0.0.1:8000/static/style.css yields .test_blue_2 { color:blue; } here is my file structure: -
images do not match pil, django model
I'm trying to create a QR Code in my Django model which creates itself whenever a new record is saved. The problem is that when testing in my dev environment everything is fine but in production I get an error on the specified line below saying: ValueError, images do not match. from django.core.files import File import qrcode from io import BytesIO from PIL import Image from datetime import date def save(self, *args, **kwargs): img = qrcode.make(self.account_id) canvas = Image.new('RGB', (400, 400), 'white') canvas.paste(img) # Error occurs on this line buffer = BytesIO() canvas.save(buffer, 'PNG') canvas.close() fname = f'pdf-qr-code-{self.account_id}.png' self.menu_qr_code.save(fname, File(buffer), save=False) super(PDFMenu, self).save(*args, **kwargs) I don't know if maybe the problem is with my configurations on my ubuntu server since that's the place where the problem takes place but maybe a new way of creating a qr code within this custom save method is necessary. Thanks in advance for the help. -
Customized PasswordResetSerializer and now it's throwing error 500
I am contributing to an open-source org where they are using django-rest-auth for authentication purposes. I have to simply override the email template for a password reset. So I used imported PasswordResetSerializer and then customized it. It worked in the first place but when I restarted the whole environment it stopped working and just showed this in terminal django_1 | [pid: 65|app: 0|req: 1/1] 172.19.0.1 () {42 vars in 696 bytes} [Thu Jan 7 22:06:59 2021] OPTIONS /api/auth/password/reset/ => generated 0 bytes in 4 msecs (HTTP/1.1 200) 7 headers in 365 bytes (1 switches on core 0) django_1 | [pid: 67|app: 0|req: 1/2] 172.19.0.1 () {42 vars in 696 bytes} [Thu Jan 7 22:06:59 2021] POST /api/auth/password/reset/ => generated 22264 bytes in 796 msecs (HTTP/1.1 500) 5 headers in 177 bytes (1 switches on core 0) It's showing me error 500. I tried to use debugger but here the all environment is setup using docker and I couldn't figure out what's going wrong. Here are the files settings.py """ Django settings for evalai project. Generated by 'django-admin startproject' using Django 1.10.2. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ … -
How can I redact a Django object instance based on the user's view permission?
I would like to redact object instances based on the user's view permission. For instance, if I have the following model class Data(models.Model): value = models.FloatField() I would like users that have view permission, i.e. myapp.view_data, to see the full value, and users without view permission to only see a redacted version, say round(value). I could implement this for every view and template, but that doesn't seem very DRY and would have a risk of overlooking some occurrences. Also, I suppose in a template the mechanism might be bypassed through relation queries. How can I implement this redaction mechanism in the model? Would this be good practice? Or is there a better way? Thank you! -
what does forward slash do in this django settings.py python list?
I'm new to python and I don't understand how this forward slash works in the django settings.py STATICFILES_DIRS = [ BASE_DIR / "static", ] It seems like it is concatenating the value of BASE_DIR + "static", but that would actually be str(BASE_DIR) + "static" correct? Is it a special Django delimiter of sometype? This is the correct usage according to the Django documentation: https://docs.djangoproject.com/en/3.1/howto/static-files/#configuring-static-files STATICFILES_DIRS Is not a parameter list - so this doesn't seem to apply https://docs.python.org/3/faq/programming.html#what-does-the-slash-in-the-parameter-list-of-a-function-mean It's not a binary division operator: https://docs.python.org/3/reference/expressions.html#binary -
Issue comparing datetime objects in django html template
I am passing in class objects and a variable into my html template in Django Using Classbased Views, I have get_context_data(self, **kwargs): ... context['time'] = datetime.now() ... return context I also pass in my objects using model = Object and context_object_name = 'obj' In my html template my comparison looks like this: {% if obj.start_time > time %} <h1 style="color:white">ITS WORKING</h1> {% endif %} Regardless of whether I use >, <, or ==, the h1 template is never displayed. I have used {{obj.start_time}} and {{time}} to ensure that there really are values attached to these variables, and I see both of the times displayed on the page. The values themselves work, but for some reason the comparison isn't working. -
saving a booking form + current user data to customer profile
i am creating a reservation system for booking, i would like the user to view their booking details once they've booked and would like for their details to show on their customer profile, i am struggling to link the form to the user/customer profile #models.py class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) surname = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Booking(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) surname = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) confirm_email = models.CharField(max_length=200, null=True) PACKAGES_CHOICES = [('FULL DAY SPA', 'Full Day Spa'), ('HALF DAY SPA', 'Half Day Spa'), ('MOONLIGHT SPA', 'Moonlight Spa')] packages = models.CharField(max_length=100, choices=PACKAGES_CHOICES, default='FULL DAY SPA') PEOPLE_CHOICES = [('ONE', '1'), ('TWO', '2'), ('THREE', '3'), ('FOUR', '4'), ('FIVE', '5'), ('SIX', '6'), ('SEVEN', '7'), ('EIGHT', '8'), ('NINE', '9'), ('TEN', '10'), ] people = models.CharField(max_length=100, choices=PEOPLE_CHOICES, default='ONE') booking_date = models.DateField() created = models.DateTimeField(auto_now_add=True, auto_now=False, blank=True) def __str__(self): return self.name #views.py @allowed_users(allowed_roles=['customer']) @login_required(login_url='login') def booking(request): if request.method == 'POST': print(request.POST) book = BookingForm(request.POST, ) if book.is_valid(): booking = book.save booking.user = request.user book.save() #forms.py class BookingForm(ModelForm): class Meta: model = Booking fields …