Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-countries how to add serializer field
I'm trying to add the CountryField to a serializer for the Register process (using dj-rest-auth) and can't find the correct way to implement it. All the answers I found just say to use what the documentation says, but that doesn't help for me, maybe Im just not doing it right. This is what the documentation of django-countries says: from django_countries.serializers import CountryFieldMixin class CountrySerializer(CountryFieldMixin, serializers.ModelSerializer): class Meta: model = models.Person fields = ('name', 'email', 'country') I need to add the field here: class CustomRegisterSerializer(RegisterSerializer, CountryFieldMixin): birth_date = serializers.DateField() country = CountryField() gender = serializers.ChoiceField(choices=GENDER) # class Meta: # model = User # fields = ('country') # Define transaction.atomic to rollback the save operation in case of error @transaction.atomic def save(self, request): user = super().save(request) user.birth_date = self.data.get('birth_date') user.country = self.data.get('country') user.gender = self.data.get('gender') user.save() return user I tried different things besides this and nothing worked. -
Permission Denied When Installing Packages Using Pip In Docker Container Django
I'm unable to install the package inside my docker container, please let me know how can I solve this. Warning: WARNING: The directory '/home/app/.cache/pip' or its parent directory is not owned or is not writable by the current user. The cache has been disabled. Check the permissions and owner of that directory. If executing pip with sudo, you should use sudo's -H flag. error: ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied: '/home/app' Check the permissions. Dockerfile: FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /app EXPOSE 8000 COPY ./core/ /app/ COPY ./scripts /scripts RUN pip install --upgrade pip COPY requirements.txt /app/ RUN pip install -r requirements.txt && \ adduser --disabled-password --no-create-home app && \ mkdir -p /vol/web/static && \ mkdir -p /vol/web/media && \ chown -R app:app /vol && \ chmod -R 755 /vol && \ chmod -R +x /scripts USER app CMD ["/scripts/run.sh"] command inside container: pip install django-storages -
Django Azure SQL ProgrammingError Invalid Object name
I am trying to use Azure SQL with Django by using mssql-django. I get this error during "makemigrations": django.db.utils.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'customer_group_customergroup'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") The connection to Azure SQL is already working. If I start a new app, I could make the migrations and migrate it into Azure SQL without problem. If I migrate only the "customer_group" App, there is no problem. The problem only occurs when I want to migrate apps, whose model contains a foreign key field named customer_group. I tried renaming the field (suspecting it was some naming conflict) but the error still persists. Does anyone know how to correct this error? Thank you! Edit: My customer_group app has this model: class CustomerGroup(models.Model): name = models.CharField(max_length=50, unique=True, blank=False, null=False, verbose_name="Customer group name") owner_first_name = models.CharField(max_length=20, blank=False, null=False) owner_last_name = models.CharField(max_length=20, blank=False, null=False) address = models.CharField(max_length=100, blank=False, null=False) phone = models.CharField(max_length=15, blank=False, null=False) billing_info = models.CharField(max_length=200, blank=False, null=False) uuid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False, blank=False, null=False) def __str__(self): return self.name -
Django-respondive-images dosen't find files when not in local
i use responsive-images https://pypi.org/project/django-responsive-images/ on my PC django works well and also django-responsive-images when i move all up to my website responsive images dosen't find images in my template file if i use <img class="card-img-top" srcset="{% srcset item.img 200x400 400x800 nocrop %}" src="{% src item.img 400x800 nocrop %}" alt="Card image cap"> i get that error it seems dosen't find file FileNotFoundError at / [Errno 2] No such file or directory: '/code/uploads\\Item\\0\\817_img.jpg' Request Method: GET Request URL: http://www.mysite.it/ Django Version: 3.2.5 Exception Type: FileNotFoundError Exception Value: [Errno 2] No such file or directory: '/code/uploads\\Item\\0\\817_img.jpg' Exception Location: /usr/local/lib/python3.9/site-packages/django/core/files/storage.py, line 238, in _open Python Executable: /usr/local/bin/python Python Version: 3.9.4 Python Path: ['/code', '/usr/local/lib/python39.zip', '/usr/local/lib/python3.9', '/usr/local/lib/python3.9/lib-dynload', '/usr/local/lib/python3.9/site-packages'] Server time: Tue, 25 Jan 2022 14:16:46 +0000 but if i don't use responsive images it works <img class="card-img-top" src="{{item.img.url}}" alt="Card image cap"> do you know why it dosen't work? -
Django Admin route Redirects to /login
i'm a newbie to Django and i just started this project.... After Creating Superuser using this command python manage.py createsuperuser I tried to access the admin route but on typing the /admin on the browser it's displays this error on the browser Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/login Using the URLconf defined in myblog.urls, Django tried these URL patterns, in this order: 1. admin/ I tried adding: LOGIN_REDIRECT_URL = '/admin/' in the settings.py as someone suggested on stackoverflow but it shows the same thing. Kindly direct me on what i'm not doing right -
How to Debug S3direct with django
in settings.py AWS_ACCESS_KEY_ID = ************* AWS_SECRET_ACCESS_KEY = ************** AWS_STORAGE_BUCKET_NAME = "my-bucket-develop-whitebear" S3DIRECT_DESTINATIONS = { 'images': { # "key" [required] The location to upload file # 1. String: folder path to upload to # 2. Function: generate folder path + filename using a function 'key': resource.create_filename, 'key_args': 'my-assets/images', # "auth" [optional] Limit to specfic Django users # Function: ACL function 'auth': lambda u: u.is_authenticated, # "allowed" [optional] Limit to specific mime types # List: list of mime types 'allowed': ['image/jpeg', 'image/png'], 'acl': 'private', # "cache_control" [optional] Custom cache control header # String: header 'cache_control': 'max-age=2592000', # "content_disposition" [optional] Custom content disposition header # String: header 'content_disposition': lambda x: 'attachment; filename="{}"'.format(x), # "content_length_range" [optional] Limit file size # Tuple: (from, to) in bytes 'content_length_range': (10, 10000000), # 10MB # "server_side_encryption" [optional] Use serverside encryption # String: encrytion standard 'server_side_encryption': 'AES256', # "allow_existence_optimization" [optional] Checks to see if file already exists, # returns the URL to the object if so (no upload) # Boolean: True, False 'allow_existence_optimization': False, }, 'videos': { 'key': resource.create_filename, 'key_args': 'my-assets/videos', 'auth': lambda u: u.is_authenticated, 'allowed': ['video/mp4'], 'acl': 'private', 'content_length_range': (10, 200000000), # 200MB } } in forms.py class ResourceCreateForm(BaseModelForm): image = forms.URLField(widget=S3DirectWidget(dest='images'), required=False) class Meta: model = Resource … -
Django: Retrieve list of unique m2m combinations
I have the following model schema in Django (Note that I left out a detailed overview of class ModelB as it is irrelevant for the question) ``` class ModelA(Models.model): b = models.ManyToManyField(ModelB, blank=True) ``` Given a QuerySet of ModelA objects, I would like to receive all unique M2M combinations (of ModelB objects) that are present in the queryset. For example, for the following queryset of 4 ModelA objects: -
Launch script from Django
I have a file named "update_job.py"(it's an ETL). It should be executed each 1h to update data. Now I have an idea for it: using a infinit loop inside the update_job.py and make a sleep of 1h for each time we pass inside the loop and excute the script separately. I think it's a bad practice. Now I wanna know how can I make a job to exectute it from Django. Please help, I'm new to Django. Regards, Minonja -
django updating wrong post
Made a update post fucntion and it is working, however it is always updating just the first post. I am using tabs in html and i think it is because how i pass the form, but cannot figure it out. at first in the html, next to the post to update, is a button <a class="dropdown-item"> <button class="btn btn-info" data-toggle="modal" data-target="#note-update-modal">Update</button> </a> That brings up a form, which is located futher down on the html {% for note in checklist.notes.all %} <form method="POST" action="{% url 'update_notes' note.id title.slug %}" class="modal fade" id="note-update-modal" tabindex="-1" aria-hidden="true"> {% csrf_token %} <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">New Note</h5> <button type="button" class="close btn btn-round" data-dismiss="modal" aria-label="Close"> <i class="material-icons">close</i> </button> </div> <div class="modal-body"> <div class="form-group row align-items-center"> <label for="{{ form.title.id_for_label }}" class="col-3">{{ form.title.label }}: </label> <input class="form-control col" name="{{ form.title.html_name }}" type="text" id="{{ form.title.id_for_label }}" value="{{ note.title }}" placeholder="Note title" required /> </div> <div class="form-group row"> <label for="{{ form.content.id_for_label }}" class="col-3">{{ form.content.label }}</label> <textarea class="form-control col" rows="6" name="{{ form.content.html_name }}" id="{{ form.content.id_for_label }}" placeholder="{{ note.content }}"> </textarea> </div> </div> <div class="modal-footer"> <button role="button" class="btn btn-primary" type="submit"> Update Note </button> </div> </div> </div> </form> {% endfor %} It only brings up the first note, … -
Update fields on reverse M2M relation
Having two models: class Publication(model.Models): title = models.CharField(max_lenght=30) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Article(model.Models): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication, related_name='articles') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I want that, when I add a Publication to an Article, the updated_at field of Publication also gets updated: a1 = Article.objects.create(name='Article 1') p1 = Publication.objects.create(name='Publication 1') a1.publications.add(p1) print(a1.updated_at) # Will print the timestamp when I added p1 to a1. print(p1.updated_at) # Will print the timestamp when I **created** p1. I want to print the time when it was added to a1. I know I can do this using signals but I was wondering if there's an easier way, as think that signals add extra complexity to the code. -
Django display Image of User
Good Day, every user has an image, how can I display the specific user image? \\models.py class UserImage(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE) photo = models.ImageField( upload_to='images/', height_field=None, width_field=None, max_length=100) def __str__(self): return str(self.user) \\forms.py class UserImageForm(forms.ModelForm): class Meta: model = UserImage fields = ( 'photo', ) \\views.py def photo_view(request): try: profile = request.user.userimage except UserImage.DoesNotExist: profile = UserImage(user=request.user) if request.method == 'POST': form = UserImageForm(request.POST, request.FILES, instance=profile) if form.is_valid(): form.save() return redirect('/dashboard/user/photo') else: form = UserImageForm(instance=profile) return render(request, 'photo.html', {'form': form, 'profile': profile}) test.html <img src="{{ WhatHere? }}" alt="User Profile Image" /> So in src="" must be the URL to the image what the user has added. Each user can only see his own image, not all existing images should be displayed. -
frontend get request vs backend get request
I am currently working on a project with a frontend page that is not served by django just a random html page and a backend built with django. I need to make a get request from my frontend to get the csrf token then put that token in <input type="hidden" name="csrfmiddlewaretoken" value={response from get request}> (as my understanding to make a post request to django server). But when I make a get request with axios from my frontend vs backend ( same url, same parameters) I get different results hence I don't get the token that I'm looking for on the frontend request. Can anyone help/ explain that to me please. frontend request: <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script> (async () => { try { // make a get request to this url to get the cookie const request = await axios.get("http://127.0.0.1:8000/accounts/signup/",{withCredentials:true}); console.log(request.config) // the line below prints out null because there is nothing in the response // console.log("request->", request.headers["set-cookie"][0].split(";")[0]); } catch (error) { console.error(error); } })(); </script> front end result: Object { transitional: {…}, adapter: exports(e), transformRequest: (1) […], transformResponse: (1) […], timeout: 0, xsrfCookieName: "XSRF-TOKEN", xsrfHeaderName: "X-XSRF-TOKEN", maxContentLength: -1, maxBodyLength: -1, validateStatus: validateStatus(e), … } backend request from dummy server to … -
Django Admin - Add extra dialogue on field
I would like to have an extra layer of input security on a certain field in admin, very much like the password field: class MyModel(models.Model): very_important_field = models.CharField() So instead of showing the input form for very_important_field There should be a link (as with password) that leads to it's own action (like /password) with an own form where you would have to type in this very_important_field twice. Could you please point me to some docs how to achieve that? I do not need an explanation how to change the widget or how to write the proper form for this, just how to wire it in admin in a way that there is an extra action. -
Cannot import module in Django project
My Django project directory looks like this : I can import from the CPRS_admin app folder to my main folder and it works fine.But the moment I import the CPRS_admin app folder to the recommendation_model app folder it shows the error ModuleNotFound. This is the image of the import of CPRS_admin into CPRS and it works. But the moment when I import CPRS_admin into a file under the recommendation_model app it shows this error. -
I can't access my video content using pk in urls.py file
i want: when a user click on the video file, then it will take the user to the viewVideo templates: that is the place where video would start playing like: YouTube.com or other social media platforms, How can I set that ? the one I did down here is not display the video contents. and i want to pass video at bottom of the viewVideo templates: this is my urls.py file from os import name from django.urls import path from . import views urlpatterns = [ path('', views.dashboard, name='dashboard'), path('home', views.home, name='home'), path('view/<str:pk>/', views.viewVideo, name='video'), path('addvideo', views.addvideo, name='addvideo'), path('login', views.login, name='login'), path('register', views.register, name='register'), ] this is the views.py file: def dashboard(request): posting = Post.objects.select_related('user') return render(request, 'dashboard.html', {'posting': posting}) def home(request): posting = Post.objects.select_related('user') return render(request, 'home.html', {'posting': posting}) def viewVideo(request, pk): posting = Post.objects.get(id=pk) return render(request, 'video.html', {'posting': posting }) this is my dashboard templates: <div class="container"> {% for post in posting %} <div class="row"> <div class="col-md-5"> <div class="card"> <a href="{% url 'video' post.id %}"> <video id="my-video" class="video-js" controls width="640" height="264" poster="MY_VIDEO_POSTER.jpg" data-setup="{}" type="video/mp4" > <source src="{{post.file.url}}"> </video> </a> <div class="card-body"> <small>{{post.date_added}}</small> <br> <small>{{post.user.username}}</small> <br> <small>{{post.title}}</small> </div> </div> </div> </div> {% endfor %} </div> this is my viewVideo … -
python script that extracts column names from files and maps with alias column names
Task is to write a python script that reads the columns from the uploaded file(csv) and map all the column names with its alias name and finally write a function which will return the updated column names. for ex: emp_id equivalent column names could be ecn_id, e_id, etc. Basically I am stuck at the function part where mapping of column names with alias names takes place. -
UnboundLocalError at /products/add_review/2/ local variable 'form' referenced before assignment
I'm trying to add a review section to a product detail page. I'm running into this error and can't seem to find the cause. Any help appreciated. I hacen't used stackoverflow before so I'm not sure if I've given enough details. <div class="columns is-justify-content-center has-text-centered"> <div class="column"> <h1 class="title-heading has-text-centered ">Reviews of {{ product.name }}</h1> </div> </div> <div class="columns is-justify-content-center is-multiline"> {% if reviews %} {% for review in product.reviews.all %} <div class="column is-10 is-offset-1 card m-3"> <div class="card-header"> <div class="card-header-title"> <h2 class="title-heading-small">{{ review.review_title }} </h2> </div> </div> <div class="card-content"> <p class="">{{ review.review }}</p> </div> <div class="card-footer"></div> <p class="">Reviewed by: {{ review.review_author }}</p> <p class="">Posted on: {{ review.added_on }}</p> </div> {% endfor %} {% else %} <div class="column"> <h2 class="title-heading-small">No reviews have been added.</h2> </div> {% endif %} </div> <div class="columns is-justify-content-center m-3"> <div class="column is-6-desktop is-10-touch is-offset-1-touch"> <form action="{% url 'add_review' product.id %}#reviews" method="POST"> {% csrf_token %} <div class="columns"> <div class="column"> {{ form | crispy }} </div> </div> <div class="columns has-text-centered"> <div class="column is-6"> <button class="button is-danger" type="submit">Add Review</button> </div> </div> </form> </div> </div>``` -
Django API Endpoints 504 Timeout Only When Authenticated
I have an Application Server (APP) and an API Server (API). Requests to /api are sent via proxy_pass to the API server. I can access an api endpoint by going directly to the API server, or the preferred way via the APP server. Everything works as expected. The problem comes in as soon as I authenticate/login to my Django application. When I authenticate and I try and reach an api endpoint via my APP server I get a 504 Gateway Timeout. This has nothing to do with increasing the timeout configuration as I am able to reach the API server when I am not logged in. Django 3.2.x Python 3.9 Gunicorn Nginx APP and API server are using exactly the same codebase. See Nginx configuration below: APP Server server { server_name cr-prod-app.example.com; location ^~ /static { alias /home/www/app/static_prod; } location / { proxy_pass http://unix:/home/www/app/cr.sock; } location /api { proxy_pass https://cr-prod-api.example.com/api; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_cache_bypass $http_upgrade; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/cr-prod-app.example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/cr-prod-app.example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot proxy_connect_timeout 1000s; … -
Django-cleanup to remove files and folders
I'm testing django-cleanup to take care file delete. When i add a new object model is create a folder with object id, when i delete that object,the images is deleted, but the folder id is not. In the docs, i can find reference to do that. Any tip are welcome -
Django Rest Framework - Default filter if not sent
I have a Property model which has a lot of fields, but I am interested in the is_shared one class Property(models.Model): .... is_shared = models.BooleanField(blank=True, null=True) I also have a pretty standard, out of the box, viewset, serializer and a filter for this model. I want my filter to work so if the is_shared query parameter is NOT sent, it will return properties with is_shared=False For that, I have the following filter method: class PropertyFilter(dj_filters.FilterSet): is_shared = dj_filters.BooleanFilter(method='filter_by_is_shared') @staticmethod def filter_by_is_shared(queryset, name, value): return queryset if value else queryset.filter(is_shared=False) This works well if True or False are sent in the request, but if is_shared isn't sent at all it won't work. I've tried adding this to the serializer without luck. class PropertySerializer(serializers.ModelSerializer): class Meta: model = Property fields = ['is_shared'] extra_kwargs = { 'is_shared': {'default': False} } How can I achieve so if the is_shared query parameter is not sent, I treat it as if it was false? -
django get_name_display() not work in django admin page for integer fields
I have a Type Model that hase a name IntegerField There is a Choices Tuple that is like below: CHOICES = ( (1, 'test'), ) name = models.IntegerField(choices=CHOICES) def __str__(self): return "{}".format(self.get_name_display()) I want to show the human-readable value of choice item in Django Admin Page, but when I use self.get_name_display() in str method, it doesn`t work and show the DB value of it. How can I show the human readable value in django admin? -
Django annotate a field based on info from another database without ORM
I would like to annotate a QuerySet with the info from another database table User model has fields 'user_id' in Database A with ORM Address table has fields 'user_id' and 'address' in Database B without ORM, i.e. only raw sql is available. So I would like to do somthing like this: Users.objects.annotate(addr="B__address if A_user_id == B__user_id") is this even possible? I am thinking Users.objects.annotate(addr=RawSQL('select user_id, address from B where B.user_id=A.user_id')) I don't think this will work though....Can RawSQL run from another DB? Or, addr_dict = {'user_id1':'addr1', 'user_id2':'addr2', ...} # from raw sql of B Users.objects.annotate(addr=addr_dict[usr_id]) # how can I do this? thank! -
Many-Many nested serializer create method does similar n+1 queries
I have a many-many relation between User model and my custom Team model. Where i can add multiple users to my team. I have used prefetch_related on my team model so the get (list) operation is optimized, whereas the post (create) operations does query every time for a user. Below is my code. models.py class Team(models.Model): team_name=models.CharField(max_length=50,blank=False,null=False) user=models.ManyToManyField(User,related_name='user') def __str__(self) -> str: return self.team_name serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username'] def to_representation(self, instance): return [instance.id ,instance.username] def to_internal_value(self, data): try: return User.objects.get(id=data) # this queries the db for every user except Exception as e: print(e) raise serializers.ValidationError("User does not exists") class TeamSerializer(serializers.ModelSerializer): user=UserSerializer(many=True) class Meta: model=Team fields=('team_name','user') def create(self, validated_data): users = validated_data.pop('user') team = Team.objects.create(**validated_data) for user in users: team.user.add(user) return team views.py class TeamView(viewsets.ModelViewSet): queryset=Team.objects.all().prefetch_related('user') serializer_class=TeamSerializer as it can be seen, for 7 users added to the team, it does 7 queries. how can this be optimized ? Any help is appreciated. -
uwsgi worker hangs on exit, but only if it used async trio module
I have a Django site that uses the trio_cdp package to generate PDFs using a headless Google Chrome. This package is async, but my Django project is sync, so it has to run inside trio.run() It's also using uwsgi locks so that only one client can generate a PDF at a time (headless Chrome loads the page in a single virtual tab, so it can only do one at a time) Here is the code: import trio import base64 import requests from django.conf import settings from trio_cdp import open_cdp, page, target try: import uwsgi have_uwsgi = True except ModuleNotFoundError: have_uwsgi = False async def render_pdf_task(url, params): r = requests.get(url=settings.CDP_URL) if r.status_code == 200: out = r.json() ws_url = out[0]['webSocketDebuggerUrl'] else: return None async with open_cdp(ws_url) as conn: targets = await target.get_targets() target_id = targets[0].target_id async with conn.open_session(target_id) as session: async with session.page_enable(): async with session.wait_for(page.LoadEventFired): await page.navigate(url) await trio.sleep(0.5) pdf = await page.print_to_pdf(**params) pdfdata = base64.b64decode(pdf[0]) await conn.aclose() return pdfdata def render_pdf(url, params): if have_uwsgi: uwsgi.lock(1) pdfdata = trio.run(render_pdf_task, url, params) if have_uwsgi: uwsgi.unlock(1) return pdfdata Annoyingly, any uwsgi worker that has run this particular task will later hang on exit until it is forcibly killed. If uwsgi runs and … -
Django, DRF: To remove a specific field of the serializer only on the first page
How can I remove field3 and field4 only on the first page? I need something that can be dynamically reused as I plan to use it in multiple views. class CustomSerializer(serializers.ModelSerializer): class Meta: model = Model fields = ('field', 'field2', 'field3', 'field4') class CustomView(ListAPIView): serializer_class = CustomSerializer