Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check if request user is in a models class
Lets say you have a class with name Car_club and in the class is members, which is a manytomany field to the User. Then you want to limit some part of the page for only members. class Car_club(models.Model): members = models.ManyToManyField(User, on_delete=CASCADE Lets say in the html there is parts where only the members of that class should see, how to manage that? -
How to exclude certain fields from a Model.save() in Django?
I tried solutions mentioned here but my model is inherited and it sometimes fails because when you set update_fields, it makes sure that something has updated. But that might not always be the case. Is there some other way where I can explicitly exclude certain fields from saving. Is there something available in the framework I can use. I would like to do something like if flag: super.save(exclude_fields=[field_1, field_2...]) else: super.save(*args, **kwargs) -
How to join two custom m2m tables - Django
I have the following: class Primera(models.Model): name = models.CharField(_("name"), max_length=50) def __str__(self) -> str: return self.name class PrimeraSegunda(models.Model): primera = models.ForeignKey(Primera, verbose_name=_("primera"), on_delete=models.CASCADE, related_name='primera_segunda_pri') segunda = models.ForeignKey('Segunda', verbose_name=_("segunda"), on_delete=models.CASCADE, related_name='primera_segunda_seg') amount = models.DecimalField(_("Amount"), max_digits=6, decimal_places=2, default=0) created_at = models.DateTimeField(_("Created at"), auto_now_add=True) class Segunda(models.Model): name = models.CharField(_("name"), max_length=50) primera = models.ManyToManyField(Primera, through=PrimeraSegunda, verbose_name=_("Clase Primera"), related_name='segundas') def __str__(self) -> str: return self.name class SegundaTercera(models.Model): segunda = models.ForeignKey(Segunda, verbose_name=_("segunda"), on_delete=models.CASCADE, related_name='segunda_tercera_seg') tercera = models.ForeignKey('Tercera', verbose_name=_("tercera"), on_delete=models.CASCADE, related_name='segunda_tercera_ter') amount = models.DecimalField(_("Amount"), max_digits=6, decimal_places=2, default=0) created_at = models.DateTimeField(_("Created at"), auto_now_add=True) class Tercera(models.Model): name = models.CharField(_("name"), max_length=50) segunda = models.ManyToManyField(Segunda, through=SegundaTercera, verbose_name=_("Clase Segunda"), related_name='terceras') def __str__(self) -> str: return self.name What I want to be able to do, is join both custom m2m tables to have access to their fields and also do calculations with the "amount" fields in both of the tables. Below you will find a sql statement equivalent: select st.* , ps.* from test_app_segundatercera as st join test_app_primerasegunda as ps on st.segunda_id = ps.segunda_id where st.tercera_id = 1 So far I have something like this: obj1 = PrimeraSegunda.objects.filter(segunda__segunda_tercera_seg__tercera=1).select_related() But I can't access the field in "SegundaTercera" pls help! -
On django framework, how can Put forms on footer
I am using django frame work for first time for a project. I have seperate header.html, footer.html and others page I want to put a newsletter subscription form in footer. Now how can I save the files on database. How can I call that particular form from every page.. I tried calling on footer.html, base.html and index.html everytime this doesn't works. Here's my model.py class NewsletterUser(models.Model): email = models.EmailField(max_length=254, null=False) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email And Views.py def subscription(request): if request.methods == "POST": email = request.POST['emailsubscription'] ins = NewsletterUser() ins.save() return render(request, 'footer.html') -
Django CORS from chrome extension
I'm deploying a Django app that will use help from a chrome extension to add some info to the app without the need to have it open on my browser, it worked ok when I made test on my computer but now I get the following django error: "Forbidden (Origin checking failed - chrome-extension://theIDfrommyextension does not match any trusted origins.): /smoke/add/" This is strange because I have the following CORS HEADERS configuration: CORS_ALLOW_ALL_ORIGINS = True CSRF_TRUSTED_ORIGINS = ['chrome-extension://*'] CORS_ALLOW_HEADERS = ( 'x-requested-with', 'content-type', 'accept', 'origin', 'authorization', 'x-csrftoken' ) I tought that with that configuration it should work because as far as I know I'm allowing CORS from all origins (I know that allow all CORS is insecure but is with test purposes) (I used django-cors-headers: https://pypi.org/project/django-cors-headers/): This is how I make fetch from my extension: function makeRequest(value) { // Send data to server url = 'https://my-test-app.herokuapp.com/smoke/add/'; let request = new Request(url, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'text/plain', 'X-CSRFToken': value.csrftoken, }, body: JSON.stringify({ info: value, }), }); return request; } serverRequest = makeRequest(contactData); fetch(serverRequest) .then((response) => response.json()) .then((data) => { if (data.error !== undefined) { sendResponse({ error: 'Ocurrió un error' }); } else { // data['leadId'] = data.contact.lead; … -
Connect to Sybase database from Django
I tried to connect to Sybase database from Django using sqlanydjango, but I have stuck. One answer saying that sqlany-django is no longer maintained; it was last updated in May 2016. What is the other possibility to connect to Sybase database? -
how to conditional render html element in a Django template
I am using django server to send user email notifications, I came into a place where I need to say if this elemet doesn't exist add margin/space underneath the text <tr style="padding:0;margin:0;" height="30"> <td width="190" style="font-family:Roboto;color:#000000;font-weight:bold">Date</td> <td width="400" style="font-family:Roboto;color:#000000;">{{ processed_datetime|date:"d/m/Y H:i" }}</td> <!--I want to say here if there is no other party email add this element underneath --> {% if ! counterpart.email} <!--not sure about this line syntax --> <tr style="padding:0;margin:0;" height="20"> <td width="190" height="20" style="font-family:Roboto;color:#000000;font-size:24px;line-height:32px;"></td> </tr> -
How to add custom title to django form fields?
I wanna add my own title to django form fields like this image. My models.py file from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): ad_soyad = models.CharField(max_length=255, default="") tarih = models.CharField(max_length=255, default="") dogum_tarihi = models.CharField(max_length=255, default="") dogum_yeri = models.CharField(max_length=255, default="") medeni_hali = models.CharField(max_length=255, default="") birinci_evlilik = models.CharField(max_length=255, default="") ikinci_evlilik = models.CharField(max_length=255, default="") bosanma_tarihi = models.CharField(max_length=255, default="") ogrenim_durumu = models.CharField(max_length=255, default="") meslek = models.CharField(max_length=255, default="") kan_grubu = models.CharField(max_length=255, default="") boy = models.CharField(max_length=255, default="") kilo = models.CharField(max_length=255, default="") max_kilo = models.CharField(max_length=255, default="") max_kilo_tarih = models.CharField(max_length=255, default="") author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() def __str__(self): return self.title + '|' + str(self.author) def get_absolute_url(self): # return reverse('article-detail', args=(str(self.id))) bu kod olursa yazı ekledikten sonra o eklenen yazıya gidiyor return reverse('home') And my forms.py file from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = 'all' #field = ('title', 'author') yapılabilir widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'author': forms.Select(attrs={'class': 'form-control'}), 'body': forms.Textarea(attrs={'class': 'form-control'}), 'ad_soyad': forms.TextInput(attrs={'class': 'form-control'}), 'tarih': forms.TextInput(attrs={'class': 'form-control'}), 'dogum_tarihi': forms.TextInput(attrs={'class': 'form-control'}), 'dogum_yeri': forms.TextInput(attrs={'class': 'form-control'}), 'medeni_hali': forms.TextInput(attrs={'class': 'form-control'}), 'birinci_evlilik': forms.TextInput(attrs={'class': 'form-control'}), 'ikinci_evlilik': forms.TextInput(attrs={'class': 'form-control'}), 'bosanma_tarihi': forms.TextInput(attrs={'class': 'form-control'}), 'ogrenim_durumu': forms.TextInput(attrs={'class': 'form-control'}), 'meslek': forms.TextInput(attrs={'class': 'form-control'}), 'kan_grubu': forms.TextInput(attrs={'class': 'form-control'}), 'boy': forms.TextInput(attrs={'class': 'form-control'}), 'kilo': forms.TextInput(attrs={'class': … -
Django rest framwork - how to prevent 1062, "Duplicate entry"
at my Django application (DRF only), I'm trying to create a new object where one of the fields is setup like this: resource_name = models.CharField(verbose_name="Resource Name", blank=False, null=False, max_length=50, unique=True) If I now try to create an Object with the same resource_name twice, I'm always running into the following exception: django.db.utils.IntegrityError: (1062, "Duplicate entry 'test_ressource123' for key 'resource_name'") Is there any good solution that I can apply to all kinds of these situations? Would be awesome to simply make the API response that the object already exists, kinda strange that this is not already a built-in of DRF. Can I maybe overwrite the def create function call of the serializer ? Any good advice welcome. -
Reverse for 'location-posts' for django
I'm trying to list all the posts on the same page that are shared in the same location. (when i create a post so if the location is "manhattan" when I click on the location of a post in the main page it will show me all the posts that have been shared in the same location by all users. I've watched some tutorials and I managed to list specific user's posts in the same page (nothing to do with location just by username) and I thought it would be fairly similar but didnt work. i guess theres something wrong with the way i use urls.py or the def so it gives me Reverse for 'location-posts' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<loc>[^/]+)$'] error so these are the related parts of my code: views.py class LocationPostListView(ListView): model = Post template_name = 'blog/location_posts.html' context_object_name = 'posts' paginate_by = 199 def get_queryset(self): user = get_object_or_404(User, loc = self.kwargs.get('loc')) return Post.objects.filter(location = user).order_by('-date_posted') urls.py from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, UserPostListView, LocationPostListView . . . path('post/<str:loc>', LocationPostListView.as_view(), name="location-posts"), location_posts.html <a class="mr-2" href="{% url 'location-posts' post.location.loc %}">{{ post.location }}</a> also: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = … -
How to select a group when registering a new user in Django
So whenever I create a new user I would like to select a group (executive or employee). What is the right way to do this? *The groups are already made in the Django Admin environment. -
Extract features from blob with Librosa
I am trying to record a voice message in the frontend and send it to the Django backend to test it against a ML algorithm of voice gender recognition. In the frontend I record the voice using videojs-record and I use AJAX to send the blob to the backend like so: {% extends 'base.html' %} {% load static %} {% block title %}Voice Detector{% endblock %} {% block extracss %} <link href="{% static 'css/voice_detector.css' %}" rel="stylesheet" /> <link href="{% static 'css/video-js.css' %}" rel="stylesheet" /> <link href="{% static 'css/all.min.css' %}" rel="stylesheet" /> <link href="{% static 'css/videojs.wavesurfer.min.css' %}" rel="stylesheet" /> <link href="{% static 'css/videojs.record.css' %}" rel="stylesheet" /> {% endblock %} {% block content %} <div class="banner"> <div class="max-width"> <div class="banner-content"> <p class="motto">Test your voice right now!</p> <p class="description"> Register your voice while reading the text below and our program will detect your gender in a few seconds! </p> </div> </div> </div> <div class="details"> <section class="section"> <div class="container"> <div class="columns"> <div class="column is-offset-4 is-4"> <h1 class="title">Record audio</h1> <article class="message is-success" id="alert"> <div class="message-header"> <p>Recorded successfully!</p> <button class="delete" aria-label="delete"></button> </div> <div class="message-body"> You have successfully recorded your message. You can now click on the Submit button to post it. </div> </article> <div class="field"> <div … -
Obtain absolute path on image ckeditor + django + react
Django There are 2 question about this topic, but both of them (this is one Absolute paths on images uploaded by django-ckeditor) are not updated. For example, in Django 4.X, url was removed. Despite this, I've tried these solutions, but no one worked for me. I've also tried to use: CKEDITOR_MEDIA_PREFIX on my settings.py But it didn't work either. So here is my question, how can I set up my Django-rest-framework app in such way that I get the absolute path when I render the html on my next.js site? This is what I get right now: <img alt=\"\" src=\"/media/uploads/2022/01/19/video.svg\"/> This is what I'd like to get: <img alt=\"\" src=\"http://website.com/media/uploads/2022/01/19/video.svg\" React Is there any way to achieve these from the frontend? For example, updating all img's src -
Why do I get model DoesNotExist but server is able to display it?
I don't understand the Traceback of the error, but Server is running fine (0 problems), and I get all the data I needed from the view.py. Seems it has to be with the get() method... DoesNotExist: matching query does not exist This are the models I used. from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): id = models.AutoField(primary_key=True) name = models.CharField(max_length=64, blank=True) image = models.ImageField(upload_to="portraits", blank=True, default="default.jpg") def __str__(self): return f"{self.username}" class Category(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=64) description = models.CharField(max_length=255, blank=True) def __str__(self): return f"{self.name}" class Item(models.Model): id = models.AutoField(primary_key=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="inventory") name = models.CharField(max_length=64) description = models.CharField(max_length=255) image = models.ImageField(blank=True, default="Megamind.jpg") starting_bid = models.PositiveIntegerField(default=0) category = models.ForeignKey(Category, on_delete=models.CASCADE, default="1", related_name="stuff") active = models.BooleanField(default=True) favorited = models.ManyToManyField(User, blank=True, related_name="favorites") def __str__(self): return f"{self.name} of {self.owner}" and the related view.py file def index(request): auctions = Item.objects.filter(active=True) context = {'auctions':auctions, 'title':'Active Listings'} return render(request, "auctions/index.html", context) def category_view(request, category): category = category.capitalize() category_obj = Category.objects.get(name=category) category_id = category_obj.id items = Item.objects.filter(category=category_id, active=True) context = {'auctions':items, 'title':category} return render(request, "auctions/index.html", context) If it helps: I'm passing from urls.py to view as str path("<str:category>", views.category_view, name="category") -
How to render Django context data (JSON) within external JavaScript file?
The question I have is: How do I get template-ed JSON data to be usable by .js file to see and use JSON data from my Django context? The problem I am trying to solve is: I am working on adding a CSP (Content Security Policy) to my Django website. The catch is that I have some inline JavaScript when templating JSON variables. This wouldn't be a problem, but the templating is inside the JavaScript section of the .html file. Thus, in order to abide by a strict CSP, I need to move the entire JavaScript portion out of the .html file and into a .js file. The code I need to move looks like this: <script> let data = [ { "key" : "Last 10 Days", "values" : {{ last_ten_days }}, }, { "key" : "Daily Score", "bar": true, "values" : {{ daily_scores }}, } ].map(function(series) { series.values = series.values.map(function(d) { return {x: d[0], y: d[1] } }); return series; }); </script> I am passing the values via a Django TemplateView to the context so I can render the data to plot, using NVD3.js, on my webpage. It looks something like this: class TheScores(LoginRequiredMixin, TemplateView): template_name = 'the_scores.html' def … -
Url not parsed when testing a ModelViewSet
I am trying to test a Django Rest Framework view. When I call my endpoint from a real api client, pk is correctly set. When it is called from the test, pk is None. class ResourceViewSet(ModelViewSet): serializer_class = ResourceSerializer @action(detail=True) def foo(self, request, pk=None): print(pk) # None when called by the test def test_foo(client: Client, db): request = factory.post(f'/api/resource/1/foo/') view = ResourceViewSet.as_view({'post': 'foo'}) response = view(request) How can I do to fix my test? -
Django url path is duplicated
I am getting a duplicate url pattern from newly added app : http://127.0.0.1:8000/quote/quote/new/ base app urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('', include('post.urls')), path('quote/', include('quote.urls')), ] New app urls.py: urlpatterns = [ path('quote/new/', QuoteCreateView.as_view(), name='quote-create'), ] I have tried: path('', include('quote.urls')), in base urls.py but get the same problem. -
Count booleans inside a for-loop in a django template
I would like to know how to count all the true/false booleans inside a for-loop in my django template, but im not sure how to achieve this inside the loop. My goal is to show the user how many questions are unsolved/solved. lets say these are my models: class Category(models.Model): name = models.CharField(max_length=50) class Question(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=50) description = models.TextField(max_length=250) solved = models.BooleanField(default=False) ListView: class CategoryView(ListView): model = Category context_object_name = 'categories' Template: {% for category in categories %} {{ category.name }} # I would like to show: 5/10 questions solved {% for question in category.question_set.all %} {{ question.name }} {{ question.title }} {{ question.description }} {{ question.solved }} {% endfor %} {% endfor %} Usually i print the total number of objects with .count like: {{ cagetories.count }} But i cant do this inside the loop because it returns: 1 1 1 1 1 1: {% for question in category.question_set.all %} {% if not question.solved %} {{ question.count }} ## returns 1 1 1 1 1 1 {% endif %} {% endfor %} Same thing with the {{ forloop.counter }} it returns multiple numbers because of the loop, but i only need that last … -
Django: foreign key (many-to-many) return empty queryset despite not being empty
My Model: class Account(models.Model): """ An account is for a team of users, or a single customer """ name = models.CharField(max_length=100, unique=True) admins = models.ManyToManyField('AccountUser', related_name='+', blank=True) metadata = models.JSONField(default=dict, blank=True) def __str__(self): return self.name @property def customers(self): """Accounts linked to this account""" return self.linked_accounts.linked_accounts.all() and my code: >>>account = Account.objects.get(id=1) >>> print(account) Bramble CFD >>> print(account.name) Bramble CFD when I try to get the admins many_to_many field I get the following empty queryset: >>> print(account.admins.all()) <QuerySet []> but the admins field is not empty as demonstrate by the following screen shot -
How to make dropdownlist of currency codes using django model
I need to make dropdownlist of all countries iso-4217 currencycodes like below, AFN-Afghani EUR-Euro USD-Dollar ... I have tried lot I don't get what I want. I just want to make it like CountryField() from django-countries.I have tried django-internation there i have got confused with how to implement that. If there is any possible to implement this one do reply.. Any help Appreciable.. -
Updating a django project from local to server
I want to have my local work in production so I pushed to gitlab what I had done locally and I pull to the django project on the server but when I do a python3 manage.py makemigrations then python3 manage.py migrate , that I restart nginx and that I go on my url of my api of the server I have an error message on what I have pull. I also had this error message locally but by doing a makemigrations followed by a migrate it was fixed there no... Error message on API: -
Django render function takes forever to load
I have a function definition in the views.py file of my Django app as follows: def dashboard_page(request, date_range=None): ''' This is the function ''' template = 'accounts/dashboard.html' dashboard_data_url = reverse('dashboard_data') return render(request, template, {'dashboard_data_url': dashboard_data_url}) The Templates configuration on the settings.py file is as follows: DEBUG = False TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates/'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages' ], }, }, ] I tried to debug the issue using the pdb and got the following error as shown in the screenshot. I tried to add print statements before the render function, that works fine. But the render function takes forever and returns no response. -
Currently file-upload is not present in ModelAdmin change page
I have a model ProductImages(models.Model) with a fk to Product(models.Model). In /admin/<app>/product/<id>/change/, all fields of Product(models.Model), even other models with fk to Product, show a data stored on db to edit, only ProductImages(models.Model) not display currently p.file-upload, like: That is other model(User model) with a expected bahavoir work. But in ProductImages(models.Model) part of Product(models.Model), this data is not present, i check the html maybe for css mistakes but not. Im not use a custom View, use admin.urls with custom site.admin. The code: models.py class Product(models.Model): ...#some fields def __str__(self): return self.slug or '' def get_absolute_url(self): return reverse('product_change', kwargs={'slug': self.slug, 'pk': self.pk}) def save(self, *args, **kwargs): self.product_title_seo = self.fn_product_title_seo self.product_title = self.product_title.capitalize() if not self.slug: self.slug = slugify(self.product_title_seo) return super().save(*args, **kwargs) class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image_file_w200_png = models.ImageField( verbose_name = "Imagens", upload_to=upload_to_image_file_w200_png, null=True, blank=True, default='magickhat-profile.jpg' ) ... admin.py class AdminProductImages(admin.TabularInline): model = ProductImages form = ProductImagesForm extra = 10 max_num = 10 list_display = ('image_file_w200_png',) fieldsets = ( (None, {'fields': ('image_file_w200_png',)}), ) add_fieldsets = ( (None, { 'fields': ( 'image_file_w200_png'), }), ) class Media: js = ('users/js/img_product_upload.js',) class AdminProductModel(admin.ModelAdmin): inlines = [AdminProductImages,AdminProductFeatures] model = Product def product_thumb(self, obj): # return HTML link that will not be escaped return mark_safe( … -
The view form.views.form_view didn't return an HttpResponse object. It returned None instead
I try to learn about form validation and this ValueError appears , here is my views.py and forms.py file forms.py : from django import forms from django.core import validators class SignUp(forms.Form): user = forms.CharField(label='User Name', max_length=100) email = forms.EmailField(label='Email', max_length=100) password = forms.CharField(widget=forms.PasswordInput, label='PassWord') botcatcher = forms.CharField(required=False, widget=forms.HiddenInput, validators=[validators.MaxLengthValidator(0)]) views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import SignUp # Create your views here. # 127.0.0.1/ def index(request): return render(request, 'home/index.html') # 127.0.0.1/form def form_view(request): if request.method == ('POST'): form = SignUp(request.POST) if form.is_valid(): return HttpResponseRedirect('/') else: form = SignUp() return render(request, 'form.html', {'signupForm' : form}) -
How to stop save -data if the data is saved within today for a user
class RequestPop(models.Model): request_pop = models.PositiveIntegerField(default=0) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE,unique=False,null=True) created_at = models.DateTimeField(auto_now_add=True) available_pop = models.PositiveIntegerField(default=0) def __str__(self): return "{}-{}".format(self.user,self.request_pop) def save(self, *args, **kwargs): if self.user: old_obj = RequestPop.objects.filter(user=self.user).filter(created_at = datetime.today).last() if not old_obj: super(RequestPop, self).save(*args, **kwargs) But my code is not working. How to stop save data if data already saved within today.