Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to retrieve data based on specific field in Django Rest Framework using RetrieveAPIView?
With the code below, I am able to retrieve data based on id, how can I update this code so I can retrieve data based on fileName instead? My urls is urlpatterns = [ path("items/<pk>", SingleUploadItem.as_view()), ] My views is: class SingleUploadItem(RetrieveAPIView): queryset = fileUpload.objects.all() serializer_class = fileUploadSerializer My model is class fileUpload(models.Model): fileName = models.CharField(max_length=200, unique=True, blank=True) -
Django comments deletion
I am having challenges in getting user comment deletion functionality for my django blog. The logic is as follows: user who made a comment under blog post and is logged in will see Delete button next to their comment once the user click on delete comment button they are taken to Comment_confirm_delete page to confirm deletion Below is what I have: Models.py from django.db import models from django.contrib.auth.models import User from cloudinary.models import CloudinaryField STATUS = ((0, "Draft"), (1, "Published")) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog_posts") updated_on = models.DateTimeField(auto_now=True) content = models.TextField() featured_image = CloudinaryField('image', default='placeholder') excerpt = models.TextField(blank=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) likes = models.ManyToManyField(User, related_name='blog_likes', blank=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def number_of_likes(self): return self.likes.count() class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=False) class Meta: ordering = ['-created_on'] def __str__(self): return f"Comment {self.body} by {self.name}" def get_absolute_url(self): return reverse('post-detail', kwargs={'comment': id}) urls.py from . import views from .views import CommentDeleteView from django.urls import path urlpatterns = [ path("", views.PostList.as_view(), name="home"), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), path('like/<slug:slug>', views.PostLike.as_view(), name='post_like'), path('delete/<comment_id>', views.CommentDeleteView.as_view(), name='comment_confirm_delete') ] views.py … -
Change boolean data when adding new registration
in this code i want change a boolean data of room when adding new registration For example: when i add new registration in django admin the boolean data of room change to False please can u help in it from django.db import models from django.contrib.auth.models import User class Rooms(models.Model): room_num = models.IntegerField() room_bool = models.BooleanField(default=True) category = models.CharField(max_length=150) def __str__(self): return f'{self.room_num}' class Meta: verbose_name = 'Room' class Registration(models.Model): rooms = models.ForeignKey(Rooms, on_delete=models.CASCADE) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) admin = models.ForeignKey(User, on_delete=models.CASCADE) pasport_serial_num = models.CharField(max_length=100) birth_date = models.DateField() img = models.FileField() visit_date = models.DateTimeField() leave_date = models.DateTimeField() guest_count = models.IntegerField() def func(self): room = Rooms.objects.filter(room_bool=True) for i in room: if i.room_num == int(self.rooms): i.room_bool = False #this should change when adding new registration i.save() -
How to let Kombu consumer return or stream queued message
I am using Kombu and RabbitMq to queue the JPEG image data and stream or return the dequeued message back so it shows the video streaming on the webpage. Kombu consumer detects the message sent from the producer declared in detection.py file, but it does not save or return any message back so basically nothing is showing on the web. I read Kombu documentation but still I have trouble understanding the problem of my code. Any help would be greatly appreciated.. color_detection.py: The following code declares Kombu producer and publish the message to the exchange called video-exchange. from kombu import Connection from kombu import Exchange from kombu import Producer from kombu import Queue import numpy as np import cv2 import sys # Default RabbitMQ server URI rabbit_url = 'amqp://guest:guest@localhost:5672//' # Kombu Connection conn = Connection(rabbit_url) channel = conn.channel() # Kombu Exchange # - set delivery_mode to transient to prevent disk writes for faster delivery exchange = Exchange("video-exchange", type="direct", delivery_mode=1) # Kombu Producer producer = Producer(exchange=exchange, channel=channel, routing_key="video") # Kombu Queue queue = Queue(name="video-queue", exchange=exchange, routing_key="video") queue.maybe_bind(conn) queue.declare() ''' ML object detection algo(haarcascade)used to identify objects. the XML file consists of trained Haar Cascade models. ''' face_cascade = cv2.CascadeClassifier( 'accounts/personal_color/self_detection/haarcascade_frontalface_default.xml') # … -
Is there a way to display all user last_login and date_joined in django
I want to display all users information on admin dashboard with their last_login and join date I filter user date to display on template data = Profile.objects.filter(Q(user__is_superuser=False), Q(user__is_staff=False)).order_by('-user__last_login')[:10] Profile model user = models.OneToOneField(User,default="1", on_delete=models.CASCADE, related_name="profile") image = models.ImageField(upload_to="images",default="default/user.png") def __str__(self): return f'{self.user} profile' I want to do like -
I am gettitng post method not allowed
from rest_framework.decorators import api_view @api_view(['GET', 'POST']) def contact(request): if request.method == 'GET': contact = ContactMe.objects.all() serializer = ContactMeSerializer(contact, many=True) return JsonResponse(serializer.data, safe=True) elif request.method == 'POST': data = JSONParser().parse(request) serializer = ContactMeSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.data, safe=False) I am getting post method not allowed, i don't know why i keep getting post method not allowed. The source code is below. Thanks from django.urls import path from .views import ListingView, SearchView, ListingsView, contact urlpatterns = [ path('contact/', contact) ] -
showing date from db in html date in django
How can i show date from db in django html template with input type date. As You can see if we use input type 'date'. we can see the below widget showing in html. But if i want to it to show date from DB in below picture. Is there anyway i can do? [![enter image description here][1]][1] Showing like this, so user can see the current date from DB and change if needed. forms.py class ProfileUpdateForm(ModelForm): #birthdate = forms.DateField( # input_formats=['%dd-%mm-%yyyy'], # widget=forms.DateInput(format='%dd-%mm-%yyyy', attrs={'type': "date"}) # ) class Meta: model = User fields = [ 'email', 'full_name', 'address', 'city', 'state', 'postcode', 'phone_number', 'birthdate', ] widgets = { 'full_name': Textarea(attrs={'cols': 35, 'rows': 1}), 'address': Textarea(attrs={'cols': 80, 'rows': 3}), 'city': Textarea(attrs={'cols': 35, 'rows': 1}), 'birthdate': forms.DateInput(format='%d %b %Y', attrs={'type':'date'}), } -
Add template variable into URL and satisfy reverse match
I found a way to inject variables into the URL per Django Template: Add Variable Into URL As Parameter, but my reverse match is not working. Do I need to use re-path and use regular expressions? Current url.py path('student/item/drilldown/<str:type>/<int:num>/',views.StudentBehaviorListView.as_view(),name='student_item_list_drilldown'), Original w/hard-coding: <a href="{%url 'registration:student_item_list_drilldown' type='grade' num=6%}"> With variable injection: <a href="{%url 'registration:student_item_list_drilldown'%}?type=grade&num={{i.grade}}">{{i.grade}}th Grade</a> Error message: NoReverseMatch at /registration/dashboard/ Reverse for 'student_item_list_drilldown' with no arguments not found. 1 pattern(s) tried: ['registration/student/item/drilldown/(?P<type>[^/]+)/(?P<num>[0-9]+)/\\Z'] -
Django Form "'ForwardManyToOneDescriptor' object has no attribute 'all'"
Hey so I'm having quite some problems. In effect trying to add a form to a home-page with options for a user to select based on a DB object. Then once submitted the page will refresh, and the form can be used again. Forms.py rom django import forms from django.forms import ChoiceField, ModelForm, RadioSelect from .models import command_node class command_form(ModelForm): class Meta: model = command_node fields = ( 'host_id', 'current_commands' ) host_id = forms.ModelChoiceField( required=True, queryset=command_node.host_id, widget=forms.Select( attrs={ 'class': 'form-control' }, ) ) current_comamnds = forms.ChoiceField( required=True, attrs={ 'class': 'form-control' }, choices=[ ('Sleep', "Sleep"), ('Open SSH_Tunnel', 'Open SSH_Tunnel'), ('Close SSH_Tunnel', 'Close SSH_Tunnel'), ('Open TCP_Tunnel', 'Open TCP_Tunnel'), ('Close TCP_Tunnel', 'Close TCP_Tunnel'), ('Open Dynamic', 'Open Dynamic'), ('Close Dynamic', 'Close Dynamic'), ('Task', 'Task'), ]) Models.py from tkinter import CASCADE from turtle import update from django.db import models class beacon(models.Model): host_id = models.BigAutoField('Id', primary_key=True) hostname = models.CharField('Hostname', max_length=200) internalIp = models.CharField('Internal-IP', max_length=200) externalIp = models.CharField('External-IP', max_length=200) current_user = models.CharField('Current_User', max_length=200) os = models.CharField('OS', max_length=200) admin = models.CharField('Admin', max_length=200) def __str__(self): return self.hostname class command_node(models.Model): host_id = models.ForeignKey(beacon, on_delete=models.CASCADE) current_commands = models.CharField('current_command', max_length=50, null=True) previous_commands = models.CharField('previous_commands', max_length=2000, null=True) def __str__(self): return str(self.host_id) views.py from django.shortcuts import render from django.http import HttpResponse from .models import … -
How to compare model fields using Django-filter package
I am trying to compare two model fields ma8, ma21 using Django-filter but I am not sure where to start. I think I should use F objects like in this answer: How to create a Django queryset filter comparing two date fields in the same model Below is my filters.py file from .models import TheModel from .tables import The TableTable import django_filters class MyFilter(django_filters.FilterSet): ma8__lt = django_filters.NumberFilter(field_name='ma8', lookup_expr='lt') ma8__gt = django_filters.NumberFilter(field_name='ma8', lookup_expr='gt') ma21__lt = django_filters.NumberFilter(field_name='ma21', lookup_expr='lt') ma21__gt = django_filters.NumberFilter(field_name='ma21', lookup_expr='gt') activeYN = django_filters.BooleanFilter(field_name='activeYN') # Here I want to be able to compare two model fields ma8, ma21 ex. ma8 > ma21 class Meta: model = TableData table_class = TableTable fields = ['ma8','ma21','activeYN'] -
Provide initial data for Django models from txt file
I have a .txt file with 3 columns (longitude, latitude, distance) and 40 million rows. These are the first lines of the file. -179.98 89.98 712.935 -179.94 89.98 712.934 -179.9 89.98 712.933 -179.86 89.98 712.932 -179.82 89.98 712.932 -179.78 89.98 712.931 -179.74 89.98 712.93 -179.7 89.98 712.929 -179.66 89.98 712.928 -179.62 89.98 712.927 Is there a way to provide these 40 million rows as initial data to this Django model? from django.db import models class Location(models.Model): longitude = models.FloatField() latitude = models.FloatField() distance = models.FloatField() -
How to annotate a QuerySet with the result of another QuerySet that uses a field of the first?
I'm currently working on the django backend of an app that allows users to place camera markers, each containing multiple cameras. The models I'm working with: class CameraMarkers(models.Model): # Field name made lowercase. marker_id = models.AutoField(db_column='Marker_ID', primary_key=True) # Field name made lowercase. city = models.CharField(db_column='City', max_length=25) # Field name made lowercase. num_of_cams = models.IntegerField(db_column='Num_of_Cams') # Field name made lowercase. zipcode = models.CharField( db_column='Zipcode', max_length=6, blank=True, null=True) # Field name made lowercase. street = models.CharField( db_column='Street', max_length=50, blank=True, null=True) # Field name made lowercase. house_num = models.CharField( db_column='House_num', max_length=10, blank=True, null=True) # Field name made lowercase. company = models.CharField( db_column='Company', max_length=12, blank=True, null=True) # Field name made lowercase. contact_name = models.CharField( db_column='Contact_name', max_length=50, blank=True, null=True) # Field name made lowercase. email_address = models.CharField( db_column='Email_address', max_length=50, blank=True, null=True) # Field name made lowercase. phone_num = models.CharField( db_column='Phone_num', max_length=15, blank=True, null=True) # Field name made lowercase. date_of_visit = models.CharField( db_column='Date_of_visit', max_length=10, blank=True, null=True) class Meta: managed = False db_table = 'Camera Markers' class Cameras(models.Model): # Field name made lowercase. camera_id = models.AutoField(db_column='Camera_ID', primary_key=True) # Field name made lowercase. status = models.CharField(db_column='Status', max_length=20) # Field name made lowercase. view = models.TextField(db_column='View', blank=True, null=True) # Field name made lowercase. marker = models.ForeignKey( CameraMarkers, models.DO_NOTHING, db_column='Marker_ID') … -
Noreversematch: "url-name" not found a valid function or pattern name
I built a simple app to register and login users. Whenever a user registers, redirect to login, when login is successful, redirect to another page. But I get this error, reverse for "url-name" not found. "Url-name" is not a valid view function or pattern name. From the browser traceback it highlighted this code for me 47. return redirect ("videos") Local vars Below is the code. from django.urls import path from .views import Display_all,Registration_view,Login_view,logout_view,index_view urlpatterns = [ path('videos/', Display_all, name ="video"), path('register/',Registration_view, name ='registration'), path('login/', Login_view, name = "login"), path('logout/', logout_view, name = "logout") The views from django.http import HttpRequest, HttpResponse from django.shortcuts import redirect, render from django.views import View from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from .forms import RegistrationForm from django.contrib.auth import authenticate,login, logout from .models import Video def Display_all(request): all_videos = Video.objects.all() context = {"all_videos":all_videos} return render(request, 'videos/displayall.html', context) def Registration_view(request): form = RegistrationForm(request.POST or None) if form.is_valid(): form.save() return redirect("login") else: form = RegistrationForm() context = {"form":form} return render(request, 'profiles/registration.html', context) def Login_view(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request,username=username,password=password) if user is not None: login(request,user) return redirect ("videos") return render(request, 'profiles/login.html',{}) The simple login template <!DOCTYPE html> <html lang="en"> … -
ERROR: Invalid requirement: 'asgiref 3.5.2'
I am new to heroku and I wanted to deploy a simple app, when i push to heroku it is given me the error below. I check online unfortunately I dont find the right answer to it. ERROR GIVEN Enumerating objects: 73, done. Counting objects: 100% (73/73), done. Delta compression using up to 4 threads Compressing objects: 100% (71/71), done. Writing objects: 100% (73/73), 24.58 KiB | 719.00 KiB/s, done. Total 73 (delta 11), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> No Python version was specified. Using the buildpack default: python-3.10.4 remote: To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.10.4 remote: -----> Installing pip 22.0.4, setuptools 60.10.0 and wheel 0.37.1 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: ERROR: Invalid requirement: 'asgiref 3.5.2' (from line 1 of /tmp/build_44a6c2b3/requirements.txt) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to olakaymytodo. remote: To https://git.heroku.com/olakaymytodo.git ! [remote rejected] main -> main (pre-receive … -
how to Serialize multiple objects in Django
I have 2 models for admin and member positions and I would like to get both of the models in one API call to fetch the data on my front end. I tried to do many things so can some one help me :( class ClinetAdminPosition(models.Model): name = models.CharField(max_length=128, null=True) company = models.ForeignKey( to="Company", on_delete=models.CASCADE, related_name="admin_positions", null=True ) modified_at = models.DateTimeField(verbose_name="Updated", auto_now=True, editable=True) created_at = models.DateTimeField(verbose_name="Created", auto_now_add=True, editable=False) def __str__(self): return f"{self.name}" class ClinetMangerPosition(models.Model): name = models.CharField(max_length=128, null=True) company = models.ForeignKey( to="Company", on_delete=models.CASCADE, related_name="manger_positions", null=True ) modified_at = models.DateTimeField(verbose_name="Updated", auto_now=True, editable=True) created_at = models.DateTimeField(verbose_name="Created", auto_now_add=True, editable=False) def __str__(self): return f"{self.name}" I want to get both models' data from 1 API request to be like this: [ { "admin_positions": [ { "name": "test", "company": 1 }, { "name": "test2", "company": 1 }, { "name": "test3", "company": 1 } ], "manger_position": [ { "name": "test", "company": 1 }, { "name": "test2", "company": 1 }, { "name": "test3", "company": 1 } ] } ] -
Django CSRF not working on SSL(HTTPS), but working on local(linux), tried all things
Following is the Error i get : 403 : CSRF verification failed. Request aborted. When Debug = True : Reason given for failure: Origin checking failed - https://example.com does not match any trusted origins. Basic Checks : site is having valid working ssl browser is accepting cookie for this site In settings.py "CSRF_COOKIE_SECURE = True" is set In settings.py "django.middleware.csrf.CsrfViewMiddleware" is above other View Middleware I have tried many things, nothing works. It works perfectly on development environment -
How do I destructure an API with python Django and django-rest-framework?
I have a successfully compiled and run a django rest consuming cocktaildb api. On local server when I run http://127.0.0.1:8000/api/ I get { "ingredients": "http://127.0.0.1:8000/api/ingredients/", "drinks": "http://127.0.0.1:8000/api/drinks/", "feeling-lucky": "http://127.0.0.1:8000/api/feeling-lucky/" } but when I go to one of the links mentioned in the json result above, for example, http://127.0.0.1:8000/api/ingredients/ I get an empty [] with a status 200OK! I am learning and I would appreciate any tips on where I should focus on. Thanks in advance. -
filter Boto3 s3 file filter does not find file
I am trying to check if a file exists in boto3 with django before adding it to the django model session = boto3.Session( aws_access_key_id=env("AWS_ACCESS_KEY_ID"), aws_secret_access_key=env("AWS_SECRET_ACCESS_KEY"), ) s3 = session.resource( "s3", region_name=env("AWS_S3_REGION_NAME"), endpoint_url=env("AWS_S3_ENDPOINT_URL") ) bucket = s3.Bucket(env("AWS_STORAGE_BUCKET_NAME")) Then when I try to search the file: objs = list(bucket.objects.filter(Prefix="media/" + name)) It shows that it could not find the file with according to the name passed. Although when I do bucket.objects.all(), I find the file existing under media/NAME_HERE -
When I use Bootstrap to build a web apps by python but it didn't show me the correct page
enter image description here enter image description herecom/KF5ap.png -
template rendering works fine but when I use template inheritance it displays error
I tried the using {% include 'navbar.html'%} on room.html template both of them work fine and display the template but when I add {% include 'navbar.html'%} in room.html try to render it displays this error I adjust have also include the templates in the setting what seems to be the problem. The urls file in first app is from django.urls import path from . import views urlpatterns =[ path('',views.home), path('room/',views.room), path('navbar/',views.navbar), and the views file is like this from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request,'firstapp/home.html') def room(request): return render(request,'firstapp/room.html') def navbar(request): return render(request,'firstapp/navbar.html') def main(request): return render(request,'main.html') images of error displayed in Django and setting file [1]: https://i.stack.imgur.com/MH8fL.png error displayed in Django [2]: https://i.stack.imgur.com/Wh8Ot.png error displayed in Django [3]: https://i.stack.imgur.com/phUt0.png settings file -
Media Files and Static files not Displaying and working in Django
when deployed server then static files not working and media files not diplaying. 404 error here is the urls.py from django.views.static import serve import django from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path ('' , include('home.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and settings.py STATIC_URL = 'static/' STATIC_ROOT = '/usr/local/lsws/Example/html/demo/static' """STATICFILES_DIRS=( BASE_DIR / "static", )""" # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_URL = 'media/' MEDIA_ROOT = '/usr/local/lsws/Example/html/demo/static/media' CKEDITOR_UPLOAD_PATH = 'uploads' -
Strange Unterminated String literal error
I'm making a simple todo app with Django but the error Unterminated String literal is creating a lot of problems. I know there is no unterminated string literal but the error keeps arriving? What might be the cause? Line 11 is causing the trouble. -
Get 1,2,3,4,5 star average individually except from the main average
Suppose i have rated a user with 1 star 3 times, 2star 1times, 4star 4 times, 5star 10times.now from here anyone can find out overall average rating but how can i get the percentage of 1star,2star ,3star,4star and 5star from total rating #show it on a django way rating = Rating.objects.filter(activity__creator=u) one_star_count = rating.filter(star='1').count() two_star_count = rating.filter(star='2').count() three_star_count = rating.filter(star='3').count() four_star_count = rating.filter(star='4').count() five_star_count = rating.filter(star='5').count() total_stars_count = one_star_count + two_star_count+ \ three_star_count + four_star_count+ five_star_count -
unsuppoted operand type(s) for *: 'NoneType' and 'NoneType'
Helo everyone, am trying to compute unit price and the quantity from this table as follows class Marketers(models.Model): category =models.ForeignKey(Category, on_delete=models.CASCADE, null=True) name =models.CharField(max_length=50, null=True, blank =True) grade =models.CharField(max_length=50, null=True, blank =True) quatity_received = models.IntegerField(default=0, null=True, blank =True) unit_price =models.IntegerField(default=0, null=True, blank =True) customer = models.CharField(max_length=50, null=True, blank =True) date_received = models.DateTimeField(auto_now_add=True) date_sold = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = self.quatity_received * self.unit_price return total this is how i call it in my template <td class="align-middle text-center"> <span class="text-secondary text-xs font-weight-bold">{{ list.get_total }}</span> <p class="text-xs text-secondary mb-0">Overall Price </p> </td> this is the erro am receiving TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType' please i need help. Thanks -
API request doesn't return results
I am trying to run an API request equivalent to following: curl -X POST "https://api.mouser.com/api/v1.0/search/partnumber?apiKey=*****" -H "accept: application/json" -H "Content-Type: application/json" -d "{ \"SearchByPartRequest\": { \"mouserPartNumber\": \"RR1220P-512-D\", }}" with this function: MOUSER_API_BASE_URL = 'https://api.mouser.com/api/v1.0' MOUSER_PART_API_KEY = os.environ.get('MOUSER_PART_API_KEY') def get_mouser_part_price(request, pk): part = Part.objects.get(id=pk) headers = { 'accept': 'application/json', 'Content-Type': 'application/json' } data = { 'SearchByPartRequest': { 'mouserPartNumber': part.part_number, } } url = MOUSER_API_BASE_URL + '/search/partnumber/?apiKey=' + MOUSER_PART_API_KEY response = requests.post(url, data=data, headers=headers) part_data = response.json() print(part_data) But for some reason I am getting zero results from the function, while curl returns a result. Where is the error?