Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I specify the path of the config class in INSTALLED_APPS in Django?
The following tree, show my Django project structure. Now, in plain English, how do I add a new entry to INSTALLED_APPS in Django setting.py? (have already wasted 6 hours on this :( | manage.py | db.sqlite3 | +---journal | | asgi.py | | settings.py | | urls.py | | wsgi.py | | __init__.py | \---apps \---cards | admin.py | apps.py | models.py | tests.py | urls.py | views.py | __init__.py -
Django+React, API connection doesn't work
[Django + React API Communication fail][1] [1]: https://i.stack.imgur.com/IaSYY.jpgstrong text -
how to create download link for django uplouded files
ihave three types of files iam uploading (book,slide,question) so iwant to add this files to the a element to download this uploaded files sorry iam not very good in django and this is my last code in my project so can any body solve this for me .. and please tell me what i should put between href double couts def course_directory_path(instance, filename): return f'MU/Materials/{instance.number}/{filename}' def file_directory_path(instance, filename): if instance.type == "Slide": folder = "Study-materials" elif instance.type == "Book": folder = "Text-Books" elif instance.type == "Question": folder = "Exams-and-Homeworks" _, file_extension = os.path.splitext(filename) return f'MU/Materials/{instance.course.number}/{folder}/{instance.name}{file_extension}' class Course(models.Model): number = models.CharField(max_length=7, primary_key=True) name = models.CharField(max_length=30) # All Files download link # All Books download link # All Slides download link # All Questions download link bg_image = models.ImageField(upload_to=course_directory_path, null=True, default="defult_course.jpg") image = models.ImageField(upload_to=course_directory_path, null=True, default="defult_course.jpg") # Book picture for the card youtube = models.URLField(max_length=200, null=True, blank=True) discord = models.URLField(max_length=200, null=True, blank=True) whatsapp = models.URLField(max_length=200, null=True, blank=True) def all_files(self): files = File.objects.filter(course=self) s = StringIO.StringIO() with zipfile.ZipFile("", mode="w") as archive: for filename in files: print(f"{filename.file.url =}") fdir, fname = os.path.split(filename.file.url) print(f"{fdir = }, {fname = } ") zip_path = os.path.join("MU/Materials", fname) archive.write(filename.file.url, zip_path) return "multiple_files.zip" def __str__(self): return self.name class College(models.Model): number … -
How to do multiple request POST in django?
I have a view that sends a form to another view so that the user can review his form, and then after making another request post to save at that moment... so when the user enters the review view, he enters in request.POST and the form ends up being saved at the wrong time def resumo(request, avaliado_id): print(request.method == 'POST') perfil = Perfil.objects.filter(user_id=avaliado_id) queryDict = request.POST notas = (list(queryDict.values())) criterios = (list(queryDict.keys())) valores = (list(queryDict.values())) valores = [float(x.replace(",",".")) for x in valores[2:]] pesos = (queryDict.getlist('pesos')) pesos = [float(x.replace(",",".")) for x in pesos] res_list = [valores[i] * pesos[i] for i in range(len(valores))] media = sum(res_list) lista = zip(criterios[2:], notas[2:]) print(list(lista)) query_criterio = Criterio.objects.filter(ativo = True).values_list('id', flat=True) lista_criterio_id = list(query_criterio) if request.method == 'POST': avaliado = Perfil.objects.get(pk = avaliado_id) avaliador = request.user.perfil avaliacao = Avaliacao.objects.create(avaliador = avaliador, avaliado= avaliado, media = media) avaliacao.save() print(avaliacao.id) for nota, criterio in zip(notas[2:], lista_criterio_id): nota = Notas.objects.create(avaliacao = Avaliacao.objects.get(pk = avaliacao.id), notas = nota, criterios = Criterio.objects.get( pk = criterio)) nota.save() context = { 'media' : media, 'chaves_e_valores' : zip(criterios[2:], notas[2:]), 'perfis' : perfil, } return render(request, 'admin/resumo.html', context) in the first line "request.method == 'POST'" returns True and because of that it ends up hitting … -
Django REST - Invalid data. Expected a dictionary, but got {datatype}
Using DRF I'm attempting a PUT request to update a file in my database. I'm receiving the error seen in the title, exactly Invalid data. Expected a dictionary, but got {datatype}.. The full body says this (serializer.error_messages): { "required": "This field is required.", "null": "This field may not be null.", "invalid": "Invalid data. Expected a dictionary, but got {datatype}." } I don't see any additional helpful information in the terminal, just this exactly. My model is this: from django.db import models class File(models.Model): name = models.CharField(max_length=1024) upload_timestamp_date = models.DateField(auto_now_add=True) upload_timestamp_time = models.TimeField(auto_now_add=True) file = models.FileField() def __str__(self): return self.name My serializer is this: from rest_framework import serializers from .models import File class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields = '__all__' My view so far is this: @api_view(['GET', 'PUT', 'DELETE']) @csrf_exempt def file(request, file_id, format=None): try: data = File.objects.get(pk=file_id) except File.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = FileSerializer(data) return Response({'file': serializer.data}, status=status.HTTP_200_OK) elif request.method == 'PUT': serializer = FileSerializer(data, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.error_messages, status=status.HTTP_400_BAD_REQUEST) It comes down to the is_valid() call being false, with those error messages. I know that a GET request returns data like this: { "file": { "id": 1, "name": "test", … -
Django request doesn't save the logged in user
So I'm starting to learn Django authentication. from django.contrib.auth import login as log_in def login(request): ... if request.method == "POST": form = UserLoginForm(request.POST) if form.is_valid(): user = User.objects.filter(email=form.cleaned_data["email"]) if user.exists(): user = user.first() if check_password( form.cleaned_data["password"], user.password ): log_in(request,user) return redirect("/main/") else: messages.warning(request, "email/password are incorrect") else: messages.warning(request, "User not found") ... and I'm trying to access the request.user in another view like this: if request.user.is_authenticated: #do somthing but while debugging I found that after the first code log_in() statement the request.user is authenticated, but in the seconed code it's not. -
Why is Django generating a new session_key every time I refresh and hit a route?
I don't have SESSION_EXPIRE_AT_BROWSER_CLOSE set to true, I don't have req.session.modified set to true. And it seems like my browser cookie has a session id that's not changing on refresh. BUT, when I refresh the page and it re-hits the route, poof, I get a new session_key. So what could be causing this? I would like to keep the same session key, because I'm using it for user analytics tracking. -
IntegrityError at /signup UNIQUE constraint failed: auth_user.username
I'm trying to make an authentication system using Django using only 3 fields for SignUp (username & email & password ) and 2 fields for sign in ( username & password ) I think that the error that I get has relation to database, which I haven't used my models file yet, I don't know where the problem is coming from, is it from the signup function or the signing function IntegrityError at /signup UNIQUE constraint failed: auth_user.username Request Method: POST Request URL: http://127.0.0.1:8000/signup Django Version: 3.2.6 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: auth_user.username Exception Location: C:\Users\dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\Users\dell\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.0 Python Path: ['C:\\Users\\dell\\Desktop\\greenaftech', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32\\lib', 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\Pythonwin'] Server time: Sat, 30 Apr 2022 00:24:12 +0000 this is my views.py: from django.shortcuts import render,redirect from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib import messages # Create your views here. def home(request): return render(request,"website/index.html") def signup(request): if request.method=="POST": username=request.POST.get('username') password=request.POST.get('password') email=request.POST.get('email') myuser= User.objects.create_user(username,email,password) myuser.save() messages.success(request,"Your Account has been created.") return redirect('signin') return render(request,"website/signup.html") def signin(request): if request.method=='POST': usern=request.POST.get('username') passs=request.POST.get('password') user=authenticate(username=usern,password=passs) if user is not None: login(request,user) userr=user.username return render(request,"website/index.html",{'username':userr}) else: messages.error(request,"Wrong Infos") return redirect('home') return render(request,"website/signin.html") def … -
HTMX hx-trigger two functions
I have a selected dropdown list that triggers a function in my Django application. So I need to execute another function too. is it possible? this is the HTML code I tried to use hx-trigger with load after 0.5s but is executed once before the user selects the item! then I moved the function inside the page that it run after the user selects the item. it works but the returned request is shown in the wrong place! and I need it to be at the down of the page? <div class="col-md-3"> <select class="custom-select mb-4" name="fields" hx-get="{% url 'select_field' %}" hx-trigger="change" hx-target="#Wells" hx-include="[name='Toggle']"> <option selected>Select a field</option> {% for Field in TFTFields %} <option ue="{{Field.Perimeter}}">{{Field.Perimeter}}</option> {% endfor %} </select> </div> <div class="row"> <div class="col-md-12" > <div id="Wells"> {% include 'Home/Data_visa/part_Wells.html' %} </div> </div> </div> <div class="col-md-12" > <div id="part_MyWellsList"> {% include 'Home/Data_visa/part_MyWellsList.html' %} </div> </div> And this my part_Wells.html as <div class="col-md-3" > <select class="custom-select mb-4" name="Wells" hx-get="{% url 'addplotly' %}" hx-trigger="change" hx-target="#plotly_production" hx-include="[name='Toggle']"> <option selected>Select Well</option> {% for well in TFTWells %} <option value="{{well.WellID}}">{{well.WellID}}</option> {% endfor %} </select> </div> <div id="part_MyWellsList" class="d-inline-flex" hx-get="{% url 'LoadWells' %}" hx-trigger="load delay:0.5s" hx-include="[name='fields']"> </div> and this part_MyWellsList page: {% if FieldWells %} <div … -
Dynamically Sending Email
I have email verification working in Django, it sucessfully sends an email to inbox when I click the submit button at the bottom of the signup page, but the only problem is that it does not yet have the function where it sends an email to the address of the user who just signed up, instead, it only sends the email to the email address hard coded in the views .py file . Signup page: Views.py: Settings.py Register.html I don't even know where to begin here. I think I need a get function to pull the value from the email address form field, but I have no clue how I would even get that. Anyone have any idea? -
Trying to delete a comment from a post in django
I am currently trying to delete a comment from my database via a button in django template. Model looks like this from django.db import models from django.contrib.auth.models import User from cloudinary.models import CloudinaryField from profiles.models import UserProfile class Post(models.Model): user_profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, related_name='user_posts') title = models.CharField(max_length=220, unique=True) location = models.CharField(max_length=220) rating = models.DecimalField( max_digits=6, decimal_places=2) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="activity_post") updated_on = models.DateTimeField(auto_now=True) description = models.TextField() featured_image = CloudinaryField('image', blank=False) created_on = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, related_name='activity_likes', blank=True) like_count = models.BigIntegerField(default='0') class Meta: ordering = ['-created_on'] def __str__(self): return self.title def number_of_likes(self): return self.likes.count() def liked_by_user(self): return self.likes.values_list('id', flat=True) class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="user_comment") post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created_on'] def __str__(self): return f"Comment {self.body} by {self.name}" Delete function def delete_comment(request, post_id): users_comment = get_object_or_404(Comment, post=post_id) users_comment.delete() return redirect(reverse('activity')) URLS from . import views from django.urls import path urlpatterns = [ path('like/', views.like, name='like'), path("add/", views.add_post, name="add_post"), path('edit/<int:post_id>/', views.edit_post, name='edit_post'), path('delete/<int:post_id>/', views.delete_post, name='delete_post'), path('edit_comment/<int:id>/', views.edit_comment, name='edit_comment'), path('delete_comment/<int:post_id>/', views.delete_comment, name='delete_comment'), path("activity/", views.PostList.as_view(), name="activity"), path('comment/<int:post_id>/', views.Comment.as_view(), name='comment'), path('searched_posts/', views.search_posts, name='searched_posts'), path('post/<int:post_id>/', views.post_detail, name='post_detail') ] here is the comment part that … -
Django 'list' object attribute 'startswith'
I've been working to deploy my Django app to AWS but suddenly can't run in local due to an attribute error: 'list' object has no attribute 'startswith' Tracebacks i'm getting when I attempt to runserver include bootstrap and various django/core listings. I can't seem to find any 'startswith' issues in my urls.py or views.py files but hope there is any easy solution. BTW: I am not attempting to upload any csv and removed the 'script' directory from my project to make sure there wasn't some errant call going there. -
How to disable a form from views.py .?
How do I achieve the below: @login_required def close_auction(request,listing_id): listing = Listing.objects.get(pk=listing_id) if request.method == "POST": listing.Auction_closed = True **Disable the Bids on the Listing And display some message such as "The auction is Closed"** return render(request, "auctions/index.html",{ "listing": Listing.objects.get(pk=listing_id), "user": User.objects.get(pk=request.user.id), "owner": listing.owner }) Below is my code in index.html: <!-- if the user is the one who created the listing: they can close the listing go to the close_auction view to close --> {% if user == owner %} <form action="{% url 'close_auction' listing.id %}" method="post"> {%csrf_token%} <button>Close this Listing</button> </form> {% endif %} Below is my models.py: class Listing(models.Model): Title = models.CharField(max_length=64) Description = models.TextField(max_length=500) Category = models.CharField(max_length=16) Starting_Bid = models.IntegerField() Image = models.ImageField() Auction_closed = models.BooleanField(default=False) #def bid(self): #return self.Starting_Bid class User(AbstractUser): watchlist = models.ManyToManyField(Listing, blank= True, related_name="watcher") listing_owner = models.ForeignKey(Listing,on_delete=models.CASCADE,related_name="owner",null=True) class Bid(models.Model): Bid_amount = models.IntegerField() listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="bids") bid_placed_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="bid_placer", null=True) What I am trying to achieve here: If the user is the owner of the listing then he/she should be able to 'close the listing'. Once the listing is closed, the 'Place a Bid' form should be disabled and some message should be shown instead. -
Showing items on or after the current date and time
I asked a similar question before, regarding my Django site that I am developing and I am trying to only show users appointments on or after the current date and current time. It was recommended that I try this: now = datetime.today() appointment_wanted = Appointment.objects.filter( title=title_wanted, date__gte=now) However, once I started to test it, I noticed it works correctly for all appointments except ones that are within four hours of the current time today. -
Nginx not calling static files on site
Django works fine but static files are not called server { listen 80; server_name www.bakuklinik.shop bakuklinik.shop; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { autoindex on; alias /root/myprojectdir/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } settings.py STATIC_URL = 'static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) STATIC_ROOT = os.path.join(BASE_DIR, 'static') I'm using Ubuntu 20.04 on DigitalOcean You can view the site here: http://bakuklinik.shop/ -
Python error when using Django and Djongo on fresh computer
I recently reformatted my computer and had to setup my enviornment. I pip installed django, djongo, and then installed MongoDB with Compass. I pulled my code from Github and tried to run it. I get the following error: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python310\lib\site-packages\django\db\utils.py", line 113, in load_backend return import_module("%s.base" % backend_name) File "C:\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Python310\lib\site-packages\djongo\base.py", line 12, in <module> from .cursor import Cursor File "C:\Python310\lib\site-packages\djongo\cursor.py", line 4, in <module> from .sql2mongo.query import Query File "C:\Python310\lib\site-packages\djongo\sql2mongo\query.py", line 16, in <module> from sqlparse import parse as sqlparse ModuleNotFoundError: No module named 'sqlparse' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Python310\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] … -
Django Celery Task: AttributeError: type object 'Command' has no attribute '__annotations__'
I'm trying to set up a celery task which basically runs a script to deactivate a bunch of facilities inside a json file. I used to run it manually and it ran fine but now i get the following error when Celery tries to run it as a task: AttributeError: type object 'Command' has no attribute '__annotations__' Can anyone tell me why it is not working? This is the code i am using: tasks.py import requests import json from project.users.models import Facility from django.core.management.base import BaseCommand from config import celery_app IMPORT_URL = 'https://example.com/file.json' @celery_app.task() class Command(BaseCommand): def delete_facility(self, data): data = data if Facility.objects.filter(UUID=data, ReportedStatusField='closed'): print("Facility status already set to closed") else: facility, facility_closed = Facility.objects.update_or_create(UUID=data, defaults={ 'ReportedStatusField': 'closed' } ) print("Facility status set to closed") def handle(self, *args, **options): headers = {'Content-Type': 'application/json'} response = requests.get( url=IMPORT_URL, headers=headers, ) response.raise_for_status() data = response.json() for data, data_object in data.items(): if data in ["deleted"]: for data in data_object: self.delete_facility(data) -
Get input from user to use in django class based view
I have the following code: class ObjectiveCreate(LoginRequiredMixin, UserPassesTestMixin, CreateView): model = Objective form_class = ObjectiveCreateForm template_name = "internalcontrol/objective_create_form.html" # Check that user is a consultant def test_func(self): user = self.request.user return user.is_consultant # Get user profile and entity and inject identity and entity into ObjectiveCreateForm def form_valid(self, form): user = self.request.user profile = UserProfile.objects.get(user=user) entity = profile.entity new_profile = UserProfile.objects.get(user=user, entity=entity) form.instance.consultant = new_profile form.instance.entity = entity return super().form_valid(form) # Enable use of self.request in form def get_form_kwargs(self): kwargs = super(ObjectiveCreate, self).get_form_kwargs() kwargs["request"] = self.request return kwargs It works well when the consultant works with only one entity. Within each entity, the consultant has only one profile, and so the profile can therefore be uniquely associated with the applicable entity. The problem is when the consultant works with more than one entity. That is what I would like to handle with the revised code. I cannot move beyond the line below with the elif: # Get user profile and entity and inject identity and entity into ObjectiveCreateForm def form_valid(self, form): user = self.request.user if len(UserProfile.objects.filter(user=user)) == 1: # As mentioned above, this section of the code works well. profile = UserProfile.objects.get(user=user) entity = profile.entity new_profile = UserProfile.objects.get(user=user, entity=entity) form.instance.consultant = … -
Distinct values on filtered queryset and 'Q' operator
I have these models: class Event(models.Model): title = models.CharField(max_length=200) [...] class dateEvent(models.Model): event = models.ForeignKey('Event', on_delete=models.CASCADE) start_date_time = models.DateTimeField(auto_now=False, auto_now_add=False) [...] and in my views.py I want to create a query which selects an event given specific parameters (start date, etc.). I have no issues with my query: distinct = Event.objects.values('id').annotate(id_count=Count('id')).filter(id_count=1) events = Event.objects.filter(Q(dateevent__start_date_time__gte=start_date) & Q(dateevent__start_date_time__lte=end_date)) This pulls up more ideantical results if there is more than one dateevent for each event though, which I don't want. This is my attempt of getting distinct values, which fails with a 'QuerySet' object has no attribute 'Q' error. what am I missing? events = Event.objects.filter(id__in=[item['id'] for item in distinct]).Q(dateevent__start_date_time__lte=end_date).distinct().exclude(type='recording release').order_by('dateevent__start_date_time') -
Django. Model. how to create request and get value with two conditions
I have django Model below class Bid(models.Model): bid = models.DecimalField(max_digits=20, decimal_places=2, verbose_name="Bid") user = models.ForeignKey(User, on_delete=models.CASCADE) lot = models.ForeignKey(Lot, on_delete=models.CASCADE) how can I get username from field 'user' with two conditions: known 'lot' and max 'bid' value. Try explain, I know 'lot' and I need to get 'user' for this 'lot', where value of 'bid' is max. -
Autofill django fields when entering user ID
i have been searching for solution to auto fill all the fields in my execution profile page, 2 I have a modelform with seven fields: execution_number, matter, client, opponent, date, court, update.(date is set to auto_now and so does not appear in the form) basically all i want is when i enter execution_number it should automatically fill in all other fields that will inherent from the database. would appreciate the help, i am still a beginner in programing, so would appreciate the support :) MODELS from django.db import models class Execution(models.Model): COURT = ( ('Muscat', 'Muscat'), ('Seeb', 'Seeb'), ) execution_number= models.CharField(max_length =200, null= True) matter=models.CharField(max_length =200, null= True) client = models.CharField(max_length =200, null= True) opponent =models.CharField(max_length =200, null= True) date= models.DateTimeField(auto_now_add=True, null= True) court= models.CharField(max_length =200, null= True, choices = COURT ) update = models.CharField(max_length =200) def __str__(self): return self.execution_number VIEWS def search_execution(request): execution_number = request.execution_number # form = ProfileUpdateForm(request.POST, request.FILES) <-- remove if request.method == 'POST': form = Execution(request.POST, request.FILES, instance=execution_number) if form.is_valid(): form.save() # <-- you can just save the form, it will save the profile # user.save() <-- this doesn't help you, it doesn't save the profile and since user isn't changed you don't need to save … -
psycopg2.errors.UndefinedTable: relation "libman_classbooks" does not exist
I had mistakenly deleted my migration folders for all my apps in my project. I therefore had to redo makemigrations and migrate for each of those apps. When thence I try to access the specific areas with relational paths I get an error. relation "libman_classbooks" does not exist When I try to make some changes on the models, save and try to run makemigrations and migrate. this does not go on well but returns. django.db.utils.ProgrammingError: relation "libman_classbooks" does not exist. I have been forced to guess that I need to manually create the tables in the database. Using CREATETABLE. I don't know if this is the best option though. So I think my option may be possible in development thro' the pgAdmin, but what about in production? If CREATETABLE is the best option to take, how will I do it for the production database??. I already have data in my database which do not need interference. -
405 Error when trying to update picture in Django
I cannot update user profile_picture, I can update all other information related to a user but not their profile picture. When I try to update a profile_picture I get a null value for the picture and this error: Method Not Allowed: /update_profile/2/ [29/Apr/2022 14:11:16] "GET /update_profile/2/ HTTP/1.1" 405 13924 This is my API endpoint: path('update_profile/<int:pk>/', views.UpdateProfileView.as_view(), name='update_profile'), This is my UpdateProfileView: class UpdateProfileView(generics.UpdateAPIView): queryset = User.objects.all() serializer_class = UpdateUserSerializer def profile(request): if request.method == 'PUT': try: user = User.objects.get(id=request.user.id) serializer_user = UpdateUserSerializer(user, many=True) if serializer_user.is_valid(): serializer_user.save() return Response(serializer_user) except User.DoesNotExist: return Response(data='no such user!', status=status.HTTP_400_BAD_REQUEST) My UpdateUserSerializer: class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=False) city = serializers.CharField(source='profile.city', allow_blank=True, required=False) country = serializers.CharField(source='profile.country', allow_blank=True, required=False) profile_pic = Base64ImageField(max_length=None, use_url=True, required=False) # serializers.ImageField(source='profile.profile_pic', use_url=True, required=False) class Meta: model = User #, 'city', 'country', 'bio' fields = ['username', 'email', 'password', 'first_name', 'last_name', 'city', 'country', 'profile_pic'] # fields = UserDetailsSerializer.Meta.fields + ('city', 'country') extra_kwargs = {'username': {'required': False}, 'email': {'required': False}, 'password': {'required': False}, 'first_name': {'required': False}, 'last_name': {'required': False}, 'city': {'required': False}, 'country': {'required': False}, 'profile_pic': {'required': False} } def update(self, instance, validated_data): profile_data = validated_data.pop('profile', {}) city = profile_data.get('city') country = profile_data.get('country') profile_pic = profile_data.get('profile_pic') instance = super(UpdateUserSerializer, self).update(instance, validated_data) profile = instance.profile if … -
Is there a way to filter out items from RelatedManager in a ModelViewSet?
I'm using DRF for a simple API, and I was wondering if there's a way to achieve this behavior: I've got two models similar to the following: class Table(models.Model): name = models.CharField(max_length=100) ... class Column(models.Model): original_name = models.CharField(max_length=100) name = models.CharField(max_length=100, blank=True, null=True) ... table = models.ForeignKey(Table, on_delete=models.CASCADE, related_name="columns") And their serializers as follows: class ColumnSerializer(serializers.HyperlinkedModelSerializer): table = serializers.HyperlinkedRelatedField( read_only=True, view_name="table-detail" ) class Meta: model = Column fields = ["url", "name", "table"] class TableSerializer(serializers.HyperlinkedModelSerializer): dataset = serializers.HyperlinkedRelatedField( read_only=True, view_name="dataset-detail" ) tags = serializers.SlugRelatedField( many=True, slug_field="name", queryset=Tag.objects.all() ) columns = ColumnSerializer(many=True, read_only=True) class Meta: model = Table fields = [ "url", "name", ... "columns", ] This returns me an output similar to { ... "results": [ { "url": "http://0.0.0.0:8001/api/tables/1/", "name": "some-name", "columns": [ { "url": "http://0.0.0.0:8001/api/columns/1/", "name": "id", "table": "http://0.0.0.0:8001/api/tables/1/" }, ... } which is totally fine. But what I'd really want to do is, if a Column has name=None, it's filtered out from every API ViewSet. I've managed to do it on the ColumnViewSet by doing queryset = queryset.filter(name__isnull=False), but I can't do it for the TableViewSet or others that might show a Column list. I've tried tinkering with the ColumnSerializer, but the best I could get from it was … -
Is it possible to rename the application's group name in Django?
For example, you have "Groups" and "Users" under "AUTHORIZATION AND AUTHENTICATION" (or something named like that). If you make a new app and register its model, it's gonna write out the name of the application. I want to rename that in the admin.