Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What to use for building a chat based on js and webhooks?
I'm building a Django application with Myzap as free whatsapp REST API backend. How to build a chat on a HTML by using some jquery plugin and receive messages based on webhooks? Is there any free plugin to do this? -
Django ArrayAgg- unsupported lookup error
Here are my models simplified, only essential fields. class Employee(Model): /*some fields */ class EmployeeConnection(Model): manager = models.ForeignKey('employee.Employee', related_name="manager_connection") class EmployeeGrouper(Model): group = models.ForeignKey("EmployeeGroups") connection = models.ForeignKey("EmployeeConnection") ArrayAgg gives me the next error: Unsupported lookup employeegrouper_set for AutoField or join on the field not permitted .annotate( group_ids=ArrayAgg( 'employee__manager_connection__ employeegrouper_set__group' ) can anyone help me to understand why 'employee__manager_connection_id' works good in ArrayAgg , but 'employee__manager_connection__employeegrouper_set__group' this one doesnot? And how to make it work? -
How do i manually accept a users sign up request in a social media website using django?
So im working on building a user verification form , so what's supposed to happen is that' - - User will come & sign up in the website After signing up the user's details will be sent to a moderator Moderator will manually reiew the details & then he'll be allowed to join the website Please help me out with the approach to tackle this situation -
Why django runserver command starts 2 processes? What are they for? And how to distinguish between each in the code?
While building some standalone Django app, which will be running tasks in the background as a separate daemon Thread, I ran into a problem because it seemed as if there are two MainThreads when starting the Django server, each Thread has a different id. After digging more into the problem, it turned out that it's because it's actually two processes. Experiement: Run django-admin startproject example && cd example to start a new project. Edit example/settings.py adding imoprt os if it's not already imported and then add the line print(f"Current processes ID:{os.getpid()}") Run python manage.py runserver and look at the output Current processes ID:426286 Current processes ID:426288 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. August 21, 2022 - 15:30:42 Django version 2.2.12, using settings 'example.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Change any file (for example just add a new line to settings.py) and save and look at the output /pathtoproject/example/example/settings.py changed, reloading. Current processes ID:426417 Watching for file … -
I want to create a user in django but create_user() method doesn't work
I'm trying to create a user using create_user method but it's not working and not showing any errors in my views.py I have the following code from django.contrib.auth.models import User from django.views import View from django.shortcuts import render, redirect from django.contrib import messages class Signup(View): def get(self, request): return render(request, 'myqpp/signup.html') def post(self, request): username=request.POST.get('username') pas = request.POST.get('password') email = request.POST.get("email") user = User.objects.create_user(username, email, pas) user.save() return redirect('/signin/') class Signin(View): def get(self, request): return render(request, 'myapp/signin.html') def post(self, request): username = request.POST.get('username') pas = request.POST.get('password') user = authenticate(username=username, password=pas) if user is not None: login(request, user) print('Success') return redirect('/', context={"user":user}) else: print('Failed') messages.error(request, 'Bad Credentials') return redirect('/signin/') I always get the message "Bad credentials" and when I review the Users table in django admin/ page it shows that there is no new user added When I click the submit button on the signup page, console log is like this [21/Aug/2022 15:31:50] "GET /signup/ HTTP/1.1" 200 3907 Failed [21/Aug/2022 15:32:07] "POST /signin/ HTTP/1.1" 302 0 [21/Aug/2022 15:32:07] "GET /signin/ HTTP/1.1" 200 3304 I don't know what is the problem as it's not showing any errors This is myqpp/urls.py from django.urls import path from . import views urlpatterns = [ path('', … -
Page not found. Django blog page not rendering
I am new to Django and learning this python framework. I have created a virtual environment called Virtual_Django_Project and installed Django in it. Moving ahead I created folder called Django_project and added an app called blog you can see my files here File Directories. Error >Page not found at /blog/ blog.views.py Code from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse('Home') blog.urls.py Code from django.urls import path from . import views urlpatterns = [ path('', views.home, name ='blog-home'), ] Main Django_Project.urls Code from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('blog.urls')), ] Can anyone tell me why my blog page is not opening and showing the error page not found? PS: Server is running in cmd. -
Error 111 connecting to 127.0.0.1:6379. Connection refused. cPanel (Django)
I'm using django-redis for caching. Everything works fine on local, but I got an error on production development (using cPanel). Does anyone know how to use django-redis on the production server? -
(django) I want to update it after registering the picture, but the picture doesn't come up whenever I update it
I'm making a review function, but if I register a picture in the review and update it, the picture doesn't come up properly. However, other writing contents are updated well. I don't know why only the picture doesn't show properly. here is view.py: def update(request, id): review = Post.objects.get(id=id) category = review.postType placeId = review.placeId if category == 'cafe': place = Cafe.objects.get(id=placeId) elif category == 'accomo': place = Accomodation.objects.get(id=placeId) else: place = Place.objects.get(id=placeId) if request.method == "POST": postGood = request.POST["postGood"] postBad = request.POST["postBad"] try: postImage = request.FILES['postImage'] except: postImage='NULL' ranking = request.POST["ranking"] Post.objects.filter(id=id).update(postGood=postGood,postBad=postBad,postImage=postImage,ranking=ranking) posts = Post.objects.filter(Q(postType=category)&Q(placeId=placeId)) total = 0 len_posts= len(posts) for p in posts: total += p.ranking place.star = total/len_posts place.save() return redirect(f"/reviewDetail/{review.id}") placeName = place.name location = place.location context = {"review":review, "placeName":placeName} return render(request, "reviewUpdate.html", context=context) here is update.html: def update(request, id): review = Post.objects.get(id=id) category = review.postType placeId = review.placeId if category == 'cafe': place = Cafe.objects.get(id=placeId) elif category == 'accomo': place = Accomodation.objects.get(id=placeId) else: place = Place.objects.get(id=placeId) if request.method == "POST": postGood = request.POST["postGood"] postBad = request.POST["postBad"] try: postImage = request.FILES['postImage'] except: postImage='NULL' ranking = request.POST["ranking"] Post.objects.filter(id=id).update(postGood=postGood,postBad=postBad,postImage=postImage,ranking=ranking) posts = Post.objects.filter(Q(postType=category)&Q(placeId=placeId)) total = 0 len_posts= len(posts) for p in posts: total += p.ranking place.star = total/len_posts place.save() … -
Django/Python thread returns --> TypeError: 'str' object is not callable
I have the following thread that returns the error TypeError: 'str' object is not callable # traceback Exception in thread Thread-164: <Thread(Thread-162, started daemon 6162526208)> Traceback (most recent call last): File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner [21/Aug/2022 14:29:36] "GET /tentacle/ HTTP/1.1" 200 24 self.run() File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) TypeError: 'str' object is not callable # threads.py def post_publisher_thread(): """ A thread that executes the post publisher """ t = threading.Thread(target=run_post_publisher()) t.start() print(threading.current_thread()) with run_post_publisher being a function inside utils.py. Why is this error popping up? I also checked these answers but it seems I don't pass strings, but a function to the target parameter already. -
bonsoir j'ai un problème j'essai de démarrer mon server django mais sa ne marche pas et sa le donne des erreurs
ImportError: cannot import name 'django' enter code herefrom 'myblog' (C:\Users\HIPMAN\Desktop\Myblog\myblog\myblog_init_.py)enter code here -
How to handle empty argument value in python function of Django views?
I have an application that passes the user name from the HTML template to the URL and functions in the views. views.py def cv_detail_view(request, username): if username=='': return redirect("accounts:login") else: user = get_object_or_404(User, username=username) try: personal_info = PersonalInfo.objects.get(user=user) except PersonalInfo.DoesNotExist: # if personal info doesn't exist redirect to create or 404 page. if user == request.user: return redirect("cvs:create_personal_info") else: raise Http404("CV Does Not Exist.") work_experience = WorkExperience.objects.filter(user=user) education = Education.objects.filter(user=user) context = { "personal_info": personal_info, "work_experience": work_experience, "education": education, } return render(request, "detail.html", context) Html snippet: <li><a class="nav-link" href="{% url 'cvs:cv_detail' user.username %}">Use templates</a></li> ursl.py path(r'^(?P<username>[\w._-]+)/$',views.cv_detail_view,name='cv_detail'), My idea is to redirect users to login page if the parameter username is empty i.e, if the user is not logged in. However, I get the following error: NoReverseMatch at / Reverse for 'cv_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['cvs/templates\\Z'] Request Method: GET Request URL: http://127.0.0.1:9090/ Django Version: 4.0.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'cv_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['cvs/templates\\Z'] Is there any way to handle the empty value in function arguments? -
Django send_mail dont sending non ascii symbols (cyrillic)
I'm trying to send like this: send_mail(u'Тема', u'Тело письма', EMAIL_HOST_USER, ['EMAIL_RECIPIENT']) But got smthing like this: "Sубьект" as subject. And "Тело РїРёСЃСЊРјР°" as body of message. How can I fix this problem. Help please. -
Get Context Data on Attribute within Model in Django DetailView
I am trying to filter all reviews that correspond to listings created by a certain viewer. The purpose is to put all the reviews someone has received on their listings on a profile page. I am able to use get_context_data to pull in the listing reviews, but I want to filter on a relationship within the listing itself. Views.py class ProfileDetailView(DetailView): model = Profile template_name = 'account/profile_detail.html' context_object_name = 'profile_detail' def get_object(self): return self.request.user.profile def get_context_data(self, **kwargs): context = super(ProfileDetailView, self).get_context_data(**kwargs) context['reviews'] = RentalListingReviews.objects.filter(RentalListing.lender = self.request.user) return context Models.py class RentalListing(models.Model): item_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) lender = models.ForeignKey( get_user_model(), on_delete = models.CASCADE, ) item_name = models.CharField(max_length=200) def __str__(self): return self.item_name def get_absolute_url(self): return reverse('rental_listing_detail', args=[str(self.item_id)]) class RentalListingReviews(models.Model): listing = models.ForeignKey( RentalListing, on_delete = models.PROTECT, related_name = 'listing_reviews', ) review = models.TextField(max_length = 1000) author = models.ForeignKey( get_user_model(), on_delete = models.PROTECT, ) def __str__(self): return self.review def get_absolute_url(self): return reverse('rental_listing_detail', args=[str(self.listing.item_id)]) -
conditional querysets Django
I'm trying to show the server to the user only if the user is a moderator or the creator of the server. so i wrote this code: class ServerModeratingView(LoginRequiredMixin, View): def get(self, request, server_tag): moderator = ServerModerator.objects.get(user=request.user) server = Server.objects.get(Q(tag=server_tag), Q(creator=request.user) | Q(moderators=moderator)) ... I thought Q object will make this code conditional like if the request.user is not the creator then user is a moderator this works fine if the user is a moderator of the server but the creator(creator is not one of the moderators so moderator queryset will be empty) shows this error: ServerModerator matching query does not exist. models.py: class Server(models.Model): ... tag = models.CharField(max_length=50, unique=True) moderators = models.ManyToManyField('ServerModerator', related_name='server') ... class ServerModerator(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='moderator_of') allow_create_tag = models.BooleanField(default=True) allow_create_rule = models.BooleanField(default=False) allow_remove_user = models.BooleanField(default=True) allow_remove_moderator = models.BooleanField(default=False) allow_delete_post = models.BooleanField(default=False) -
Django dynamic reverse url
Im using detailview to view user data as staff, and I also want to edit it. How do I approach the reverse url. Right now it reverses me on my staff pk but the goal is to reverse back to the user view page the update view class SVAVerwaltung(LoginRequiredMixin, UpdateView): model = SchulverzeichnisTabelle fields = ['Konto', 'S_Form', 'Schulname', 'SAB', 'GL', 'Zuege', 'Teilstandort', 'IH', 'SSt_OGS', 'OGS_Grp', 'VK', 'Z_SW', 'Z_besG', 'U_Ausf', 'U_Org', 'Schulleitung_Vorname', 'Schulleitung_Nachname', 'Lehrer_FK', 'GL_Lehrer_FK'] template_name = 'SCHUK/SVAVerwaltung.html' context_object_name = 'SVAVerwaltung' def get_success_url(self): return reverse('Ansicht', kwargs={'pk': self.object.pk}) the detail view from django.shortcuts import get_object_or_404 class Dashboard (AdminStaffRequiredMixin, LoginRequiredMixin, ListView): model = User template_name = 'SCHUK/Dashboard.html' context_object_name = 'Dashboard' def ansicht(request, pk): user = get_object_or_404(User, pk=pk) return render(request, 'SCHUK/Ansicht.html', context={'user': user}) class Ansicht(AdminStaffRequiredMixin, LoginRequiredMixin, DetailView): model = User template_name = 'SCHUK/Ansicht.html' context_object_name = 'Ansicht' def get_success_url(self): return reverse('Ansicht') ``` urls path('', Dashboard.as_view(), name="Dashboard"), path('Ansicht/<int:pk>', Ansicht.as_view(), name='Ansicht'), path('SVAVerwaltung/<int:pk>', SVAVerwaltung.as_view(success_url="Ansicht/<int:pk>"), name='SVAVerwaltung'), -
What will be the future of these Django vs React vs Flask framework?
I need suggestions about these web frameworks. I am confused which to choose for my carrier. -
Adding Alpine attributes to Django's form fields
I'm rendering django template form fields this way : <div x-data="{ amount: 0 }"> {% render_field field class=class %} </div> I want to add to the input : x-on:input.change="console.log('test');" How can I add this to render_field ? In forms.py as widgets = { 'amount': forms.TextInput(attrs={'x-on:input.change': "console.log('test');" }) } the only way ? Is there a way to add x-on:input.change via JavaScript ? -
How to make the ForeignKey either one of two models
I'm trying to make a social media web application using Django, I made a user model and a page model that can be managed by multiple users now I'm trying to make Posts model, Posts should be able to be posted by either users or pages, It's something like that: posted_by = models.ForeignKey(("accounts.User" or "accounts.Page"), verbose_name=_(""), on_delete=models.CASCADE) Can anyone help? -
problem with Django prepopulated.fields ModelAdmin option version(4.1)
hi guys i have simple model in django I have class model below: class Book(models.Model): title = models.CharField(max_length=75) author = models.CharField(max_length=75) rating = models.IntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)]) best_selling = models.BooleanField(null=False, default=False) slug = models.SlugField(default='', null=False, db_index=True, blank=True) I made admin page modification with below code: class BookAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("title",)} admin.site.register(Book) but problem is prepopulated_fields won't work not in database not in admin page in database I get blank as slug column can anyone help me with this issue thank you. -
Django Models - Form saves but model is blank
Not sure my title is fully representing my problem. I thought I would put a screenshot of the problem (admin panel), so it's clearer for everyone It looks like the form is savings, but nothing goes inside. Here is the models code: class Venue(models.Model): name = models.CharField(verbose_name="Name",max_length=100, null=True, blank=True) address = models.CharField(verbose_name="Address",max_length=100, null=True, blank=True) town = models.CharField(verbose_name="Town",max_length=100, null=True, blank=True) county = models.CharField(verbose_name="County",max_length=100, null=True, blank=True) post_code = models.CharField(verbose_name="Post Code",max_length=8, null=True, blank=True) country = models.CharField(verbose_name="Country",max_length=100, null=True, blank=True) longitude = models.CharField(verbose_name="Longitude",max_length=50, null=True, blank=True) latitude = models.CharField(verbose_name="Latitude",max_length=50, null=True, blank=True) city = models.CharField(max_length=120) def __str__(self): return str(self.name) if self.name else '' Obviously, I am aware I have asked to return '' if self.name wasnt there. The reason why I did it, is because initially, the models was visible on the admin panel under "-" but was throwing an error message when clicking on it. Considering I am working with a form, here is the form code: class VenueForm(forms.ModelForm): name = forms.CharField(max_length=100, required=True, widget = forms.HiddenInput()) address = forms.CharField(max_length=100, required=True, widget = forms.HiddenInput()) town = forms.CharField(max_length=100, required=True, widget = forms.HiddenInput()) county = forms.CharField(max_length=100, required=True, widget = forms.HiddenInput()) post_code = forms.CharField(max_length=8, required=True, widget = forms.HiddenInput()) country = forms.CharField(max_length=40, required=True, widget = forms.HiddenInput()) longitude = forms.CharField(max_length=50, required=True, widget … -
Cannot migrate in django using mysql
I'm trying to migrate my data from sqlite to mysql database but when I'm migrating the models, i'm getting the following error: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': (2059, "Plugin http could not be loaded: The specified module could not be found. Library path is 'http.dll'") django.db.utils.OperationalError: (2059, "Plugin http could not be loaded: The specified module could not be found. Library path is 'http.dll'") what can be the problem? I'm using Django 4.0.5, python 3.10.2, mysqlclient 2.1.1 -
Django signals: why create and save profile on 2 different functions?
I noticed from many django tutorials that Profiles are created and/or saved upon User post_save signal. Most codes go like this: from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() My question is, why do they use 2 functions instead of just one like this? @receiver(post_save, sender=User) def save_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() To my understanding, (1) when a new user is created, a new profile will also be created and saved thereafter; and (2) when a user is updated, its profile will also be updated but not created. Am I missing something? -
How do I convert this postgresql code to Django code?
This is my code in Postgresql -- create CREATE TABLE EMPLOYEE ( empId INTEGER PRIMARY KEY, username TEXT NOT NULL, userrole TEXT NOT NULL, roles TEXT NOT NULL, accesses TEXT NOT NULL ); -- insert INSERT INTO EMPLOYEE VALUES (0001, 'Clark','President', 'Admin','privileged'); INSERT INTO EMPLOYEE VALUES (0002, 'Dave','sales rep', 'Operational role','not privileged'); INSERT INTO EMPLOYEE VALUES (0003, 'Ava','finance manager', 'Managerial role','privileged'); -- fetch SELECT * FROM EMPLOYEE; SELECT *, CASE WHEN (roles, accesses) IN ( ('Admin','privileged'), ('Operational role','not privileged'), ('Managerial role','not privileged') ) THEN 'GRANTED' ELSE 'REVOKED' END AS permissions FROM employee; -
Helping with models in DjangoREST
I am making API in Django rest and I am not sure what to do with groupID. I have just 1 model - countries. I have assigned request and response. Request for POST is : {"name": "Czech Republic","countryCode": "CZ"} Response is: { "name": "Czech Republic","countryCode": "CZ","id": 123,"createdAt": "2022-08-21T11:49:39.239Z", "groupId": 123 } And I am supposed to create API for that. I am not sure what to do with groupI in model. class Countries(models.Model): name = models.CharField(unique=True, max_length=100) countryCode = models.CharField(unique=True, max_length=100) createdAt = models.DateTimeField(auto_now=True) groupId = models.CharField(unique=True, max_length=100) def __str__(self):return self.name -
Passing Information from Another Django Model Createview - Listing and Reviews
I have two Django apps, one with listings and another for accounts. Within the accounts app, I have a reviews model attached to the account, and I want users to have the ability to create a review for a listing that ultimately attaches to the account, not the listing, that way any listing reviews under a particular account are attached to the account itself, not necessarily the listing. Part of the reviews model is the listing and listing_author fields, that way I can filter on these fields later on. From the listing detail page, I want users to be able to click "Create Review" and create a review for a listing that is under the profile. I am running into an issue where I cannot pass the user_id and listing_id in the CBV CreateView, as the information from the listing_detail page (including these two fields) is not passed. Accounts Models.py class ProfileReviews(models.Model): user = models.ForeignKey( get_user_model(), on_delete = models.CASCADE, related_name = 'reviews' ) listing_item_id = models.UUIDField() review = models.TextField(max_length = 1000) rating = models.IntegerField() reviewer = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.review Listings Model.py class Listing(models.Model): item_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) lender = models.ForeignKey( get_user_model(), on_delete …