Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Initialize django ModelForm user field with current logged user
I'm trying to initialize some fields of my NewArticleForm with static data. In particular, I want to set the author field with the current logged user/author, and shouldn't be modifyable. This page is reachable only from logged user, and the information is also stored in the url: path('<int:user_id>/create', views.add_article, name='insert'), forms.py: class NewArticleForm(forms.ModelForm): class Meta: model = Article fields = ['author','title', 'content', 'pub_date'] pub_date = forms.DateTimeField(initial=timezone.now()) def save(self, commit=True): article = super(NewArticleForm, self).save(commit=False) if commit: article.save() return article models.py: from django.db import models from django.contrib.auth.models import User class Article(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateTimeField() title = models.CharField(max_length=50) content = models.TextField() def __str__(self): return self.title def get_year(self): return self.pub_date.year def get_month(self): return self.pub_date.month views.py: @login_required def add_article(request, user_id): if request.method == 'POST': form = NewArticleForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Articolo inserito con successo!') return redirect('/blog_app/') else: messages.warning(request, 'Qualche campo non è corretto, operazione fallita.') form = NewArticleForm() return render(request, template_name='blog_app/insert.html', context={'insert_form':form}) How can I set author with the current logged user? Bonus question: Why pub_date field, which is a DateTimeField, is displayed as text type? I can't change it. -
Default tabular inline to a, b ,c & d
I want to default my tabular inline form to A B C D class AnswerInline(admin.TabularInline): model = Answer extra=4 -
IntelliJ IDEA not loading dependencies from docker compose - python django
I have set up a remote interpreter from the docker-compose option for a Django project. Still, it is showing me red squiggly lines under the package imports. How can I fix this? docker-compose.yml services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=devdb - DB_USER=devuser - DB_PASS=changeme depends_on: - db db: image: postgres:14.5-alpine3.16 volumes: - dev-db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=devdb - POSTGRES_USER=devuser - POSTGRES_PASSWORD=changeme volumes: dev-db-data: Code ss Docker ss Docker config ss -
Calling same celery task multiple times in Django
I am totally new to celery and trying to call the same celery task multiple times parallel. Basically, my task creates some data in an external third-party app through API and export created data with a third-party generated id. Now if I run the same tasks multiple times, third-party generated id changes to the latest instance of the task. Can I know how can I solve this issue? I tried saving the third-party generated id with task id in the results backend, but then how to do I, access this data form results backend? Is there any other way to do it? -
Django - button redirecting to {% url 'index' %}
I can't find any solution on any article so I'm asking here. I'd like to make button which is gonna redirect user to specific url. I have already did it this way: <button onclick="location.href='create_recipe/'" type="button" >Create new Recipe</button> but instead of passing whole link I'd like to use {% url 'some_view' %} but I do not have an idea how I should do that. Is it even possible to do that ? It has to be <button>, edit: something like: <button type="button" class="btn btn-outline-secondary"><a href="{% url 'index' %}">Create new Recipe</a></button> also does not work -
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 …