Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send a JSON message via Python Requests/URL Module to a Pi Django server from a Pizero W on the same router/LAN?
I have a Raspberry Pi 3+ and a Raspberry Pizero W connected to the same home wireless network. The Pi 3+ is hosting a Django server, and the IP address of the Pi 3+ is static on the home network at 192.384.5.767. The Pizero W has a static IP address on the home network of 192.384.5.343. When I ping the Pi 3+ Server from the Pizero W, I can see that it is up: pi@PIZEROW:~$ ping 192.384.5.767 64 bytes from 192.384.5.767: icmp_seq=1 ttl=64 time=10.5 ms 64 bytes from 192.384.5.767: icmp_seq=2 ttl=64 time=30.0 ms 64 bytes from 192.384.5.767: icmp_seq=3 ttl=64 time=32.1 ms Additionally, when I access the website hosted by the Django server on a tablet, there are no issues. However, I need two-way communication between the Pizero W and the Django server so would like to test sending a super simple JSON message from the Pizero W to the Pi 3+ server and receive an acknowledgement from the server that it received the message. I don't need the server to do anything with the message other than to receive it, discard it, and send a confirm that the message was received. I tried doing this from the Pizero W using: … -
Django 'Page not found' error when setting up URLs
I'm following this tutorial: https://www.youtube.com/watch?v=Z4D3M-NSN58 This is the point where I get the 404 error: https://www.youtube.com/watch?v=Z4D3M-NSN58&t=1044s What I did so far: Set up a new project, Created a virtualenv, Set up views.py, from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(response): return HttpResponse("<h3>MySite</h3>") Created urls.py inside my main folder, from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ] Modified the urls.py inside pycache folder from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('home/', include("main.urls")), ] Upon connecting to http://127.0.0.1:8000/ I receive the 404 error. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in firstwebsite.urls, Django tried these URL patterns, in this order: admin/ home/ The empty path didn't match any of these. I am unable to proceed. -
Refactoring clean method of django form
I'm trying to refactoring the form code of a django app. The form have this view belong that to a crispy form but I don't know that is relevant. My doubt is if exists a way for simplify or separate the clean method of the form. def clean(self): cleaned_data = super(RequirementsForm,self).clean() stand_type = cleaned_data.get('stand_type') interviewers = cleaned_data.get('numeroentrevistadores') lunch_number = cleaned_data.get('lunch_number') veggie_lunch_number = cleaned_data.get('veggie_lunch_number') dp1 = cleaned_data.get('day_preference_1') st1 = cleaned_data.get('stand_preference_1') st2 = cleaned_data.get('stand_preference_2') st3 = cleaned_data.get('stand_preference_3') rs = cleaned_data.get('require_stand') pn = cleaned_data.get('producerName') pp = cleaned_data.get('producerPhone') pe = cleaned_data.get('producerEmail') total_lunch = lunch_number + veggie_lunch_number #if stand_type and total_lunch: # if stand_type == "1" and total_lunch > 2: # raise forms.ValidationError( # "error1" # ) #if stand_type == "2" and total_lunch > 4: # raise forms.ValidationError( # "error2" # ) if interviewers: if (stand_type == "1" or stand_type == "2") and interviewers > 2: raise forms.ValidationError( "error3" ) if (stand_type == "4" or stand_type == "5") and interviewers > 4: raise forms.ValidationError( "error4" ) if stand_type == "3" and interviewers > 3: raise forms.ValidationError( "error5" ) if total_lunch: if (stand_type == "1" or stand_type == "2") and (lunch_number + veggie_lunch_number) > 2: raise forms.ValidationError( "error6" ) if (stand_type == "4" or stand_type == … -
Django- Update an object with a list of dictionaries
I am trying to update multiple objects with different values using a list of dictionaries. I am able to update all of the objects with the code shown below. However, all of the objects are updated with the values contained in the last dictionary in the list. The dictionary and lists shown below contain the values that I expect them to, so there does not seem to be an issue there... I'm at a loss on how to solve this. Any help or advise is greatly appreciated. models.py ... event_set = (Event.objects.filter(recurring_event__pk=self.id)) event_set_list = [] for events in event_set: event_set_list.append(object) update_event = [] for item in recurring_event_list: defaults = {} defaults['recurring_event']=item[0] defaults['title']=item[1] defaults['start']=item[2] defaults['end']=item[3] update_event.append(defaults) for event in event_set_list: obj = Event.objects.get(id=event.id) for index in range(len(update_event)): for d in update_event[index]: setattr(obj, 'recurring_event', update_event[index]['recurring_event']) setattr(obj, 'title', update_event[index]['title']) setattr(obj, 'start', update_event[index]['start']) setattr(obj, 'end', update_event[index]['end']) obj.save() -
Django filter "__contains" lookup throwing " is not defined"
I'm trying to get all the objects in my database that the name is LIKE '%something%' After reading the documentation and searching online I figured out that using django I would have to use __contains lookup. But when I try to, the console throws me an error 500 'NameError: name 'ingredient_name__contains' is not defined' My model is the following: class Ingredient(models.Model): article_number = models.AutoField(primary_key=True) ingredient_name = models.CharField(max_length=100, null=False) cost_amount = models.FloatField(validators=[MinValueValidator(0.1)]) cost_per_unit = models.FloatField(validators=[MinValueValidator(0)]) unit = models.ForeignKey(MeasurementUnit,on_delete=models.CASCADE) def __str__(self): return self.ingredient_name And the filtering method is: def filter(request, filter): filtered = Ingredient.objects.all().filter(ingredient_name__contains(filter)) I can't figure out what I missing in this, it's driving me mad. If anyone could help I qould really appreciate it! -
accessing a different user's information in django
I know to access the logged-in user's data we use request.user. My goal is to list all the users in the table and have a link to their profile page. How do I make the link go to the user's profile page? I have the following: # app/views.py def tutors_list(request): user_list = CustomUser.objects.all() context = { 'user_list': user_list } return render(request, 'tutors_list.html', context) def show_profile(request, username): user = CustomUser.objects.get(username = username) ### NOT DISPLAYING RIGHT USER #user = CustomUser.objects.get(id=id) context = { 'user': user } return render(request, 'show_profile.html', context) # myproject/urls.py url_patterns = [ # ... path('show_profile/', views.show_profile, name='show_profile'), # ... I'm getting an error saying show_profile is expecting 1 more argument, username. How exactly would this model work if I need to pull data for a specific user in the database and not the logged-in user? -
Allow user to connect their database to django app
I am developing an app in which user stores their data. I want to add option to allow user to connect their database (on their server) to the django project so that they can store their sensitive information. Eg:- Data stored on my app database -> Name, Username, Email Data stored on user database -> Phone, Bank Details etc. I cannot configure user database credentials in settings.py as it will be dynamic and different for different users. So, how do i accomplish this? -
Use existing ModelSerializer with JSONResponse
I have a Twitter authentication view that doesn't use a viewset so the auth can be handled on the backend. The view takes in the oauth_token & uses Twython to get the profile & create a Twitter model. Currently I just return status 201 on success, but to alleviate the need for another request after creation, I'd like to return the created model. I have a TwitterSerializer already which defines the fields that I want to include, so I'd like to be able to reuse this if possible. TwitterSerializer class TwitterSerializer(serializers.ModelSerializer): class Meta: model = Twitter fields = ( "id", "twitter_user_id", "screen_name", "display_name", "profile_image_url", ) When I try to use this, I get the error that Instance of TwitterSerializer is not JSON serializable. serialized = TwitterSerializer(instance=twitter) return JsonResponse({ "created": serialized }) I could return a serialized instance of the model using serializers.serialize() serialized = serializers.serialize('json', [twitter, ]) serialized = serialized[0] return JsonResponse({ "created": serialized }) I could pass the fields kwarg to serialize() but I don't want to have to repeat myself if I don't have to. So would it be possible to re-use my TwitterSerializer in this case? I'm having trouble finding a direct answer since most docs assume … -
How to change a form's data after already populating it in Django
This might be a duplicate but I tried lots of solutions and none worked for me. views.py class signup_view(View): def get(self, request): signup_form = SignUpForm() return render(request, 'signup.html', {"forms": signup_form}) def post(self, request): signup_form = SignUpForm(data=request.POST) if signup_form.is_valid(): email = signup_form.cleaned_data.get('user_email') password = signup_form.cleaned_data.get('user_pass') print("Original password is: ", password) hashed_password = make_password(password) print("Hashed password is: ", hashed_password) signup_form.inital['user_pass'] = hashed_password signup_form.save() request.session['username'] = email return render(request, 'main_page.html') else: return render(request, 'signup.html', {"forms": signup_form}) I have this django view that I populate with information from the post request, however, I need to make sure that both the password and the password confirmation (in the forms) are the same so that I can procced, I do that in the clean() function I'll post below. However, I need to save the hashed password on my database and not the actual password and I have no idea what I can do the change the contents of the form after I already verified that it's valid (not sure if I can even do this). class SignUpForm(forms.ModelForm): user_pass_check = forms.CharField(label="Password confirmation", widget=forms.PasswordInput()) class Meta: model = AppUser fields = ["user_email", "user_country", "user_pass"] widgets = {"user_pass": forms.PasswordInput()} def clean(self): cleaned_data = super(SignUpForm, self).clean() pass1 = cleaned_data.get('user_pass_check') pass2 … -
How to use django SelectBox in our templates
I want to design template with form that be same as Django SelectBox. Like this: How to use Django form, templates ,and js files for this purpose? -
django-admin startapp v/s python manage.py startapp [duplicate]
This question already has an answer here: When should you use django-admin.py verus manage.py? 2 answers What is the difference between django-admin startapp and python manage.py startapp? They both create apps and the files are also same so what's the difference between these two? -
Many to many relationship model on Django
I have two tables called User and Courses and I want to show the relationship between them my implementing a many-to-many relationship model. I want to implement 3 model classes in total as so: # user/model.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_status = models.BooleanField(default=False) is_newbie = models.BooleanField(default=False) #courses/model.py from django.db import models from register.models import User class Courses(models.Model): course_name = models.CharField(max_length=100, null = False) class StatusHasCourse(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) course = models.ForeignKey(Courses, on_delete=models.CASCADE) How do I implement this so only the relationship between User that have is_status = True are only accessed in the StatusHasCourse model? -
How can I efficiently concatenate two nested ForiegnKey relationships?
In a Django 2.2 model, I have the following setup: class Kiosk(Model): newspapers = ForeignKey('Newspaper') class Newspaper(Model): articles = ForeignKey('Article') class Article(Model): pass Now, I can get all articles of one newspaper sold in a kiosk like so: kiosk = Kiosk.objects.first() articles = kiosk.newspapers.first().articles What I want to do is get one QuerySet (or RelatedManager) spanning all articles in all newspapers sold by a kiosk. I can of course achieve this by iterating over the newspapers and concatenating the articles lists in a for loop, but that seems inefficient. How can I get this from the ORM? -
How to make Dynamic Slug URL in Django with <slug: > URL Dispatcher
For example, I have a model Service, and that service has a title: # services\models.py class Service(models.Model): title = models.CharField(max_length=100) Here's what urls looks like: # services\urls.py from . import views urlpatterns = [ # /services/ path('', views.index, name='index') # /services/name-of-service/ path('<slug:service_title>', views.service_detail, name='service_detail') ] I'm wanting the index to display a list of my services: # services\views.py from .models import Service def index(request): services = Service.objects return render(request, 'services/index.html' {'services': services} How would you write the script for the "service_detail" view? # services\views.py #... def service_details(request, ?): ? return ? -
How to set the VATLAYER_ACCESS_KEY in Saleor eCommerce Platform?
Saleor Django eCommerce Platform. I have just started setting up and learning Saleor and I am stuck setting the VATLAYER_ACCESS_KEY. I get the following error (Could not fetch tax rates. Make sure you have supplied a valid API Access Key. Check the server logs for more information about this error.). I have registered for a key API at VatLayer https://vatlayer.com/ I have set the key "this key is an example" in the common.env file as VATLAYER_ACCESS_KEY=2bb221d7fbce9fd274791959e120999d. Is this the correct location to set the key or should it be in the saleor/settings.py file and are there additional settings I need to apply to enable VatLayer? Any assistance would be greatly appreciated. Thank you. -
Nginx 502 bad gateway for deploying Django Project even it works with uwsgi
the nginx web server is successfully installed and working. But I get 502 bad gateway error. When I check the socket file path I can't see any file. /home/bilal/uwsgi/sites/testproject.ini -> [uwsgi] home = /home/bilal/my-first-project/venv chdir = /home/bilal/my-first-project wsgi-file = /home/bilal/my-first-project/projectname/wsgi.py socket = /home/bilal/uwsgi/testproject.sock vacuum = true chown-socket = bilal:www-data chmod-socket = 660 /etc/nginx/sites-available/testproject -> server { listen 80; server_name <domain> <www.domain>; location / { include uwsgi_params; uwsgi_pass unix:/home/bilal/uwsgi/testproject.sock; } } When I try to connect to server with ip address I get welcome to nginx page because ip isn't written for server_name. But when I try to connect to server with domain I get this error: 502 Bad Gateway nginx/1.14.0 (Ubuntu) I think this problem is about the .sock file but I don't know how can I handle it. -
Django populating form field from another model
i have two apps first is inputs and second is boq inputs contains a model building boq contains a model boq model My inputs model looks like class building(models.Model): building = models.CharField(max_length=300) My boq model looks like class boqmodel(models.Model): code = models.IntegerField() building =models.CharField(max_length=300) level = models.CharField(max_length=300) activity = models.CharField(max_length=300) subactivity = models.CharField(max_length=300) duration=models.IntegerField() linkactivity= models.CharField(max_length=300) linktype= models.CharField(max_length=300) linkduration=models.IntegerField() plannedstart=models.DateField() plannedfinish=models.DateField() actualstart=models.DateField() actualfinish=models.DateField() i have aform in boq class boqform(forms.ModelForm): class Meta: model = boqmodel fields=['code', 'building', 'level', 'activity', 'subactivity', 'duration', 'linkactivity', 'linktype', 'linkduration', 'plannedstart', 'plannedfinish', 'actualstart', 'actualfinish'] Now in my boqform for field building i need the form to have a dropdown from values in building model -
How do I transform a python dictionary to an HttpRequest appropriately?
I have a builtins.dict dictionary that looks like this: request = {"data": {"var": "hello", "content": "jello"}} I am writing a test for an API endpoint in django. I am calling the post method of that class and sending this request to it, and I am accessing the data in the request using request.data. But of course that won't work, because the request that goes into my post function is actually a django.http.HttpRequest, not a builtins.dict. How do I make it so that my request argument is a HttpRequest and not a dict so my function can consume it right? -
how do I outputting multiple foreign key values in django model forms
So i have been experimenting with django and its inbuilt databases and seem to have gotten stuck in displaying multiply foreign keys the refered models.py : from django.db import models # Create your models here. class flight(models.Model): fl_no =models.CharField(max_length=6,primary_key=True) inbound= models.CharField(max_length=15,blank=True) dest= models.CharField(max_length=15,blank=True) park_bay= models.CharField(max_length=3) airline= models.CharField(max_length=15) dep_time= models.TimeField() arr_time= models.TimeField() def __str__(self): return self.fl_no the referencing models.py: from django.db import models from postlog.models import flight # Create your models here. class FlightStatus(models.Model): Yes = 1 No = 2 CLEANING_CHOICES = ( (Yes, 'Yes'), (No,'No'), ) fl_no= models.ForeignKey(flight,on_delete=models.CASCADE,related_name='fli_no') park_bay= models.ForeignKey(flight,on_delete=models.CASCADE,related_name='parki_bay') catering= models.CharField(max_length=9) fuel= models.IntegerField() pas_cnt= models.IntegerField() dest= models.ForeignKey(flight,on_delete=models.CASCADE,related_name='desti') dep_time=models.ForeignKey(flight,on_delete=models.CASCADE,related_name='dept_time') Cleaning = models.PositiveSmallIntegerField(choices=CLEANING_CHOICES) my html code: {% extends 'base_template1.html' %} {% load static from staticfiles %} {% load crispy_forms_tags %} <!DOCTYPE html> {% block title %} Status {% endblock %} {% block content %} <button type="button" class="butra button1ra" data-toggle="modal" data-target="#Add_Modal">Add Flight Status</button> <!-- Adding a Flight Status --> <div class="modal fade" id="Add_Modal" tabindex="-1" role="dialog" aria-labelledby="Add_ModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="AddModalLabel">Flight Details</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form method="post"> {% csrf_token %} {{ form|crispy }} </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Add Details</button> </div> … -
Django error: "Related Field got invalid lookup: icontains" despite using proper double-underscore syntax
I'm using Django 2.2.6 and Python 3.7.0, and I'm getting the infamous "Related Field got invalid lookup: icontains" error. The weird thing is, I believe I am using the proper double-underscore syntax to access the CharField in the model behind the ForeignKey field (in this case, location_type__type in the search_fields of LocationAdmin). Any thoughts on this one? models.py class Location(models.Model): long_name = models.CharField(max_length=255, blank=True, null=True) location_type = models.ForeignKey(LocationType, models.DO_NOTHING, blank=True, null=True) abbreviation = models.CharField(max_length=15, blank=True, null=True) short_name = models.CharField(max_length=50, blank=True, null=True) class Meta: managed = False db_table = 'location' def __str__(self): return self.long_name class LocationType(models.Model): type = models.CharField(max_length=100, blank=True, null=True) description = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'location_type' def __str__(self): return self.type admin.py class LocationAdmin(admin.ModelAdmin): list_display = ['long_name', 'location_type', 'abbreviation', 'short_name'] search_fields = ['long_name', 'location_type__type', 'abbreviation', 'short_name'] class LocationTypeAdmin(admin.ModelAdmin): list_display = ['type', 'description'] search_fields = ['type', 'description'] -
Issue while sending response for multiple data in Django Get
I am executing GET request for DJANGO REST API call with comma separated values. http://localhost:8080/xyz/abc/123,456,789 in views.py i am splitting this value and sending the response listVal=values.split(",") for val in listVal: do some processing update dictionary dict.update(newdict) print(dictionary) i am getting all 3 values printed here return response(dictionary) But , i am getting only the last value i.e 789 of the comma separated values and for other 2 i am not getting any response in json data. Is returning response suitable for multiple values or it takes only one value at a time. -
Django executing python script in web
I am trying to run my tensorflow script so that the result image will be exported and will be use to my site. At first, I'm using flask but I decided to shift to django because the script is too slow read and sometimes it won't run. That's why, I use django. But then, the script still wont run. Please, need help... At first, I'm using flask but I decided to shift to django because the script is too slow read and sometimes it won't run. That's why, I use django. But then, the script still wont run. Please, need help... Files that the tensorflow script needed were placed at the same location where views.py, urls.py are in. views.py # Import packages import os import cv2 import numpy as np import tensorflow as tf import sys import easygui # This is needed since the notebook is stored in the object_detection folder. sys.path.append("..") # Import utilites from utils import label_map_util from utils import visualization_utils as vis_util from api import object_counting_api from django.shortcuts import render def mandaluyong(request): # Name of the directory containing the object detection module we're using path = easygui.fileopenbox() MODEL_NAME = 'inference_graph' IMAGE_NAME = path # Grab path to … -
VSCode autocomplete for Django QuerySet.filter(property__regex='^This not autocomplete')
How to autocomplete property of Django QuerySet.filter in VSCode? Just like it works in Pycharm as follow, I think it's really useful, because Django use too many python magic that will make developer confused -
I cant delete img on server when delete post or delete img in post with summernote-django
I cant find the way delete img on server when upload via summernote-django. (in short: I can run summernote-django nows. but in template when i del img in post. img on server not delete sync) my code : my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('summernote/', include('django_summernote.urls')), my form.py from django import forms from django_summernote.widgets import SummernoteWidget from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title','content',) widgets = { 'content': SummernoteWidget(), } my views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post form_class = PostForm Thank you so much. -
get_object() that depends on `request` in UpdateView
I am writing a class-based view to allow users to edit their profile. Since I want the users to access this view with a URL of the type my_profile/edit/ rather than something like profile/<int:pk>/edit/, using a view based on UpdateView is quite cumbersome since getting the user profile object requires to access the request object, and get_object does not directly have access to it. My two questions: Shall I use UpdateView in this case? If so, what would be the best way to override get_object(self, queryset=None)? My best attempt so far is the following: class EditProfileView(UpdateView): model = UserProfile _request = None def get_object(self, queryset=None): return get_user_profile(self._request) def dispatch(self, request, *args, **kwargs): # can also override setup() in newer Django versions self._request = request return super().dispatch(request, *args, **kwargs) This looks clean enough to me except that if one day the Django framework decides that get_object should be called early in the workflow of the view generation, this piece of code could break.