Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django search for child models via foreign key
I have a models.py file that more or less looks like this: class Match(models.Model): match_id = models.BigIntegerField() class Team(models.Model): team_id = models.CharField(max_length=4) match = models.ForeignKey( Match, related_name='teams', on_delete=models.CASCADE, ) win = models.BooleanField() class Player(models.Model): player_id = models.IntegerField() team = models.ForeignKey( Team, related_name='players' on_delete=models.CASCADE, ) For each match, I want to find the two teams that played, and for each team, I want to find the players that were on the team. This is what I tried so far: match_id = 123456789 match_info = Match_model.objects.get(match_id=match_id) red_info = Team_model.objects.get(match=match_info, team_id='Red') blue_info = Team_model.objects.get(match=match_info, team_id='Blue') red_players = Player_model.objects.filter(team=red_info) blue_players = Player_model.objects.filter(team=blue_info) but Django is giving me the error: Team matching query does not exist. How would I go about fixing this error? Any pointers on how to correct my queries would be greatly appreciated! -
mongo DB+flask vs Django. Which one do you think is better for python based website? [closed]
Hi~ I want to make a python based website. Which language do you think is better to make a python based website? mongo DB + flask vs Django of course, they all have pros and cons but I want to ask you if you are in my situation, what would you choose? and why? -
how to create django multiple user types
I am working on a project where I need to have 3 types of Users. Admin Vendor Customer My first approach to this problem was to define all models by sub-classing the AbstractUser model class Customer(AbstractUser): pass class Vendor(AbstractUser): pass so the question is do i need to craete a UsermManager for every usertype model ? -
Check if ManyToMany relationship on certain date exists, then exclude that entry
I have this model: class Assignment(models.Model) assignment_date = models.DateField(blank=True, null=True) chosen_driver = models.ManyToManyField('driver.Driver', blank=True, verbose_name=_( "Chosen driver"), related_name="driver_chosen") ... A chosen driver can only have one assignment per day. So when getting the Assignment queryset I want to check for the assignment_date and then see if the Driver model already has an assignment with this date. So I though something like this: driver = get_object_or_404(Driver, pk=1) dcl = [] for entry in driver.driver_chosen.all(): dcl.append(entry.assignment_date) Then we have a list with all the dates of assignments where this Driver is chosen. Then when constructing the queryset of Assignment maybe something like this to compare the dates to each other and exclude from the queryset: for entry in Assignment.objects.all() if entry.assignment_date in dcl: queryset = Assignment.objects.exclude(entry.pk) return queryset But this returns a TypeError: cannot unpack non-iterable int object error. Can someone help? -
Yelp API call with python Requests
I've got a Django project with a class based view where my frontend makes a call to and sends through a user input. The View then collects that input and makes an API call and is expected to return a json object but I keep getting a 404. I'm not exactly sure which part is broken as nothing gets returned. Views.py class YelpLocation(APIView): def get(self, request): API_KEY= '***' API_HOST = 'https://api.yelp.com/v3/businesses/search/' location = self.request.GET['location'] headers = { 'Authorization': 'Bearer %s' % API_KEY, } params = { 'location' : location, 'term' : 'coffee' } response = requests.get( API_HOST, headers=headers, params=params) return Response(response) -
Where to put global html/css files in Django (Navbar.html, general.css, etc...) so that it's referable by all apps?
1) I want my project to be able to call {% include navbar.html %} from every template but I'm not sure where I'm supposed to place navbar.html. I tried placing it in mysite/templates/navbar.html but calling {% include navbar.html %} just gave me a TemplateSyntaxError. 2) I also want to be able to have a general.css referable by all of my apps. Is placing it in mysite/static/general.css a good idea?. -
What the Difference between Django synthax
hello guys what the difference between this two syntax 'blog' and 'blog.apps.BlogConfig' in project this is located in installed app. i think both are same but there should be difference between this 2 commands because they looks like different first one is this INSTALLED_APPS = [ 'blog', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] seccond one is : INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC
I am recording voice using javascript in .wav format: navigator.mediaDevices.getUserMedia({audio:true}) .then(stream => {handlerFunction(stream)}) function handlerFunction(stream) { rec = new MediaRecorder(stream); rec.ondataavailable = e => { audioChunks.push(e.data); if (rec.state == "inactive"){ let blob = new Blob(audioChunks,{type:'audio/wav;codecs=0'}); sendData(blob) } } } sending the file to convert it to text using speech_recognition: filename = "name.wav" print(filename) data = request.body BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) uploadedFile = open(filename, "wb") uploadedFile.write(request.body) uploadedFile.close() os.path.join(BASE_DIR,filename) r = sr.Recognizer() file = sr.AudioFile(filename) with file as source: audio = r.record(source) msg = r.recognize_google(audio) print(msg) return redirect('/') Error:- ValueError: Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format P.S. audio file is saving and I can hear sound/voice clearly well -
How to get data from two tables with DjangoORM?
I have two tables in the database: class CustomerEquipment(models.Model): serial_number = models.CharField(max_length=255) state_timestamp = models.DateTimeField() state_type = models.IntegerField() class Meta: managed = False db_table = 'customer_equipment' class LogCustomerEquipment(models.Model): state = models.IntegerField() state_timestamp = models.DateTimeField() serial_number = models.CharField(max_length=255) class Meta: managed = False db_table = 'log_customer_equipment' I execute two database queries: customer_equipment_list = CustomerEquipment.objects.using('portal').filter( Q(state_type=10) & Q(state_timestamp__icontains='2020-02-27') ) log_customer_equipment_list = LogCustomerEquipment.objects.using('portal').filter( Q(state=2) & Q(state_timestamp__icontains='2020-02-27') ) I need to get serial_number which are in both tables. How to do it? How can I optimize queries? -
ValueError: not enough values to unpack (expected 2, got 1) how can i solve this problem i am just tried
ValueError: not enough values to unpack (expected 2, got 1) how can I solve this problem I am just tried to get this Error for a long This is The Error (myDjangoEnv) D:\Django\User\learning_users>python manage.py migrate Traceback (most recent call last): File "manage.py", line 21, in main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\core\management__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\core\management__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\core\management\base.py", line 366, in execute self.check() File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\core\management\commands\migrate.py", line 64, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\contrib\staticfiles\checks.py", line 7, in check_finders for finder in get_finders(): File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\contrib\staticfiles\finders.py", line 282, in get_finders yield get_finder(finder_path) File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\contrib\staticfiles\finders.py", line 295, in get_finder return Finder() File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\contrib\staticfiles\finders.py", line 59, in init prefix, root = root ValueError: not enough values to unpack (expected 2, got 1) **models.py** from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): # user = models.OneToOneField(User) user = models.OneToOneField(User, on_delete=models.CASCADE) # user = models.ForeignKey(User,models.SET_NULL,blank=True,null=True) # user = models.ForeignKey(User, on_delete=models.PROTECT) #additional profile_site = models.URLField(blank = True) … -
Implement sessions on database in flask
I can't understand how to implement sessions on the database in the flask. I need a single connection from the database and multiple sessions from that single connection. The database used is pyodbc -
Django logging configuration working on local server but not on remote server
I'm trying to configure django logging in the django settings file so that it logs django info and info for my application to a custom file for easy viewing. Here's my logging config: 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'console': { # exact format is not important, this is the minimum information 'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s', }, 'file': { # exact format is not important, this is the minimum information 'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s', }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'formatter': 'file', 'filename': 'logs/django_log.log', 'backupCount': 10, # keep at most 10 log files 'maxBytes': 5242880, # 5*1024*1024 bytes (5MB) }, 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'console', }, }, 'loggers': { 'django': { 'handlers': ['file', 'console'], 'level': 'INFO', 'propagate': True, }, 'py.warnings': { 'handlers': ['console'], }, 'my_application': { 'level': 'INFO', 'handlers': ['file', 'console'], # required to avoid double logging with root logger 'propagate': False, }, }, } This works on my local manage.py test server, both with django events appearing and events that I log, initialized with my_application as the logger name. However, on my web server, the logging file is created and, oddly, only populated with occasional django WARNING messages. So, there … -
How to pass multiple <li> element from template to Django view?
I am trying to pass list elements from template to view when I click a button. My template looks like the following. <ul id="listFrom"> <li data-id="1"><a href="#">Element 1</a></li> <li data-id="2"><a href="#">Element 2</a></li> <li data-id="3"><a href="#">Element 3</a></li> <li data-id="4"><a href="#">Element 4</a></li> </ul> Thank you in advance. -
Models aren't loaded yet
I try to get all pages of ProgramPage where the field program_types has a certain pk Everything was fine before I had added this. program_type = ProgramType.objects.get(pk=1) programs = ProgramPage.objects.live().public().filter(program_types__in=[program_type]) Here is the full code of models.py: # program/models.py from django import forms from django.db import models from modelcluster.fields import ParentalManyToManyField from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel from wagtail.snippets.models import register_snippet @register_snippet class ProgramType(models.Model): name = models.CharField(max_length=255) panels = [ FieldPanel('name'), ] def __str__(self): return self.name class Meta: verbose_name_plural = "Program types" class ProgramPage(Page): description = RichTextField(blank=True) program_types = ParentalManyToManyField("program.ProgramType", blank=True) content_panels = Page.content_panels + [ FieldPanel('description'), FieldPanel('program_types', widget=forms.CheckboxSelectMultiple), ] class IndexProgram(Page): program_type = ProgramType.objects.get(pk=1) programs = ProgramPage.objects.live().public().filter(program_types__in=[program_type]) after "makemigrations" or "runserver" I get an error: raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. -
django create rtl PDF file dynamically
I have tried many library to create rtl PDF file with Arabic language dynamically and I couldn't figure how work it out as all working in ltr direction but not rtl direction, any suggestions? -
lists to Dictinary and printing in required format
I have 2 lists like this list1=['TEL', 'TEL', 'TEL', 'US0_STU', 'infocollect feml sfx-infocollect.sh CCR', 'TEL', 'TEL', 'TEL TEL.SYM dbase.mgr maoagent maoagent.SYM sysopt confmem'] listcr=['RA CROXES-23814', 'RA CROXES-23772', 'RA CROXE-16484', 'RA CROXE-16387', 'RA CROXE-16294', 'RA CROXE-16210', 'RA CROXE-16140', 'RA CROXE-16101'] I have tried to form a dictionary with the below following code mydict = {} k=0 for i in range(len(list1)): index=i if list1[i].find(" ")>=0: bin_list = list1[i].split(" ") for binary in bin_list: mydict.update({k:[binary,listcr[index]]}) k+=1 else: mydict.update({k:[list1[i],listcr[index]]}) k+=1 print(mydict) so the myDict is like this mydict={0: ['TEL', 'RA CROXES-23814'], 1: ['TEL', 'RA CROXES-23772'], 2: ['TEL', 'RA CROXE- 16484'], 3: ['US0_STU', 'RA CROXE-16387'], 4: ['infocollect', 'RA CROXE-16294'], 5: ['feml', 'RA CROXE- 16294'], 6: ['sfx-infocollect.sh', 'RA CROXE-16294'], 7: ['CCR', 'RA CROXE-16294'], 8: ['TEL', 'RA CROXE-16210'], 9: ['TEL', 'RA CROXE-16140'], 10: ['TEL', 'RA CROXE-16101'], 11: ['TEL.SYM', 'RA CROXE-16101'], 12: ['dbase.mgr', 'RA CROXE-16101'], 13: ['maoagent', 'RA CROXE-16101'], 14: ['maoagent.SYM', 'RA CROXE-16101'], 15: ['sysopt', 'RA CROXE-16101'], 16: ['confmem', 'RA CROXE- 16101']} In Django UI page I want to display the elements like this TEL RA CROXES-23814 RA CROXES-23772 RA CROXE- 16484 RA CROXE-16101 RA CROXE-16210 RA CROXE-16140 US0_STU RA CROXE-16387 infocollect RA CROXE-16294 feml RA CROXE- 16294 sfx-infocollect.sh RA CROXE-16294 CCR RA CROXE-16294 TEL.SYM RA CROXE-16101 dbase.mgr … -
Login is not working with newly set password in django?
I am implementing the UserCreationForm and with this I am setting some default password1 and password2 for user.After successful creation it sends email to this user instance and after clicking the email user activates and redirect to the set_user_password view. The view is posted below. It successfully creates the password for this user but the user is not being able to login with this newly created password. What might be the reason ? forms.py class SetPasswordForm(forms.ModelForm): password1 = forms.CharField(widget=forms.PasswordInput, validators=[validate_password]) password2 = forms.CharField(widget=forms.PasswordInput) class Meta: model = get_user_model() fields = ['password1', 'password2'] def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1: if not password1 == password2: raise forms.ValidationError("Sorry the two passwords didn't match") views.py def set_user_password(request, pk): user = get_object_or_404(get_user_model(), pk=pk) form = SetPasswordForm() if request.method == 'POST': form = SetPasswordForm(request.POST) if form.is_valid(): password = form.cleaned_data.get('password2') user.set_password(password) user.save() messages.success(request, 'Password created successfully.') return redirect('login') return render(request, 'user_invitation/set_password.html', {'user': user, 'form': form}) urls.py path('user/<int:pk>/set/password/', views.set_user_password, name='set_user_password'), -
Retrieving a Has Many Model Values with django-rest-framework serializers
class User(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Address(models.Model): name = models.CharField(max_length=100) user = models.ForeignKey(User, related_name='users') def __str__(self): return self.name How can i retrieve the address of a specific user using drf serializers ? -
Encryption in Flutter and Decryption in python
I'm trying to connect two different applications, flutter web and django application. I need to encrypt my data in flutter and decrypt it in python. Is there any solution for this? Is there any compatible encryption and decryption algorithm for both dart and python. -
Django Dropdown Menu Search Form With Multiple Model Field Sorting Ascending / Descending
I want to make a single dropdown menu for a search form where you are able to sort by all sorts of different fields in the model in ascending and descending order. How does this get accomplished? I started it off in my forms.py sort field but I am not sure how to write the view to be able to combine all of the sorts in a single dropdown menu. Desired Result: https://imgur.com/a/zgU2BMy Forms.py: class CourseForm(forms.Form): name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control col-12', 'autocomplete':'off', 'id':'title', 'type':'search', 'placeholder': 'Course Name'}), required=False) min_views = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control', 'autocomplete':'off','id':'min_views', 'type':'number', 'min':'0', 'placeholder': '0'}), required=False, validators=[MinValueValidator(0), MaxValueValidator(99999999999999999999999999999999999)]) max_views = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control', 'autocomplete':'off', 'id':'max_views', 'type':'number', 'min':'0', 'placeholder': '1000000'}), required=False, validators=[MinValueValidator(0), MaxValueValidator(99999999999999999999999999999999999)]) min_date = forms.DateField(widget=forms.TextInput(attrs={'class':'form-control', 'autocomplete':'off', 'id':'max_date','type':'date', 'placeholder': 'mm/dd/yyy'}), required=False) max_date = forms.DateField(widget=forms.TextInput(attrs={'class':'form-control', 'autocomplete':'off', 'id':'min_date', 'type':'date', 'placeholder': 'mm/dd/yyy'}), required=False) expertise = forms.ChoiceField(widget=forms.Select(attrs={'class':'form-control', 'autocomplete':'off','id':'skill_level'}), choices = ([('',''), ('Beginner','Beginner'), ('Intermediate','Intermediate'),('Advanced','Advanced'), ]), required=False) subject = forms.ModelChoiceField(queryset=Subject.objects.filter().order_by('name'), to_field_name="name", empty_label="", widget=forms.Select(attrs={'class':'form-control', 'autocomplete':'off', 'id':'subject'}), required=False) membership = forms.ModelChoiceField(queryset=Membership.objects.all(), to_field_name="membership_type", empty_label="", widget=forms.Select(attrs={'class':'form-control', 'autocomplete':'off', 'id':'membership'}), required=False) sort = forms.ChoiceField(widget=forms.Select(attrs={'class':'form-control', 'autocomplete':'off','id':'sort'}), choices = ([('',''), ('title','Ascending Title'), ('title','Descending Title'),('created_at','Ascending Date'), ('created_at','Descending Date'), ('visited_times','Ascending Views'), ('visited_times','Descending Views'), ]), required=False) def __init__(self, *args, **kwargs): super(CourseForm, self).__init__(*args, **kwargs) self.fields['name'].label = "Course Name:" self.fields['min_views'].label = "Min Views:" self.fields['max_views'].label = "Max Views:" self.fields['min_date'].label = "Min Date:" self.fields['max_date'].label … -
Visual Studio Code don't recognize HTML file
I am learning to build a Website on Python Django, but when I create a HTML file in VS code, this Editor don't recognize this file. You can see in following picture. I don't know how to solve this problem. Pls help me if you know, thank you very much -
Unable to add time to TimeField in django model [<class 'decimal.InvalidOperation'>]
I have a django model like this... class ConversionResults(models.Model): conversion_results_id = models.AutoField(primary_key=True) conversion_rate_a = models.DecimalField(max_digits=4, decimal_places=2) clicks_a = models.IntegerField() conversion_rate_b = models.DecimalField(max_digits=4, decimal_places=2) clicks_b = models.IntegerField() week = models.IntegerField() date = models.DateField() time = models.TimeField() objects = models.Manager() class Meta: db_table = 'conversion_results' def __int__(self): return self. conversion_results_id When I try to add data to the model, like below ConversionResults( conversion_rate_a=conversion_rate_today_a, conversion_rate_b=conversion_rate_today_b, clicks_a=ctc_today_a, clicks_b=ctc_today_b, week=week, date=today_date, time=datetime.datetime.today().time() # the error is here ).save() I am getting error with the time field as shown below graphql.error.located_error.GraphQLLocatedError: [<class 'decimal.InvalidOperation'>] I don't get how this is even related to decimal, the model contains a TimeField. Any help will be appreciated -
can't able to add DIV element using a button
<!DOCTYPE html> <html> <head></head> <body> <form method="POST" action="act.php"> <p>Click the button to create a DIV element with some text, and append it to DIV.</p> <div id="myDIV"> MATHS PAPER </div> <button onclick="myFunction()">Add Question</button> <input type="submit" value="Create"> </input> <script> function myFunction() { var para = document.createElement("DIV"); para.innerHTML = "<div style='background-color:lightgreen'>QUESTION<div><input type='text' id='q1' placeholder='enter question'></div><div></input><input type='text' placeholder='enter option1 here'></input></div><div></input><input type='text' placeholder='enter option2 here'></input></div></div>"; document.getElementById("myDIV").appendChild(para); } </script> </form> </body> </html> How to make this code work? I observed on removing form tag, it is working. But I want it to be in form tag, so that I can post those questions and options, and save it in a database. reference: https://www.w3schools.com/jsref/met_document_createelement.asp -
Jenkins fails to install Django 2.0+
I am new to Docker & Jenkins. I want to build a CI/CD using docker & Jenkins. The issue that I have is, I cannot get Jenkins to install Django == 2.0.8. The cause of this issue is, Jenkins uses python2.7. I install python 3.5 on Jenkins, and set the PYTHONPATH = "/usr/bin/python3/lib", PYTHON="/usr/bin/python3/bin". But this doesn't work. I also tried online solutions, such as install ShiningPanda and it failed too. Anyone could shed me some lights? I have been struggle with it for 3 hours. It shouldn't be this difficult right. -
Key_error using self.cleaned_data[] in Django forms
I keep getting a key_error on line email = self.cleaned_data["email"] of the below in my forms.py. I am trying to also add an email validation or clean_email method, because somehow it seems that the key_error only occurs when I try registering with an invalid email address. Is adding def clean_email() the right approach? And if so, is the forms.py inside my class the right place to do so? forms.py: from django import forms from django.contrib.auth.models import User class RegisterForm(forms.Form): first_name = forms.CharField(widget=forms.TextInput(attrs={'class': "form-control", 'placeholder': "First Name", 'autocomplete': "nope"}), label="First name", max_length=64, required=True) last_name = forms.CharField(widget=forms.TextInput(attrs={'class': "form-control", 'placeholder': "Last Name", 'autocomplete': "new-password"}), label="Last name", max_length=64, required=True) email = forms.EmailField(widget=forms.TextInput(attrs={'class': "form-control", 'placeholder': "Email", 'autocomplete': "new-password"}), label="Email", max_length=132, required=True) password = forms.CharField(label="Password", max_length=32, widget=forms.PasswordInput(attrs={'class': "form-control", 'placeholder': "Password"})) confirmation = forms.CharField(label="Confirmation", max_length=32, widget=forms.PasswordInput(attrs={'class': "form-control", 'placeholder': "Confirm"})) def clean(self): email = self.cleaned_data["email"] if User.objects.filter(username=email).exists(): raise forms.ValidationError(u'Email "%s" is already in use.' % email) password = self.cleaned_data["password"] confirmation = self.cleaned_data["confirmation"] if password != confirmation: raise forms.ValidationError("Password and confirmation do not match!") The correspoinding method in views.py is: from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.contrib import messages def register_client(request): if request.method == "POST": …