Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django rest how to post comments in a post blog
I would like to know how to delete comments in a board using an url like this: DELETE /api/boards/{board_id}/comments/{comment_id} Current I can list all comments and post a comment using this: GET /api/boards/{board_id}/comments # will get all comments POST /api/boards/{board_id}/comments # will create a comment. I dont know how to get a single comment and dont know how to delete a comment using the extra action below this is my current view: class BoardViewSet(ModelViewSet): queryset = Board.objects.exclude(deleted=True) serializer_class = BoardSerializerList permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly] def destroy(self, request: Request, *args, **kwargs) -> Response: board = self.get_object() if not board.deleted: board.deleted = True board.save() return Response(status=status.HTTP_204_NO_CONTENT) return Response(status=status.HTTP_400_BAD_REQUEST) def get_serializer_class(self): if self.action == 'retrieve': return BoardSerializerRetrieve return super().get_serializer_class() @action(detail=True, methods=['get', 'post', 'delete'], serializer_class=CommentSerializer) def comments(self, request, pk=None): if self.request.method == 'GET': board = self.get_object() comments = board.comment_set.all() serializer = CommentSerializer(comments, many=True) return Response(serializer.data) if self.request.method == 'POST': board = self.get_object() serializer = CommentSerializer(data=request.data) if serializer.is_valid(): user = serializer.data['user'] text = serializer.data['text'] Comment.objects.create(board=board, user=user, text=text) return Response(status=status.HTTP_201_CREATED) these are my models: class Board(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=200, blank=False, null=False) description = models.TextField(max_length=1000) share_with_company = models.BooleanField() share_list = ArrayField(models.CharField(max_length=15), null=True, blank=True) last_update = models.DateTimeField(auto_now=True) owner = models.ForeignKey('auth.User', related_name='boards', on_delete=models.CASCADE) deleted … -
how to ship a Django app as a docker image?
I would like to package and ship a Django web app as a Docker image. When I do a docker-compose up, I see a tree hierarchy in Docker desktop containers and works as expected when I navigate to http://localhost:85 django-dashboard-volt |___appseed_app |___nginx If I save and load the image, I see the following in the Docker desktop containers and the web application does not work: django-dashboard-volt_appseed-app nginx Here's how I save and load the images: docker save django-dashboard-volt_appseed-app:latest nginx:latest | gzip > django.tar.gz docker load --input django.tar.gz Here's the Dockerfile: FROM python:3.9 COPY . . ADD test . ADD data . # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV PYTHONPATH /test ENV APP_USER=xxxx ENV APP_HOME=/home/$APP_USER # install python dependencies #RUN pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --upgrade pip RUN pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --no-cache-dir -r requirements.txt RUN tar xvzf gurobi9.5.0_linux64.tar.gz ENV GUROBI_HOME /gurobi950/linux64 RUN cd /gurobi950/linux64 && python setup.py install RUN rm gurobi9.5.0_linux64.tar.gz RUN echo "TOKENSERVER=xxxx" > /gurobi.lic RUN groupadd -r $APP_USER && \ useradd -r -g $APP_USER -d $APP_HOME -s /sbin/nologin -c "Docker image user" $APP_USER ENV TZ 'America/Los_Angeles' RUN echo $TZ > /etc/timezone && apt-get update && \ apt-get … -
cant get profile images to display with django
I am working through a basic django upload image tutorial and I have become stuck. I am trying to let a user upload a file, store it in in a folder, and then save the address to that image in the db. This part all seems to be working. Then I try and have a simple page to display all images to make sure its working and the img tag in the HTML keeps having a src of "unknown". I am unsure of what exactly the problem is because there are no errors thrown anywhere. Views.py from django.http.response import HttpResponseRedirect from django.shortcuts import render from django.views.generic.edit import CreateView from django.views.generic import ListView from .models import UserProfile # Create your views here. class CreateProfileView(CreateView): template_name = "profiles/create_profile.html" model = UserProfile fields = "__all__" success_url = "/profiles" class ProfilesView(ListView): model = UserProfile template_name = "profiles/user-profiles.html" context_object_name = "profiles" Models.py from django.db import models # Create your models here. class UserProfile(models.Model): image = models.ImageField(upload_to="image") User-Profiles.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <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>User Profiles</title> </head> <body> <ul> {% for profile in profiles %} <li> <img src="{{ profile.url }}"> </li> {% endfor %} … -
Does anyone know of a plugin to do dynamic calculations in the django formset?
Does anyone know if there is a jquery plug-in that can do calculations for a django formset (it is a dynamic form, it changes the id of each field per row each time the add button is clicked) -
How to copy the data in old col to new col with only unique values?
I'm trying to create a new unique field called last_name_unique. I need to copy the data from last_name to last_name_unique. The new field can be nullable so we can add null for the repeated values. For example, if there are two last names with value "Junior", under the last_name_unique there will be one value "Junior" and then null for the other "Junior" value. from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) Any idea how to achieve this would be appreciated. -
Django - How to set ordering on ManyToMany field queryset
I have following models: class Hashtag(models.Model): ... created = models.DateTimeField(auto_now_add=True) ... class Tweet(models.Model): ... hashtags = models.ManyToManyField( to='Hashtag', through='TweetHashtag', through_fields=('tweet', 'hashtag'), ) ... class TweetHashtag(models.Model): comment = models.ForeignKey( to='Tweet', on_delete=models.CASCADE, ) hashtag = models.ForeignKey( to='Hashtag', on_delete=models.CASCADE, related_name="tweets" ) created = models.DateTimeField(auto_now_add=True) My problem is when I get a Tweet, I want to get hashtags order by created. tweet = Tweet.objects.get(id=1) hashtags = list(tweet.hashtags.all()) When I check hashtags, I see the hashtags are in incorrect ordering. I want to get tweet.hashtags order by created (created of TweetHashtag) Is there anyway? I have one idea but I don't know how to do that. The idea is to override relation manager of hashtags in Tweet model. Is there any way? -
How to add markers to leaflet map in an ajax call? leaflet Cannot read properties of undefined (reading 'addLayer') Layer.js:52
I am trying to add markers to my leaflet map in an ajax call, but I am getting an error. I'm able to add markers to the map in the console, but don't know why I can't in the ajax call. Any help would be appreciated. Ajax Call // get reference to map var map = window['leafletmapid_location-map']; $('#id_sub_areas').change(function (event) { $.ajax({ type: 'GET', url: 'my_url', success: function (response) { L.marker([40.383061, -111.773658]).addTo(map) }; }); }); When I trigger the ajax call I get the error message- leaflet Cannot read properties of undefined (reading 'addLayer') Layer.js:52 However if I load the page I can add a marker to the map with the following code in the console. Console Code var map = window['leafletmapid_location-map']; L.marker([40.383061, -111.773658]).addTo(map); -
Whitenoise Not Working when DEBUG = FALSE - Django - Hosting Static Files
I am running a Django website and it's about to go into production. I am now at the point where I need to set DEBUG = False in my settings.py file. I am getting the typical 500 errors because I have static files that are being hosted locally. I am working on getting Whitenoise to work to host my static files so I can move on with DEBUG = False. I have followed a lot of documentation and a lot of tutorials and think all of my configurations are all set but I am still getting the same error. When DEBUG = False I am still getting 500 errors on my production pages that have static files. Also when I inspect any static files on the page when DEBUG = True the URL has not changed at all. I am posting all of my configuration below in hopes that there is a simple mistake I made that I have been continuously skipped over but Whitenoise doesn't seem to be working and there seems to be no different from the way it was before now as Whitenoise is "implemented". I have run python manage.py collect static I have run pip install … -
not getting right URL for entering specific project
I have my site set up, that every user can join many teams, but each team can have many projects, and each project can have many tasks, and I am listing all projects in a team, but i want to use the href to get to the specific project, which is displayed as a task. but i cannot direct it correctly. Here is my models.py class Note(models.Model): title = models.CharField(max_length=55) content = models.TextField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Checklist(models.Model): title = models.CharField(max_length=55) slug = models.SlugField(max_length=500, unique=True, blank=True) check_completed = models.BooleanField(default=False) notes = models.ManyToManyField(Note, blank=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Checklist, self).save(*args, **kwargs) def get_url(self): return reverse('checklists', kwargs={ 'slug':self.slug }) def __str__(self): return self.title @property def last_comment(self): return self.notes.latest("date") class Task(models.Model): title = models.CharField(max_length=55, null=True, blank=True) slug = models.SlugField(max_length=500, unique=True, blank=True) task_completed = models.BooleanField(default=False) description = models.TextField(default="Task description") start_date = models.DateTimeField() due_date = models.DateTimeField() checklist = models.ForeignKey(Checklist, blank=True, null=True, on_delete=CASCADE) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Task, self).save(*args, **kwargs) def get_url(self): return reverse('tasks', kwargs={ 'slug':self.slug }) def __str__(self): return self.title @property def num_task_completed(self): return self.task_completed.count() class Project(models.Model): project_manager = models.ForeignKey(Profile, on_delete=CASCADE) title = models.CharField(max_length=55, null=True, blank=True) developers = models.ManyToManyField(Profile, … -
Django how to pass custom error message in class based views
I need to be show custom error message for invalid forms. I don't know how to do it in class based views. here is my class based views: class EditPatient(UpdateView): model = Patient form_class = PatientUpdateFrom template_name = 'hospital/edit-patient.html' def form_valid(self, form): error_message = None if form.is_valid(): name = self.request.POST["patient_name"] email = self.request.POST["phone"] if len(name) > 20: error_message = 'maximum 20 character allowed in name' if len(phone) > 20: error_message = 'maximum 15 character allowed in phone' """ #I tried this but didn't work def get_context_data(self, **kwargs): context = super(EditPatient,self).get_context_data(**kwargs) context['error_message'] = error_message return context """ if not error_message: messages.add_message(self.request, messages.INFO, 'Patient Sucessfully Updated') form.save() return redirect('hospital:edit-patient',self.object.slug) -
Django Rest Framework :How to serialize many to many field
I have my models Certificates and Suppliers and Suppliers has many to many relationship with certificates class Certificates(models.Model): name = models.CharField(max_length=500, null=False) description = models.CharField(max_length=500, null=False) image_url = models.CharField(max_length=500, null=False) def __str__(self): return f'{self.name}' class Suppliers(models.Model): name = models.CharField(max_length=500, null=False) location = models.CharField(max_length=500, null=False) longitude = models.CharField(max_length=500, null=True) latitude = models.CharField(max_length=500, null=True) certificates = models.ManyToManyField(Certificates, null=True) bio = RichTextField(blank=True, null=True) environmental_info = RichTextField(blank=True, null=True) social_info = RichTextField(blank=True, null=True) governance_info = RichTextField(blank=True, null=True) def __str__(self): return f'{self.name}' This is my Serializers: class CertificatesSerializer(serializers.ModelSerializer): class Meta: model = Certificates fields = '__all__' class SuppliersSerializer(serializers.ModelSerializer): certificates = CertificatesSerializer() class Meta: model = Suppliers fields = ('id', 'name', 'certificates') and this is my view @api_view(['GET']) def supplier_response_list(request): suppliers_list = Suppliers.objects.all() serializer = SuppliersSerializer(suppliers_list, many=True) return Response(serializer.data) am getting this error: AttributeError: Got AttributeError when attempting to get a value for field description on serializer CertificatesSerializer. The serializer field might be named incorrectly and not match any attribute or key on the ManyRelatedManager instance. Original exception text was: 'ManyRelatedManager' object has no attribute 'description'. -
Checking message value in Django template
I am working with a Google ReCaptcha on a Django site and would like to check the value of the error messages. If the value is 'Invalid reCAPTCHA. Please try again.' then I would like to show an error message under the ReCaptcha. However, the way that I have this set up is not currently working. <div id="g-recaptcha-error"> {% if messages %} {% for message in messages %} {% if message is 'Invalid reCAPTCHA. Please try again.' %} <span style="color:red;">{{ message }}</span> {% endif %} {% endfor %} {% endif %} </div> How do I check the actual value of the recaptcha message? There could possibly be additional errors so I don't want this to show up if the value is different. When I include this below it shows 'Invalid reCAPTCHA. Please try again. test' So I know the message is correct. {% for message in messages %} <p>{{ message }} test</p> {% endfor %} -
How do I connect django-tinymce with the javascript from TinyMCE?
I have successfully added TinyMCE to my site using the django-tinymce library in the fields in my admin. Looking through a lot of posts on here, there seems to be a utility in adding some javascript, too, but the installation guide does not mention javascript. I have attempted downloading TinyMCE js from the official site and added it in my static/js folder, and then added this to my settings.py: STATIC_URL = '/static/' TINYMCE_JS_URL = os.path.join(STATIC_URL, "js/tinymce/tinymce.min.js") But it did not change anything, so I suspect it does not work. After looking through tons of documentation, posts here and Youtube guides, I have not come to a conclusion. So I have two questions: What is the benefit of adding javascript from TinyMCE to my site - besides the django-tinymce plugin? How do I add it to my site given I already have the django-tinymce installed? EDIT: I actually already know one utility that I want from the js. That is, I want to be able to not include image dimensions in the HTML output of the TinyMCE forms of my admin. Apparently this is edited in the JS - unless the option can be edited elsewhere? -
Django Rest Framework modify field value depending on condition
as a Python, Django and DRF newbie I have a very basic question when building a Rest API for a test project. I am sure the experts here can assist me on this as it is really more than simple (but I run into the wrong direction): Below is the core extract of a very simple API endpoint. When the endpoint is called (GET) I want to return the "Description" value as it is stored in the database (this is clear of course). But if the field "ISO2CODE" has a value (for example "de") I want to change the "Description" value in the API to a different output (e.g. German). Means the API will not return the value in the database but a manipulated value. How should I do this. What is the common way to manage such a (simple) requirement (add a condition - how? in the model definition?). Thank you for any help on this. class Territory(models.Model): ISO2Code = models.CharField(max_length=2) Description = models.CharField(max_length=128) class Meta: ordering = ['pk'] class TerritorySerializer(serializers.ModelSerializer): class Meta: model = Territory fields = ['id', 'ISO2Code','Description'] class TerritoryViewSet(ModelViewSet): queryset = Territory.objects.all() serializer_class = TerritorySerializer def get_serializer_context(self): return {'request': self.request} -
How to handle conflicting basic auth from NGINX reverse proxy with JWT auth from Django?
we have a standard Django web app running behind a reverse proxy. I want to setup a two layer authentification : one from the nginx reverse proxy to shield the application (presently a HTTP Basic authentication -yes we plan to upgrade to something stronger like SSL client certificate or smartcards-), and one at the application level However we are currently running into a issue because the HTTP Basic Authorization header is conflicting with the Django Authorization header The problem arises because the JWT auth from Django requires us to fill the "Authorization" header with the token while NGINX uses another type of authentication. I'm looking for the best way to solve this problem and have the following questions : is it possible to require Django to use an alternative HTTP header to carry its authentication token (instead of "Authorization") or, conversely, is it possible to configure our nginx to use an alternative header for the HTTP Basic authentication (but it seems unlikely as it is done at the browser level) or to require the nginx to do the header translation : i.e. converting back and forth header before pushing them to the Django app. or, even better, can we configure … -
Django CORS Headers works when allowing all, but not for a specified origin
I have a React frontend (hosted at http://localhost:3000/) that is trying to send JWT refresh tokens via HttpOnly Cookies to a Django REST API (hosted at http://localhost:8000/, but tunnelled using ngrok to an https address). I am using django-cors-headers to deal with the cross-origin aspect of this. However, no matter what I do, I cannot seem to get this to work (despite days of research). Any help would be greatly appreciated :D I think I am addressing the endpoint correctly (i.e. https://ngrokapiurl/api/token/refresh/) and I have put 'corsheaders.middleware.CorsMiddleware', at the top of the middleware block. The CORS errors go away when I specify CORS_ORIGIN_ALLOW_ALL = True. However, not only do I understand that security-wise this is not ideal, but it also does not work when I set CORS_ALLOW_CREDENTIALS = True to allow the withCredentials: True part of my axios request to send over the HttpOnly cookie containing the refresh token. Therefore, I remove the CORS_ORIGIN_ALLOW_ALL = True and set CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] to specify the allowed origin. However, it is at this point that nothing seems to work. Please help me fix this - I am very new to all of this! The error I get is: error In … -
Django - Count every installment in a balance every month
I made a program to control bills and monthly installments. I don't know if the way I made my Model is wrong, but I achieved to make the month we are now + months to pay. Here's a picture of 2 month installment, I want to appear in 2 months, but only appear in the last (Feb) Now I want in the view to show in balance the installments and its months (i.e: Jan and Feb), but I'm stuck. Can anyone help me, please ? Model.py class Balance(models.Model): account = models.ForeignKey(Account, null=True, on_delete=models.SET_NULL) value = models.FloatField(null=True) installment = models.IntegerField(null=True, default=0) #How many installments installment_value = models.FloatField(null=True, default=0) #Value of it months = models.IntegerField(null=True, default=0) #From a range (1, 12) calculates the last month def save(self, *args, **kwargs): self.months = (int(datetime.now().strftime("%m")) + int(self.installment))-1 if self.months > 12: self.months = int(self.months) - 12 super().save(*args, **kwargs) View.py #BALANCE def balance(request, pk): name = Client.objects.all().get(user=request.user) account = Account.objects.all().get(id=pk) balance = account.balance_set.all() ctx = {'account': account, 'name': name, 'balance': balance, 'months': {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6, 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}} #Months dict is for view, it goes in a for … -
Django Images not uploading via S3
I am attempting to upload files to s3 via s3 from this tutorial. I created a group and and user with full s3 privilege's and when i upload an image it stays local instead of being uploaded to bucket. block all public access is false on the bucket boto is installed as well as django-storages added to the apps. Having a hard time figuring out the issue as i don't have any error messages to work with any help would be great! settings.py USE_S3 = os.getenv('USE_S3') == 'TRUE' if USE_S3: # aws settings AWS_ACCESS_KEY_ID = os.getenv('...') AWS_SECRET_ACCESS_KEY = os.getenv('...') AWS_STORAGE_BUCKET_NAME = os.getenv('...') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # s3 static settings AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'my_app.storage_backends.PublicMediaStorage' else: STATIC_URL = '/staticfiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/mediafiles/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) storage_backends.py from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class StaticStorage(S3Boto3Storage): location = 'static' default_acl = 'public-read' class PublicMediaStorage(S3Boto3Storage): location = 'media' default_acl = 'public-read' file_overwrite = False bucket CORS: [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "POST", "GET", "PUT" ], "AllowedOrigins": [ … -
fetching not with custom primary id in django
I have created a table in which the primary id have to customize id product_id like class Product(models.Model): product_id = models.BigIntegerField(auto_created = True,primary_key = True, unique=True) name = models.CharField(max_length=200) ref = models.CharField(max_length=100) number= models.CharField(max_length=100) class Meta: db_table = "products" def __str__(self): return self.name after creating the record I want to get the id of the latest record but when I retrieve the data with this id getting None product = Product.objects.create(name=name, ref=ref, number=number) print(product.product_id) product.product_id id getting null Pleae give me a solution to why this is happening. -
Can I deploy a django app to heroku from windows 10 operating system
I tried to deploy a django app to heroku from my windows 10. I used gunicorn in the Procfile which gives me error after successful deployment. what can I use in place of gunicorn in the Procfile? -
I have this problem here why I can't runserver
[enter image description here][1] the problem is I cannot do the runserver thing even though the venv and all the stuff are completly fine -
How to manage two applications in django single project [closed]
i have django project in which i have two application User side website Admin panel (backend). Not the admin provided by django. i am unable to manage two application setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'app_admin' ] urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')), path('', include('app_admin.urls')), ] -
Django Serializers - Datetime with multiple possible formats
I want my Django Serializer to validate the format of a date according to several possible formats. Essentially, these formats are: just the date (YYYY-MM-DD) date + hours (YYYY-MM-DD HH) date + hours + minutes (YYYY-MM-DD HH:MM) date + hours + minutes + seconds (YYYY-MM-DD HH:MM:SS) I know that the final two are possible together, using the DateTimeField with format= '%Y-%m-%d %H:%M:%S. I know the first one is possible by default using the DateField. I assume the second one is possible using the DateTimeField with format= '%Y-%m-%d %H', but I haven't tested. What I want to know is: is there a straightforward way to combine all these validators together, without having to use custom functions/validators? For example, my first instinct was to provide a list of possible formats to the format parameter on the Date/DateTime fields, but with no success. Is there something I'm missing? -
How to implement to get percentage task completed by a celery task in djano?
Let I have a celery task task_func() is it possible to write some code so that i can get the percentage of a task completed in django. def task_func(): # some logic ... ... -
Django pass field from serializer to model.save() that is not present in the model
I need to pass fields that are present in serializer, but not present in model to model save method (I have complicated saving logic and I want to make some decisions in object creation based on these fields). How can I do that? I tried to add non_db_field = property to model, but I still get error Reading() got an unexpected keyword argument 'negative_amount'