Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CORS request external redirect not allowed
I faced a problem during send GET request to a django view from react, and those view redirect to GOOGLE_AUTH_ENDPOINT., and this url hit a callback function. But after request from react, it give this error: Access to fetch at "google auth url" (redirected from 'localhost:8000') from origin 'localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. view class Glogin(APIView): params = { 'client_id': CLIENT_ID, 'response_type': 'code', 'scope': 'openid email profile', 'redirect_uri': CALLBACK_DOMAIN, 'state': state, } if APPS_DOMAIN: params['hd'] = APPS_DOMAIN def get(self,request): request.session['googleauth_csrf'] = state request.session['next'] = request.META.get('HTTP_REFERER', None) print('Here') print(urlencode(self.params)) return HttpResponseRedirect("%s?%s" % (GOOGLE_AUTH_ENDPOINT, urlencode(self.params))) #data = {'link':GOOGLE_AUTH_ENDPOINT, 'params':self.params} #return Response(data) ReactJs static GLogIn() { return fetch("http://127.0.0.1:8000/glogin/", { //method: "POST", method: "GET", headers: { "Content-Type": "application/json", }, //body: JSON.stringify(body), }).then((response) => response.json()); } URL urlpatterns = [ path('', include(router.urls)), path('auth/', obtain_auth_token), path('login/',views.LogInViewSet.as_view()), path('logout/',views.LogOutViewSet.as_view()), path('articles/',views.ArticlesView.as_view()), path('articles/<int:pk>/',views.ArticlesView.as_view()), path('glogin/',views.Glogin.as_view()), path('callback/',views.Callback.as_view(), name='googleauth_callback'), #path('articales/',views.ArticlesViewSet.as_view()) ] settings.py CORS_ORIGIN_WHITELIST = ( 'localhost:3000', #'accounts.google.com', #'accounts.google.com/o/oauth2/v2' ) CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] -
django with automatic curd rest api
Django will generate UI automatically, I like to enhance so that all it also has rest API CURD operation automatic so if a order page builder a CURD(Post, Put, Get, Delete) API automatically created with pagination like following: GET <context-url>/orders --> get all orders POST <context-url>/order {"name": "pizza", "quantity" : 2} PUT <context-url>/order {"id" 1, "name": "pizza", "quantity" : 3} DELETE <context-url>/order/1 GET <context-url>/order/1 -
why django is not adding user to my table (i'm using postgres)?
i'm trying to add users to user table which comes default by django, but unfortunately it is not adding the users to table after submitting the register form . whenever i'm submiting the form it is not adding user to the table , even when i'm trying to print on console it is also not working :( don't know what to do , please help me this is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'telusko', 'USER':'postgres', 'PASSWORD':'root', 'HOST':'localhost' } } this is my register.html <Html> <head> <title> Registration Page </title> </head> <body bgcolor="Lightskyblue"> <br> <form action="/users/register" method="post" > {% csrf_token %} <label> Firstname </label> <input type="text" name="firstname" size="15"/> <br> <br> <label> Lasttname </label> <input type="text" name="laststname" size="15"/> <br> <br> <label> username </label> <input type="text" name="username" size="15"/> <br> <br> <label> Password: </label> <input type="password" name="password2" size="15"/> <br> <br> <label> Conform Password: </label> <input type="password" name="password2" size="15"/> <br> <br> <label> Email: </label> <input type="email" name="email" size="15"/> <br> <br> <input type="submit" value=" Register " size="15"/> <br> </form> this is my views.py for register app from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.models import User,auth from django.contrib import messages # Create your views here. def register(request): if request.method=='POST': … -
Increment Value independent of for loop in Django Template
On my template I have the need to include the next css elements: collapseOne collapseTwo collapseThree collapseFour Currently the structure on the template looks like this: for i in list_i: for j in list_j: collapseOne <- On the first iteration this is generated. collapseTwo <- On the second iteration this is generated. collapseTree <- On the Third iteration this is generated. I generate the css element with the next template tag {{ forloop.counter|num_to_word|title }}. but the forloop.counter only consider the second for (list_j). I know that's the behavior expected. I want that the elements are generated for each time that loop is iterated considering the two fors. As result I want : # First Iteration for i in list_i: for j in list_j: collapseOne <- On the first iteration this is generated. collapseTwo <- On the second iteration this is generated. collapseTree <- On the Third iteration this is generated. # Second Iteration for i in list_i: for j in list_j: collapseFour <- On the first iteration this is generated. collapseFive <- On the second iteration this is generated. collapseSix <- On the Third iteration this is generated. If there is another way to solve this, I'll appreciate. -
Creating new Wagtail Hooks
there is list of available Wagtail Hooks. How do I create my own Hook? To give you a little context: I want to create a hook which hooks in right before or after an Image/media or a document is deleted. Within the hook I want to validate every page, so there won't be any empty fields/blocks. For some reason it is possible to delete an image and the page will still get served, so in my opinion there should be a function/hook to validate every page again if an image is deleted. -
Django UpdateView does not save new data when testing
When I use my application on running server to update existing entry it works but when I run the test it creates entry, post it but does not update the fields title and author so I get an assertion error. When I compare prints from updating on running application and test I can't notice any difference. MODEL: class Book(models.Model): title = models.CharField(max_length=120) author = models.CharField(max_length=100) published = models.IntegerField(validators=[MaxValueValidator(datetime.date.today().year)], help_text="Use the following format: YYYY") isbn_10 = models.CharField(max_length=10, null=True, verbose_name='ISBN_10') isbn_13 = models.CharField(max_length=13, null=True, verbose_name='ISBN_13') cover_uri = models.CharField(max_length=200) language = models.CharField(max_length=56) slug = models.SlugField(max_length=120, unique=True, blank=True) TEST: def test_update_book(self): """Create book object and updates fields with correct data""" book = Book.objects.create(title='Camera Work 1', author='Alfred Stieglitz', published='2008', isbn_10='', isbn_13='9788389192868', cover_uri='image.jpg', language='english') response = self.client.post( reverse('books-update', kwargs={'slug': book.slug}), {'title': 'The Catcher in the Rye', 'author': 'J.D. Salinger', 'published': '2008', 'isbn_10': '', 'isbn_13': '9788389192868', 'cover_uri': 'image.jpg', 'language': 'english'}) self.assertEqual(response.status_code, 200) book.refresh_from_db() print('BOOK', book) self.assertEqual(book.author, 'J.D. Salinger') URL PATTERN: urlpatterns = [ path('update/<str:slug>', BookUpdateView.as_view(), name='books-update'), ] AND VIEW: class BookUpdateView(UpdateView): model = Book fields = '__all__' success_url = '/' template_name = 'books/book_update.html' def post(self, request, *args, **kwargs): print('POST', request.POST, kwargs) return super().post(request, *args, **kwargs) When I use my template to update that entry it works but … -
npm ERR! missing script: dev on linux
This is the complete error that I am getting. $ npm run dev npm ERR! missing script: dev npm ERR! A complete log of this run can be found in: npm ERR! /home/twinkle/.npm/_logs/2021-08-05T15_26_27_095Z-debug.log I am trying to integrate django and react so my django server is working on port 8000 as normal but when I type the command npm run dev or npm run build, I get this error despite including them in "scripts" in package.json. My package.json file "name": "frontend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack --mode development --watch", "build": "webpack --mode production" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.15.0", "@babel/preset-env": "^7.15.0", "@babel/preset-react": "^7.14.5", "babel-loader": "^8.2.2", "react": "^17.0.2", "react-dom": "^17.0.2", "webpack": "^5.48.0", "webpack-cli": "^4.7.2" }, "dependencies": { "@babel/plugin-proposal-class-properties": "^7.14.5", "@material-ui/core": "^4.12.3", "@material-ui/icons": "^4.11.2", "react-router-dom": "^5.2.0" } } Any help regarding this matter would be beneficial. -
django basic search function saying NoReverseMatch
I'm trying to follow this tutorial to make a todoapp and if i search something its saying NoReverseMatch at /todoapp/ with Reverse for 'search' not found. 'search' is not a valid view function or pattern name. here's my views.py def searchtodolist(request): if request.method == 'GET': query = request.GET.get('content', None) if query: results = Todoitem.objects.filter(content__contains=query) return render(request, 'todoapp.html', {"results": results}) return render(request, 'todoapp.html') and here's the urls.py urlpatterns = [ # path('url path, views.py function names) # ex. 127.0.0.1:8000/admin/ path('addTodo/', addTodo), path('admin/', admin.site.urls), path('deleteTodo/<int:todo_id>/', deleteTodo), path('search/', searchtodolist), ] and lastly my todoapp.html <body> <br> <form action="{% url 'search' %}" method="get">{%csrf_token%} <input type="text" name="content" placeholder="Search a todolist" class="form-control"> <input type="submit" name="submit" value="Search"/> </form> <table> <tr> <th colspan="2">List of Todos</th> </tr> {% for result in results %} <tr> <td>{{result.content}}</td> <td><form action="/deleteTodo/{{todo_items.id}}/" style="display: inline; " method="post"> {%csrf_token%} <input class="button button1" type="submit" value="Delete"/> </form></td> </tr> {% endfor %} </tr> </table> </body> -
How to limit Django URL parameter to a list of options?
I have the following URL in my project: from django.urls import include, path urlpatterns = [ path('case/<str:type>/<int:id>/', views.case, name='case'), ... ] It works fine, but the type URL parameter can literally only have 2 values in my database: "internal" and "external". How can I limit this in my URL path itself? Would save me from having to validate it in the view. Thanks for any help. -
Django Formset one form in each row
How to place each form of a formset on a horizontal line, one below the other without using a table? My html is putting everything on one line. Any help much appreciated. Html [<div class="form-group row"> <div class="row"> {{ formset.management_form }} {% for form in formset.forms %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} <div class="col-sm-2"> {{ form.logical_operator|as_crispy_field }} </div> <div class="col-sm-3"> {{ form.event|as_crispy_field }} </div> <div class="col-sm-2"> {{ form.operator|as_crispy_field }} </div> <div class="col-sm-2"> {{ form.event_value|as_crispy_field }} </div> <div class="col-md-1 align-self-center delete-form"> <button onclick="exclude(this)" type="button" title="Excluir" class="btn btn-danger btn-sm"> <i class="feather icon-trash-2"></i> </button> </div> {% endfor %} </div> </div> -
unit test for django models containing "User" as ManyToManyField
So, I have a model 'P' that has the already provided with django model, "User" as the manyToManyField like this, favorite = models.ManyToManyField(User, related_name='pages') I think to unit test, I first create an instance of P then assign what a user to the favorite field? For this , I would have to create an instance of User ,right ? Can you suggest how to go on about what should go in this favorite field to create an object of this kind successfully and how to have P be related to favorite to be able to conduct unit test. Also, what unit test can I do for this ManyToManyField? -
Yelp fusion api returns empty list in django
I need to get the list of nearby restaurants with yelp api , this is my function : def list_of_search_result_by_yelp(categories,lat,lng,radius): api_key = 'mykey' url = 'https://api.yelp.com/v3/businesses/search' headers = {'Authorization': 'Bearer %s' % api_key} parameters = {'categories':categories,'latitude':lat , 'longitude':lng, 'limit':50, 'radius':radius} response = requests.get(url=url, params=parameters , headers=headers ) bussines_data = response.json() return JsonResponse(bussines_data ,safe=False) and this the url i try to send parameteres with GET method : http://127.0.0.1:8000/api/time/yelplocation/?categories=restaurants&lat=29.62184903895586&lng=52.52689019901044&radius=2000 it returns empty list but i can see info of restaurants around this place on google map! -
How set example of value in input box of django form
I would like to do the exact same thing as this has the only difference that the default text disappears when the user enters text name = models.CharField(max_length=16, default="default value") Exemple : Thks -
Storing values in django template
in my random_numbers.py i have this: from django import template from random import randint register = template.Library() @register.simple_tag() def randomNumber(): return randint(1, 250) I basically want to call a random number in the Django template, store it, then compare. I tried using javascript and wrote this: {% load random_numbers %} <script> var random_number = "{% randomNumber %}" console.log(random_number); document.getElementById("random").innerHTML = random_number; </script> But I'm not sure how to collect the js variable in the Django template, can anyone help with this or show me another approach? -
Create view with more models
hi everyone I have a doubt with the use of forms and models. I have to create a code that creates records in multiple tables and I don't know how to do it. my goal is to create a page where I can enter all the data and when I save it creates the various tables filled in with the data provided by the user. I'm a beginner I still have to learn the mechanism well =) forms.py from django import forms from .models import Schede, DatiGruppi, Gruppi class CreaSchedaForm(forms.ModelForm): nome_scheda = forms.CharField( required = True, label ='Nome scheda', widget = forms.TextInput( attrs = { 'class': 'form-control', 'placeholder' : 'nome scheda', 'autocomplete' : 'off' } ) ) data_inizio = forms.DateField( label='Data inizio', widget = forms.DateInput( attrs= { 'type': 'date', 'class': 'form-control', 'placeholder' : 'data inizio' } ) ) data_fine = forms.DateField( label='Data fine', widget = forms.DateInput( attrs= { 'type': 'date', 'class': 'form-control', 'placeholder' : 'data fine' } ) ) class Meta: model = Schede fields = ['nome_scheda','data_inizio','data_fine'] class CreaDtGruppoForm(forms.ModelForm): giorni_settimana = forms.ChoiceField( choices = DatiGruppi.giorni_settimana_scelta ) dati_gruppo = forms.ModelChoiceField( queryset = Gruppi.objects.all(), empty_label = "-", required = True ) class Meta: model = DatiGruppi fields = ['giorni_settimana', 'dati_gruppo'] views.py @login_required … -
form validation redirection problems
Hi i am adding comments on a post using django, im saving the information directly in the database , this operates successfuly, but after submitting the post it suppose to redirect on the same page with the comment but, the form keep on resubmitting help please? views.py class PostDetailView(DetailView): def get(self, request, slug, *args, **kwargs): post = Post.objects.get(slug=slug) form = CommentForm() comments = Comment.objects.filter(post=post).order_by('-date_created') context = { 'post':post, 'form': form, 'comments': comments } return render(request, 'my_news/post_detail.html', context ) def post(self, request, slug, *args, **kwargs): post = Post.objects.get(slug=slug) form = CommentForm(request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.name = request.user new_post.post= post new_post.save() comments = Comment.objects.filter(post=post).order_by('-date_created') context = { 'post':post, 'form': form, 'comments':comments } return render(request, 'my_news/post_detail.html', context ) -
how to use tag url in js admin django "django.jQuery"
I have a js app using ajax, but it's being called in admin, example js django.jQuery.ajax({ type: 'post', // url: "{% url 'emails_checkout' %}", url: '{% url "emails_checkout" %}', data: { 'template': evt.editor.getData() }, but url rendering is real url plus string in http /admin/shop/post/1/change/%7B%%20url%20%22emails_checkout%22%20%%7D HTTP/1.1" 500 12622 how to use the tag {% url '' %} correting -
Could you help me please how i can put an empty file in django rest framework
I am using django rest framework my problem is that i can post image successfully but i want to post an empty image using put method only. Following is my code: My models.py file class Blog(models.Model): id = models.AutoField(primary_key=True) title = models.TextField(max_length = 50) author = models.TextField(max_length = 50) description = models.TextField() date = models.DateField(auto_now=True) time = models.TimeField(default=timezone.now) image = models.FileField(null=True, verbose_name="") user = models.ForeignKey(User, on_delete=models.CASCADE) My serializers.py file class BlogSerializer(serializers.ModelSerializer): title = serializers.CharField(max_length=128, required=True, error_messages={'blank': "Please provide title"} ) author = serializers.CharField(max_length=128, required=True, error_messages={'blank': "Please provide author"}) description = serializers.CharField(max_length=128, required=True, error_messages={'blank': "Please provide description"}) image = serializers.FileField(required=False, error_messages={'invalid': "Please upload Image, Video or Audio file"}) # user_id = serializers.SerializerMethodField('get_user_id') id = serializers.SerializerMethodField('get_id') date = serializers.SerializerMethodField('get_date') time = serializers.SerializerMethodField('get_time') class Meta: model = Blog # fields = ["id","title","author","description","image","date","time","user_id",] fields = ["id","title","author","description","image","date","time",] # Adding additional fields to a modelserializer using SerializerMethodField def get_user_id(self, user_id): user_id = self.context['request'].user.id return user_id def get_id(self, blog): id = blog.id return id def get_date(self, blog): date = blog.date return date def get_time(self, blog): time = blog.time return time My views.py file @api_view(['PUT']) # @csrf_exempt @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def update_blog(request, id): try: blog = Blog.objects.get(id=id) except Blog.DoesNotExist: return Response(status=404) if blog.user_id != request.user.id: return Response({'response':'You do … -
Pycopg2_binary is not installing in windows python 3.9
Am trying to install pycopg2_binary-2.9.1 on windows, currently am using python 3.9 and am getting this error: Error: psycopg2_binary-2.9.1-cp38-cp38-win_amd64.whl is not a supported wheel on this platform Can someone help me? -
How to use TrigramSimilarity in filtered Queryset?
I have three interconnected model: adresses/models.py: class Town(models.Model): name = models.CharField(max_length=200, db_index=True, unique=True) def __str__(self): return '%s' % self.name def get_absolute_url(self): return reverse('home:home_by_town', args=[self.slug]) class Street(models.Model): town = models.ForeignKey(Town, default=id(1), related_name='streets') name = models.CharField(max_length=200, db_index=True) def get_absolute_url(self): return reverse('home:home_by_town', args=[self.slug]) providers/models.py: class Provider(models.Model): location = models.ManyToManyField(Street, db_index=True, symmetrical=False, related_name='providers') name = models.CharField(max_length=200, db_index=True) I have implemented a search for providers that serve the streets: def search_results(request, town_slug=None): regions = Region.objects.filter(is_active=True) town = None towns = Town.objects.filter(is_active=True) streets = Street.objects.all() if town_slug: town = get_object_or_404(Town, slug=town_slug) streets = Street.objects.filter(town=town) streets_list = list(str(p.name) for p in streets) form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] results = Provider.objects.prefetch_related('location').annotate( similarity=TrigramSimilarity('location__name', query), min=Min('tariffs__price'), ).filter(similarity__gt=0.87).distinct().order_by('-similarity') # tariffs__tariff_details__price return render(request, 'home/search_results.html', locals()) else: form = SearchForm() return render(request, 'home/search_results.html', locals()) This all works fine, because we are looking for objects in all street location__name records and I would be happy with the result, but I do not understand how to put my filtered list of streets by city in the TrigramSimilarity method streets = Street.objects.filter (town = town) I want my search result to work in this performance: results = Provider.objects.prefetch_related('location').annotate( similarity=TrigramSimilarity(streets, query), … -
Toggle Django field as read-only/editable in template
I have created a BooleanField for 'dhcp_client' in my models.py file. The functionality I am looking for is that when I click on the DHCP Client check box it allows me to render 'southbound_ip', and 'southbound_subnet' as an editable field or a read-only field while the user is viewing the template 'edit_network.html'. Thus far I have been unsuccessful in my attempts to link a jQuery function to a Django form field. All help is greatly appreciated. models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete = models.CASCADE, null = True) broadcast = models.BooleanField() channel = models.CharField(max_length = 3, choices = channel_ghz_choices, default = '2.4') channel_bonding = models.CharField(max_length = 3) channel_width = models.CharField(max_length = 4, choices = channel_width_choices, default = '20') transmit_power = models.CharField(max_length = 3) enable_wireless = models.BooleanField() wifi = models.CharField(max_length = 128) wifi_password = models.CharField(max_length = 128) paid_vpn = models.BooleanField() vpn_choice = models.CharField(max_length = 20, choices = vpn_choices, default = 'openvpn') vpn_location = models.CharField(max_length = 36) ip_address = models.CharField(max_length = 16) subnet_mask = models.CharField(max_length = 16) northbound_gateway = models.CharField(max_length = 16) dns_server = models.CharField(max_length = 16) dhcp_client = models.BooleanField() southbound_ip = models.CharField(max_length = 16) southbound_subnet = models.CharField(max_length = 16) ip_range = models.CharField(max_length = 16) range_subnet = models.CharField(max_length = 16) range_gateway = … -
Why does my django app fail to deploy to heroku while "building wheel for psycopg2"?
I am trying to deploy my django app and I'm following Corey Schafer's youtube tutorial. I am at around minute 16:00 and I'm running into an error which does not occur in the video. I have googled the specific error but couldn't figure out a solution that worked for me. When I "git push heroku master" in my project's directory, I get the following console output: Enumerating objects: 937, done. Counting objects: 100% (937/937), done. Delta compression using up to 4 threads Compressing objects: 100% (711/711), done. Writing objects: 100% (937/937), 400.51 KiB | 3.08 MiB/s, done. Total 937 (delta 620), reused 271 (delta 173) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> No Python version was specified. Using the buildpack default: python-3.9.6 remote: To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.9.6 remote: -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting Django==3.1.7 remote: Downloading Django-3.1.7-py3-none-any.whl (7.8 MB) remote: Collecting djangorestframework==3.12.4 remote: Downloading djangorestframework-3.12.4-py3-none-any.whl (957 kB) remote: Collecting boto3==1.9.96 remote: … -
Django loses value if choices is dynamic
I have a following problem. Let's say w have a model with column date defined like this: date = models.DateField(verbose_name="Fueling Date", choices=generate_dates()) Definition of generate_dates() functions is like this: def generate_dates(days_in_past=10): """ Generate list of dates from today to *days_in_past* days into past. Generated elements of the list are in format required by django models. Each element is 2-element tuple: (datetime.date, datetime.date) :param days_in_past: Int number of days into past. :return: List of tuples consist of two datetime.date elements. Len of generated list equals *days_in_past* + 1 (because of today's day). """ dates = pd.date_range( start=pd.Timestamp(datetime.datetime.today()).date() - pd.offsets.Day(days_in_past), end=pd.Timestamp(datetime.datetime.today()).date(), freq="D").tolist()[::-1] dates = [(x.date(), x.date()) for x in dates] return dates Function generate_dates returns list of last x dates (so its dynamic, every day it moves one day forward). I see in django admin, that if I have old insertion of this model (old means older than the latest date returned by generate_dates function), for values in column date there is no date displayed. In database it is stored, so there is no data leakage, but django displays for this "----" instead of real date. Once I change generate_dates to return list of dates that contains the old one (I extend … -
Django unique foreign key , on_delete keep the object
I am having some problems with the below code. Is there anyway to let the shitjet object exist after deleting the foreign key reference. from django.db import models from django.contrib.auth import get_user_model class from_thirty_five_to_fourty_one(models.Model): kodi = models.CharField(max_length=100, null=False, blank=False,unique=True) # kodi = models.CharField(max_length=100,null=False,blank=False,unique=True) ngjyra = models.CharField(max_length=100,blank=True,null=True) thirty_five = models.DecimalField(max_digits=200,decimal_places=0) thirty_six = models.DecimalField(max_digits=200,decimal_places=0) thirty_seven = models.DecimalField(max_digits=200,decimal_places=0) thirty_eight = models.DecimalField(max_digits=200,decimal_places=0) thirty_nine = models.DecimalField(max_digits=200,decimal_places=0) forty = models.DecimalField(max_digits=200,decimal_places=0) forty_one = models.DecimalField(max_digits=200,decimal_places=0) def __getitem__(self, key): return getattr(self, key) def __str__(self): return self.kodi class all_products(models.Model): kodi = models.ForeignKey(from_thirty_five_to_fourty_one,to_field='kodi',on_delete=models.CASCADE) choices = [ ("35_41", "35_41"), ('39_45', '39_45'), ] kategoria = models.CharField( max_length=10, choices=choices, blank=False, null=False) def __getitem__(self, key): return getattr(self, key) def __str__(self): return self.kodi def get_kodi(): return get_user_model().objects.get_or_create(kodi='deleted')[0] class shitjet(models.Model): kodi = models.ForeignKey(all_products,to_field='kodi',on_delete=models.SET_NULL ,null=True) numri = models.DecimalField(max_digits=100,decimal_places=0) cmimi = models.DecimalField(max_digits=100,decimal_places=0) created_at = models.DateTimeField(auto_now_add=True) class Meta: models.UniqueConstraint(fields=['kodi'],name='deleted') I have tried different on_delete options but nothing has worked so far. And no adding the unique=True didnt fix it either , keeps giving the same error. Below you can see the error i get. Any help or suggestion would be appreciated. django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: shoe_shop.shitjet.kodi: (fields.E311) 'all_products.kodi' must be unique because it is referenced by a foreign key. HINT: Add unique=True to this field or … -
select with join using django models
I use django-rest-framework. I have models: class CategoryModel(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=64) class ProductModel(models.Model): id = models.IntegerField(primary_key=True) article = models.CharField(max_length=64, null=True) categories = models.ManyToManyField(CategoryModel) How i can select all products contained category = 596 and join category data (name)? Next wished SQL query: SELECT * FROM feed_productmodel JOIN feed_productmodel_categories ON feed_productmodel_categories.productmodel_id = feed_productmodel.id JOIN feed_categorymodel ON feed_categorymodel.id = feed_productmodel_categories.categorymodel_id WHERE feed_categorymodel.id = 596