Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to implement the following requirements in django
Please, I need your suggestions, contributions, advise on how to implement the following in django: on user signup, validate email formatting and only allow signups with valid emails once signed up, enrich the User with geolocation data of the IP that the signup originated from based on geolocation of the IP, check if the signup date coincides with a holiday in the User’s country, and save that info data enrichment must be performed asynchronously, i.e. independently of the signup route API request implement retries for requests towards 3rd party API -
Populating Table Based on Drop Down Selection
Hi I'm trying to create a table that will show values based on the selected name. For instance if a drop down existed and a value was chosen, the rest of the fields would show the data associated with that chosen value. <div class="main-items"> <h2>Database</h2> <div class="card-items"> <table class="main-items-table"> <tr> <td class="menu-box-tab-items-identifiers">Name:</td> {% for d in database %} <td class="menu-box-tab-items" href="/cusip/{{d.company_name}}"><span>{{d.name}}</span></td> {% endfor %} </tr> <tr> <td class="menu-box-tab-items-identifiers">Item:</td> {% for d in database %} <td class="menu-box-tab-items"><span>{{d.item}}</span></td> {% endfor %} </tr> <tr> <td class="menu-box-tab-items-identifiers">Method of Shipment:</td> {% for d in database %} <td class="menu-box-tab-items" href="#6"><span>{{d.method_of_shipment}}</span></td> {% endfor %} </tr> <tr> <td class="menu-box-tab-items-identifiers">Days:</td> {% for d in database %} <td class="menu-box-tab-items" href="#6"><span>{{d.days}}</span></td> {% endfor %} </tr> <tr> <td class="menu-box-tab-items-identifiers">Location:</td> {% for d in database %} <td class="menu-box-tab-items"><a href="https://www.google.com/search?q={{d.location}}"></span>{{d.location}}</a></td> {% endfor %} </tr> <tr> <td class="menu-box-tab-items-identifiers">Country:</td> {% for d in database %} <td class="menu-box-tab-items" href="#6"><span>{{d.country}}</span></td> {% endfor %} </tr> </tbody> </table> </div> </div> Basically, if a drop down menu existed for all the "names", I would want all the other td's to show the data associated with that name. If anyone can help it would be greatly appreciated. -
Django email validation
In my django app, I want to include an email validation. I mean, is there any library or function that checks if the email domain a user enters actually exists and is valid before letting the user sign up in django? -
CSS3 Style problem - grid-template-columns using Django
(included website image) Essentially, on my website it displays the "Browse Topics" as well as the list of Topics indented as though it is 3fr(It is navigation so it should be on the left) while the "2 Rooms Available" and their contents are displayed beneath but as 1fr. I seem to have also made a mistake where it no longer shows one of 2 of the rooms with content while trying to fix it, the only thing that was changed was the <div> markers, before it displayed both.. X.X {% extends 'main.html' %} {% block content %} <style> .home-container{ display: grid; grid-template-columns: 1fr 3fr; } </style> <div class="home-container"> <div> <h3>Browse Topics</h3> <hr> <div> <a href="{% url 'home' %}">All</a> </div> {% for topic in topics %} <div> <a href="{% url 'home' %}?q={{topic.name}}">{{topic.name}}</a> </div> {% endfor %} </div> </div> <div> <h5>{{room_count}} rooms available</h5> <a href="{% url 'create-room' %}">Create Room</a> <div> {% for room in rooms %} <div> <a href="{% url 'update-room' room.id %}">Edit</a> <a href="{% url 'delete-room' room.id %}">Delete</a> <span>@{{room.host.username}}</span> <h5>{{room.id}} -- <a href="{% url 'room' room.id %}">{{room.name}}</a></h5> <small>{{room.topic.name}}</small> <hr> </div> {% endfor %} </div> </div> </div> {% endblock content %} Website Image -
Django form not working correctly after psw changing it gives error
$ the urls.py page, password change done is not working , i trued auth_views to change psw and done view but it gives the following: error Page NoReverseMatch at /accounts/settings/change_password Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name. Request Method: POST Request URL: http://localhost:8000/accounts/settings/change_password Django Version: 4.0.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name urlpatterns = [ path('settings/change_password', auth_views.PasswordChangeView.as_view (template_name="accounts/change_psw-dj.html"), name="change_psw"), path('settings/change_password_done', auth_views.PasswordChangeDoneView.as_view (template_name="accounts/change_psw_done-dj.html"), name="change_psw_done"), ] -
Django: Method to get url of images
Im working on an website currently i would like to switch from a class Product containing the images to following: models.py: class Product(models.Model): name = models.CharField(max_length=60) price = models.DecimalField(max_digits=10, decimal_places=2) # Digital Products do not need shipping digital = models.BooleanField(default=False, null=True, blank=False) # now being handled in ProductImage: # image = models.ImageField(null=True, blank=True) @property def imageURL(self): try: url = self.image.url # get placeholder if something does not work except: url = '/images/placeholder.png' return url class ProductImage(models.Model): product = models.ForeignKey(Product, related_name="images", on_delete=models.SET_DEFAULT, default=None, null=True) image1 = models.ImageField(null=True, blank=True) image2 = models.ImageField(null=True, blank=True) image3 = models.ImageField(null=True, blank=True) image4 = models.ImageField(null=True, blank=True) image5 = models.ImageField(null=True, blank=True) image6 = models.ImageField(null=True, blank=True) i used to get the url of the single image (which works fine if image is an attribute of Product) as follows: view.html: {% for product in products %} <img class="thumbnail" src="{{ product.imageURL }}"> {% endfor %} view.py: def store_view(request): # some code "product":Product.objects.all() context.update({"products":products}) return render(request, "view.html", context) Is there a way of getting the images through the ForeignKey relation? (For example by modification of the above method imageURL)? I have tried: models.py: class Product(models.Model) # same as above @property def imageURL(self): try: url = self.images.image1.url # get placeholder if something does … -
Django & AJAX combined
I'm trying to submit a simple form in Django that will contain an image to process it on server and get a response without refreshing the page. I look up for some tutorials how to use AJAX and jQuery to do this but I don't have much knowledge at this matter. I'm completly stuck and have no idea what shall I do next. So far my code looks like this: models.py class Snip(models.Model): #some fields snip = models.FileField(upload_to="snips/") latex = models.TextField(default = '') forms.py from .models import Snip from django import forms class SnipForm(forms.ModelForm): class Meta: model = Snip fields = ['snip'] HTML: <form id="snipForm" method="POST" enctype="multipart/form-data"> <input type="hidden" name="csrfmiddlewaretoken" value="..."> <div class="row align-items-center"> <div class="col-12"> <label for="id_snip">Snip:</label> <input type="file" name="snip" required="" id="id_snip" class="btn-success p-2 rounded"> <input type="submit" name="upload" id="upload" class="btn btn-secondary"> </div> </div> </form> JavaScript/AJAX var snip = document.getElementById("id_snip"); var upload_btn = document.getElementById("upload") upload_btn.addEventListener('click', function () { var form_data = new FormData(); var ins = document.getElementById('snip_file').files.length; if(ins == 0) { return console.log("No snip!!!") } form_data.append("file[]", snip.files[0]); csrf_token = $('input[name="csrfmiddlewaretoken"]').val(); form_data.append("csrfmiddlewaretoken", csrf_token); $.ajax({ url: "{% url 'generate' %}", dataType: 'json', cache: false, contentType: false, processData: false, //data: {'data': form_data, 'csrfmiddlewaretoken': csrf_token}, data: form_data, type: 'post', success: function (response) { // … -
How to use filterset before anothers filtering in get_queryset()?
What i mean: get_queryset(): q = Model.objects.some_filtering() #use filterset for this q q = q.another_some_filtering() return q Thanks for your help! -
Could not parse the remainder: '% if survey.questiontype1 == multiplechoice %' from '% if survey.questiontype1 == multiplechoice %'
I am trying to fetch a specific instance from the 'questiontype1' field in the Survey model, part of which looks like this from django.db import models from datetime import datetime # Create your models here. class Survey(models.Model): category = models.CharField(max_length=100, blank = True) description = models.CharField(max_length=5000, blank = True) location = models.CharField(max_length=10000, blank = True) image = models.ImageField (upload_to='images/') created_at = models.DateTimeField(default=datetime.now, blank = True) question1 = models.CharField(max_length=10000, blank = True) questiontype1 = models.CharField(max_length=100, blank = True) bol1 = models.BooleanField() choice1a = models.CharField(max_length=5000, blank = True) choice2a = models.CharField(max_length=5000, blank = True) choice3a = models.CharField(max_length=5000, blank = True) choice4a = models.CharField(max_length=5000, blank = True) question2 = models.CharField(max_length=10000, blank = True) questiontype2 = models.CharField(max_length=100, blank = True) Here is part of the view template that is linked to the model in question <div class="mb-3 mx-5"> <label for="question1" class="form-label ">Question 1</label> <input type="text" name="question1" class="form-control form-control-lg" id="question1" placeholder="question1"> <div class="mb-4 mx-5"> <label for="questiontype1" class="form-label">Question type</label> <div class="col-md-6"> <select name="questiontype1" id="questiontype" class="form-select col-md-6"> <option value="null">Select question type</option> <option value="multiplechoice">Multiple choice</option> <option value="freetext">Free text</option> <option value="trueorfalse">True or False</option> </select> </div> </div> So on the survey.html, I want to check the condition of 'questiontype1' and render the following section {% extends 'base.html' %} {% block … -
Django send_mail not working while smtplib works
I have a setup where I am using "send_mail" to send emails to the users using a gmail account. For some reason this function returns "smtplib.SMTPServerDisconnected: Connection unexpectedly closed". I am using a gmail account with 2 factor security enabled and an app password. If I just build a script using smtplib, it works. I am not sure how exactly to debug this issue. Code snippets below: settings.py ... EMAIL_HOST = 'smtp-relay.gmail.com' EMAIL_HOST_USER = "myemail@costumgmail.com" EMAIL_HOST_PASSWORD = "mypass" EMAIL_PORT = 587 EMAIL_USE_TLS = True ... djangotest.py from django.core.mail import send_mail send_mail('Django mail', 'This e-mail was sent with Django.', "myemail@costumgmail.com" , ['some.other@mail.com'], fail_silently=False) # smtplib.SMTPServerDisconnected: Connection unexpectedly closed smtplibtest.py from email.message import EmailMessage import smtplib email_sender = "myemail@costumgmail.com" email_password="mypass" email_reciever ='some.other@mail.com' subject = "test" body = "test" em = EmailMessage() em['sender'] = email_sender em['to'] = email_reciever em['subject'] = subject em.set_content(body) smtpObj = smtplib.SMTP('smtp-relay.gmail.com', 587) smtpObj.ehlo() # (250, b'smtp-relay.gmail.com at your service, [188.26.233.149]\nSIZE 157286400\n8BITMIME\nSTARTTLS\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8') smtpObj.starttls() # (220, b'2.0.0 Ready to start TLS') smtpObj.login(email_sender, email_password) # (235, b'2.7.0 Accepted') smtpObj.sendmail(email_sender, email_reciever, em.as_string()) # OK traceback from django: Traceback (most recent call last): File "<console>", line 1, in <module> File "/root/.virtualenvs/myenv/lib/python3.10/site-packages/django/core/mail/__init__.py", line 87, in send_mail return mail.send() File "/root/.virtualenvs/myenv/lib/python3.10/site-packages/django/core/mail/message.py", line 298, in send return … -
how to show same value of foreign field in admin panel- field name is that prize
when i generate a voucher code in class name unique code i need to know how can i show same value of prize field in draw as per unique code value Here we can see the[ this is the voucher code admin panel this is the draw adminpanel Now I need the same value of prize as the draw as per the unique code, Here we can see in the image there should be justdo or 10% instead of nothing or sorry models.py import logging import secrets from django.db import models from django.db.models.signals import post_save Get an instance of a logger logger = logging.getLogger(__name__) class Draw(models.Model): """ Class to represent each valid draw that happened in the system. """ email = models.EmailField() code = models.CharField(max_length=8) sent = models.BooleanField(default=False) rotation = models.IntegerField(default=0) date = models.DateTimeField(blank=True, null=True) prize = models.ForeignKey('Prize', on_delete=models.CASCADE, null=False, blank=False) retry_used = models.BooleanField(default=False) @classmethod def post_create(cls, sender, instance, created, *args, **kwargs): """ Connected to the post_save signal of the UniqueCodes model. This is used to set the code once we have created the db instance and have access to the primary key (ID Field). """ # If new database record if created: # We have the primary key (ID … -
Newbie Question: How can I automaticaly create a model instance in Django?
Hi Im pretty new to all this so sorry if I don't explain this very well. I want to create a model where I can make some football projections so far I have: class Team(models.Model): name = models.CharField(max_length=20) name_short= models.CharField(max_length=3) def __str__(self): return self.name_short class Projection(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="projection", null=True) title= models.CharField(max_length=20, blank=False) def __str__(self): return self.title def get_absolute_url(self): return reverse('projection-detail', kwargs={'pk': self.pk}) class TeamProjection(models.Model): title = models.ForeignKey(Projection, on_delete=models.CASCADE) team = models.OneToOneField(Team, on_delete=models.CASCADE) total_plays = models.IntegerField(null=True, blank=True) What Im trying to do is when you create a new Projection it will auto create an instance of Team Projection for each team in Team Model. So it would be something like: Projection 1 Arizona 1050 Projection 1 Atlanta 1020 and so on? -
How can I fill the Django forms field in view?
In my Django forms I have 5 fields but I will take 4 of them from the html template. The 5. one will be filled in the views. When I try to do like this it says form is not valid. How can I fill the data in views? forms.py class ProductForm(forms.ModelForm): class Meta: model = ProductModel fields = ('category','brand','series','model','asin') productform.html <form id="firstform" action="{% url 'productpage' %}" method="POST"> {% csrf_token %} <input type="text" id="category" name="category" placeholder="Category"> <input type="text" id="brand" name="brand" placeholder="Brand"> <input type="text" id="series" name="series" placeholder="Series"> <input type="text" id="model" name="model" placeholder="Model"> <input type="submit" id="save-button" name="save-button" value="Save" > </form> views.py def productpage(request): if request.POST.get('save-button'): form = ProductForm() if request.method == 'POST': form = ProductForm(data=request.POST) print("a") if form.is_valid(): print("i") form.cleaned_data["asin"] = "B324235252" form.save() HttpResponse("KAYDEDİLDİ") else: print("iiii") HttpResponse("Form is not valid") else: form = ProductForm() return render(request,"first_app/productform.html") -
django db not show to the html views
I normally configure as I think, the view, the url and the models but I still don't understand why nothing is displayed on the template, this is my problem currently help me solve this problem from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView from .models import Poster, CategoriePost class Posterlist (ListView): queryset = Poster.objects.all() template_name = 'blog.html' from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.urls import reverse from django.utils.text import slugify from ckeditor.fields import RichTextField class CategoriePost(models.Model): Nom_de_la_categorie = models.CharField(max_length=250) def __str__(self): return self.Nom_de_la_categorie class Meta: verbose_name = ("CategoriePost") verbose_name_plural =("CategoriePosts") STATUS = ( (0,"Brouillon"), (1,"Publier") ) class Poster(models.Model): categorie = models.ForeignKey(CategoriePost, on_delete=models.CASCADE, related_name='blog_categorie') titre = models.CharField(max_length=300, unique=True) slug = models.SlugField(max_length=300, unique=True) auteur = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') contenue = RichTextField(blank=True, null=True, config_name='default') status = models.IntegerField(choices=STATUS, default=0) image = models.ImageField(upload_to='media/', height_field=None, width_field=None, max_length=100,) date_publication = models.DateTimeField(default=timezone.now) date_creation = models.DateTimeField(default=timezone.now) date_mise_a_jour = models.DateTimeField(default=timezone.now) def save(self, *args, **kwargs): self.slug = slugify(self.titre) super(Poster, self).save(*args, **kwargs) def get_absolute_url(self): return reverse("blog:Post_detail", args=[self.slug]) class Meta: ordering = ('-date_publication',) verbose_name = ("Poster") verbose_name_plural =("Posters") def __str__(self): return self.titre {% block content %} <header class="masthead"> <div class="overlay"></div> <div class="container"> <div class="row"> <div class=" col-md-8 col-md-10 mx-auto"> <div class="site-heading"> <h3 class=" site-heading my-4 … -
Django - How to make admin not have own profile model
How to make the admin not have a profile created. I have a Profile, Relationships one to one model and want to exclude admin. -
My form field doesn't appears on my web app
I'm trying to make my first personal account web app and I have a trouble with it. I've created a bio model field in models and tryied get it in forms, but there is something is going wrong - this field doesn't want to display on web-site. The rest of the fields are working. Everything is fine at admin panel. Models: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): email = models.EmailField("email address", unique=True) bio = models.TextField("bio", max_length = 300, blank=True) Forms: class ChangeUserForm(UserChangeForm): password1 = forms.CharField( label=("Password"), strip=False, widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), ) password2 = forms.CharField( label=("Password confirmation"), widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), strip=False, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({'class':'input100','placeholder':'Username','name':'username'}) self.fields['email'].widget.attrs.update({'class':'input100','placeholder':'Email','name':'email'}) self.fields['password1'].widget.attrs.update({'class':'input100','placeholder':'Password','name':'password'}) self.fields['password2'].widget.attrs.update({'class':'input100','placeholder':'Repeat password','name':'password'}) class Meta: model = User fields = ['username', 'email', 'bio', 'password', 'password2'] widgets = { 'bio': TextInput(attrs={ 'class':'input100', 'placeholder':'Your bio', 'name':'bio' }), } Views: def edit_profile(request): form = CreateUserForm(initial={ 'username':request.user.username, 'email':request.user.email, 'bio':request.user.bio, }) if request.method == 'POST': form = ChangeUserForm(request.POST) if form.is_valid(): form.save() return redirect(home) else: return render(request, 'users/edit.html', {'form':form}) else: return render(request, 'users/edit.html', {'form':form,}) HTML: <div class="wrap-input100 m-b-16"> <div class="input100">{{ form.email }}</div> <span class="focus-input100"></span> </div> <div class="wrap-input100 m-b-16"> <div class="input100">{{ form.bio }}</div> <span class="focus-input100"></span> </div> There we can see that email field appears, whereas the … -
Django form invalid before rendering with a context processor
I have a slight issue with my form using Django. On my website I have a 'settings' box on every page (rendered with an 'include') in base.html - each settings box has a form which I am rendering with a 'context processor' however when rendering the form in the template nothing shows. Rendering with {{global_rebase_form.get_context}} I get the following message: {'form': <global_rebase_form bound=False, valid=False, fields=()>, 'fields': [], 'hidden_fields': [], 'errors': []} Suggesting it is invalid? My code is as follows Settings.py 'OPTIONS': { 'context_processors': [ 'apps.home.views.global_rebase_context', ... ], context processor: def global_rebase_context(request): form = global_rebase_form() return { 'global_rebase_form': form } template <form method="POST" name="time" id="rebase-form"> {% csrf_token %} {{global_rebase_form.as_p}} </form> form.py class global_rebase_form(forms.Form): class Meta: model = profile fields = ['location_rebase', 'time_rebase'] Any help would be greatly appreciated! -
Reverse and HttpResponseRedirect don't work with DefaultRouter
I need to send back response with product details, so I use HttpResponseRedirect and reverse. It requires the app_name:name, so I tried something like below, but I get error: django.urls.exceptions.NoReverseMatch: Reverse for 'product' not found. 'ProductViewSet' is not a valid view function or pattern name. This is my view: @api_view(['POST']) @permission_classes([IsAuthenticated]) def bump(request, pk): product = get_object_or_404(Product, id=pk) product.bumps.add(request.user) return HttpResponseRedirect(reverse('products:product', args=[pk])) This is my urls: app_name = 'products' router = DefaultRouter() router.register(r'', ProductViewSet) urlpatterns = [ path('', include(router.urls), name='product'), ] What is wrong in this code? I use the correct app_name and name. -
PostgreSQL local data not showing in Docker Container
I just want some help here, I'm kinda stuck here in Docker and can't find a way out. First, I'm using Windows for a Django APP and Docker I'm using PgAdmin4 with PostgreSQL 14 and created a new server for docker The log for the Postgres Image: 2022-07-16 19:39:23.655 UTC [1] LOG: starting PostgreSQL 14.4 (Debian 14.4-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit 2022-07-16 19:39:23.673 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 2022-07-16 19:39:23.673 UTC [1] LOG: listening on IPv6 address "::", port 5432 2022-07-16 19:39:23.716 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" 2022-07-16 19:39:23.854 UTC [26] LOG: database system was shut down at 2022-07-16 16:50:47 UTC 2022-07-16 19:39:23.952 UTC [1] LOG: database system is ready to accept connections PostgreSQL Database directory appears to contain a database; Skipping initialization Log from my image: (you can see that doesn't have migrations) 0 static files copied to '/app/static', 9704 unmodified. Operations to perform: Apply all migrations: admin, auth, contenttypes, controle, sessions Running migrations: No migrations to apply. Performing system checks... System check identified no issues (0 silenced). July 16, 2022 - 16:40:38 Django version 4.0.6, using settings 'setup.settings' Starting development server at http://0.0.0.0:8000/ Quit … -
Django Error with Update view associted with model with foreign keys
I have a model, ProjectNoteComments, that is for adding comments on ProjectNotes. Comments are related to notes and notes are related to projects via foreign keys. The ProjectNoteComments are displayed via the ProjectNotesDetailView view. When I add a ProjectNoteCommentUpdateview and corresponding link to the note detail view page I get the following error: Reverse for 'project_note_comment_update' with arguments '(6, 9, 20)' not found. 1 pattern(s) tried: ['projects/note/(?P[0-9]+)/comment/comment:pk/update\Z'] I have not been able to figure out how to solve this issue. The views: class ProjectNotesDetailView(FormMixin, DetailView): model = ProjectNotes id = ProjectNotes.objects.only('id') template_name = 'company_accounts/project_note_detail.html' comments = ProjectNotes.comments form_class = NoteCommentForm crumbs = [...] def form_valid(self, form): projectnote = get_object_or_404(ProjectNotes, id=self.kwargs.get('pk')) comment = form.save(commit=False) comment.projectnote = projectnote comment.created_by = self.request.user comment.save() return super().form_valid(form) def get_success_url(self): return reverse('company_project:project_note_detail', args=[self.kwargs.get('pk'), (self.object.id)]) def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) class ProjectNoteCommentUpdateView(UpdateView): model = ProjectNoteComments template_name = 'company_accounts/update_project_note_comment.html' fields = ['body'] def get_success_url(self): return reverse('company_project:project_note_detail', args=[self.kwargs.get('pk'), (self.object.id)]) The URLs path('project/<int:project_pk>/note/<int:pk>/', ProjectNotesDetailView.as_view(), name='project_note_detail'), path('note/<int:pk>/comment/comment:pk/update', ProjectNoteCommentUpdateView.as_view(), name='project_note_comment_update'), The relevant template code link on Projectnotedetail page: <div class="header-edit-link col-sm"> {% if perms.company_project.can_change %} <div><a href="{% url 'company_project:project_note_comment_update' object.project.pk object.pk comment.pk %}"><i class="fa … -
Django/Postgres fulltext search - exclude if value contains <STRING>
Trying to use Postgres search in Django using SearchVector and I want to exclude results if contain a given string. Is it possible? Example from docs: Entry.objects.annotate(search=SearchVector('body_text', 'blog__tagline')).filter(search='Cheese') What if I want to exclude objects whose blog__tagline contains "queso"? I can't exclude objects with "queso" before annotation because I want to include them when a search is not performed. -
django webpack loader render_bundle error
We have a legacy Django-webpack app using Django webpack loader. The app code moved into a /app directory and the render_bundle stopped working. The error message is File "/usr/local/lib/python3.9/site-packages/webpack_loader/templatetags/webpack_loader.py", line 22, in render_bundle tags = utils.get_as_tags( File "/usr/local/lib/python3.9/site-packages/webpack_loader/utils.py", line 71, in get_as_tags bundle = _get_bundle(loader, bundle_name, extension) File "/usr/local/lib/python3.9/site-packages/webpack_loader/utils.py", line 47, in _get_bundle bundle = loader.get_bundle(bundle_name) File "/usr/local/lib/python3.9/site-packages/webpack_loader/loader.py", line 116, in get_bundle filtered_chunks = self.filter_chunks(chunks) File "/usr/local/lib/python3.9/site-packages/webpack_loader/loader.py", line 58, in filter_chunks ignore = any(regex.match(chunk) File "/usr/local/lib/python3.9/site-packages/webpack_loader/loader.py", line 58, in <genexpr> ignore = any(regex.match(chunk) TypeError: expected string or bytes-like object webpack-stats.json {"status":"done","publicPath":"http://localhost:8001/","chunks":{"app":[{"name":"app.js","publicPath":"http://localhost:8001/app.js","path":"/app/static/dist/app.js"}]}} I hard-coded our STATICS_URL to try to match the documentation on django-webpack-loader DJANGO STATICS_URL: /app/static/dist/ WEBPACK PATH(output.path): /app/static/dist WEBPACK_LOADER: WEBPACK_LOADER = {"DEFAULT": {"CACHE": not DEBUG}} Code that triggers the error: {% render_bundle 'app' %} inside a index.html -
How to restrict website access? for whole domain site?
I have website django based, i need access control domain based like. I already established django own auth system and 2-auth system. I need for whole domain access control even for the static files. If that possible only access code not username and password, and this need to be hard coded env or something like this. Django version v4.0, Hosting Heroku -
JSON POST and GET 404 (Not Found)
I am trying to create an API in Django but am receiving the following errors message in the JavaScript console. GET http://127.0.0.1:8000/edit/undefined 404 (Not Found) POST http://127.0.0.1:8000/edit/undefined 404 (Not Found) Does anyone know how to fix this problem? API url: path("edit/<int:post_id>", views.edit, name="edit") views.py def edit(request, post_id): try: post = Post.objects.get(user=request.user, pk=post_id) except Post.DoesNotExist: return JsonResponse({"error": "Post does not exist."}, status=404) if request.method == "GET": return JsonResponse(post.serialize()) else: return JsonResponse({"error": "Need a GET request."}, status=404) JavaScript Function function edit_email(id){ console.log("edit button is clicked") document.querySelector('#post_itself').style.display = 'none'; document.querySelector('#date_and_time').style.display = 'none'; document.querySelector('#likes').style.display = 'none'; const textarea = document.createElement('textarea'); //get post fetch(`/edit/${id}`) .then(response => response.json()) .then(post => { textarea.innerHTML = `${post.post}` document.querySelector('#p_user').append(textarea); }) //save the post fetch(`/edit/${id}`,{ method: 'POST', post: JSON.stringify({ post: textarea.value }) }) } HTML {% for post in page_obj.object_list %} <div class = "individual_posts"> <a href="{% url 'username' post.user %}"><h5 id="p_user" class = "post_user">{{ post.user }}</h5></a> <h6 id = "post_itself">{{ post.post }}</h6> <h6 id="date_and_time" class = "post_elements">{{ post.date_and_time }}</h6> <h6 id="likes" class = "post_elements">{{ post.likes }}&#x1F44D;</h6> {% if post.user == request.user %} <button id="editButton" class="edit_button">Edit</button> {% endif %} </div> {% endfor %} I think something might be wrong in the way I am passing in the id to the API, … -
set calculated property on model only once
im using python3 + django, and i have a model of User with few fields an admin page where all the users are presented a form page where a single user is presented and can be updated an external API with 2 endpoints: GET /api/users/name (get all names for all the users) GET /api/users/:id/name (get name for user by id) i want to add a name property to be presented on admin page (as a column) and on a form page (read-only, not changeable) how can i add this "calculated" property without calling an api more than needed?