Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to auto update data in django?
I am trying to build eCommerce application in Django. In each product I have three label tags which are is_new, is_hot, is_promo. is_new will be True when a product will create, I have done it. But the system needs to automatically make is_new to False when a product is older than 7 days. I have added created_date field in Product model. How could I auto update is_new to False? Any hints? is_hot will be True when a product will most sold. Actually the first two product will be hot. And when other product goes hot then previous hot products will be automatically False. How to do it? Hints? is_promo will be True when I will add discount to a product. And it will be False when I will remove the discount. Any hints? -
Django how to convert the older format url to the newer format path
I am using ajax to create a GET request to django, and I want to convert the older format url to the newer format path. This line works url(r'^setComplete/$', views.setComplete, name='setcomplete'), While this line fails with 404(http://127.0.0.1:8000/project/setComplete?item_id=1) Not found path('set_complete/<int:item_id>',views.setComplete, name='setcomplete'), Here is the Ajax code $.ajax( { type:"GET", url: "/project/setComplete", data:{ item_id: itemid }, success : function(data) { console.info("Success",data); }, error : function(e) { console.info("Error",e); }, done : function(e) { console.info("DONE",e); } }) Here is a simple view just for testing def setComplete(request): return HttpResponse("Success!") # Sending an success response -
Adding password value to serialized data during update and setting new permission (drf)
I am using django rest framework and DjangoModelPermissions, I have serialized the default User Model to get information about the users and their permissions and also admin can change the permission as per requirement from the front-end (some JavaScript) or make some user a superuser. The problem is when admin tries to do a PUT statement with new data it fails. In User model password is the mandatory required field. I have got user's authentication token(which does not work) and i have not serialized password from users model and i don't want to. I tried to append serialize data before saving to add one more field "password" by getting the values using user.objects.get(username=data_from_serializer_data).password but i am not able to add an extra field(password field) to serializer data. What may be the way to achieve my goals? how can i add password value in serializer data(at back-end) and then send complete data for update. Also i read somewhere that serializer.data is a property which can not be edited. If true what else will i have to do to complete my task? Thanks -
Django CBV. I need to fill 3 dropdowns with different models in the same template on Django?
I have a doubt, there is a way through the CBV to have results from several querysets of different models for a single template. Do I need to fill 3 dropdowns in the same template? How to do this? Thanks -
how to get other ModelField Value on my actual form? DJANGO
Thanks for your time: i want to set Validation Error with data that is already written in other modelclass. Models.py class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='person') birthday = models.DateField() cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return '%s' % (self.user) class Pets(models.Model): pessoa = models.ForeignKey(People, on_delete=models.CASCADE) nome = models.CharField(max_length=150) custo = models.DecimalField(max_digits=7, decimal_places=2) tipo = models.SmallIntegerField() def __str__(self): return '%s - %s' % (self.pessoa, self.nome) Forms.py: class PetForm3(forms.ModelForm): #SELECIONAR FORM PELO FORMS.PY field_choices = [ (1, 'CACHORRO'), (2, 'GATO'), (3, 'ANDORINHA') ] nome = forms.CharField(max_length=100) custo = forms.DecimalField(max_digits=7, decimal_places=2) tipo = forms.ChoiceField(choices=field_choices) class Meta: prefix = 'pet' model = Pets fields = ['nome', 'custo', 'tipo'] def clean_tipo(self): data = self.cleaned_data.get("tipo") data_nome = self.cleaned_data.get("pessoa") slug = slugify(data_nome) if slug.startswith('a'): data == 2 raise forms.ValidationError('nomes com A nao podem ter gatos') return data i got these two models and the Pets is a ManytoOne to People i'd like to take attributes of People like birthday and cpf in the clean_method of PetForm3. and like to get the ''pessoa'' field from Pets on the clean method either. i'm able to achieve something like that with request.user in views.py but i'd like to get it in clean_method at forms.py -
Circular importing error using wagtail-generic-chooser
I am using wagtails wagtail-generic-chooser to create customChoosers for my data models and it is working great whenever I am referencing other modelAdmin models. However, I have come across a situation where I have a Lexis model with a field that has a FK link to itself. The idea is to have a Lexis term, and then there can be related lexis terms connected to it. It works fine with a normal FieldPanel but this isn't a very good UI experience when there are hundreds of lexis terms. Accordingly, I wanted to create a custom LexisChooser for this field. However, the issue I've run into is according to the documentation in order to create a functional widget, I am required to create both a view and adminChooser that references the model the ChooserPanel is connected to. https://github.com/wagtail/wagtail-generic-chooser#chooser-widgets-model-based This makes sense, however, when I then try to import my LexisChooser into my Lexis model to use the LexisChooser as a widget, I get the error below. ImportError: cannot import name 'Lexis' from 'lexis.models' I realize this is due to a circular import error issue because I have subclasses that are importing the Lexis Class in order to build the LexisChooser widget … -
Django channels testing failed
I am trying to make a chat application on django using channels 2. I am following the tutorial here : https://channels.readthedocs.io/en/latest/tutorial/part_4.html , though am following it on windows while the code is actually meant for linux. I am getting this error while testing : (hackathon) C:\Users\PARAM BHATT\PycharmProjects\ChatHead\chatsite>py manage.py test chat.tests Creating test database for alias 'default'... Destroying old test database for alias 'default'... System check identified no issues (0 silenced). DevTools listening on ws://127.0.0.1:52430/devtools/browser/6d5d1d7f-3df0-4583-bc1d-992f7803932e EETraceback (most recent call last): File "<string>", line 1, in <module> File "c:\users\param bhatt\appdata\local\programs\python\python38-32\lib\multiprocessing\spawn.py", line 109, in spawn_main fd = msvcrt.open_osfhandle(new_handle, os.O_RDONLY) OSError: [Errno 9] Bad file descriptor Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\users\param bhatt\appdata\local\programs\python\python38-32\lib\multiprocessing\spawn.py", line 107, in spawn_main new_handle = reduction.duplicate(pipe_handle, File "c:\users\param bhatt\appdata\local\programs\python\python38-32\lib\multiprocessing\reduction.py", line 79, in duplicate return _winapi.DuplicateHandle( OSError: [WinError 6] The handle is invalid ====================================================================== ERROR: test_when_chat_message_posted_then_not_seen_by_anyone_in_different_room (chat.tests.ChatTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\PARAM BHATT\PycharmProjects\ChatHead\hackathon\lib\site-packages\django\test\testcases.py", line 267, in __call__ self._pre_setup() File "C:\Users\PARAM BHATT\PycharmProjects\ChatHead\hackathon\lib\site-packages\channels\testing\live.py", line 52, in _pre_setup self._server_process.start() File "c:\users\param bhatt\appdata\local\programs\python\python38-32\lib\multiprocessing\process.py", line 121, in start self._popen = self._Popen(self) File "c:\users\param bhatt\appdata\local\programs\python\python38-32\lib\multiprocessing\context.py", line 224, in _Popen return _default_context.get_context().Process._Popen(process_obj) File "c:\users\param bhatt\appdata\local\programs\python\python38-32\lib\multiprocessing\context.py", line 326, in _Popen return Popen(process_obj) File "c:\users\param bhatt\appdata\local\programs\python\python38-32\lib\multiprocessing\popen_spawn_win32.py", line 93, in __init__ … -
Django - Annotate multiple fields from a Subquery
I'm working on a Django project on which i have a queryset of a 'A' objects ( A.objects.all() ), and i need to annotate multiple fields from a 'B' objects' Subquery. The problem is that the annotate method can only deal with one field type per parameter (DecimalField, CharField, etc.), so, in order to annotate multiple fields, i must use something like: A.objects.all().annotate(b_id =Subquery(B_queryset.values('id')[:1], b_name =Subquery(B_queryset.values('name')[:1], b_other_field =Subquery(B_queryset.values('other_field')[:1], ... ) Which is very inefficient, as it creates a new subquery/subselect on the final SQL for each field i want to annotate. I would like to use the same Subselect with multiple fields on it's values() params, and annotate them all on A's queryset. I'd like to use something like this: b_subquery = Subquery(B_queryset.values('id', 'name', 'other_field', ...)[:1]) A.objects.all().annotate(b=b_subquery) But when i try to do that (and access the first element A.objects.all().annotate(b=b_subquery)[0]) it raises an exception: {FieldError}Expression contains mixed types. You must set output_field. And if i set Subquery(B_quer...[:1], output_field=ForeignKey(B, models.DO_NOTHING)), i get a DB exception: {ProgrammingError}subquery must return only one column In a nutshell, the whole problem is that i have multiple Bs that "belongs" to a A, so i need to use Subquery to, for every A in A.objects.all(), pick … -
Keep same web page after POST request on iOS devices (Django sending 204 status response)
My Django project has a number of buttons on the web page that do POST requests to the main view.py which in turn handles the action and returns a 204 No content response. The results of the action show up asynchronously later on the web page (at the time the response is generated there's nothing new to show). On any non-iOS based browser the 204 response works fine and the web page remains in the browser, as expected from RFC 7231. Unfortunately all iOS based browsers I've tried (Safari, Firefox, Chrome) navigate to a blank page after the POST, which is not what I want (see this question). Apparently this is a long standing bug in WebKit. Is there any way to achieve the same thing across all browsers? ie. Click button, POST, web page stays as is, change appears later. I've looked at this but no sure it's really what I'm after. Changing the response code is possible but I don't see a viable alternative that doesn't navigate away from the current page. My current hacky fix is to reload the whole page for an iOS device, but this moves the page if the user had scrolled down earlier … -
django.core.exceptions.FieldError: Cannot resolve keyword 'ModelList' into field. Choices are: borrows, dept_list, dept_list_id, email_ad
i am a beginner of Djanog, i am experiencing a problem of django.core.exceptions.FieldError: Cannot resolve keyword 'ModelList' into field. Choices are: borrows, dept_list, dept_list_id,..... i have try to remove the files on migrations folder excuted python manage.py makemigrations and migrate ,and reload nginx, restart uwsgi, issue will appear again after the server run normally for a moment. the issue is not heppen immediately after the server up, also , i have try to rename the field name, but this is not helpful for solving the issue. could you please help chech where is wrong, where does the issue come from ? ''' class pc_list(models.Model): host_name=models.CharField(max_length=64, unique=True) service_tag=models.CharField(max_length=45,unique=True) #hosttype_list=models.ForeignKey('hosttype_list', to_field='id',default=1, on_delete=None) ModelList=models.ForeignKey('ModelList',to_field='id',on_delete=None) host_spec=models.CharField(max_length=45) price=models.FloatField(default=0) receive_date=models.DateField(auto_now_add =False, default='2018-01-01') user_list = models.ForeignKey('user_list', to_field='id', on_delete=None, default=180) seat_no = models.IntegerField(default=14000) PcStatus=models.ForeignKey('PcStatus', to_field='id', on_delete=None, default=2) studio = models.CharField(max_length=45, default='-') site_list=models.ForeignKey('site_list', to_field='id', on_delete=None) asset_code = models.IntegerField(default=1) remark=models.TextField(max_length=200, default='-') mac=models.CharField(max_length=15, default='-') class Meta: ordering = ('host_name',) def __str__(self): return self.host_name class PcStatus(models.Model): statusname=models.CharField(max_length=45,default='--') def str(self): return self.statusname class ModelList(models.Model): name = models.CharField(max_length=40) hosttype_list = models.ForeignKey('hosttype_list',to_field='id',on_delete=False) def __str__(self): return self.name class Meta: ordering = ('name',) view as below class pcDataView(FeedDataView): token = pc_listTable.token def get_queryset(self): siteid = self.request.session.get('current_site') hosttypeid=self.request.session.get('hosttype_id') if hosttypeid ==0: return super(pcDataView, self).get_queryset().filter(site_list_id=siteid , ModelList__hosttype_list_id__in=(1,2,3,12)).exclude(PcStatus_id=4) else: return … -
Manage Parent Child Category in django
Django Models I'm working on a e-commerce website where I need to assign child category to a parent category like if when add product admin will select parent category then its relevant child category should come to select in I tried doing like this but didn't able to find solution class MainCategory(models.Model): # name = models.CharField(max_length=50) # date_created = models.DateTimeField(auto_now_add=True) # def __str__(self): # return self.name # class SubCategory(models.Model): # perentcategory = models.OneToOneField(MainCategory, on_delete=models.CASCADE, primary_key=True) # name = models.CharField(max_length=50) # date_created = models.DateTimeField(auto_now_add=True) # def __str__(self): # return self.name # class Items(models.Model): # main = models.ForeignKey(SubCategory, on_delete=models.CASCADE) # name = models.CharField(max_length=255) Please Share How I can do that -
How can I solve this error [missing 1 required positional argument: 'request']?
When I tried using a session on DetailView class in the Django project, I have an error and it does not work because of the missing a request object. in that case, how should I do? Would you mind telling me how should I solve this problem? Thank you in advance. the error code TypeError at /detail/41/ check_session() missing 1 required positional argument: 'request' views.py class DetailView(LoginRequiredMixin, generic.DetailView): model = sampleDB template_name = 'detail.html' def check_session(self, request): if not 'history' in request.session: request.session['history'] = {'user': self.request.user, 'id': self.kwargs['pk']} def get_context_data(self, **kwargs): self.check_session() context = super().get_context_data(**kwargs) return context Development environment Python: 3.7.5 Django: 2.2.2 -
When creating a new user in /admin using the django rest framework, the users password is not encrypted
I built an API using the Django rest framework. When you access the /admin page and are logged in as a superuser you have the ability to create new user profiles. However, creating one from the /admin tab means that when the users profile is created the password that is used does not get encrypted like it usually would if created from the /API tab. What do I need to add to encrypt the users password even if it created in the /admin tab? If I need to upload any code or anything please let me know this is my first time using StackOverflow so I am sorry if things are not formatted the right way. -
How to Validate entering Multiple url in one URLfield In Django?
I am Working with Django URLfields. this is my model: class Settings(models.Model): facebook_url = models.URLField(verbose_name='Facebook URL') linkedin_url = models.URLField(verbose_name='Linkedin URL', blank=True,null=True) twitter_url = models.URLField(verbose_name='Twitter URL', blank=True,null=True) logo_url = models.ImageField(upload_to='logo/', blank=True) class Meta: verbose_name = strings_settings.SETTINGS_VERBOSE_NAME verbose_name_plural = strings_settings.SETTINGS_VERBOSE_NAME_PLURAL db_table = 'settings' def __str__(self): return self.facebook_url So I want that nobody will be able to add multiple url in One field. one facebook url at a time,one linkedin and one twitter. How Can I able to do it. Advanced Thanks. -
FCM-Django what happens to a notification if the app is running?
I'm still fairly new to push notifications and I haven't developed a mobile client for testing. I'm primarily using the methods provided by fcm-django. from fcm_django.models import FCMDevice devices = FCMDevice.objects.all() devices.send_message(title="Title", body="Message", data={"test": "test"}) I know if the app is not in the foreground the user will receive a notification. My question is if the app is actually running, will the user get a notification or will we be able to handle it quietly in the background? Example live updating chats in the backgorund. -
load a html file in a particular div from attribute href in a anchor tag
Div in HTML file <div class="content"> <p class="info">Please choose a category</p> </div> anchor tag with href attribute <a class="menu__link" href="{% url 'Profile' %}">Profile</a></li> My javascript function var gridWrapper = document.querySelector('.content'); function loadDummyData(ev, itemName) { ev.preventDefault(); closeMenu(); gridWrapper.innerHTML = ''; classie.add(gridWrapper, 'content--loading'); setTimeout(function() { classie.remove(gridWrapper, 'content--loading'); gridWrapper.innerHTML = $(".menu__link--current").attr("href") console.log($(".menu__link--current").attr("href")) }, 500); } Output in console is showing the path of the url /Accounts/profile If the ev.preventDefault(); is removed, and commenting the linegridWrapper.innerHTML = $(".menu__link--current").attr("href"), the html page gets loaded but not in the particular content div. The problem is i want to load that particular html page with href attribute in content div. Any Help will be much appreciated. Thank You. -
In Django, the | operator is creating duplicates when I merge two querysets together
This is a really strange thing, because I understand the | operator is supposed to create a union of two querysets without duplicating objects. I'm trying to perform a query search, and getting sets of objects to display on the page. One of these sets are for posts. Here is a snippet of my code: if query: block_list = Block.objects.filter(Q(name__icontains=query) | Q(tags__slug__icontains=query)) user_list = CustomUser.objects.filter(Q(first_name__icontains=query) | Q(last_name__icontains=query) | Q(username__icontains=query)) post_list = Post.objects.filter(Q(tags__slug__icontains=query)) post_list_by_title = Post.objects.filter(Q(title__icontains=query)) print(post_list) print(post_list_by_title) print(post_list | post_list_by_title) Here is the outcome of the three print commands in cmd. <QuerySet []> <QuerySet [<Post: Post1>]> <QuerySet [<Post: Post1>, <Post: Post1>, <Post: Post1>]> In case you're wondering why I split the post_list by tag and post_list by title, I originally had: post_list = Post.objects.filter(Q(tags__slug__icontains=query) | Q(title__icontains=query)) But when I printed post_list, it still came out to be: <QuerySet [<Post: Post1>, <Post: Post1>, <Post: Post1>]> all the same. Do you have any idea why this could be? -
Django form problem, Repeating a form n times in one template
As title What I want to do is to add a button. After pressing the button, a duplicate form will be added to enter data. Need to add a few pieces of information, just press the button several times! How can I achieve this? -
django to display stored procedure result
I am new to Django.Below is version of Django and used database Django version: 2.1.15, django-pyodbc-azure==1.11.9.0, used sql-server 2012 django-admin startproject item Objective: To take input from user @itemnumber & give that input to EXEC ValidateBusinessrule '@itemnumber' and show result in html page setting.py connection DATABASES =\ { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'ETP', 'HOST': '10.*.*.*', 'USER': '', 'PASSWORD': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', } } } item.urls: from django.urls import path from django.urls import path from . import views urlpatterns = [path(r'item/', views.itemnumber, name='index'), ] print("hello1") views.py: from django.db import connection print("yupp") def itemnumber(request): print("hiiiiiiiiii") cursor = connection.cursor() try: Itemnumber = "1234" cursor.execute('EXEC ValidateBusinessrule Itemnumber') result_set = cursor.fetchall() finally: cursor.close() print("hello3") I am not able to go inside def itemnumber(request) in views.py are not executing or in other words not able to print (not printing--print("hiiiiiiiiii")) Currently I am not getting any error while running above code. How to retrieve stored procedure table result to my html page form? -
django send file after a process is done
I am trying to run a function foo on an uploaded file then send the output file to the user, I have written a functions to store the uploaded file and send emails (both works),I need help in attaching the output file once the function is completed foo() which takes about 1-2 hours to complete. this is my views.py import time from django.shortcuts import render from django.core.files.storage import FileSystemStorage from django.core.mail import send_mail def My_Upload(request): if request.method=="POST": uploaded_file = request.FILES['document'] fs = FileSystemStorage() name = fs.save(name=uploaded_file.name,content=uploaded_file) context = {'Name':name} #function return render(request,'my_app/homepage.html',context=context) return render(request,'my_app/upload.html',) def send_email_to(filename=None): foo(filename) send_mail("Your file is ready", "Here is your file", 'example@gmail.com', ['1234@gmail.com'],fail_silently=False) def foo(filename): #run some math on the file #creates a f'{filename}_done.csv' time.sleep(300) pass is there a way to do this, if not what alternatives do I have for accomplishing this? -
Django url collisions
Using Django==2.2.11, djangorestframework==3.8.1 Thank you for reading! The urls I am using that have the collision: urlpatterns = [ . . . url( r'^some-path/(?P<pk>\w+)$', views.MyViewSet.as_view({'get': 'retrieve'}) ), url( r'^some-path$', views.MyViewSet.as_view({'post': 'create'}), ), ... ] I am using postman to test each path, and it seems like there is a collision between these two urls. Using this url with a GET, would work: http://my_domain.com:8000/some-path But POST with same url (and with a valid payload) would throw error: WARNING 2020-03-28 19:13:57,288 "POST /some-path HTTP/1.1" 405 41 And response: {"detail": "Method \"POST\" not allowed."} I urls are swapped in order, then the POST would work, and GET would throw a similar error. I looked at this post: 405 POST method not allowed I would gladly add the view code - but I am pretty sure the issue is with the urls, since they each work when swapped order. Will add it upon request. Thank you! -
Django DRF FCM: Live Chat passively notify mobile client
I'm using fcm-django to send push notifications. Docs: https://fcm-django.readthedocs.io/en/latest/# I usually send notifications using the send bulk message method: from fcm_django.models import FCMDevice devices = FCMDevice.objects.all() devices.send_message(title="Title", body="Message", data=data) But I need a way to discrete notify the app to update chat without having to notify the user everytime. Example when they're actually in the chat. Any known solutions for this? -
How does Django Rest Framework permission_classes work?
I don't understand why the permission_classes attribute of a GenericView is a list. Say why is it permission_classes = [IsAdminUser] and not permission_class = IsAdminUser ? Also can I put 2 or more elements in the list, if so how do I interpret this? permission_classes = [IsAdminUser, IsAuthenticated] Is the snippet above the same as permission_classes = [IsAdminUser & IsAuthenticated] ? Also how should I interpret bitwise OR on the permissions? permission_classes = [IsAdminUser | IsAuthenticated] Thank you -
Django serializers vs rest_framework serializers
What is the difference between Django serializers vs rest_framework serializers? I making a webapp, where I want the API to be part of the primary app created by the project. Not creating a separate App for the API functionality. Which serializer do I need to use for Django views and models, and at the same time will work for the API? from django.core import serializers https://docs.djangoproject.com/en/3.0/topics/serialization/ from rest_framework import serializers https://www.django-rest-framework.org/api-guide/serializers/ -
Why we shouldn't keep our code in our web server's root folder?
I started learning Django, in official website(as you can see from the image below) it says we shouldn't keep our code in server's root folder but we need to keep it somewhere outside the root folder. I didn't understand two things 1) How we will be able to run our project without keeping the code in root folder? 2) How is it safe to keep the code in /home/mycode folder than keeping it in /var/www ?