Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Use foreign keys as choices for choice-field
Suppose I have the following models (Does not really matter, any model whatsoever will do) class Model0(models.Model): pass class Model1(models.Model): pass How can I pass them as choices to another Model, something like this: class Model3(models.Model): CHOICES = [ (models.ForeignKey(Model0,related_name='model_0',on_delete=models.CASCADE),'model0'), (models.ForeignKey(comment,related_name='model_1',on_delete=models.CASCADE),'model1'), ] choice_collumn = models.ForeignKey(choices=REPORT_TYPES) #it actually has a choices keyword argument The idea is that it will either have a Foreign key relationship to Model 0 or to Model 1. The way I am dealing with this is by setting one of them to null model_0_relationship = models.ForeignKey(Model0,null=True) model_1_relationship = models.ForeignKey(Model1,null=True) But what if I have way more than 2? is there a better solution? -
Use 2 pk instead of 1 in Django rest framework DELETE method
I want to delete an object that is related to a different model. Basically i need to send DELETE request to a url with 2 pks i guess, since it's impossible to send a DELETE request with additional data as body. Basically models look something like this: class Product(models.Model): name = models.CharField() class Person(models.Model): name= models.CharField() class ProductOrder(models.Model): product = models.ForeignKey(Product) person = models.ForeignKey(Person) I want to configure the DELETE method on ProductOrder, that I when i send my request to : http://127.0.0.1:8000/productorders/2/67/ It will find a Person with ID=2 , and delete a ProductOrder that is related to this person and it's related to a Product with ID=67. How can i combat this problem ? -
How to run Django docker image with server? [closed]
I have a Django docker image which is to be run on gpu and on Django's server. When I go inside the image and try to run the '''python3 manage.py runserver''' commmand it can't access the web. Please anyone could could help running the django server from docker and using GPU. -
How to Print data in django view file?
i am Selecting data using djano query.i am using following query def myfunction(request): mydata=MyModel.objects.all() #this is query return HttpResponse (mydata) # i am using this for printing data its showing me result in below formet, MyModel object(28) MyModel object(29) MyModel object(30) i want to print the data which is inside the object.How to do that? -
Django next url to HTTPS (Nginx)
I have added a SSL certificate to my nginx application, everything works fine, but when django paginates for the next url it uses: http:// not https:// How can I change this? -
Error : subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method... in Django date filtering
I'm using Django 2.2.12. In models.py, I have a model of name Webregister having field created_on = models.DateTimeField(null=True, blank=True) that returns data in the format 2020-09-04 22:17:00+00:00 Inorder to filter the date, I wrote this query Webregister.objects.filter(created_on__date=date.today()) and it returns the following error, NotImplementedError: subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method However, it's working fine If I use __year and hit the following query, Webregister.objects.filter(created_on__year="2020") PLease let me know what's the issue ? -
coming across with Cors issue after logged in
here is my axios get request async getIpAddress ({commit}) { const { data: { ip } } = await axios.get("https://www.cloudflare.com/cdn-cgi/trace", {responseType: "text", transformResponse: data => Object.fromEntries(data.trim().split("\n").map(line => line.split("="))) }); console.log(ip); commit('setIp', ip) if request.user.is_anonymous: working fine smoothly console.log is [HMR] Waiting for update signal from WDS... client-entry.js?d267:36 [Quasar] Running SPA. auth.js?e140:216 84.54.84.225 client?db9c:48 [WDS] Hot Module Replacement enabled. client?db9c:52 [WDS] Live Reloading enabled. backend.js:2237 vue-devtools Detected Vue v2.6.11 but after logged in I start struggling with cors Access to XMLHttpRequest at 'https://www.cloudflare.com/cdn-cgi/trace' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response. xhr.js?e38e:160 GET https://www.cloudflare.com/cdn-cgi/trace net::ERR_FAILED please help me out -
Django user model - is it possible to build different profile?
I'm beginning with Django. I'm using a classical user system of Django (django user model). I did not use AbstractUser. I probably made a mistake. So each user of my website has a profile: class Functionfeedcool(models.TextChoices): COOKER = 'Cooker' SUPERCOOKER = 'Super cooker' DEV = 'Dev' CEO = 'CEO' class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) ... functionfc = models.CharField(max_length=20,choices=Functionfeedcool.choices,default=Functionfeedcool.COOKER,) ... Is it possible to use one other Profile only dedicated to Supercooker user? I'm using the same dashboard for each user. What kind of code I can use to complete this profile form for supercooker? Assume I don't want Cooker, Dev and Ceo have access to this form. if it's not possible, which I hope not. what is the quickest way to replace Django User Model to AbstractUser? -
Raw Query representation In Django ORM
I have two table state , vote class State(models.Model): state_name = models.CharField(max_length=255,blank=True) value = models.IntegerField() code = models.CharField(max_length=255,blank=True) class Votes(models.Model): user = models.ForeignKey(Registeruser, on_delete=models.CASCADE) state = models.ForeignKey(State, on_delete=models.CASCADE) candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE) I want to convert my raw sql into Django ORM form '''' SELECT SUM(account_state.value) FROM account_votes INNER JOIN account_state ON account_state.id = account_votes.state_id where user_id ="%s" and candidate_id="%s";', [user_id,candidate]) ''' into a Django ORM form like Votes.object.select_related(state) kind of like that.. Please help me with that.. Im stuck.. Thanks in advance -
Django search lookup score
How can I get the score when using search lookup? Suppose you have the search shown in the documentation: >>>Entry.objects.filter(body_text__search='Cheese') [<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>] It results in two documents that must be sorted by some kind of numerical score. How to know the resulted score? -
How to import a model to a file in Django
I have the following structure of the project: manuals_project - bedienungsanleitung - migrations - admin.py - apps.py - models.py - urls.py - views.py - modules - save_to.py I have folder modules. And I have file save_to.py I need to import a model from bedienungsanleitung app. But when I try to do it, it gives an error No module named 'manuals_project.bedienungsanleitung' I try to do it the following way: from manuals_project.bedienungsanleitung.models import Link What is the mistake? Can someone help me? -
Django app running on 8000 cant be reached from windows
I am running a django app on 0.0.0.0:8000 on ec2. I can access this app using wget, but the same url does not work form windows. In my Security group i have added a rule t allow port range 8000 from source 0.0.0.0/0. Here is the wget response. Most certainly a config issue. Any AWS EC2 experts there? Thanks in advance ubuntu@ip-172-31-15-59:~$ wget 13.232.233.180:8000/events --2020-09-03 11:05:24-- http://13.232.233.180:8000/events Connecting to 13.232.233.180:8000... ^C ubuntu@ip-172-31-15-59:~$ wget http://ubuntu@ec2-13-232-233-180.ap-south-1.compute.amazonaws.com:8000/events --2020-09-03 11:07:03-- http://ubuntu@ec2-13-232-233-180.ap-south-1.compute.amazonaws.com:8000/events Resolving ec2-13-232-233-180.ap-south-1.compute.amazonaws.com (ec2-13-232-233-180.ap-south-1.compute.amazonaws.com)... 172.31.15.59 Connecting to ec2-13-232-233-180.ap-south-1.compute.amazonaws.com (ec2-13-232-233-180.ap-south-1.compute.amazonaws.com)|172.31.15.59|:8000... connected. HTTP request sent, awaiting response... 301 Moved Permanently Location: /events/ [following] --2020-09-03 11:07:03-- http://ubuntu@ec2-13-232-233-180.ap-south-1.compute.amazonaws.com:8000/events/ Reusing existing connection to ec2-13-232-233-180.ap-south-1.compute.amazonaws.com:8000. HTTP request sent, awaiting response... 200 OK Length: 2319 (2.3K) [text/html] Saving to: ‘events’ events 100%[==========================================================================>] 2.26K --.-KB/s in 0s 2020-09-03 11:07:03 (47.1 MB/s) - ‘events’ saved [2319/2319] -
How do I get an access token with a credential_id/token_id?
I have made a Django website using Google APIs. I was testing it and I logged in using Google, after that, a table called : "gfgauth_credentialsmodel" was created in my DB, it has a column called : "credentials", which is a large number. How do I get an access token using this credential_id? -
USSD on Django System
Am developing an application that will used ussd to query the database.The system is developed using django framework.There is no much information on the topic.Any infomation would be appreciated. regards -
How can solve profilepage key error in Json django deploy in web server
I have a problem that , my script run at localhost correctly but at cpanel host it doesn't run : problematic script : enter code here from django.shortcuts import render from django.http import HttpResponse import json import re import requests def home(request): return render(request,'home.html',{'name':'Shahin '}) def add(request): val = str(request.POST['num']) response = requests.get('https://www.instagram.com/' + val) json_match = re.search(r'window\._sharedData = (.*);</script>', response.text) profile_json = json.loads(json_match.group(1))['entry_data']['ProfilePage'][0]['graphql']['user'] res1 = profile_json['edge_followed_by']['count'] res2 = profile_json['edge_follow']['count'] res3 = profile_json['edge_owner_to_timeline_media']['count'] res4 = profile_json['is_private'] res5 = profile_json['is_business_account'] res6 = profile_json['business_category_name'] res7 = profile_json['is_verified'] res8 = profile_json['is_joined_recently'] res9 = profile_json['profile_pic_url_hd'] return render(request,'result.html',{'result1': res1 ,'result2': res2,'result3': res3,'result4': res4,'result5': res5,'result6': res6,'result7': res7,'result8': res8,'result9': res9,'val' : val }) and error : Exception Type: KeyError Exception Value: 'ProfilePage' Exception Location: /home/maadplat/instagram/instagram/views.py, line 14, in add Python Executable: /home/maadplat/virtualenv/instagram/3.7/bin/python3.7 error image : [1]: https://i.stack.imgur.com/48KZk.jpg -
Exception Value: join() argument must be str, bytes, or os.PathLike object, not 'function'
TypeError at /polls/ join() argument must be str, bytes, or os.PathLike object, not 'function' Request Method: GET Request URL: http://127.0.0.1:8000/polls/ Django Version: 3.1 Exception Type: TypeError Exception Value: join() argument must be str, bytes, or os.PathLike object, not 'function' Exception Location: c:\users\lenovo\appdata\local\programs\python\python38-32\lib\genericpath.py, line 152, in _check_arg_types -
Create external user with Django Rest Framework?
I would like to create a external user for use my DRF API in his application. I am using Django Oauth Tookit for verfy my user (https://django-oauth-toolkit.readthedocs.io/) The idea is, when the external user is registered by form, after a manual verification, I would like to send it a Client_id and Secret_id for use my API in his application, with his credentials. The question is: How can I create an Django oauth Toolkit Application (api/o/application) for other user, with my superuser account? And not allow the access to this user for modify his Client_id and Secret_id and obviously, Admin or other Staff resources. It is Django Oauth Tookit the best way to do it? -
How can I print query set element in Django Template?
I have this code in my template file {{markets|getSpiderItem:spider.id}} Mysql has market_timezone and market_location and it connects to another table with spider_id so I filtered as follow: @register.filter def getSpiderItem(datas, spider_id): return datas.filter(spider=spider_id) I am getting this output: <QuerySet [{'market_timezone': 'Turkey', 'market_location': 'Nigde'}]> I want to print this QuerySet item on Django Template separately. This function has already 2 for loop so I want to print just 1 time. I don't wanna use for loop like this: {% for market in markets|getSpiderItem:spider.id %} I want something like this but I couldn't figure out: For Example: {{markets|getSpiderItem:spider.id|market_timezone}} # I don't know the true way. -
Getting error while executing a django application
After running the server i am getting error as as_view() takes 1 positional argument but 2 were given please have a look on below code and suggest me. enter code here -------------views--------- from django.shortcuts import render from django.http import HttpResponse from django.http import JsonResponse from django.views.generic import View class EmpdataCBV(View): def empdata(self, request,*args,**kwargs): mydic = { 'emp_no': 1, 'emp_name': 'Pavan', 'emp_contactno': 9004981121, 'emp_sal': 50000, 'emp_addr': 'Sakinaka' } return JsonResponse(mydic) --------------url----------- from django.contrib import admin from django.urls import path from testapp import views urlpatterns = [ path('admin/', admin.site.urls), path('jsonresponseCBV/', views.EmpdataCBV.as_view), ] -
I get an error when setting a Django date field
I'm trying to set a date field to a constant date. My "models.py" with the date field: class Foo(models.Model): bar = models.DateField() In my view: import datetime from app.models import Foo foo = Foo(bar=datetime.date('1/1/2021')) The error: Exception Type: TypeError Exception Value: an integer is required (got type str) -
Duplicate UUID if we enter a new input from html?
getting error- i saved one form from html into my database while when i tried saving the next it gave me this error- IntegrityError at customer (1062, "Duplicate entry 'ad138e46-edc0-11va-b065-a41g7252ecb4'' for key 'customer.PRIMARY'") kindly explain my uuid in models.py is - class customer(models.Model): customerid = models.CharField(default=str(uuid.uuid4()), max_length=500, primary_key=True) kindly help -
Problem with request.method in django which is not recognising POST instead it is showing GET as request method
I was doing some practical with django for Post and Get request and some security related stuff related to urls so I made a form in a html file in which I have used method as post and when it is going inside the views template then it is showing my method as GET I am not able to figure it out so please solve my issue thank you! I am attaching screenshot with this Post for your reference. This code is for my form page in which I have used method as post I have attached my 'check function' in which it is always going to the else block and not if block Here I have attached my browser screen which shows that my method is using GET request Code(HTML) :- {% block body %} <form action="check" method="post"> {% csrf_token %} <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="email"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="password" class="form-control" id="exampleInputPassword1" name="password"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> {% endblock body %} Code (Python) :- def check(request): if request.method == 'POST': return HttpResponse("Now url is not having your … -
Django oscar custom benefits does not work
I am building a commercial app using Django and Django-oscar and I am trying to create a custom benefit. I have read Oscar's documentation here and I have also found this relative question in Stack Overflow. I have forked Oscar's offer app and created a benefits.py file where I want to put my custom benefit. I also have change the INSTALLED_APPS setting to include my offer app and not Oscar's default. The problem is that Oscar's doesn't see the benefits.py file no matter what I try. At first I thought that something is wrong with my custom Benefit Class but I tried using Oscar's example and that didn't work either. Then I wrote a piece of code designed to fail (for example a variable which had never been assigned a value to) but it didn't so I am thinking that the file is never accessed. My installed apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.postgres', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', 'django.contrib.flatpages', # wagtail apps 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'wagtail_modeltranslation', 'wagtail_modeltranslation.makemigrations', 'wagtail_modeltranslation.migrate', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'newsletter', 'stentor', 'consent', 'banners', 'banners.dashboard', 'contact_form', 'faq', 'faq.dashboard', 'pages', 'blog', 'oscar', 'oscar.apps.analytics', 'oscar.apps.address', 'oscar.apps.partner', 'oscar.apps.payment', 'oscar.apps.search', 'oscar.apps.voucher', 'oscar.apps.wishlists', … -
Empty M2M data if using prefetch_related django
i'm using Django with DRF, and i stucked on a N+1 problem. So, i trying to use prefetch_related now, and i have some problems with it. prefetch_related returns empty queryset in any situation. I'm using: Django 3.0.7 Djongo (Django DB Backend for MongoDB) DRF (latest version) DRF Test query @api_view(['GET']) @permission_classes([AllowAny]) def test_prefetch(request): users = User.objects.prefetch_related('roles', 'badges').all() users = UserPromptSerializer(users, many=True).data return Response(users, status=200) Models: class UserRoles(models.Model): user = models.ForeignKey(to="User", on_delete=models.DO_NOTHING, default=None) role_type = models.CharField(default="", max_length=256) given_at = models.DateTimeField(default=api.functions.get_local_time) expires_at = models.DateTimeField(default=api.functions.get_local_time, null=True) def __str__(self): return self.role_type class User(AbstractBaseUser, PermissionsMixin): .... roles = models.ManyToManyField(UserRoles, symmetrical=True) Getting roles field through all() function: def get_user_badges(clazz, obj): roles = [] try: roles = list(obj.roles.all()) except UserRoles.DoesNotExist: roles = [] print(obj._prefetched_objects_cache) # returns {"roles": []} print(roles) # returns [] -
Dajngo inline formset and errors for required field
This is my model: class dateEvent(models.Model): venue = models.ForeignKey(Venue, on_delete=models.CASCADE) event = models.ForeignKey('Event', on_delete=models.CASCADE) start_date_time = models.DateTimeField(auto_now=False, auto_now_add=False) My views.py: def event_edit_view(request, id): event = get_object_or_404(Event, id=id) #MyOtherForm instantiated by event DateEventFormSet = inlineformset_factory(Event, dateEvent, extra=5, can_delete=True, fields=('event', 'start_date_time', 'venue', 'link', 'link_description'), widgets={ 'venue': s2forms.Select2Widget(), 'start_date_time': CalendarWidget(), form_date_event = DateEventFormSet(request.POST or None, instance=Event.objects.get(id=id), prefix="dateEvent", queryset=dateEvent.objects.filter(event__id=id)) if request.method == "POST": if MyOtherForm.is_valid() and form_date_event.is_valid(): MyOtherForm.save() form_date_event.save() return redirect('my-events') else: raise forms.ValidationError(form_date_event.errors) #? context = { [other forms...] 'form_date_event': form_date_event, } return render(request, "events/template.html", context) And my template.html: <table id="dateEvent"> <thead> <th>Venue</th> <th>Date and time</th> <th>Link</th> <th>Link description</th> </thead> <tbody id='date_body'> {{ form_date_event.management_form }} {% for formDate in form_date_event.forms %} <tr class="form-row-dateEvent" style='display:table-row;'> <td>{{formDate.venue}}<br> <a href="javascript:void(0)" data-open="addVenue" onclick="sessionStorage.setItem('venueField', 'id_dateEvent-{{forloop.counter0}}-venue'); document.getElementById('addVenueForm').reset(); document.getElementById('errorVenue').innerText = '';">Add a new venue</a></td> <td>{{ formDate.start_date_time}}</td> <td>{{formDate.link}} {{formDate.this_composition}}</td> <td>{{formDate.id}}{{formDate.link_description}}</td> </tr> {% endfor %} </tbody> </table> Now, how can I enforce the user to fill in both venue and the date? As it is now if a user fills in the venue field and leaves the corresponding date field empty, Django redirects the user to an ugly yellow page ValidationError at /private/event-edit/1150/ ['This field is required.'] Request Method: POST Request URL: .../event-edit/1150/ Django Version: 3.1 Exception Type: ValidationError Exception Value: ['This …