Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django request should run in background?
When user submit request, the request should run in background so that user should not wait for the request complete and update to user via email/slack channel? i have a request to ssh and performs the task, so some commands/tasks will take longer time to completed, that's why i'm looking this option What is the better way to achieve? -
Django Weasyprint Timeout error for loading images in log
and I made a project that takes some pictures and converts them to pdf using weasyprint library. everything is alright in localhost but when I deployed it in python anywhere it generates the pdf but pictures that supposed to be in it dosent display and just the replace string of them is in the pdf please help me -
What is easiest way to do "Featured comments " in Django?
I have an requirement in Django , If mark a comment has Featured , it should be displayed in top of the home page (or any page), for next 24 hrs. And after 24 hrs it should go to normal state. i.e I will be flagging a comment has featured with a FLAG and the flag should automatically reset after 24 hrs. I am already showing the recent comments in the home page by descending date's , now the flagged comment should appear on top of it. is there any Django specific library available to achieve this (instead of going to redis) -
Django jwt token error. "Given token not valid for any token type, token_not_valid"
I am using Django Rest Framework for authentication and Axios in the frontend. When I pass the token to an axios.get method directly it fetches the API endpoint (getUserInfo) correctly, but when I use a variable (string) and pass it dynamically it fails and it gives the error described above. First case: (succeeds) const config = { headers: { Authorization: 'Bearer <token string>' }, }; await axios.get(URLS.FETCH_USER, config) Second case: (fails) const config = { headers: { Authorization: `Bearer ${accessToken}` }, }; await axios.get(URLS.FETCH_USER, config).etc Note that the token is fresh and taken directly from a postman login request. -
how to set custom sqlalchemy logging parameters?
I am using sqlalchemy for connecting to database in a django based python application. In settings.py I have configured logging like this: settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format':'%(asctime)s - %(name)s - %(levelname)s - %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' } }, 'loggers': { 'app1': { 'handlers': ['console'], 'level': 'DEBUG', }, 'sqlalchemy.engine': { 'handlers': ['console'], 'level': 'INFO', }, } In views.py sqlogger=logging.getLogger("sqlalchemy.engine") logs are getting printed like this: 2021-02-23 16:32:35,741 - sqlalchemy.engine.base.Engine - INFO - SELECT `info`.`name` AS `info_name`, `info`.`open from `info` I want to input the logged in user variable which i store it in session request.session["username"]="Designer" so that the logs are getting printed like this with the logged in user: 2021-02-23 16:32:35,741 - sqlalchemy.engine.base.Engine - Designer- INFO - SELECT `info`.`name` AS `info_name`, `info`.`open from `info` Sqlalchemy automatically emits log statements, so I am not sure , how to pass this customization of user to the sqlalchemy engine. Can anyone please help? Thanks -
Django migrate won't run new migration when migration exists
I'm working on adding a foreign relation into an existing model. I created the foreign model with no issues and implemented the foreign key into my existing model. I ran makemigrations which created the migration file. However, when I run migrate, the migration is not applied and I receive the message that there were no new migrations to apply - even though there is one. I'm not too sure what else to try at this point. I've removed my newly created migration and tried rerunning makemigrations before migrating, but this has not helped at all. I double-checked to ensure that the migration file has all the correct information and is based of the directly previous migration. I've also made sure that I am in the correct spot in the project directory with my virtual environment running and docker running. I additionally tried specifying the migration file and the app it is in when running migrate, but this did not work either. I'm brand new to docker and so I'm not sure if this is what is causing the issue. I looked at this stackoverflow post which I thought might help but after looking at it, I don't really know if … -
Accessing APi'S on a different computer in react native on the same network
I have a django rest framework running on a different computer than the computer running my react native app. Both computers are running Kali Linux. I want my react native to access the endpoint's on the other computer. I have tried setting up my endpoint using both local and external IP address but it is not workingconst BASE_URL="http://MY_IP/api / const BASE_URL="https://MY_IP/api". Any help will be appreciated -
Unsure of approach for Django custom user groups and permissions
I am creating my first Django (ver 3.1) website which is simply a blog with a home page and store page. I want to create custom user groups that define specific roles (with unique permissions) for my blog. These groups are: Reader - anonymous viewers and new accounts; has read permission for all content only Author - login required; has read and create permissions; edit and delete permissions for own content only Moderator - login required; has all CRUD permissions for all content Admin - login required, has all permissions (superuser) All new users by default are in the Reader group. Author would either be assigned manually or eventually by an online form application to determine eligibility. Moderator and Admin would of course be manually assigned. I am approaching this with possible future development, such as allowing user groups to be easily extended to other website pages. For example, a 5% discount for Author users applied to all store items, etc. Which approach to creating user groups would be best for my situation? I have seen it done within the Django Admin Panel and by creating custom User Models via extending the AbstractBaseUser and UserBaseManager classes. -
Django: linking from one API view to another API view
I am currently trying to develop a plugin for the Netbox software. For this I am trying to add an additional API endpoint. Since the total amount of data is very large, I want to split up the endpoints a bit. My current state is something like this: "results": [ {"cg": clusterGroup1: {cluster1, devices: [{},{},{},] vms: [{},{},{},] },{cluster2, devices: [{},{},{},] vms: [{},{},{},] } }, {"cg": clusterGroup2: {cluster1, devices: [{},{},{},] vms: [{},{},{},] } ] Sorry for the not totaly correct JSON but I just wanted to show the Structure of the JSON. One respons containse around 40 cluster groups and each of them containes multiple clusters with devices and virtual machines. Because of the amount of data, one API call takes roughly a minute. Now I would like to split the cluster groups for enhanced performance. To do this I would put all cluster groups into one list but without the additonal data of clusters, devices and virtual machines. This List shut containe a Link to the detailed view of a cluster group. The link in the following JSON shut refer to the view seen in the first JSON data but just for one specific cluster group rather then all. "results":[{ … -
OrderAddView is missing a QuerySet. Python Django
Why such a mistake? OrderAddView is missing a QuerySet. Define OrderAddView.model, OrderAddView.queryset, or override OrderAddView.get_queryset(). urls from django.urls import path from .views import * urlpatterns = [ path('add/<str:tag>', OrderAddView.as_view(), name='order_add'), ] view class OrderAddView(CreateView): from_class = FastOrdersForm template_name = 'orders/order_add.html' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) context['tag'] = self.kwargs['tag'] print('tag ', context['tag']) return context form class FastOrdersForm(forms.ModelForm): class Meta: model = Orders fields = ['device', 'serial', 'comment', 'status'] widgets = { 'device': forms.TextInput(attrs={'class': 'form-control'}), 'serial': forms.TextInput(attrs={'class': 'form-control'}), 'comment': forms.Textarea(attrs={'class': 'form-control', 'rows': 5}), } -
While deploying my python2.7 code to production my pip==8.1.1 version gets changed to the latest version automatically to pip==20.0.3
While deploying my python2.7 code to production my pip==8.1.1 version gets changed to the latest version automatically to pip==20.0.3 can anyone help me on this? -
Django DRF Token authentication over https/ssl
I'm trying to implement Djangos' rest framework token authentication working over https. It works great over http but I can't get it working over https. On http I login, get my token and I can use that token for authentication with valid response. over https I can login, get back token successfully, However when I try to use that token for authenticate api requests over https, I get 401 unauthorized status code and response is "detail": "Authentication credentials were not provided." I followed this tutorial for http https://www.pythondecoders.com/2021/01/token-authentication-in-drf-django-rest.html#comment-form and http works fine. I have been trying to look for answers but didn't see anything anywhere. Is there any extra settings changes I need to make to make it work? -
Create a foreign key for a django model with specialized accessors
I'd like workers to be able to supervise other workers. A worker does not need a supervisor. They cannot supervise themself. (I don't care about loops) I'm not sure about the most django standard way to go about this. I can create a custom setter function, but I notice that the model still has supervisor and supervisor_id, which can be written to directly, circumventing the requirements I have in place. Here's what I have, but it's telling me "AttributeError: 'ForeignKey' object has no attribute 'setter'" class Worker(models.Model): supervisor = models.ForeignKey(Worker, blank=True, null=True, on_delete=models.CASCADE) @supervisor.setter def assign_supervisor(self, s_id): if s_id == self.id: raise Error("can't supervise yourself!") self.supervisor_id = s_id self.save() -
What would make django remove a trailing slash?
I need to make sure all of my urls are ending with a slash. Most off them are adding the slash to the end of a request, but I have a few that are removing the slash if I explicitly add it to the url. For example: http://127.0.0.1/about/testing/ will redirect to http://127.0.0.1/about/testing I am using 'django.middleware.common.CommonMiddleware' and APPEND_SLASH=True in my base.py, there are no overrides in my other settings.py. In urls.py the regex that catches this request is urlpatterns += [url(r'^.+/', nav_views.default), ], if I comment this line I will get a 404, but the trailing slash still gets removed. I know there is something that is missing, what possible way could the slash be getting removed? -
issue when running django site on IIS server
I am new to django. I am facing an unusual error. When I am running my site on localhost it is running smoothly. but when I run the same site via IIS server I am sometimes getting "Query doesn't exist issue". It is same query when I run on localhost it always give a correct result but when run via IIS (1 out of 5 times) it give "query doesn't exist issue". I have used try and except for the "query doesn't exist issue ". but can someone tell me why I am getting this issue. what should I add to the site. I am not sure of what code to present. so please let me know and I will share the code. Also I am using django modelforms to save the data. Thanks in advance. -
Partial Updating MongoDB Document - Mongoengine
I want to update part of my mongodb document in Django using Mongoengine rest framework. But the documentation is sadly really bad when it comes to updating a dict in a list of dicts. Both options are yet not working. Sample MongoDB document { delivery: "One", sequences: [ { "_id": "503505f14548f73d20ae067a", "name": "Sequence_1", "name_short_form": "IGI", "sequence_number": "050", "descriptions": "Description_1", "active": true }, { "_id": "191526f14548f73d20ae067a", "name": "Sequence_2", "name_short_form": "IGP", "sequence_number": "060", "descriptions": "Description_2", "active": true } ] } Update MongoDB Document in Django sequence_id = "191526f14548f73d20ae067a" # Fields I want to update (only replace given fields) new_sequence_data = { "name": "Sequence_2", "name_short_form": "PGP", "sequence_number": "070", "descriptions": "Description_2_Updated", "active": true } # Mongoengine set sequence data (option 1) document.update(set__sequences={{"_id": sequence_id}, new_sequence_data }) # Mongoengine set sequence data raw (option 2) document.update(__raw__=({"sequences.id": shot_id}, {"$set": { new_sequence_data }) # Save full document document.save() return Response(status=status.HTTP_200_OK) -
when an order is placed the quantity of products should be decremet
I am working on ecommerce site. Where I want when order is placed , The product quantity should be decrement by 1. I guess thee change should be done in orders models.py. But what should be the change I do not know here is my product models.py file: class Product(models.Model): title = models.CharField(max_length=110) slug = models.SlugField(blank=True, unique=True) status = models.CharField(choices=CATEGORY_CHOICES, max_length=10) price = models.DecimalField(decimal_places=2, max_digits=6) quantity=models.IntegerField(default=1) discount_price=models.FloatField(blank=True, null=True) size = models.CharField(choices=SIZE_CHOICES, max_length=20) color = models.CharField(max_length=20, blank=True, null=True) image = models.ImageField(upload_to=upload_image_path) description = RichTextField(max_length=1000) featured = models.BooleanField(default=False) author = models.ForeignKey(User, on_delete=models.CASCADE) time_stamp = models.DateTimeField(auto_now_add=True) my orders models.py is : class OrderManager(models.Manager): def new_or_get(self , billing_profile , cart_obj): created = False qs = self.get_queryset().filter(billing_profile=billing_profile, cart=cart_obj, active=True,) if qs.count() == 1: obj = qs.first() else: obj = self.model.objects.create(billing_profile=billing_profile, cart=cart_obj) created = True return obj , created class Order(models.Model): billing_profile = models.ForeignKey(BillingProfile, null=True , blank=True , on_delete=models.CASCADE) order_id = models.CharField(max_length=120 , blank=True) shipping_address = models.ForeignKey(Address, related_name="shipping_address" ,null=True , blank=True , on_delete=models.CASCADE) billing_aaddress = models.ForeignKey(Address, related_name="billing_address" ,null=True , blank=True , on_delete=models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) status = models.CharField(max_length=120 , default='created', choices=ORDER_STATUS_CHOICES) shipping_total = models.DecimalField(default=5.99, max_digits=100 , decimal_places=2) total = models.DecimalField(default=0.00, max_digits=100 , decimal_places=2) active = models.BooleanField(default=True) def __str__(self): return self.order_id objects = OrderManager() def update_total(self): … -
AJAX JQUERY Only Works With PreventDefault On
My form only works with e.preventDefault() but i need the page to refresh to show the filtered queryset on the page Why does this function only work when prevent default is on? (gives error function when not prevent default) $('.filter_form').submit(function(e){ e.preventDefault() const url = $(this).attr('action') var genres_selected_initial = []; var genre_item = document.getElementById(`filter_idAction`); var genres_selected_id = $(genre_item).attr('value'); var g = parseInt(genres_selected_id) if (genre_item.classList.contains("clicked_filter")) { genres_selected_initial.push(g); } var genres_selected = genres_selected_initial; $.ajax({ type: 'POST', url: url, data: { 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), 'genres_selected': genres_selected, }, success: function(response){ console.log(genres_selected) }, error: function(response){ console.log('error', genres_selected) } }) }) view def find(request): Posts = Post.objects.all() genre_list = Genres.objects.all() if request.method == 'POST': genres_selected_use = request.POST.getlist('genres_selected[]') for arg in genres_selected_use: arg = int(arg) Posts = Posts.filter(genres=arg) print(arg) print(genres_selected_use) #return redirect('find') context = { 'products': Posts, 'genre_list': genre_list, } return render(request, 'find/find.html', context) -
How do we add a label to a Django models.dateTimeField?
We are trying to assign a more sensible label with an input date in our Django admin's console. Code in the models file: bacteria_time = = models.DateTimeField(datetime.now(tz=ZoneInfo("America/New_York")), null=True, blank=True) In the changelist to the left of the date created we see a long date string. We would like to either format it with a label, or name, or something that relates it as the "Bacteria Sample Time" instead of the date on the laft and the date in the box. I'm sure we are just haven't the page of proper documentation. -
how to link java script variable to django if statement tag
i have some variabl in javascript start: function() { const ws = new WebSocket("ws://192.168.8.110/"); ws.onmessage = function (evt) { let message = JSON.parse(evt.data); document.getElementById("stat_c").innerHTML = message.status_c; console.log(JSON.parse(evt.data)); } }, and all works, but i will like to pass message.status.c to if statement tag in django template {% if message.status_c == 'progress'%} <a>In Progress</a> {% else %} <a>Finished</a> {% endif %} with this solution is howing nothing -
Django DRF Response returns "nested" array
I am trying to get json response from django server. Here are the views.py: class RnDCalculationView(APIView): def get(self, request, format=None): qs = Model.objects.filter(...).values(...).annotate(all_hours=Sum('hours'), filtered_hours=Sum('hours', filter=Q(...))) return Response(qs) If I get response from this endpoint I receive the correct data but they are nested in another array like this: [ [ { "all_hours": 15, }, { "filtered_hours": 5 } ] ] Is there any way to get rid off one of the [] so the response will look like: [ { "all_hours": 15, }, { "filtered_hours": 5 } ] -
Is it okay to display a page in a language taken from a cookie?
The Rails documentation says: You may be tempted to store the chosen locale in a session or a cookie. However, do not do this. The locale should be transparent and a part of the URL. This way you won't break people's basic assumptions about the web itself: if you send a URL to a friend, they should see the same page and content as you. A fancy word for this would be that you're being RESTful. Read more about the RESTful approach in Stefan Tilkov's articles. Sometimes there are exceptions to this rule and those are discussed below. But a couple of screens above, it teaches how to set locale from user preferences. Which equals to setting it from a cookie. I saw no such warnings in Django documentation. And although you probably can avoid it, storing it in a cookie seems like a recommended way. Is it okay to display a page in a language taken from a cookie? To cookie or to not? -
when i do command prompt for the django version it doesnt come up even though its successful on pycharm help please
when i do command prompt on windows for the django version it doesn't come up even though its successful installed on pycharm help please. i am new to python as well. when i go on to command prompt on windows to check django version after adding python -m django --version i get this result: C:\Users\User\AppData\Local\Programs\Python\Python39\python.exe: No module named django i am using pycharm as IDE and it seems when i did install django on pycharm it was successful should i worry about the django version coming up on command prompt or not. -
Last value onlyadded to a list
I am facing one issue to add element to my list Here is my code def summary(request,): data = [] values = {} fruits = ['apple','mango','orange','grapes'] for i in fruits: values['fruits'] = i values['count'] = calculating_count(i) data.append(values) What I am expecting is that my data list need to come like this data = [{'fruits':apple,'count':10},{'fruits':mango,'count':20},{'fruits':orange,'count':30},{'fruits':grapes,'count':40}] But what I am getting it as data = [{'fruits':grapes,'count':40},{'fruits':grapes,'count':40},{'fruits':grapes,'count':40},{'fruits':grapes,'count':40}] Only it appending the last element -
UserPaymentInformation matching query does not exist
I want to implement UserPaymentInformation update in django rest framework But for request http://127.0.0.1:8000/api/payments/update/ I have an error DoesNotExist at /api/payments/update/ UserPaymentInformation matching query does not exist. Full stacktrace https://pastebin.com/WVjQ5aYN models.py class UserPaymentInformation(models.Model): full_name = models.CharField(max_length=200) card_number = models.CharField(max_length=16) account_number = models.CharField(max_length=24) bik = models.CharField(max_length=255) user = models.OneToOneField( User, related_name="payment_information", on_delete=models.SET_NULL, null=True, ) class Meta: ordering = ("-pk",) verbose_name = "user payment information" verbose_name_plural = "user payment informations" serializers.py class UserPaymentInformationUpdateSerializer(serializers.ModelSerializer): class Meta: model = UserPaymentInformation fields = ("id", "full_name", "card_number", "account_number", "bik") views.py class UserPaymentInformationUpdateAPIView(generics.UpdateAPIView): permission_classes = (IsAuthenticatedDriver,) serializer_class = UserPaymentInformationUpdateSerializer queryset = serializer_class.Meta.model.objects.all() def get_serializer_class(self): if self.request.version == "1.0": return UserPaymentInformationUpdateSerializer # return UserPaymentInformationUpdateSerializer2 def mark_user_as_new(self): user = self.request.user user.is_new_user = True user.save() def update(self, request, *args, **kwargs): partial = kwargs.pop("partial", False) instance = self.serializer_class.Meta.model.objects.get( user=self.request.user ) self.mark_user_as_new() serializer = self.get_serializer( instance, data=request.data, partial=partial ) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response({"result": serializer.data}) How can I fix the error?