Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Apply filter to nested reverse Foreign Key using queryset
Context I am trying to filter a list of objects based on the value of a reverse foreign key attribute. I was able to solve it at the view level but, but other attempts to solve using ORM feature result in additional queries. The outcome I want to is queryset with all objects, but related fkey objects are filtered inside each object. Sample Models class Student(models.Model): name = models.CharField(max_length=128) class Subject(models.Model): title = models.CharField(max_length=128) class Grade(models.Model): student = models.ForeignKey("Student", related_name="grades", on_delete=models.CASCADE) subject = models.ForeignKey("Subject", related_name="grades", on_delete=models.CASCADE) value = models.IntegerField() Given the Fixtures +------+------------------------+ | name | subject | grade_value | +------+----------+-------------+ | beth | math | 100 | | beth | history | 100 | | beth | science | 100 | | mark | math | 90 | | mark | history | 90 | | mark | science | 90 | | mike | math | 90 | | mike | history | 80 | | mike | science | 80 | +------+----------+-------------+ Desired Outcome Let's say I want to render a list of students, but only include math and history grades. eg. GET students/grades/?subjects=math,history subject might be provided through request or hard coded. not sure yet, but … -
django-tables2 table is not displayed anymore when e-mail form is added
I face a problem that my django-tables2 disappears when I add an e-mail form to my website. I think the problem lies in urls.py but I really can't figure out what is causing the problem (I'm learning django). urls.py urlpatterns = [ path('',PersonListView.as_view()), path('', views.email, name='email'), ] models.py class Person (models.Model): name = models.CharField(max_length=100, verbose_name="full name") views.py class PersonListView(SingleTableView): Person.objects.all().delete() CSV_PATH = 'data/names.csv' with open(CSV_PATH, newline='') as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar=',') for row in spamreader: Person.objects.create(name=row[0]) author=row[2]) model = Person table_class = PersonTable template_name = 'blog/people.html' def email(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['youremail@gmail.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('thanks') return render(request, "blog/email.html", {'form': form}) def thanks(request): return HttpResponse('Thank you for your message.') forms.py class ContactForm(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea) people.html {% extends 'blog/base.html' %} {% load render_table from django_tables2 %} {% block people %} <div> {% render_table table %} </div> {% endblock %} Could anyone help me to figure out how I could get a django-tables2 and an e-mail form on the same main page? Thank you in advance! -
Django - object is not creating after form.save()
In my django application there are some tasks, and users can write solutions or feedbacks. I'm doing this with form.save(), but this feedback object is not creating in database. My views.py codes are like: def task_details(request, slug): if slug: task = get_object_or_404(Task, slug=slug) form = CreateFeedbackForm() if request.method == 'POST': form = CreateFeedbackForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: form = CreateFeedbackForm() messages.info(request, 'Feedback uğurla göndərildi.') context = { 'task': task, 'form': form, } return render(request, 'task-details.html', context) What is not correct in my code, help please. -
Django - Cannot assign "2": "Wallet.coin" must be a "Coins" instance
This my code and i see error "Django - Cannot assign "2": "Wallet.coin" must be a "Coins" instance." , please help. I’ve been looking for a reason for 10 hours, I can’t decide. And maybe there are still mistakes? Thanks views.py def load_user_balance(request, wallet_id, imei): try: user = User.objects.get(imei=imei) except ObjectDoesNotExist: create = User.objects.create(imei=imei, wallet_mx=wallet_id) create.save() url_wallet = f"https://explorer-api.minter.network/api/v1/addresses/{wallet_id}" response_wallet=requests.get(url_wallet).json()['data'] for coin in response_wallet['balances']: coin_w = coin['coin'] amount_w = coin['amount'] coin_id_1 = Coins.objects.get(symbol=coin_w) coin_id = coin_id_1.id user_id = User.objects.get(imei=imei) user_id_1 = user_id.id obj, created = Wallet.objects.update_or_create(user_id_id=user_id_1, coin=coin_id, amount_w=amount_w, defaults={'user_id_id': user_id_1, 'coin': coin_id, 'amount_w': amount_w}, ) obj.save() models.py class Coins(models.Model): name = models.CharField(max_length=150) symbol = models.CharField(max_length=45) crr = models.CharField(max_length=3) class User(models.Model): imei = models.CharField(max_length=100) wallet_mx = models.CharField(max_length=50) class Wallet(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) coin = models.ForeignKey(Coins, on_delete=models.CASCADE) amount_w = models.DecimalField(max_digits=19, decimal_places=4) amount_d = models.DecimalField(max_digits=19, decimal_places=4) cap_w = models.DecimalField(max_digits=19, decimal_places=4) cap_d = models.DecimalField(max_digits=19, decimal_places=4)