Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible in Django to have 2 different types of users with theirs own login fields in the same app?
I have 2 types of users on my site, one is the store owner, I want to log him in with the usual custom user email and password, the other is the buyer, I want to login the buyer using just a pin number only. Is it possible to have both types of login users in the same django app. Thanks in advance. -
Making a web game in django?
Does anyone have advice on how to make a web game using Django? I have found one tutorials that combines Django channels and React, but it was outdated. -
axios put request doesn't work while performing an Update operation
While writing CRUD operations, I had troubles editing my data table, it doesn't update the database (I used axios, vuejs and vuetify in frontend and django rest framework in the backend): this is my frontend page (vuejs page) <v-container> <v-row> <v-col> <v-text-field v-model="editedItem.category_name" label="Nom Catégorie" ></v-text-field> </v-col> </v-row> </v-container> </v-card-text> <v-card-actions> <v-spacer></v-spacer> <v-btn color="blue darken-1" text @click="save" > Sauvegarder </v-btn> </v-card-actions> <script> import axios from 'axios'; export default { name: 'user-profile', data: () => ({ dialog: false, dialogDelete: false, headers: [ { text: 'category_id', value: 'category_id' }, { text: 'category_name', value: 'category_name'}, { text: 'Actions', value: 'actions'}, ], categories: [], editedIndex: -1, editedItem: { category_id: 0, category_name: '', }, defaultItem: { category_id: 0, category_name: '', }, }), save () { if (this.editedIndex > -1) { Object.assign(this.categories[this.editedIndex], this.editedItem) console.log('edited data'); axios.put('http://127.0.0.1:8000/api/categories/'+this.editedItem.category_id,{category_id:this.editedItem.category_id, category_name:this.editedItem.category_name}) .then(response=>{ console.log(response); }) </script> Here is my models.py file : from django.db import models # Create your models here. class Categories(models.Model): category_id = models.AutoField(primary_key=True) category_name = models.CharField(max_length=250) -
Files not available in docker volume: only recover old files
I am a bit lost with my Django app configured with docker. Stack: Django/Celery/Celery-beat/Gunicorn/Nginx/Postgresql/Docker So I have an app with automatic Postgresql database backup using dbbackup (django app that make backup) app and Celery/Celery-beat (run command to make backup every hour for example). I can build and run my project but something is going wrong with my backup files. backup are done and store locally where expected. But in my web container, I can only see old backup that are not more locally in my app (but probably in persistent folders) so vene if I was able to remove this old files, problem will still be the same as new backup are not available in container I run docker-compose -f docker-compose-preprod.yml down -v to remove all volumes and rebuild container but doesn't change anything So locally I have - django-project - app - backup <- backup are made every hour and store in this bvackup folder - backup_2021-01-19-1600.psql - backup_2021-01-19-1700.psql - ... - manage.py - core But when I 'jump' into my web container with docker exec -it web sh - usr - src - app - backup - backup_2021-01-18-0800.psql <- different backup files - backup_2021-01-18-0900.psql <- different backup files … -
django app how to get a string from a function before
I am building a django app in which the user has to write a sentence in a text box. This sentence gets then sent to the server and received by it. After that the user has to click on continue and gets on a another html page. Here the user has to record an audio of a word he sais. The word is then turned into a string and after that sent to the server. Now I would like the function in views.py to find out if the word the user said is in the sentence the user wrote before. But the sentence is only in the first function that receives the sentence after it is sent. I know I could first store the sentence but is there also another way? -
Discord bot doesn´t connect
I have created this little sample code for a discord bot, but when i try to connect i get the following error. import discord import os from discord.ext import commands from dotenv import load_dotenv import urllib.request import json load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') bot = commands.Bot(command_prefix='¿') # prefix del bot @bot.event async def on_ready(): await bot.change_presence(activity=discord.Streaming(name="Tutorial", url="http://www.twitch.tv/palmart69")) print('bot listo') @bot.command(pass_context=True) async def ping(ctx): await ctx.send("Pong!") @bot.command(name='suma') async def sumar(ctx, num1, num2): response = int(num1) + int(num2) await ctx.send(response) bot.run(TOKEN) --------ERROR------------------ Traceback (most recent call last): File "C:\Users\Alvaro\PycharmProjects\bot-pruebas\venv\lib\site-packages\aiohttp\connector.py", line 969, in _wrap_create_connection return await self._loop.create_connection(*args, **kwargs) # type: ignore # noqa File "C:\Users\Alvaro\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 1081, in create_connection transport, protocol = await self._create_connection_transport( File "C:\Users\Alvaro\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 1111, in _create_connection_transport await waiter File "C:\Users\Alvaro\AppData\Local\Programs\Python\Python39\lib\asyncio\sslproto.py", line 528, in data_received ssldata, appdata = self._sslpipe.feed_ssldata(data) File "C:\Users\Alvaro\AppData\Local\Programs\Python\Python39\lib\asyncio\sslproto.py", line 188, in feed_ssldata self._sslobj.do_handshake() File "C:\Users\Alvaro\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 944, in do_handshake self._sslobj.do_handshake() ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1123) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Alvaro\PycharmProjects\bot-pruebas\main.py", line 31, in bot.run(TOKEN) File "C:\Users\Alvaro\PycharmProjects\bot-pruebas\venv\lib\site-packages\discord\client.py", line 718, in run return future.result() File "C:\Users\Alvaro\PycharmProjects\bot-pruebas\venv\lib\site-packages\discord\client.py", line 697, in runner await self.start(*args, **kwargs) File "C:\Users\Alvaro\PycharmProjects\bot-pruebas\venv\lib\site-packages\discord\client.py", line 660, in start await self.login(*args, bot=bot) … -
Django UpdateView using formset and bootstrap fails
I'm new to django and I'm trying to write an application that given an activity allows me to save the information of the partecipants (i.e. Person) and how long the partecipation was. I was able to setup a CreateView, with bootstrap and JavaScript to allow my formset to be dynamic and I'm able to register the activity and the partecipants though the create view. However, when I try to modify an already existing activity, using an UpdateView, I get several errors. I tried to reproduce a minimal example of my problem and I got the error "This field is required" that is one of the error I obtain in my main application. I'm trying also to reproduce the second error: the instruction formset.is_valid() in views.py return False since it has an Activity already linked to the Person (violating the unique_together rule). This happens everytime: even if I'm just trying to add a second person to the form without changing anything about the first one. Please, let me know if I missed some files: here's the small example. models.py from django.db import models # Create your models here. class Person(models.Model): surname = models.CharField(max_length=30) class Activity(models.Model): name = models.CharField(max_length=30) person = models.ManyToManyField(Person, … -
Select a valid choice Django Filtered Drop Down Menu
Devs, In my project I have a form that has a field that has a student name selection, it is a drop down field by the students that are currently enrolled in that particular class. It gets this information from table Section Enrollment than checks the master Student table. The filtering works out correctly, however when I submit my form, it says the student name is not a valid choice. My guess is because its submitting that student name and not a ID, I'm not 100% sure. Here is my models and view. I don't know how to fix this. Appreciate that help. QUERY IN QUESTION: getstudents = SectionEnrollment.objects.filter(section_id=classid).select_related().values_list('studentpsid_id__student_name', flat = True) MODELS: # Creation of Classrooms and Assigned Teachers class SectionEnrollment(models.Model): sectionenrollmentpsid = models.CharField(primary_key = True,max_length = 50, default = "") section = models.ForeignKey(Section,on_delete = models.PROTECT, default = "" ,) studentpsid = models.ForeignKey(Student,on_delete = models.PROTECT, default = "" ,) entry_date = models.DateField(blank=True) exit_date = models.DateField(blank=True) dropped = models.BooleanField(default = False, blank = True) class Meta: verbose_name = "Student Section Enrollment" def __str__(self): return self.sectionenrollmentpsid # Where Basic Student Data Is Stored class Student(models.Model): studentpsid= models.CharField(primary_key = True , default = "", max_length = 50, unique = True) student_name = … -
Display django form initial without brackets
I have a object from query object_query = werknemer_object_query = user.objects.filter(profile__werkgevers_id=werkgeversId) Created f string based on query result = [f"{item.first_name} {item.last_name}" for item in werknemer_object_query if item.pk == int(werknemer_get)] ---> this creates a list form initial with created f string form.initial = {"test": result} In html page when i call this field test its beeing displayed as ["result"] so with brackets. How can i get instead of ["result"] just result. -
DRF Serialize only selected keys of JSONField
I want to serialize specified key:value pair of JSONField in DRF but not the whole JSON. What I got from their website: Starting from Django Rest Framework 3.12, the JSONField of Django is supported. Nested search with JSONField started to be supported with double underscore notation as used in Django itself. You can read the exact statement from https://www.django-rest-framework.org/community/3.12-announcement/#support-for-jsonfield But I didn't find anything related to my problem. When I use double underscore notation for serialization (ex. details__link), I get error saying model doesn't contain that field. -
Django Register Page refill input data after site reload
Im looking for a solution to refill my select fields of a Register Page after a site reload, if the user has given invalid data and should correct the problem. The use of the Django Template works fine on the input field. There I can just give the value of the tag a django variable and when the variable is filled it gets displayed. But on the birthdate selections i have to use an if statement for every option that sets the select attribute selected="selected". And this for 31 days, 12 months and around 90 years. So there are 133 if statements and I think this is slowing down the backend unecesserily. I try to avoid java script and I have some safety concerns about window.sessionStorage so I would rather use my way with Django Templates. Do you know a more elegant solution for refilling a select field? the function: ``` def registerPage(request): context = {} #needed for the value rebuild when user has to reload the register page if request.method == 'POST': first_name = request.POST.get('fname') last_name = request.POST.get('lname') password1 = request.POST.get('password1') password2 = request.POST.get('password2') email = request.POST.get('user_email') birth_day = request.POST.get('bday') birth_month = request.POST.get('bmonth') birth_year = request.POST.get('byear') gender_type = request.POST.get('gender_type') … -
Join tables which doesnot have any relation but common field
I have two tables clinicalvariable and adherencemeasure. I need to get all records which satisfies condition clinicalvariable.id = adherencemeasure.id. Both tables donot have any foreign key relation so i couldn't use select_related. I need to use Subquery in django.Similar postgres query select * from clinicalvariable as a, adherencemeasure as b where a.id = b.id I tried below code but no luck with it cvar = Clinicalvariable.objects.filter(pmdclinicalvariablerefid=OuterRef('pk')).values('pmdclinicalvariablerefid') Adherencemeasure.objects.filter(crefadherencemeasureid=Subquery(cvar)) I am getting more than one row returned by subquery. -
Django template inheritance doesn't seem to work properly
So I'm trying to use Django inheritance in a program but it doesn't really work, and I'm sure it's something trivial that I'm messing up. It's a simple webpage that saves the birthdays of people and stores them into a database. I'll only be showing the HTML files because I already know that the Python files work. Take a look. That's the default layout template. <!DOCTYPE html> <html lang="en"> <head> {% block head %}{% endblock %} </head> <body> {% block body %}{% endblock %} </body> That's the other template called "index.html". {% extends "layout.html" %} {% block head%} <meta name="viewport" content="initial-scale=1, width=device-width" <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet"> <link href="/static/styles.css" rel="stylesheet"> <title>Birthdays</title> {% endblock %} {% block body %} <div class="jumbotron"> <h1>Birthdays</h1> </div> <div class="container"> <div class="section"> <h2>Add a Birthday</h2> <form action="/" method="post"> <input name="name" autocomplete="off" autofocus type="text" placeholder="Name"> <input name="month" autocomplete="off" autofocus type="text" placeholder="Month"> <input name="day" autocomplete="off" autofocus type="text" placeholder="Day"> <input type="submit" value="Add Birthday"> </form> </div> <div class="section"> <h2>All Birthdays</h2> <table> <thead> <th>Name</th> <th>Birthday {% for name in name %} </thead> <tbody> <tr> <td> {{ name.name }} </td> <td> {{ name.month }}/{{ name.day }}</td> </tr> {% endfor %} </tbody> </table> </div> </div> {% endblock %} I get a 500 Internal error and … -
WebRTC: ICE failed error in browser with Mesibo Video/Audio chat
I am working on a video/audio chat application in React and Django using Mesibo Javascript SDK. It is working locally on the same network but when trying to connect through different networks, Firefox browser gives me this error WebRTC: ICE failed, add a TURN server and see about:webrtc for more details. In Chrome, this error doesn't show up but still the video/audio chat is not working and gives me Mesibo_OnCallStatus: 50. I noticed that Mesibo uses stun:stun.l.google.com:19302 as the STUN server and tried changing it to stun:stun.l.google.com:19305 but of no use. I even created a numb.viagenie.ca account to add a TURN server which worked for a few minutes and then gave this error webrtc: ice failed, your turn server appears to be broken. When checked on https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/, chrome is giving error code:701 for all the above turn/stun servers whereas firefox doesn't. As suggested by Mesibo Documentation, my website is fully secure with https and the Rest APIs are called from Django backend. I'm invoking https://api.mesibo.com/mesibo.js as a script tag in the index.html file in react. I'm also able to successfully get Mesibo_OnConnectionStatus=1 and the incoming call notification is also working. Upon answering the call, the call status changes from 3 … -
Anyone out there have advice for deploying a Django/React app to heroku?
I wanted to open a thread to see how people have had success in doing so. I have viewed a couple articles, like this, but I was hoping to hear more perspectives. Also, as I am running a docker container in development, I was wondering if people had any example dockerfiles for deploying a react/django app to heroku. -
Update ImageField using Django Rest Framework
I am using REST framework for creating APIs. I have ImageField to store Images. class GeneralInfo(models.Model): logo = models.ImageField(upload_to="logo/") school_name = models.CharField(max_length=50) address = models.CharField(max_length=50) Now using PUT request, I want to update the logo which is ImageField. Serializer class looks like this: class GeneralInfoSerializer(serializers.ModelSerializer): class Meta: model = GeneralInfo fields = ["id", "school_name", "address"] def create(self, validated_data): return GeneralInfo.objects.create(**validated_data) def update(self, instance, validated_data): instance.logo = validated_data.get("logo", instance.logo) instance.school_name = validated_data.get("school_name", instance.school_name) instance.address = validated_data.get("address", instance.address) What am I missing? -
How to filter a field by its belonging to the model defined in the original model in Django?
For example I have such models: class Person(models.Model): ... class Group(models.Model): persons = models.ManyToManyField(Person, through='Membership') ... class Membership(models.Model): group = models.ForeignKey(Group) person = models.ForeignKey(Person) class Team(models.Model): group = models.ForeignKey(Group) ... class TeamPerson(models.Model): team = models.ForeignKey(Team) person = # Question about this # So Membership links the Person with the Group and we have Team that relates to a Group. The thing what I need to do is to use in TeamPerson the persons related through the Team -> Group -> Membership -> Person so Django knows that I can choice only the persons that are in the group choose for the team that was choose in the TeamPerson. Actually what I expected is automatic filtering the persons in the TeamPerson admin page when I choice the team. Is there a (right) way to do that? -
Is there any way to add html file dynamically from django admin?
I am very new to django. I want to include html file from django admin dashboard. Let me explain a little. Let, My model is like below class myModel(models.Model): fileName= models.CharField(max_length=100) my views.py file def calcView(request): template_name = 'index.html' filename = Adsense.objects.first() context = {} context['filename'] = filename return render(request, template_name, context) Now i enter filename in as 'anyfile.html'. It already available in template folder. Now in index.html file how can i it from dashboard. Pseudo code {% include "{{ filename.fileInclude}}" %} Is it possible ?? if yes, how can I do this ? Thanks in advance -
Refactoring part of template into own file breaks django
I have something weird: I got a base.html that acts as a skeleton with blocks for the website. It contains this part: <main class="main"> {% block main %} <div class="content"> {% block content %} content {% endblock %} </div> {% endblock %} </main> I also got a base_with_sidebar.html that looks like this: {% extends "core/base.html" %} {% block main %} {{ block.super }} <div class="sidebar"> {% block sidebar %} {% include "polls/recent_polls.html" %} {% endblock %} </div> {% endblock %} and index.html which fills the content: {% extends "app/base_with_sidebar.html" %} {% block content %} somecontent {% endblock %} This all works so far. The problem arises if I want to refactor base.html: from this: <main class="main"> {% block main %} <div class="content"> {% block content %} content {% endblock %} </div> {% endblock %} </main> to this: base.html <main class="main"> {% block main %} {% include './main.html' %} {% endblock %} </main> main.html <div class="content"> {% block content %} content {% endblock %} </div> This results in my index.html always displaying 'content' - instead of the block content specified in index.html -
Using prefetch_related() in Django in combination with raw_id_fields
I'm trying to eliminate queries by prefetch_related(). In the admin with TabularInline this works in all cases, except the ForeignKeyRawIdWidget created by raw_id_fields = ('article',). This is due to the Queryset.get() it does, and filter actions are not supposed to work when prefetching. So for every row in the inline I'll get a seperate query. This blogpost illustrates a workaround: https://blog.mounirmesselmeni.de/2017/02/06/accessing-prefetched-objects-inside-your-models-methods/ The workaround looks quite messy to me, and won't work in this case since the widget does the get. Is there some proper way to do prefetching here or is this a Django prefetching limitation? Not using raw_id_fields is not an option since the default widget does even more queries. Also, I don't understand why filter actions do not check the prefetching cache before actually querying the database. This small step could potentially save multitudes of queries, right? -
You're accessing the development server over HTTPS, but it only supports HTTP. in django
I am building a django app to bookmark images from other sites. But, when I go to any website and click on the "Bookmark" button, I get this error in my terminal: [19/Jan/2021 21:15:00] code 400, message Bad request version ('÷b%2Eí\x10Ð\x80ðB\x90\x00"\x8a\x8a\x13\x01\x13\x02\x13\x03À+À/À,À0̨̩À\x13À\x14\x00\x9c\x00\x9d\x00/\x005\x00') [19/Jan/2021 21:15:00] You're accessing the development server over HTTPS, but it only supports HTTP. I don't get any error in my website though. Is this a problem in my code? -
Is there a way in django to update the same page with the response without totally rendering it?
Is there a way in django to update the same page with the response without totally rendering it. I am trying to create a code editor to test. But when I am returning the results my contents are removed. I understand it is because I am rendering the page . I need the contents to retain. How can I do it using redirect? I am including the render statement I used and a screenshot of how it looks here: Steps: Handle post request Program execution code Save the result in a variable called "message". Then I used return render(request, 'editor.html', {'message': message}) I want to redirect the message to the same page without rendering a new page. [Before submission][1] [After submission][2] [1]: https://i.stack.imgur.com/BxoLU.png [2]: https://i.stack.imgur.com/uiEOU.png Any help will be appreciated. Thank you. -
Can a contains search be made in ElasticSearch in the search query?
I created a django project to learn ElasticSearch and when I search for users in this project, when I enter the username of the user exactly, the result is returned. Can I set this to contains as in django ORM? i use "match" because i just know it. q = request.GET.get('q') users = UserDocument.search().query("match",username=q) -
Posted data doesnt appear on DRF serializer attrs
im having an issue here and cant find out whats happening. I have and DRF REST API which must receive a POST to create an AlertRule object and a couple of EmailAddress objects related to it. The problem is that when debugging the validator method, the email data should come on the attr param on the validator mathod, but its just not there when i send the data obver http post. Example of what im sending: {'alert_event_max_count': 2, 'alert_time_window': 2, 'company': 'Q29tcGFueToxNw==', 'company_id': 17, 'comparison_rule': 4, 'comparison_value': '0', 'daily_start_time': '07:00:00', 'daily_stop_time': '17:59:59', 'emails': [{'email':'bruno.carli@smartgreen.net'}], 'end_date': '2022-01-01', 'installation_ids': [], 'monitored_property_id': 30, 'name': 'kk', 'start_date': '2019-01-01', 'week_day_bitmask':17} The attr only shows: OrderedDict([('alert_time_window', 2), ('alert_event_max_count', 2), ('company', <Company: Company object (17)>), ('comparison_rule', 4), ('comparison_value', '0'), ('daily_start_time', datetime.time(7, 0)), ('daily_stop_time', datetime.time(17, 59, 59)), ('end_date', datetime.date(2022, 1, 1)), ('installations', []), ('monitored_property', <Property: None - None>), ('name', 'loli'), ('start_date', datetime.date(2019, 1, 1)), ('week_day_bitmask', 17)]) Where is the 'emails': [{'email':'bruno.carli@smartgreen.net'}], data i have sent? Here the code: serializers class EmailSerializer(serializers.ModelSerializer): class Meta: fields = ['id', 'email'] model = EmailAddress class AlertRuleSerializer(serializers.ModelSerializer): emails = EmailSerializer(many=True, required=False) ... # other fields class Meta: model = AlertRule fields = [ ... # other fields 'emails' ] depth = 2 def … -
TimeoutError Error while sending email using Django and SMTP protocol
I have a Django project and an app inside the project. Now I am trying to send email using SMTP. But when I am trying send email it's showing this error: TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond The configuration for sending email in settings.py is : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = "MyEmailId" EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_PASSWORD = "MyPass" The code for sending email in views.py is : from django.core.mail import send_mail send_mail( 'email_subject', 'email_body', 'MyEmailId', ['ReceiverEmailId'], fail_silently=False, ) Thanks a lot for help.