Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django TemplateDoesNotExist when generating URL
I want to have my URL to change based on the results displayed. For example, I want the URL to be .../profile_detail/1, but it always returns: NoReverseMatch at /search/ Reverse for 'profile_detail' with arguments '(UUID('f3ef1f95-f374-4ac4-b1aa-b5db5fd76af7'),)' not found. 1 pattern(s) tried: ['profile_detail/(?P<profile_id>[0-9]+)/$'] views.py def profile_detail(request, profile_id): user = get_object_or_404(CustomUser, pk=profile_id) return render(request, 'network/profile_detail.html', {'user': user}) models.py class CustomUser(AbstractUser): username = None uniqueID = models.UUIDField(max_length=20, default=uuid.uuid4) email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_("first name"), max_length=100) last_name = models.CharField(_("last name"), max_length=100) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [first_name, last_name] objects = CustomUserManager() def __str__(self): return self.email class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="profile") date_of_birth = models.DateField(blank=True, null=True) image = models.ImageField(upload_to='users/%Y/%m/%d/', blank=True) def save(self, *args, **kwargs): # Opening the uploaded image try: im = Image.open(self.image) output = BytesIO() # Resize/modify the image and convert to RGB from RGBA im = im.convert('RGB') im = im.resize((300, 300)) # after modifications, save it to the output im.save(output, format='JPEG', quality=90) output.seek(0) # change the imagefield value to be the newly modified image value self.image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.image.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) except: pass super(Profile, self).save() urls.py from django.urls import path from . import views from .views import SearchResultsView urlpatterns = [ path('feed', views.home, name="home"), path('', views.landing, … -
How to serialize incoming string array?
While working on a pet project, I ran into a problem. I have a post request with foreward data: { "name": "Name", "description": "Description", "questions": [ { "question": "question", "multiple": true, "variants": [ { "variant": "cloudy" }, { "variant": "cold" } ], "answer": ["cloudy","cold"] } ] } After saving the data to the database, when receiving this data, the answer field looks like this "answer": [ "[", "'", "c", "l", "o", "u", "d", "y", "'", ",", " ", "'", "c", "o", "l", "d", "'", "]" ], Why is this happening and how can I fix it? I have the following setup in Django REST Framework: models.py class Quiz(models.Model): name = models.CharField(max_length=250) description = models.TextField() date_created = models.DateTimeField(auto_now=True, db_index=True) class Question(models.Model): quiz = models.ForeignKey(Quiz, related_name='questions', on_delete=models.CASCADE) question = models.CharField(max_length=250) multiple = models.BooleanField(default=False) answer = models.CharField(max_length=30, default='') class Variant(models.Model): question = models.ForeignKey(Question, related_name='variants', on_delete=models.CASCADE, db_index=True) variant = models.CharField(max_length=30) serializers.py class VariantSerializer(serializers.ModelSerializer): class Meta: model = Variant fields = ['id', 'variant'] class QuestionSerializer(serializers.ModelSerializer): variants = VariantSerializer(many=True) answer = serializers.ListSerializer(child=serializers.CharField()) class Meta: model = Question fields = ['id', 'question', 'variants', 'answer', 'multiple'] class QuizSerializer(serializers.ModelSerializer): questions = QuestionSerializer(many=True) class Meta: model = Quiz fields = ['id', 'name', 'description', 'questions'] def create(self, validated_data): questions_data = validated_data.pop('questions') … -
Python: How to join an operator?
I'm currently developing a Django application with i18n support. This works by providing a field for each language for a given field. Example model: class Article(models.Model): title_en = models.CharField() title_de = models.CharField() title_fr = models.CharField() # etc... (under the hood this is automatically done using django-translated-fields) I would now like to filter for Articles with a given title. The title should be checked in every available language. (so in this case title_en, title_de and title_fr). If there was only one title, I could query like this: Article.objects.filter(title=my_title) I don't want to use this: Article.objects.filter(Q(title_en=my_title) | Q(title_de=my_title) | Q(title_fr=my_title)) since the fields are created dynamically and the available languages could change. My question I need to somehow join classes using the __or__ operator. I came up with this: Article.objects.filter(*[ Q(**{ f"name_{code}": my_name }) for code in available_languages ]) but the joining is missing. Is there any method to do this? Or is there a better method available to filter for the names? -
how to make thunk HTTP POST request to Django rest api
I'm pretty new to this, so I will show you the error first and then display my thought process. I am attempting to use a thunk (Http request in redux) to make a post request to my personal rest api in django. (so it can run cURL commands and use a authorization code to gain an access token and get user data from an API) when I make this request, the network returns a 201 status to stay it worked, while my console logs the dispatch as rejected, and gives the error, "message: "Unexpected end of JSON input". In this message, payload is undefined, and my payload is living in meta under arg. After much reserach, it looks like I either need to JSON.strigify something on my front end, OR that django is receiving a null object and not knowing what to do with it. I believe it is the latter, and not sure how to proceed. Here is my code: FRONTEND: slice.py import {createAsyncThunk} from '@reduxjs/toolkit' export const postRequest= createAsyncThunk('slice/postRequest', async postData => { const response= await client.post('url', {slice:postData}) return response.slice } ) component.py import {useDispatch} from 'react-redux' import {postRequest} from './slice' const Component = () => { const … -
Django DetailView - display boolean from models as checkboxes
There's a number of snippets to display booleans in Django Forms as checkboxes (i.e. specifying Checkbox as a widget). For instance (assuming a boolean field defined in the model for bar): class FooForm(forms.ModelForm): class Meta: model = Foo fields = ['bar'] widgets = { 'bar' : CheckboxInput(attrs={'class': 'required checkbox form-control'}), } However I also need to display a (disabled) checkbox in DetailView (client says so). But I can't figure out an elegant way to do this, since I don't have a form meta for details view... My current thinking is something like this (bootstrap checkbox): <div class="form-check"> <label class="form-check-label"> <input type="checkbox" {% if foo.bar %}checked{% endif %} disabled>Bar </label> <\div> Any way to accomplish this in a fashion closer to the Form's widgets? -
I am getting ERROR: AttributeError at /customer/5/ type object 'Customer' has no attribute 'orderitem_set'
Please help me I stuck at this problem. When Click on the view button I want to show all the orders from that user as shown in the image below, but when i click on it I am getting this error instead of order details for that customer. The models file contains models.py class Customer(models.Model): user = models.OneToOneField( User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=50, null=True) phone = models.CharField(max_length= 200, null = True) email = models.CharField(max_length=100) def __str__(self): return self.name class Order(models.Model): customer = models.ForeignKey( Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=True) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.customer) @property def shipping(self): shipping = False orderitems = self.orderitem_set.all() for i in orderitems: if i.product.digital == False: shipping = True return shipping @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class OrderItem(models.Model): product = models.ForeignKey( Product, on_delete=models.SET_NULL, null=True, blank=True) order = models.ForeignKey( Order, on_delete=models.SET_NULL, null=True, blank=True) quantity = models.IntegerField(default=0, null=True, blank=False) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.product.name @property def get_total(self): total = self.product.price * self.quantity return total The views.py file contains Views.py … -
Django filter by field on a relationship
How can I replicate this query with Django's ORM? SELECT * FROM commit INNER JOIN object on commit.object_id = object.id WHERE commit.created_at = object.created_at; My models: class Object(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) created_at = models.DateTimeField(default=timezone.now) class Commit(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) object = models.ForeignKey(Object, null=True, blank=True, related_name="commits") created_at = models.DateTimeField(default=timezone.now) -
Django Model field to populate another field
I'm back again, I've been on this for more than 48 hours, still couldn't find a response to this. I have this model. The Position table has Site Engineer, Site Manager, HVAC Engineer, etc Engineers have only one position each, and I want the manager field to be populated only if the Engineer created has a position Site Manager. If an Engineer is created, the manager field will be a dropdown list of Engineers who have the Site Manager position. from django.db import models class Position(models.Model): name = models.CharField(max_length=100, default='Site Engineer') def __str__(self): return self.name class Engineers(models.Model): region = ( ('SS', 'South-South'), ('SW', 'South-West'), ('SE', 'South-East'), ('NE', 'North-East'), ('NW', 'North-West'), ('NC', 'North-Central'), ) firstname = models.CharField(max_length=20) lastname = models.CharField(max_length=20) email = models.EmailField(max_length=50) username = models.CharField(max_length=20, default='Leave Blank', unique=True) phone = models.CharField(max_length=11) position = models.ForeignKey(Position, on_delete=models.DO_NOTHING) workarea = models.CharField(max_length=20, choices=region) manager = models.CharField(verbose_name='Site Manager', max_length=80, default=None) def save(self, *args, **kwargs): self.username = self.firstname +'.'+self.lastname self.manager = self.firstname +' '+self.lastname super(Engineers, self).save(*args, **kwargs) def __str__(self): return self.firstname + ' ' + self.lastname This code only fills the manager field with the name of the Engineers, even if they are not Site Managers. Please help -
Django REST API set allowed hosts for individual endpoints
I would like to have different values for ALLOWED_HOSTS for different Django REST API endpoints. Is this possible? Here are more details: I have a setup consisting of a Django REST API backend, a React frontend, a Postgresdb and nginx, each running in a docker container, managed by docker compose. I am exposing Django API endpoints that are accessed by the frontend from the user's browser, so I am adding the domain of the frontend to allowed hosts. However, I have one specific API endpoint that should only accept requests from the frontend docker container but never accept requests from outside. It should only be used for communication between the frontend and the backend container. So in this case i would have to restrict allowed hosts to the ip of the docker container. Both settings are possible and working, but I can only choose one of both in the global Django settings. My question is: Is it possible to set allowed hosts for an individual endpoint/url? -
How to serve form to multiple Django views
I have a Django form in a modal which needs to be included in many pages across my website. I've read and re-red all similar issues on StackO and been through the documentation but still have questions as to the best way to achieve this. So: I want to put a subscribe modal on many pages. I want a single view to handle the form submission. The form has pre-filled fields so I need to put some things into the context of the view, which sounds like a middleware thing, but I'm not sure. I've created a class-based view which serves the form to some of the urls like the first two listed here ('about' and 'faq'): urls.py url(r'^about/$', views.SubscribeFormView.as_view(template_name='about.html'), name='about'), path('faq/', views.SubscribeFormView.as_view(template_name='faq.html'), name='faq') views.py class SubscribeFormView(View): form_class = forms.SubscribeForm template_name = 'modals/subscribe-modal.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) form_error = False if form.is_valid(): ... return redirect('{}?{}'.format( reverse('site_subscribe', args=[site.id]), urlencode({ 'duration': request.POST.get('duration', ''), }) )) else: form_error = True context = { 'form': form, 'form_error': form_error } ... return render(request, self.template_name, context) However I run into a problem with how to get this view to … -
Django: Certain users get random 404 error
I'm facing a strange issue that I can't handle on my own. In normal cases when users click on a link, then they are directed to a page where they can edit their hook baits (objects). However, certain users get 404 errors, but I don't know why because the page is rendered for most users. html where the link is <div class="row justify-content-center mx-2" > <div class="col-12 p-0"> <ul class="list-group text-center custom-borders m-2 p-0"> {% if own_hookbaits.count == 0 %} <a href="{% url 'user_profile:hookbaits' request.user.fisherman.fisherman_id %}" class="list-group-item" >No hook baits yet</a> {% else %} {% for hookbait in own_hookbaits %} <a href="{% url 'user_profile:hookbaits' request.user.fisherman.fisherman_id %}" class="list-group-item">{{ hookbait.name }}</a> {% endfor %} {% endif %} </ul> </div> views.py class HookBaitUpdateView(UpdateView): model = HookBait template_name = "user_profile/hookbaits.html" form_class = HookBaitForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['formset'] = HookBaitFormset(queryset=HookBait.objects.filter(fisherman=self.request.user.fisherman)) return context def post(self, request, *args, **kwargs): formset = HookBaitFormset(request.POST) if formset.is_valid(): return self.form_valid(formset) else: return self.form_invalid(formset) def form_valid(self, formset): instances = formset.save(commit=False) for instance in instances: instance.fisherman = self.request.user.fisherman instance.save() return super().form_valid(formset) def form_invalid(self, formset): return HttpResponse("Invalid") def get_success_url(self): return reverse('user_profile:profile', args=(self.kwargs['pk'],)) urls.py app_name = "user_profile" urlpatterns = [ path("profile/<int:pk>/", views.ProfileView.as_view(), name="profile"), path("profile/<int:pk>/hookbaits/", views.HookBaitUpdateView.as_view(), name="hookbaits"), ] rendered html <div class="row justify-content-center … -
ERROR: null value in column "fname" of relation "app_form" violates not-null constraint
select * from PUBLIC.app_form COPY PUBLIC.app_form(pincode, district) FROM 'C:\Users\HP\Desktop\pincode2.csv' DELIMITER ',' CSV HEADER; ERROR: null value in column "fname" of relation "app_form" violates not-null constraint DETAIL: Failing row contains (6, null, null, Wayanad, 673575). CONTEXT: COPY app_form, line 2: "673575,Wayanad" SQL state: 23502 -
Django,Docker - Cannot use ImageField because Pillow is not installed
I`m trying deploy the Django project for productions.I use Postgres, Nginx and Gunicorn. In a Docker container I have installed package Pillow==8.3.1 (I also tried version 8.3.0). In Dockerfile I have dependencies: RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev jpeg-dev zlib-dev libjpeg RUN pip install --upgrade pip COPY . . COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt when I execute the migrate command: docker-compose exec web python3 manage.py migrate Shows me errors: SystemCheckError: System check identified some issues: ERRORS: poszukiwania.Rzeczy.image_obverse: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". poszukiwania.Rzeczy.image_reverse: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". Any suggestions on how to fix this? -
Is there a way to do more coding/refresh screen after a return FileResponse in django?
I've created a pdf successfully, code roughly: .......blah blah ..... c.setFont('Arial', 55) c.drawString(140, 160, '30 DAYS') c.setFont('Arial', 38) c.drawString(110, 260, 'Terms of Payment') c.showPage() c.save() buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='hello.pdf') messages.success(request, f'Thank you file in download folder!') return HttpResponseRedirect(request.META.get('HTTP_REFERER')) i would like to include the message and reload after the fileresponse is there a way of doing this? as the last two lines of code are ignored -
How to fix "exit status 1 " error when deploying on digital ocean
I'm trying to deploy a django website on digital ocean. I was able to clone my project from GitHub to droplet on digital ocean. This web project I cloned has requirements.txt file. When I ran the command pip install -r requirements.txt in other to install all the packages in my project, the packages installed halfway and threw back an error message ERROR: Command errored out with exit status 1 as found in the the attached photograph. Also, I used MySQL locally but I want to use postgrel on live server. Why am I getting the error message? I can't find where I made any mistake. -
Django admin - property options based on a related parent model
I have a parent and a child class. The relation between them is many-to-one like this: class Parent(AccessmanagerMixin, models.Model): name = models.CharField(max_length=150) def __str__(self) -> str: return self.name class Child(AccessmanagerMixin, models.Model): name = models.CharField(max_length=150) parent_group = models.ForeignKey(Parent, on_delete=models.CASCADE, null=True ) def __str__(self) -> str: return self.name they both have a many-to-many relation with User class,named read_users (its a custom security on object level). class AccessmanagerMixin(models.Model): read_users = models.ManyToManyField(User, related_name='read_users') class Meta: abstract = True For example in the admin I would like to use the users from Parent read_users as an option for selecting the read_users for the Child entity? How can I do this in a best way? Can I override the read_users property in the Child admin.ModelAdmin. -
how to create auto slugfield in ddjango restframework in django like
class AddCategory(admin.ModelAdmin): list_display = ['name', 'slug'] prepopulated_fields = {'slug': ('name',)} class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ['name', 'slug', 'icon'] lookup_field = 'slug' -
Django: Cant Update/save form
Just a small question in relation to updating my form. I have 2 main pages, the dashboard and auditform pages. Everything works when i click on any item on the home page it directs me to the form page, and all the required information relating to the clicked item populates. The issue is when im trying to Save/Update the file. I believe the issue has to do with the views.py when trying to save, as after i click submit it doesnt redirect me to the home page. Here are the relevant files: urls.py: urlpatterns = [ path('Home/', views.homePage, name='Home'), path('AuditForm/<str:pk>/', views.auditFormPage, name='AuditForm'), path('register/', views.registerPage, name='Register'), path('Login/', views.loginPage, name='Login'), ] urlpatterns += staticfiles_urlpatterns() views.py: def auditFormPage(request, pk): data= datas.objects.get(Task_ID=pk) form = auditForm(instance=data) context = {'data': data} if request.method == 'POST': form = auditForm(request.POST , instance=data) if form.is_valid(): form.save() return redirect('Home') return render(request,"main/auditform.html", context) HTML Webpage: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}" /> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>QS Tool Demo 1</title> <!-- Google Fonts --> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <!-- Lightbox --> <link href="path/to/lightbox.css" rel="stylesheet" /> <!-- Stylesheets --> … -
Passing HTML value to django view returning NoReverseMatch error
I want to pass a pk value from my html to my django view. My button: <a href="{% url 'acceptdonation' pk=donation.pk %}" >Accept</a> The problem is that I am getting an error saying NoReverseMatch at /donations/73/ Reverse for 'acceptdonation' with keyword arguments '{'pk': 73}' not found. 1 pattern(s) tried: ['acceptdonation/$'] But if I remove the part where I pass a pk into my view, the code works fine. Why is this? I want to be able to pass a pk from my HTML into my django view. My view is down bellow (Basically I am deleting the Donation by the pk) def acceptdonation(request, pk): #add pk after request deleteitem = Donation.objects.filter(id = pk) deleteitem.delete() return redirect('/dashboard/') -
How do I host my django rest framework app on plesk
I have a django rest framework application. I want to host that on Plesk Obsidian 18.0.37, os:Ubuntu 20.04.2 can anyone help me to configure the plesk panel , beside the django app? thanks in advance -
Django display HTML content in templates with CK editor
I'm working on a project using Python(3.9) and Django 3 in which I have a model for Blog posts with the content field of type RichTextUploadingField for CKeditor upload. Here's the model: From models.py: class PostModel(models.Model): title = models.CharField(max_length=120) author = models.ForeignKey(User, on_delete=models.CASCADE) content = RichTextUploadingField(blank=True, null=True, config_name='default',) slug = models.SlugField(blank=True, max_length=120) photo = models.FileField(upload_to='blog_images') created_at = models.DateTimeField(auto_now=timezone.now()) category = models.CharField(choices=CAT_CHOICES, max_length=100, blank=False, default='Default') read_time = models.IntegerField(blank=False) Now in the template, I want to display the content using the following HTML: <div class="post-rich-text w-richtext"> {{ object.content|striptags|make_list|slice:'1:'|join:'' }} </div> When I place my content from the admin panel, the content is in multiple p tags along with other HTML tags, but when It displays in the browses everything goes under without the p tag. Here's how content looks in admin: And Here's how content looks in the browser: I want to display all the tags as we placed them from the admin. What can be wrong here? -
Django sort posts by comments count
I have created two Django models namely Post and Comment. class Post(models.Model): title = models.CharField(max_length=255) post = models.TextField() class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.TextField() I would like to show all the posts on the homepage and order them by comments count. please help to achieve it. -
Django how to get input value by it's ID (not input name)
I have an input like <div class="input-group mb-3"> <input value="0" type="number" class="form-control summand" id="id_name" name="another_name"> </div> I know that if I use request.GET.get('another_name') I will get the value of the input, but how can I get the value of the input using its id, and not the name. Is there really no such way to get the value of input by id? Following code doesn't work. if request.method == 'GET': value = request.GET.get('id_name') -
how to return the values of a django page as a global variable in a python file?
So here I would like to take values on my django page to pass them in several python functions but I can't do it ideas? here I need to take the month and the region to apply some filter and and calculation with pandas for visualization <select id="dropdown"> {% for i in list_region %} <option value="{{ i }}">{{ i }}</option> {% endfor %} </select> <select id="month"> {% for j in list_mois %} <option value="{{ j }}">{{ j }}</option> {% endfor %} </select> <input type="submit" value="Select"> the function in file.py : def visualize(region,mois): data = df.loc[( df['region'] == region )] # ... return data -
python Azure webapp linux container not starting
I am trying to deploy this application from Azure repos. https://github.com/pointerness/Check I have cloned this into my companies Azure repo. This is a simple Python Django Hello World app. I have deployed this code on my personal Azure account many times and it works. I deployed this app via vscode into Azure and it works. However when I created a pipeline, It failed. I have used the same yml as available in the git. Just changed the names as per my organization. I get the error Container XXX for site XXX has exited, failing site start Things I have tried. Reset Publish Profile Tried with and without startup commands setting environment variables The docker logs has not been of much use. Any suggestions how I can debug