Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run multiple manage.py using docker file
I have Django application which has docker file and using below command to bring up the application CMD ["gunicorn", "--bind", ":8000", "--workers", "3", "--worker-class", "uvicorn.workers.UvicornWorker", "myapplication.asgi:application"] Would like to run one more process "task_process" which is present in the below directory structure taskApp/ __init__.py models.py management/ __init__.py commands/ __init__.py task_process.py How to execute task_process after loading an application ? I tried the below shell script command to execute same.. But task_process is not running using below commands in startup.sh #!/bin/sh exec gunicorn --bind :8000 --workers 3 --worker-class uvicorn.workers.UvicornWorker myapplication.asgi:application & exec python manage.py task_process Updated existing Docker file as below RUN chmod +x startup.sh CMD ["./startup.sh"] -
When I add settings folder with settings for different environments, I get CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False
I want to make two files with different settings for dev and prod. I created a python package in the app folder where my settings are, and even if I run the app with old settings, I receive an error: CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. Here is my project structure: -
Collection uploaded to Ansible Automation Hub displays all files under Documentation and Plugins
I wrote a collection containing one lookup plugin named res_query. This plugin imports two local libraries (credentials.py, resources.py) from the module_utils directory. Further it uses the common.py document fragment from the directory doc_fragments. After uploading this collection to our Ansible Automation Hub, ALL files (common.py, credentials.py, resources.py, res_query.py, README.md) are displayed under Documentation and Plugins. I expected, that only the README.md and res_query.py should be displayed. What I'am doing wrong? namespace.collname ├── CHANGELOG.md ├── galaxy.yml ├── LICENSE.md ├── meta │ └── runtime.yml ├── plugins │ ├── doc_fragments │ │ └── common.py │ ├── lookup │ │ └── res_query.py │ ├── modules │ └── module_utils │ ├── credentials.py │ └── resources.py └── README.md -
"That username is already taken." but there is no entry in DB
In my environment I'm trying to create a new superuser via python .\manage.py createsuperuser. However, when I enter the name I get the following error: Error: That username is already taken.. So I check the auth_user table in PgAdmin and I can see there are no entries. Moreover, the QuerySet is empty when I do the following: from django.contrib.auth.models import User superusers = User.objects.filter(is_superuser=True) superusers >>> <QuerySet []> I'm using a managed cloud-hosted PostgreSQL server with the postgresql_psycopg2 client, and have checked that all credentials are correct. What am I doing incorrectly? I'm using Django 4.1.2. -
Python Datetime Comparison
I'd like to check if the current date is bigger than a date put in by the user. All dates are converted using strftime('%d/%m/%Y'). But if I compare both dates, I get a wrong result: absenzen.view def absenzen(request): if request.user.is_authenticated: # if user is logged in object_list = Subject.objects.order_by('name') subject_list = [] for subject in object_list: subject_list.append(subject.name) absenzen_local = Absenzen.get_absenzen(student=request.user.id, subjects=subject_list) current_date = datetime.date.today().strftime('%d/%m/%Y') return render(request, 'absenzen.html', {'absenzen': absenzen_local, 'current_date': current_date}) else: # else redirect to login page return redirect('loginForm:login') get_absenzen method def get_absenzen(student, subjects): absenzen_dict = {} for subject in subjects: absenzen_list_complete = [] absenzen_object_list = Absenzen.objects.filter(student=student, subject__name=subject).order_by('-date') for absenz in absenzen_object_list: absenzen_list = [] expire_date = absenz.date + datetime.timedelta(days=10) if absenz.excused: absenzen_list.append('Ja') elif not absenz.excused: absenzen_list.append('Nein') absenzen_list.append(expire_date.strftime('%d/%m/%Y')) absenzen_list_complete.append(absenzen_list) print(absenzen_list_complete) absenzen_dict[subject] = absenzen_list_complete print(absenzen_dict) return absenzen_dict html {% if absenzen %} {% for subject, absenzen in absenzen.items %} <button class="collapsible" type="button">{{ subject }}</button> <div class="content"> {% if absenzen %} <ul> {% for absenzen_list in absenzen %} <div class="content-text"> <li>Entschuldigt: {{ absenzen_list.0 }}</li> {% if absenzen_list.0 == 'Nein' %} {{ absenzen_list.1 }} {{ current_date }} {% if absenzen_list.1 < current_date %} <p><strong>Abgabedatum schon abgelaufen</strong></p> {% else %} <p>--> Abgabadatum: {{ absenzen_list.1 }}</p> {% endif %} {% else %} <p>Abgegeben</p> {% … -
Hiding Django form fields using Jquery but it is not hiding form labels (using crispy forms)
I am trying to hide certain fields in a form based on select field choices. For example for Select field "system_description_1" If option "Direct" is selected following fields should be hidden (also hidden by default on page load), but when "Indirect" is selected the fields should become visible. This function is absolutely working fine using Jquery, but it is still showing the form label, It is hiding the field but not the label of the field how do I hide them ? I want to hide the field label when I hide the field, but show the field label when I unhide or show them. Fields: secondary_circulation_pump_model secondary_circulation_pump_capacity models.py: class Systemprofile(models.Model): SYSTEMDESC1 = ( ('direct', 'Direct'), ('indirect', 'Indirect') ) SECONDARYPUMPMODEL = ( ('grundfos', 'Grundfos'), ('cnp', 'CNP'), ('others', 'Others') ) SECONDARYPUMPCAPACITY = ( ('ltr-hr', 'Ltr/hr'), ('others', 'Others') ) name = models.CharField(max_length=255, null=True) system_description_1 = models.CharField(blank=True, max_length=255, null=True, choices=SYSTEMDESC1) secondary_circulation_pump_model = models.CharField(blank=True, max_length=255, null=True, choices=SECONDARYPUMPMODEL) secondary_circulation_pump_capacity = models.CharField(blank=True, max_length=255, null=True, choices=SECONDARYPUMPCAPACITY) forms.py class CreateSystemprofile(ModelForm): class Meta: model = Systemprofile fields = '__all__' system_profile.html {% extends 'base.html' %} {% load static %} {% block content %} {% load crispy_forms_tags %} <script> function Hide() { if(document.getElementById('id_system_description_1').options[document.getElementById('id_system_description_1').selectedIndex].value == "Direct") { document.getElementById('id_secondary_circulation_pump_model').style.display = 'none'; document.getElementById('id_secondary_circulation_pump_capacity').style.display = … -
how to create unicode slug in bangla language in django from title field
I am getting this error in Django: when i click slingle view page in djanog my slug is insert properly but when i try to view single page this error is shown what to do now: Not Found: /ফবরযর-থক-বস-ভড-দয-হব [25/Oct/2022 10:40:42] "GET /%E0%A6%AB%E0%A6%AC%E0%A6%B0%E0%A6%AF%E0%A6%B0-%E0%A6%A5%E0%A6%95-%E0%A6%AC%E0%A6%B8-%E0%A6%AD%E0%A6%A1-%E0%A6%A6%E0%A6%AF-%E0%A6%B9%E0 %A6%AC HTTP/1.1" 404 5408 Module.py user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) type = models.ForeignKey(Type, on_delete=models.CASCADE, null=True) division = models.ForeignKey(Division, on_delete=models.CASCADE, null=True) district = models.ForeignKey(District, on_delete=models.CASCADE, null=True) upazila = models.CharField(max_length=50, blank=True, null=True) postcode = models.ForeignKey(Postcode, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=50, blank=True, null=True) mobile = models.CharField(max_length=50, blank=True, null=True) postoffice = models.CharField(max_length=50, blank=True, null=True) detail = QuillField(null=True, blank=False) bedroom = models.IntegerField(blank=True, null=True) bathroom = models.IntegerField(blank=True, null=True) veranda = models.IntegerField(blank=True, null=True) drawing = models.BooleanField(blank=True, null=True, default=False) dining = models.BooleanField(blank=True, null=True, default=False) status = models.BooleanField(blank=True, null=True, default=True) rent = models.IntegerField(blank=True, null=True) address = models.CharField(max_length=200, blank=True, null=True) google_location = models.CharField(max_length=500, blank=True, null=True) date = models.DateField(auto_now=False, blank=False, null=False) image = models.FileField(blank=True, default="feature_image.jpg") slug = models.SlugField(null=True, blank=True, allow_unicode=True, unique=True) create_date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.title def save(self, *args, **kwargs): if self.slug is None: slug = slugify(self.title, allow_unicode=True) has_slug = AddPost.objects.filter(slug=slug).exists() count = 1 while has_slug: count += 1 slug = slugify(self.title, allow_unicode=True) + '-' + str(count) has_slug = AddPost.objects.filter(slug=slug).exists() … -
How to get the Django model from its name
I have the name of the model table, for example, main_masterinventory, as a string. How do I get the model table given this name? I'm not really understanding the logic of this task, so I've got nothing to show for my work, but if you have any questions about my query, feel free to ask in the comments. -
Django filter where every item in an object's many to many list is included in provided queryset
I'm having a bit of trouble phrasing my question title, which might be why I can't find an answer. It doesn't need to be query set, it could just be a list of pks or some other method. I'll explain with an example and say what I want and what I don't. I have the following models. class Document(models.Model): allowed_groups = models.ManyToManyField(Group, related_name='allowed_documents') class Person(models.Model): permission_groups = models.ManyToManyField(Group, related_name='people') class Group(models.Model): id = models.BigIntegerField() I want to find all the documents that Person can access with the condition that they have to be a member of all of the allowed groups. I want this: Case Document(allowed_groups=1,2,7) with Person(permission_groups=1,2,6,7,11,15) -> MATCH Document(allowed_groups=1,2,7) with Person(permission_groups=1,7) -> NO_MATCH Document(allowed_groups=1,2,7) with Person(permission_groups=1,2) -> NO_MATCH Document(allowed_groups=1,2,7) with Person(permission_groups=2) -> NO_MATCH Document(allowed_groups=1,2,7) with Person(permission_groups=8) -> NO_MATCH Document(allowed_groups=1,2,7) with Person(permission_groups=1,2,7) -> MATCH If I do this: person = Person.objects.get(pk=1) Document.objects.filter(allowed_groups__in=person.permission_groups.all()) I would match on all of the above cases except 8 (not what I want) There are many questions on stack overflow that are asking about exact matching i.e. match only on case 6 but not case 1. (also not what I want) So my question is how can I use django to do this? I've considered … -
How to properly serialize a PrimaryKeyRelatedField in Django Rest Framework
I have two Django models: Book -- which has some Wagtail StreamFields: class Book(models.Model): title = models.CharField(max_length=255) cover_image = StreamField(...) ... Publisher -- which is pure Django: class Publisher(models.Model): name = models.CharField(max_length=255) ... I wanted to have a PublisherChooser in my Wagtail admin. So I [created all that was required and then] added a field to my Book model: class Book(models.Model): title = models.CharField(max_length=255) cover_image = StreamField(...) ... publisher = models.CharField(max_length=10) panels = [ FieldPanel("title"), FieldPanel("cover_image"), FieldPanel("publisher", widget=PublisherChooser), ] Now I have a proper PublisherChooser whenever I want to create a Book in Wagtail Admin. Problem Now I want to serialize my Book model. So I have tried: class PublisherSerializer(serializers.ModelSerializer): class Meta: model = Publisher fields = [ "name", ... ] name = serializers.CharField() ... and class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = [ "title", "cover_image", ..., "publisher", publisher = serializer.PrimaryKeyRelatedField(queryset=Publisher.objects.all()) def update(self, instance, validated_data): publisher = validated_data.pop("publisher") instance.publisher_id = publisher.id return instance def to_representation(self, instance): data = super().to_representation(instance) publisher_serializer = PublisherSerializer( Publisher, context={"pk": instance.publisher} ) data["publisher"] = publisher_serializer.data return data I get publisher in the response but the publisher data doesn't seem to look right: "publisher": { "name": "<django.db.models.query_utils.DeferredAttribute object at 0x7f9ffa146310>", } -
Different format of currency using DecimalField based on choices from other models
What I am trying to do I would want Django to save different format of currency based on which preferred language that user wants to use without using localization. But I am totally lost from where to start. I have two types of currencies: US Dollar($) and Thai Baht. US Dollar can have upto maximum 2 decimal places whereas Thai Baht does not have any 2 decimal places. Here, when user chose their preferred language as USD, I would like Django save price per night of hotel room (this is defined in other models) upto 2 decimal places although its value does not have any decimal numbers. On the other hand, Thai Baht should always have 0 decimal places. Example Preferred currency is USD and price per night is $600 -> Want to save as $600.00 Preferred currency is USD and price per night is $600.12 -> Want to save as $600.12 Preferred currency is THB and price per night is ฿600 -> Want to save as ฿600 (without any decimal points) Preferred currency is THB and price per night is ฿600.12 -> This will throw validation error as there is no such 2 decimal places in THB. Below is … -
Django ORM - Annotate
G'day All, I'm trying to create a running balance of all negative transactions with a date less than or equal to the current transaction object's transaction date however if I use __lte=transaction_date I get multiple rows, while this is correct I want to sum those multiple rows, how would I do that and annotate to my queryset? Current Attempt: #getting transaction sum and negative balances to take away from running balance totals = queryset.values('transaction_date','award_id','transaction').annotate(transaction_amount_sum=Sum("transaction_amount"))\ .annotate(negative_balance=Coalesce(Sum("transaction_amount",filter=Q(transaction__in=[6,11,7,8,9,10,12,13])),0))\ #adding it all to the queryset queryset = queryset\ .annotate(transaction_amount_sum=SubquerySum(totals.filter(award_id=OuterRef('award_id'),transaction_date=OuterRef('transaction_date'),transaction=OuterRef('transaction'))\ .values('transaction_amount_sum')))\ .annotate(negative_balance=SubquerySum( totals.filter(award_id=OuterRef('award_id'),transaction_date=OuterRef('transaction_date'),transaction=OuterRef('transaction'))\ .values('negative_balance') ))\ .annotate(total_awarded=SubquerySum("award__total_awarded"))\ .annotate(running_balance=F('total_awarded')-F('negative_balance')) #This doesnt work correct, we need transaction date to be less than or eqaul not just the transaction date. #filtering on distinct, we only want one of each record, doesnt matter which one. :) distinct_pk = queryset.distinct('transaction_date','award_id','transaction').values_list('pk',flat=True) queryset = queryset.filter(pk__in=distinct_pk) What needs to be fixed: .annotate(negative_balance=SubquerySum( totals.filter(award_id=OuterRef('award_id'),transaction_date=OuterRef('transaction_date'),transaction=OuterRef('transaction'))\ .values('negative_balance') The above should really be: .annotate(negative_balance=SubquerySum( totals.filter(award_id=OuterRef('award_id'),transaction_date__lte=OuterRef('transaction_date'))\ .values('negative_balance') It will return multiple rows if I do this, what I want to do is sum those multiple rows on negative_balance. Hope the above makes sense. Any help will be greatly appreciated. Thanks, Thomas Lewin -
django rest: AssertionError at /api/v1/users/1/ 'UserDetail' should either include a `queryset` attribute, or override the `get_queryset()` method
I'm trying to follow a tutorial from the book 'Django for APIs', this tutorial consists on doing a blog project API with django rest framework. I cant get to work the UserDetail view at url: 'http://127.0.0.1:8000/api/v1/users/int:pk/' it raises the following error ,although queryset is defined in the UserDetail class in views.py: AssertionError at /api/v1/users/1/ 'UserDetail' should either include a queryset attribute, or override the get_queryset() method. here is the code: urls.py views.py serializers.py models.py urls.py: from django.urls import path from .views import UserList, UserDetail, PostList, PostDetail urlpatterns = [ path('users/',UserList.as_view()), path('users/<int:pk>/', UserDetail.as_view()), path('',PostList.as_view()), path('<int:pk>/', PostDetail.as_view()), ] views.py: from django.contrib.auth import get_user_model from rest_framework import generics from .models import Post from .permissions import IsAuthorOrReadOnly from .serializers import PostSerializer, UserSerializer # Create your views here. class PostList(generics.ListCreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer class PostDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = (IsAuthorOrReadOnly,) queryset = Post.objects.all() serializer_class = PostSerializer class UserList(generics.ListCreateAPIView): queryset = get_user_model().objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveUpdateDestroyAPIView): queryset_= get_user_model().objects.all() serializer_class = UserSerializer serializers.py: from django.contrib.auth import get_user_model from rest_framework import serializers from .models import Post class PostSerializer(serializers.ModelSerializer): class Meta: fields = ('id','author','title','body','created_at',) model = Post class UserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = ('id','username',) models.py: from django.db import models from django.contrib.auth.models import User # … -
How to improve myself to become a full-stack freelancing developer in the aspect of technicalities and career?
I started learning coding from 5 months. My goal is to work as a full-stack web freelancing developer. I have learned programming basics (cs50) and then learned python through Youtube courses. Then I learned HTML and CSS also on youtube. Finally, I learned Django, Javascript needed for interactive client-side interface (like DOM, event listeners, fetch, API) by CS50 web programming with python and Javascript. I have applied what I learned on 5 projects (mail, auctions(e-commerce), Twitter like web site, bookstore, and google like interface). Know I'm confused about two points. The first point is what is the most compatible front-end framework that I can use with Django which will help me make better projects. The second thing is how can I work as a freelancer and any suggestions for courses or anything that will help me start my career as a freelancer. And finally, if there are any suggestions for libraries, frameworks or programming languages that will help me improve my projects and myself in web development? to summarize my questions in points: What is the best front-end framework that works and is compatible with Django? What should I do to become a full-stack freelancer (I have good experience with … -
Comparing sensor data and sending warning to Django website when below threshold
I'm able to read data from a flow sensor into python terminal and now I need to compare it to a threshold value and if it's below I need to send warning to a Django website I have created. Can anyone help with this? Thank you -
How to Ban Webmail Registration in a Django Application
How can I effectively ban: 1) Webmail (GMail, Outlook, Yahoo! and so on); and 2) Free, temporary e-mail addresses (like EmailOnDeck, 10minutemail, Mailnator) registrations in my Django Application? Is it possible to solve this problem only using built-in, Django validations? Do some Mail Sender Tool offer this feature out of the box? Thanks. -
Accordion element makes whole page move
When opening a long text accordion, the whole page (or the whole div) moves slightly. I attach a little video to show the problem visually here. I have the accordions displaying information from a django template engine loop, here's the template code: <div class="accordion accordion-borderless" id="accordion_{{ forloop.counter }}"> <div class="accordion-item"> <h2 class="accordion-header" id="heading_{{ forloop.counter }}"> <button class="accordion-button collapsed" type="button" data-mdb-toggle="collapse" data-mdb-target="#collapse_{{ forloop.counter }}" aria-expanded="false" aria-controls="collapse_{{ forloop.counter }}" > {{event.title}} </button> <div id="collapse_{{ forloop.counter }}" class="accordion-collapse collapse" aria-labelledby="heading_{{ forloop.counter }}" data-mdb-parent="#accordion_{{ forloop.counter }}"> <div class="accordion-body"> {{event.description|safe}} </div> </div> </div> </div> What is causing that movement and how can it be solved? -
Time before full counter with percent python
how to calculate based on timestamp and get the progress before the max full value? def full_energy(): time_now = 1666650096 #changes every update time_end = 1666679529 max_energy = 50 diff = datetime.utcfromtimestamp(time_now) - datetime.utcfromtimestamp(time_end) secs = diff.total_seconds() ??? # expected output # x/y (z) # 25/50 (50%) how to get the value of x and z based on this sample? -
Return Redis cached Django views with rendered React
I recently started using Django and as many Django lovers out there would say, there is nothing that beats its admin interface, auth and users out of the box. The issue is, the template syntax. That's why I am trying to integrate it with React, but I am struggling to figure out how to use Vite for development and production, but getting served from the Django server so the views are cached with Redis. I guess I am trying somehow to reinvent Next.js concept of Incremental Static Generation but in Django. What I am trying to achieve is a website where pretty much all text, titles, descriptions, images, etc. will be retrieved from a Django model that the admin can change, but it will barely be changed in the first place, thus the use of Redis an caching the views. A SPA where the html is rendered first and then the text is retrieved from an API is the solution I am trying to get away from as that affects the SEO. It could be considered Server Side Rendering (returns html with already parsed data) but caching the view. Thank you in advance. -
How to save multiple model object instances using one single form in django?
I have the three following models: class AnswerItem(models.Model): item_name = models.CharField(max_length=320) item_number = models.PositiveIntegerField() class AnswerMenu(models.Model): menu_name = models.CharField(max_length=320) answer_item = models.ForeignKey(AnswerItem) class QuestionAnswer(models.Model): answer = models.ForeignKey(AnswerMenu) answer_item = models.ForeignKey(AnswerItem) Answer menus are currently displayed on a single page using a list view, with the following template: {% for answer_menu in answer_menus %} <div>{{ answer_menu.menu_name }}</div> {% for answer_item in answer_menu %} <p> <label> <input id="{{ answer_item.pk }}" name="{{ answer_menu.pk }}" type="radio"> </label> </p> Now, the trouble I have is I would like to create a single form to save all selected answers using the radio buttons on the page. Since there are multiple answer menus shown on the page, posting through this form would create several QuestionAnswer items. How would you approach this? -
Django user model override
I'm not advanced in Django and would like to know how and if it's possible to do it. I need to override Django's user model, and change the fields "username" to "sr_usuario" and "password" to "sr_password", but I would like to continue using all Django's default authentication scheme and permissions. I want not only to change the description in the database or a label, I want to change the name of the field in the model, for when for example I needed to make a query, I would use User.objects.filter(sr_usuario="user_name") and everything would work usually. It's possible? I couldn't find anything in the documentation or on forums I've searched. Thank you very much in advance! -
Hello! Help to make dependent <select> from a database
Help to make dependent from a database. enter image description here I don't know how to configure this dependency between database tables. if possible, tell me how, or show an example of how to implement it. the tables in the database are configured one-to-many, and so many dependencies need to be made. models.py class Car_mark(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name.title() class Meta: verbose_name = 'Марка' verbose_name_plural = 'Марки' class Car_model(models.Model): model = models.ForeignKey(Car_mark, on_delete = models.CASCADE) name = models.CharField(max_length=20) def __str__(self): return self.name.title() class Meta: verbose_name = 'Модель' verbose_name_plural = 'Модели' class Car_engin_type(models.Model): engin = models.ForeignKey(Car_model, on_delete=models.CASCADE) name = models.CharField(max_length=20) def __str__(self): return self.name.title() class Meta: verbose_name = 'Двигатель' verbose_name_plural = 'Двигатели' views.py class MarkList(ListView): model = Car_mark ordering = 'name' template_name = 'index.html' context_object_name = 'marka' class ModelList(ListView): model = Car_model ordering = 'name' template_name = 'index.html' context_object_name = 'model' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', MarkList.as_view()), path('', ModelList.as_view()), index.html {% load static %} <!DOCTYPE html> <html lang="ru"> <head> <link rel="stylesheet" href="{% static 'Zayavky/css/stail.css' %}"> </head> <body> <h1>Выберите автомобиль:</h1> <label> <select class="select-css"> {% for el in marka %} <option>{{ el }}</option> {% endfor %} </select> </label><br> <label> <select class="select-css"> {% for el2 in model %} <option>{{ … -
Django - how to export and import user data for database migration?
I am moving my website to another cloud server for delpoying, so I have to export all the user information (account name, password, accounts.profile from the existing database, then import to the new website hosted by the new server. I have tried to export user data using default: python manage.py dumpdata > users.json the users.json looks like: [{"model": "accounts.profile", "pk": 1, "fields": {"user": 2, "telephone": "0755-25187181", "company_name": "watchtech"}}, {"model": "accounts.profile", "pk": 2, "fields": {"user": 3, "telephone": "18696511023", "company_name": "King's Machinery"}},....}}] I noticed there is no password information exported. when I use "python manage.py loaddata user.json", how to ensure it also loads the password of users, so that users can login the new website? -
FOREIGN KEY constraint failed Django Models
I'm creating a small-ish django application using AllAuth for the authetncation, which I have customised myself to include some additional fields. Part of the sites functionality requires me to refrence the logged in user through a Foreign Key multiple times and I'm approaching this through the custom model I created, called UserProfile; (I tried Django's User model & this also gave me errors) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') phone_number = models.CharField(max_length=30, null=False) postcode = models.CharField(max_length=500, null=True, blank=True) town_or_city = models.CharField(max_length=40, null=True, blank=True) street_address1 = models.CharField(max_length=80, null=True, blank=True) street_address2 = models.CharField(max_length=80, null=True, blank=True) county = models.CharField(max_length=80, null=True) I'm referencing the above model in the activity table: class Activity(models.Model): class Meta: verbose_name_plural = 'Activities' activity_id = models.CharField(max_length=32, null=False, editable=False) host = models.ForeignKey(UserProfile, on_delete=models.CASCADE) name = models.CharField(max_length=254, null=False, blank=False) date = models.DateField() start_time =models.TimeField() end_time = models.TimeField() duration = models.DurationField(blank=True, null=True) location = models.CharField(max_length=40, null=False, blank=False) description = models.CharField(max_length=140, null=False, blank=False) available = models.BooleanField(default=True) Everything works smoothly, as I can use this to create one activity per user, however I want to make this a Many to One field, which required me to update from settings.AUTH_USER_MODEL to the Foreign Key. Unfortunately, I'm getting the following error: FOREIGN KEY constraint failed when … -
How to get information from option field in django?
I have django application with authentication and I have dropdown menu inside. Before I did it like: <select name="country" id="id_category" data="{{ data.country }}"> {% for each in living_countries_list %} <option name="country" value="{{ each.0 }}" class="living_countries">{{ each.1 }}</option> % endfor %} </select> And now I changed it to: <input list="brow" placeholder="Search for your country..." class="input_country"> <datalist id="brow"> {% for each in living_countries_list %} <option name="country" value="{{ each.0 }}" class="living_countries">{{ each.1 }}</option> {% endfor %} </datalist> <p class="country_text">Please select your living country</p> In my views.py file I passed context like: country = request.POST.get('country') professors = models.Professor.objects.all() living_countries_list = LIVING_COUNTRIES print(country) In models.py I have options like: LIVING_COUNTRIES = [ ('AFGANISTAN', 'Afganistan'), ('ALBANIA', 'Albania'), ('ALGERIA', 'Algeria'), ('ANGORRA', 'Andorra'), ('ANGOLA', 'Angola')] class Professor(models.Model): country_living = models.CharField(max_length=50, choices=LIVING_COUNTRIES, default=FRESHMAN, blank=True, null=True) So I have few options which are displayed either way but in changed I can type in input and that's what I want to be able to do. If you want me to post anything else let me know in comments