Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is my Django model organization involving a ManyToManyField and list_display efficient
I'm trying to modelise the projects undertaken by a company, where each project can have an arbitrary number of tags which relate to specific aspects of the project. An example would be a project whose language would be French, therefore the project would have a language tag whose value is french. However, any project can have an arbitrary amount of tags which point themselves to an arbitrary value. My goal is customizing the ModelAdmin of Django so that the list_view will display a column for each tag pointed to by the ManyToMany field of the project handled by said ModelAdmin Here's what I have so far models.py from django import models class Tag(models.Model): category = models.CharField(max_length=500, blank=False) value = models.CharField(max_length=500, blank=False) class Book(models.Model): name = models.CharField(max_length=500, blank=False) tags = models.ManyToManyField(max_length=500) admin.py @admin.register(Book) @admin.register(Tag) class BookAdmin(admin.ModelAdmin): list_display = ('name', 'tags') def tags(self, object): tags = object.tags.all() output = "" for tag in tags: output += "{0} : {1}".format(tag.category, tag.value) return output For now the solution only works for displaying all tags in one column. Any possible paths I could take to solve this problem ? -
How can i add phone number and data of birth to this signup from?
i want to add phone number and date of birth(dd/mm/yyy) for this form how can i add it? Views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from .forms import * def home(request): context = {} return render(request, 'authenticationapp/home.html', context) def signup(request): signup_form = SignUpForm() if request.method == 'POST': signup_form = SignUpForm(request.POST) if signup_form.is_valid(): signup_form.save() user = signup_form.cleaned_data.get('username') messages.success(request, 'Hi'+ ' '+user+ ' ' +'Your Account Created Successfully...') return redirect('signin') context = {'signup_form':signup_form} return render(request, 'authenticationapp/signup.html', context) forms.py from .views import * from .models import * from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] signup.html <h1>SignUp</h1> <form method="POST" action=""> {% csrf_token %} {{ signup_form.as_p }} <input type="submit" name="SignUP"> </form> i want to add phone number and date of birth(dd/mm/yyy) for this form how can i add it? -
how to display the values from .py file in web browser using django?
I am having the .py file which is printing values in command prompt when I run but I need it to be print in web browser can anyone say how can I achieve this? my .py file is # Here using selenium for scraping # importing necessary modules import selenium.webdriver from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By # the relevant url url = 'https://web.bet9ja.com/Sport/SubEventDetail?SubEventID=76512106' driver = webdriver.Chrome(r"c:/Users/SATYA/mysite/chromedriver") driver.get(url) driver.implicitly_wait(10) # seconds elements = [ item.text for item in driver.find_elements_by_css_selector("div.SEOddLnk.ng-binding")] print(elements[0:6]) names = [ item.text for item in driver.find_elements_by_css_selector("div.SECQ.ng-binding")] print(names[0:2]) values = [ item.text for item in driver.find_elements_by_css_selector("div.SEOddsTQ.ng-binding")] print(values[0:6]) driver.quit() output coming in command prompt is: ['3.60', '4.20', '1.87', '1.83', '1.19', '1.25'] ['1X2', 'Double Chance'] ['1', 'X', '2', '1X', '12', 'X2'] My requirement is to get the same output in the web browser can anyone help me? -
'docker-compose up' hangs when attaching files for running Django server in virtualization
I'm trying to run Django inside a Docker container and connect to it using VS code remote, but it keeps hanging at the attach part. Here is my Dockerfile FROM registry.gitlab.com/datadrivendiscovery/images/primitives:ubuntu-bionic-python36-v2020.1.9 ENV PYTHONPATH=$PYTHONPATH:/app WORKDIR /app/ EXPOSE 8000 COPY requirements.txt /app/requirements.txt WORKDIR /app RUN pip install --upgrade pip RUN pip install -r requirements.txt CMD ["sh", "-c", "python3 /app/manage.py runserver"] COPY . . My docker-compose.yml version: '3' services: web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" I don't have a database setup so I don't have that in the yml. -
In Django how to querry High, Medium, Low in order?
I want to querry my priority data in order(Low, Medium, High) but it doesnt querry well views.py @allowed_users(allowed_roles=['teamleader']) def bug_list(request): bug = Bug.objects.all().order_by('priority') total = Bug.objects.all().count() content = { 'form_list': Bug.objects.all(), 'total': total, } return render(request, 'app/bug_list.html',content) models.py class Bug(models.Model): priority_choices=( ('Low','Low'), ('Medium','Medium'), ('High','High'), ) status_choices=( ('New','New'), ('Pending','Pending'), ('Fixed','Fixed'), ) bugtitle = models.CharField(max_length=100) description = models.TextField(null=True, blank=True) priority = models.CharField(max_length=10, choices=priority_choices,null=True, blank=True) status = models.CharField(max_length=10, choices=status_choices,null=True, blank=True) developer = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) screenshot = models.ImageField(upload_to='screenshot', null=True, blank=True) deadline = models.DateField(auto_now=True,null=True, blank=True) comment = models.TextField(null=True, blank=True) def __str__(self): return self.bugtitle I have tried using dictionary but it still fails -
I want to display all the products related to one particular shop in Django?
Views.py matching_product = Product.objects.filter(shop__shop_slug=single_slug) return render(request, 'products/shop_products.html',{"part_ones":matching_product}) urls.py path("<single_slug>",views.single_slug, name="single_slug") shop_products {% for shops in matching_product %} shop.html (for url) <a href="{{shop.shop_slug}}"><strong>{{shop.shop_location}}</strong></a> It is not displaying any products -
What is the best way to get all linked instances of a models in Django?
I am trying to create a messaging system in Django, and I came across an issue: How could I efficiently find all messages linked in a thread? Let's imagine I have two models: class Conversation(models.Model): sender = models.ForeignKey(User) receiver = models.ForeignKey(User) first_message = models.OneToOneField(Message) last_message = models.OneToOneField(Message) class Message(models.Model): previous = models.OneToOneField(Message) content = models.TextField() (code not tested, I'm sure it wouldn't work as is) Since it is designed as a simple linked list, is it the only way to traverse it recursively? Should I try to just get the previous of the previous until I find the first, or is there a way to query all of them more efficiently? -
Django TypeError 'ChoiceField' object is not iterable
I have written this by amalgamating other suggestions, which I thought might work for the logic that I'm using to produce this Select field. I want the first in the dropdown to be pulled from the Student model, if it isn't null. If it is null, then display the options without an initial attribute. Template: schedule.html <section id="AddEventPopup"> <form> <select name="teacher" id="teacher_select"> {% for teacher in teacher_availability_form.teacher_select_options %} {{ teacher.tag }} {% endfor %} </select> </form> <button class="AddEventPopup_close">Close</button> </section> forms.py class TeacherAvailabilityForm(forms.Form): def __init__(self, *args, **kwargs): sid = kwargs.pop('sid') default_teacher = StudentProfile.objects.has_default_teacher(sid) TEACHER_CHOICES_QUERYSET = TeacherProfile.objects.available_teachers() names = [] for teacher in TEACHER_CHOICES_QUERYSET: teacher_id = teacher[0] teacher_name = teacher[1] + ' ' + teacher[2] teacher_tuple = (teacher_id, teacher_name) if teacher[0] == default_teacher: names.insert(0, teacher_tuple) INITIAL_TEACHER = teacher_tuple else: names.append(teacher_tuple) TEACHER_CHOICES = tuple(names) super(TeacherAvailabilityForm, self).__init__(*args, **kwargs) if default_teacher: self.teacher_select_options = forms.ChoiceField( label='Pick a Teacher', initial=INITIAL_TEACHER, choices=TEACHER_CHOICES, widget=forms.Select, required=True) else: self.teacher_select_options = forms.ChoiceField( label='Pick a Teacher', choices=TEACHER_CHOICES, widget=forms.Select, required=True) class Meta: fields = ('teacher_select_options',) views.py def schedule(request): studentid = request.user.id form = TeacherAvailabilityForm(sid=studentid) args = {'student_id': studentid, 'teacher_availability_form': form} return render(request, 'students/schedule.html', args) I'm thinking the init function is causing the error and is not generating the iterable output that I was aiming … -
Django: modify model’s field before saving
I have a model, course, with an ImageField and FileField so I’d like to create a folder each time the user create a course. I think I can do this before the model is saved so here is my question. How can I access a model’s fields in a method? Models.py Class Course(models.Model): Thumbnail = model.ImageField(upload_to=“...”,...) def save(self, *args, **kwargd): ... #How can I alter here the ImageField parameters? super().save(*args, **kwargs) -
How to add a custom serializer to Djoser token field when using Simple JWT?
In the Djoser docs they show you how to add custom serializers to various fields including token and token_create (djoser docs) however I can't seem to be able to add a custom serializer for the token field when using Simple JWT. -
Django FreedTDS: Adaptive Server is unavailable or does not exist
I'm trying to connect Django 3.0 with sql_server.pyodbc but I have next error: jango.db.utils.OperationalError: ('08S01', '[08S01] [FreeTDS][SQL Server]Unable to connect: Adaptive Server is unavailable or does not exist (20009) (SQLDriverConnect)') My DATABASES settings: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': '....', 'USER': 'sa', 'PASSWORD': '....', 'HOST': '....', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server' } } } Can you help me to find the bug, please? Is there another way to connect django wiht SQL Server? -
can we use dynamodb database with django rest framework
i have to work on the project in which i have to use Django rest framework with DynamoDB database. and if not the what are the reasons behind it. -
Python Django Way to check if an email address is a business email?
I'm trying to add a field to validate if an email is personal or a company email. Is there an easy way to recognize a company email. Obviously, not a gmail, yahoo or other common domain. What other specs should I also include? Is there a package that does something like this in Django? -
nginx error - The page you are looking for is temporarily unavailable. Please try again later
I get this following page I am having an error while loading my domain name my /etc/nginx/ngin.conf file is below user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; # Load dynamic modules. See /usr/share/doc/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/sites-enabled/*.conf; server { listen 80 default_server; listen [::]:80 default_server; server_name ec2-3-135-224-122.us-east-2.compute.amazonaws.com; root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/sites-enabled/*.conf; location / { proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 10m; client_body_buffer_size 128k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; proxy_buffers 32 4k; proxy_pass http://unix:/home/ec2-user/medikit_project/app.sock; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } } my nginx file list is list of file in nginx both the file /etc/nginx/sites-available/ && /etc/nginx/sites-enabled/ are empty. even these files are not already in cd /etc/nginx/. I created that separately. MY Goal - … -
Django Rest Framework + django_filters on serialized values
I'm trying to filter on a serialized value that is not on my model but I can't get my head around this. Here is my model.py : class Post(models.Model): post_id_number=models.AutoField(primary_key=True) variable_1 = models.CharField(max_length=50) variable_2 = models.CharField(max_length=50) variable_3 = models.CharField(max_length=50) Here is my Views.py : class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializers queryset = Post.objects.all() filterset_class = PostFilter Here is my serializers.py: class PostSerializers(serializers.ModelSerializer): variable_not_in_the_model = serializers.SerializerMethodField() class Meta: model = Post fields = ('post_id_number', 'variable_1', 'variable_2', 'variable_3', 'variable_not_in_the_model', ) def get_variable_not_in_the_model(self, instance): return instance.variable_1 + ' ' + instance.variable_2 + ' ' + instance.variable_3 Here is my actual filters.py : from .models import Post import django_filters class PostFilter(django_filters.FilterSet): class Meta: model = Post fields = { 'variable_1': ['icontains'], 'variable_2': ['icontains'], 'variable_3': ['icontains'] } Here is what I would like my filters.py to look like but it doesn't work : from .models import Post import django_filters class PostFilter(django_filters.FilterSet): class Meta: model = Post fields = { 'variable_not_in_the_model': ['icontains'] } Is there a way I can Filter on the serialized variables and not on the model's variables ? Thanks so much for your help ! -
Cannot restore postgres dump on heroku
I am using this command to create dump locally PGPASSWORD=admin pg_dump -h 127.0.0.1 -p 5432 -U postgres --no-owner --no-acl -f database.dump and my is created successfully. then uploaded this dump to dropbox and make it public with this link http://www.dropbox.com/s/rsqeiuqzusejz5x/database.dump?dl=1 notice I have changed https to http and dl=0 to dl=1 (dl=1 to make it downloadable) then on my terminal I am running this command heroku pg:backups:restore "http://www.dropbox.com/s/38prh2y7pdwhqqj/database.dump?dl=1" --confirm tranquil-anchorage-39635 but I am getting this error ! An error occurred and the backup did not finish. ! ! pg_restore: error: did not find magic string in file header ! waiting for restore to complete ! pg_restore finished with errors ! waiting for download to complete ! download finished successfully ! ! Run heroku pg:backups:info r010 for more details. I have tried all the official documentation and various answers but nothing seems to work. -
Is Firebase and Django possible?
I want to use Firebase database in place of django's default database ( i.e. Sqlite3 ) for production to store all data including authentication and data of each model. If possible please tell me some library to implement it with its docs or code snippet. -
Do we need to write the translations manually when translating django templates?
I am at a point of a project where I have to use Internationalization and for that, I just added trans to the template strings that I want to translate. I also performed "Django-admin.py make messages".Now it just created the .po file where I have to fill my translations into but the question is I have almost 40 strings that need to be translated. Do I have to manually do that? I mean literally just finding out the translation for a string and then copy-pasting that or is there in automation tool I could use? -
How to get fields from Serializer into ListView for filtering
the model in question: class CustomerPrices(models.Model): url = models.OneToOneField('CustomerProductUrls', models.DO_NOTHING, db_column="url", primary_key=True) written = models.DateTimeField() reseller = models.CharField(max_length=250) price = models.FloatField(blank=True, null=True) class Meta: managed = False db_table = 'customer_prices' unique_together = (('url', 'written', 'reseller'),) the serializer (and one related serializer) in question: class CustomerProductUrlsSerializer(serializers.ModelSerializer): ean = CustomerProductsSerializer() url = serializers.CharField(max_length=255, required=False) class Meta: model = CustomerProductUrls fields = '__all__' class CustomerPricesSerializer(serializers.ModelSerializer): written = serializers.DateTimeField(format='%Y-%m-%d %H:%M:00', required=False) reseller = serializers.CharField(max_length=250, required=False) url = CustomerProductUrlsSerializer() name = serializers.SerializerMethodField('get_name') ean = serializers.SerializerMethodField('get_ean') url = serializers.SerializerMethodField('get_url') price = serializers.FloatField() class Meta: model = CustomerPrices fields = '__all__' def get_name(self, obj): return obj.url.ean.name def get_ean(self, obj): return obj.url.ean.ean def get_url(self, obj): return obj.url.url and the ListAPIView for the CustomerPrices class: class CustomerPricesListView(generics.ListAPIView): serializer_class = CustomerPricesSerializer filter_backends = (DjangoFilterBackend, OrderingFilter) fields = ('written', 'url', 'price') filter_fields = fields search_fields = fields def get_queryset(self): """ This view should return a list of all the products where price >= 70 """ return CustomerPrices.objects.filter(price__gte=70) Inside my CustomerPricesSerializer I've got a field named ean as well as name the values for these two come through the related CustomerProductUrlsSerializer (and corresponding model). The code is working so far, I get a response looking like this: "results": [ { "url": "https://www.example.com/p/12345678", … -
Show numpy array as image in Django
I am new to Django framework. I am building a website that take an image from user, then process the image and return to a numpy array (processed image). I want to show the numpy array as image. How can I do that? Thank you for reading and helps? index.html <form name="image" method = "post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> Index view def index(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): model = MyDeepLearningModel.get_instance() file_name = request.FILES['file'] processed_image = model.run_png(file_name) #processed_image is an numpy array #how to show the processed_image in index.html? return render(request, 'lowlighten/index.html') else: form = UploadFileForm() return render(request, 'lowlighten/index.html', {'form': form}) -
Django: Include Duplicates in id__in query
How can I include duplicates when using an id__in query through an intermediary model? Example: inventory = InventoryItem.active_objects.filter(owner=self) if not inventory: return None return Item.objects.filter(id__in=list(inventory.values_list("item_id", flat=True)) In this example, a user might have 3 of the same InventoryItem (which is the intermediary model), but only one item will be returned from the following queryset. -
Django not applying full CSS to html
I currently have an HTML and CSS file made. Both display the website the way I want it to (picture). Now what I want to do is have a Python script running as well so I setup django. The problem I am currently encountering is that the CSS is only being applied to the button and not the entire index.html I have {% load static %} as well as my settings to include the static folder of the CSS. Can someone explain where I went wrong to not have it apply the CSS to the entire file? It is currently rendering like this decreased the size of the picture so it could be shown. Card wont display properly neither would the background color. HTML: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Card layout</title> <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"/> <link href="https://fonts.googleapis.com/css2?family=Dancing+Script&display=swap" rel="stylesheet"> </head> <body> <h1 class="StorySpinner"><u>Story Spinner</u></h1> <main> <section class="cards"> <div class="card"> <div class="card__image-container"> <img src="https://images.unsplash.com/photo-1528561156510-aba26bedef10?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80"/> </div> <div class="card__content"> <p class="card__title text--medium"> Watermelon Bicycle </p> <div class card="card__info"> <button><p class="card__price text--medium">Select</p></button> </div> </div> </div><div class="card"> <div class="card__image-container"> <img src="https://images.unsplash.com/photo-1528561156510-aba26bedef10?ixlib=rb-1.2.1&auto=format&fit=crop&w=1200&q=80"/> </div> <div class="card__content"> <p class="card__title text--medium"> Watermelon Bicycle </p> <div class card="card__info"> … -
Correct if/else statement syntax for django templates
I have a dating app and I need to create a link that is underneath each profile that a user matches on. Then, that link should pass their user id into the template so that messages are only displayed between the current user and that particular user based on the user id. I am having trouble here with the syntax of if/else statements within the Django template. How would I go about doing this? messages.html <div id="msg-list-div" class="panel-body"> <ul id="msg-list" class="list-group"> <br><br><br> {% for obj in messages %} {% if obj.sender == request.user and obj.receiver == profile%} {% if obj.sender == request.user%} <li class="text-right list-group-item">{{obj.message}}<br>{{ obj.date }}<li> {% elif obj.receiver == profile %} <li class="text-left list-group-item">{{obj.message}}<br>{{ obj.date }}<li> {%endif%} {%endif%} {% empty %} <li class="text-right list-group-item">No messages yet...Keep mingling!</li> {% endfor %} </ul> </div> matches.html/ href link for messages.html <p><a href="{% url 'dating_app:messages' profile.id %}">chat</a></p> views.py/messages def messages(request, profile_id): messages = InstantMessage.objects.all() profile = get_object_or_404(Profile,id=profile_id) return render(request, 'dating_app/messages.html', {'messages': messages,'profile':profile,}) models.py class ProfileManager(BaseUserManager): def create_user(self, username, email,description,photo, password=None): if not email: raise ValueError("You must creat an email") if not username: raise ValueError("You must create a username!") if not description: raise ValueError("You must write a description") if not photo: raise ValueError("You … -
djongo with rest_framework_simplejwt.token_blacklist gives create table error
Currently I started a project to learn more of django + jwt and react. Instead of using sql I used mongodb with django instead by using djongo. It works pretty well setting things up, creating new model to test out. So I started looking for django + jwt tutorials and come upon this tutorial https://hackernoon.com/110percent-complete-jwt-authentication-with-django-and-react-2020-iejq34ta Everything works fine up until the end about blacklisting tokens I have my settings.py as suggested SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=14), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUTH_HEADER_TYPES': ('JWT',), 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', } by making the BLACKLIST_AFTER_ROTATION to True, I need to do a migration by python manage.py migrate This is where the error happens, error I got is djongo.sql2mongo.SQLDecodeError: FAILED SQL: CREATE TABLE "token_blacklist_blacklistedtoken" ("id" int32 NOT NULL PRIMARY KEY AUTOINCREMENT, "blacklisted_at" date NOT NULL) I was poking around and couldn't get a solution so I tried changing db back using mysql instead, then the migration worked like a charm. Does anyone know if I do keep using mongodb instead of mysql, is there a workaround for this migration and functionality to work? Thanks in advance for any advices. -
Django: view drop-down-box selection in admin
I have a drop down box as follows: <form action="PageObjects" method="post"> <select name="size"> <option value ="Small">Small</option> <option value ="Medium">Medium</option> <option value ="Large">Large</option> </select> </form> I want to receive the user's input from this selection and collect it in admin.py, such as: class OrderAdmin(admin.ModelAdmin): list_display = ['user', 'ordered', 'size'] How do I save each user's selection?