Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to loop [('A', 1),('B', 2),('C', 4)] this type of data in graph ( django python)?
i want the result as below this code, here (A,1) A is the label and 1 is the data, so that I can present it in my graph, if you have any other solution to present this data [('A', 1),('B', 2),('C', 4)] then please let me know, var myChart = new Chart(ctx, { type: 'bar', data: { labels: ["A","B","C"], datasets: [{ label: '# of Votes', data: [1,2,4], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 2 }] }, options: { scales: { y: { beginAtZero: true } } } }); -
Django filterset and Mutiple values
This is the first time I have used the Django filterset. When a filter field uses multiple inputs for a given purpose, it only gives one output, but can actually be two or more. Here is the code: class CourseFilterSet(django_filters.FilterSet): beneficiary = django_filters.CharFilter(method='get_beneficiary', field_name='beneficiary') type = django_filters.CharFilter(method='get_type', field_name='type') def get_beneficiary(self, queryset, field_name, value, ): if value: return queryset.filter(beneficiary=value) return queryset def get_type(self, queryset, field_name, value, ): print(value) resp = [] if value: data = CourseSubscription.objects.filter(subscription_type=value).values('course') l = len(data) print(data) for i in range(l): print(data[i]['course']) d = data[i]['course'] queryset = Course.objects.filter(id=d) return queryset return queryset class CourseFilterView(viewsets.GenericViewSet): serializer_class = CourseFilterSerializer queryset = Course.objects.all() filterset_class = CourseFilterSet Use two values in the beneficiary field, which give only the first or last output, not the correct output. Give me the right way to overcome this problem..! -
Django: How to stop giving new user Staff status and Superuser status status in default
When I register a new user, I had an login error in admin page. The error is that "Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive". I found out that the new user has Staff status and Superuser status in default. And I can log in admin page in the new user account. So, I found out the login error happens because of giving the new user has Staff status and Superuser status in default. I thought these codes password1 = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Password'})) password2 = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Repeat your password'})) in forms.py are the reason. So I tried register both with them and not with them. But, the result was same. How to make the new user has only active status, not Staff and Superuser status in default? Is the reason for the admin login error right? 2-1) If not, how to solve this? This is views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.views.generic import TemplateView, CreateView from django.contrib.auth.mixins import LoginRequiredMixin from .forms import SignUpForm, ProfileForm from django.urls import reverse_lazy from .models import * from django.contrib import messages from django.contrib.auth import … -
how to display form submit value without storing in db django
I am trying to make a Sign-up page in django for a brand. I want the user register his/her brand on my web app but it will not store the information in db until the admin not accept it, but i don't know how can i do this Model.py class BrandRegister(models.Model): brand_name = models.CharField(max_length=50) owner_name = models.CharField(max_length=30) address = models.CharField(max_length=30) contact_no = models.BigIntegerField() -
NameError Occured when I add element into database
I am getting this error again and again and I don't know why I tried everything but does not seem work, I am trying to add element into mine home page! from django.db import models class ToDo(models.Model): name = models.CharField(max_length = 200, unique = False) def __str__(self): return self.name class Item(models.Model): todolist = models.ForeignKey(ToDo, on_delete = models.CASCADE) text = models.CharField(max_length = 300) complete = models.NullBooleanField() def __str__(self): return self.text my text is defined in that code but I don't understand why I am getting this error and I tried everything In [35]: lt.item_set.create(text = "moon", complete = False) Out[35]: --------------------------------------------------------------------------- NameError Traceback (most recent call last) ~\anaconda3\lib\site-packages\IPython\core\formatters.py in __call__(self, obj) 700 type_pprinters=self.type_printers, 701 deferred_pprinters=self.deferred_printers) --> 702 printer.pretty(obj) 703 printer.flush() 704 return stream.getvalue() ~\anaconda3\lib\site-packages\IPython\lib\pretty.py in pretty(self, obj) 392 if cls is not object \ 393 and callable(cls.__dict__.get('__repr__')): --> 394 return _repr_pprint(obj, self, cycle) 395 396 return _default_pprint(obj, self, cycle) ~\anaconda3\lib\site-packages\IPython\lib\pretty.py in _repr_pprint(obj, p, cycle) 698 """A pprint that just redirects to the normal repr function.""" 699 # Find newlines and replace them with p.break_() --> 700 output = repr(obj) 701 lines = output.splitlines() 702 with p.group(): ~\anaconda3\lib\site-packages\django\db\models\base.py in __repr__(self) 519 520 def __repr__(self): --> 521 return '<%s: %s>' % (self.__class__.__name__, self) … -
check if many to many field exists for using a post save method
I have a post save function as shown below def blog_notify_receiver(sender, instance, created, *args, **kwargs): if created: print(sender) print(instance) exists = instance.pricing_tier.all() print(exists) try: BlogNotification.objects.create() except: pass post_save.connect(blog_notify_receiver, sender=Blog) my blog model is as follows class Blog(models.Model): title = models.CharField(max_length=80, blank=True, null=True) pricing_tier = models.ManyToManyField(Pricing, related_name='paid_blogs', verbose_name='Visibility', blank=True) here I am getting exists as an empty queryset, how I can check it properly? if a particular plan exists I can create a notification for that plan group as follows if created and instance.pricing_tier.filter(slug='free-trial').exists(): but it doesn't work now as its output is None. Any help is much appreciated. -
Setting the max length of a string in a list - Django
I am creating a registration page for my website. I am following this tutorial. I have a bootstrap/html template with a form (Down Bellow), and I want to replace the html form with a UserCreationForm that I have already made in my forms.py file. The tutorial says to replace the html input fields with my user creation fields, but then bootstrap cannot style them. Can someone please help me so the default form fields have my python usercreationform? My code is down bellow. Register.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:400,700"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="{% static "registerstyles.css" %}"> <title>GoodDeed - Register</title> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> </head> <body> <div class="signup-form"> <form action="" method="post"> {% csrf_token %} <h2>Sign Up</h2> <p>Please fill in this form to create an account!</p> <hr> <div class="form-group"> <div class="row"> <div class="col"> <input type="text" class="form-control" name="first_name" placeholder="First Name" required="required" ></div> <div class="col"><input type="text" class="form-control" name="last_name" placeholder="Last Name" required="required"></div> </div> </div> <div class="form-group"> <input type="email" class="form-control" name="email" placeholder="Email" required="required"> </div> <div class="form-group"> <input type="password" class="form-control" name="password" placeholder="Password" required="required"> </div> <div class="form-group"> <input type="password" class="form-control" name="confirm_password" placeholder="Confirm Password" required="required"> </div> <div class="form-group"> … -
How to get updating values from python to template without refresh? Django
I have a real time database(google firebase), and its data is constantly changing, I want to display this data on my template without reloading the template itself. I couldn't find any related information, also I am sort of a beginner especially to AJAX so if you can provide an example or a documentation that would be really helpful. Any help is appreciated -
Delete answer deleting everything instead of following filter
const DeleteAnswer = () => { let input = formInput.getFieldsValue() dispatch(deleteGuidedAnswer(input)) hideModal() formInput.resetFields() } <MinusCircleOutlined className='dynamic-delete-button' style={{ paddingLeft: '10px', position: 'absolute', top: '0%', right: '-5%', }} onClick={() => DeleteQuestion()} /> @require_http_methods(["POST"]) @login_required def delete_guided_answer(request): req = json.loads(request.body) guided_answers= req["guided_answer"] for guided_answer in guided_answers: models.ModelAnswer.objects.filter(answer_id=guided_answer["answer_id"]).delete() return success({"res": True}) What my code does above is delete the answer based off answer id, however whenever i try to delete a certain item everything gets deleted instead, why is it that delete is not being filtered -
Cannot assign "'2'": "PatientProfile.user" must be a "User" instance. django
All data is saving fine but issues are while saving a ForignKey. 1 is User and another one is Address these both are FORIEGNKEY. -
How to read the content on an exception raised by a third party app in django?
Need help in a situation. I have made a request to a third party app and it is raising an exception so i want to read message of this exception exceptions.AlreadyExistError: Reason = Entered bank Account is already registered:: response = {"status": "ERROR", "subCode": "409", "message": "Entered bank Account is already registered"} request_id = fdd54b5c25c73cc3d437188278b0be26 try: add_beneficiary = Beneficiary.add( bankAccount=order.payee_bank_account_number) except Exception as e: print(e) #Reason = Entered bank Account is already registered:: response = {"status": "ERROR", "subCode": "409", "message": "Entered bank Account is already registered"} request_id = c57d9df21bd413d9a46eaec82a590e9b How do I read the message of the exception -
How to add multiple Model in one form in django
Hi I'm creating a Django project where i want multiple model in one form class. here is my Model.py class Robot(models.Model): robot = models.CharField(max_length=100) short_Description = models.CharField(max_length=200) status = models.CharField(max_length=20) parameter = models.CharField(max_length=200) jenkins_job = models.CharField(max_length=100, default='JenkinsJobName') jenkins_token = models.CharField(max_length=100, default='JenkinsToken') jenkins_build = models.CharField(max_length=10, default=0) jenkins_build_status = models.CharField(max_length=20, default="Never Run") class Lookup(models.Model): Name = models.CharField(max_length=100, unique=True) Value = models.CharField(max_length=50) Type = models.CharField(max_length=30) Description = models.CharField(max_length=200) Here's my form.py class RobotReg(forms.ModelForm): class Meta: model = Robot fields = ['robot', 'short_Description', 'status', 'parameter','jenkins_job','jenkins_token'] widgets = { 'robot':forms.TextInput(attrs={'class':'form-control','id':'robot'}), 'short_Description':forms.TextInput(attrs={'class':'form-control', 'id':'SD'}), 'status':forms.TextInput(attrs={'class':'form-control'}), 'parameter':forms.TextInput(attrs={'class':'form-control', 'id':'parameter'}), 'jenkins_job':forms.TextInput(attrs={'class':'form-control', 'id':'JJ'}), 'jenkins_token':forms.TextInput(attrs={'class':'form-control', 'id':'JT'}), } class LookupReg(forms.ModelForm): class Meta: model = Lookup fields = ['Name', 'Value', 'Type', 'Description'] widgets = { 'Name':forms.TextInput(attrs={'class':'form-control','id':'Name'}), 'Value':forms.TextInput(attrs={'class':'form-control', 'id':'Value'}), 'Type':forms.TextInput(attrs={'class':'form-control', 'id':'Type'}), 'Description':forms.TextInput(attrs={'class':'form-control', 'id':'Description'}), } In form.py i dont want to create two different class for my models. I want two models fields in my Robotreg Class. -
Django Authentication: Super User Can't Login
I have a django app and now need to add users. I am able to create superusers and to login with them through py manage.py runserver but can't login through the docker run webpage. I've read a few things that say the cause of this might be wsgi but I can't figure out how or why this happens. Here are the relevant bits of code Dockerfile FROM python:3.6 COPY manage.py gunicorn-cfg.py requirements.txt .env ./ RUN pip install -r requirements.txt COPY app app COPY authentication authentication COPY core core RUN python manage.py makemigrations RUN python manage.py migrate EXPOSE 5005 CMD ["gunicorn", "--config", "gunicorn-cfg.py", "core.wsgi"] settings.py import os from decouple import config from unipath import Path BASE_DIR = Path(__file__).parent CORE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = config('DEBUG', default=True, cast=bool) # load production server from .env ALLOWED_HOSTS = ['localhost', '127.0.0.1', config('SERVER', default='127.0.0.1')] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', # Enable the inner app 'authentication' ] ROOT_URLCONF = 'core.urls' TEMPLATE_DIR = os.path.join(CORE_DIR, "core/templates") # ROOT dir for templates TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'core.wsgi.application' DATABASES = { 'database': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '../database.sqlite3', … -
DjangoCMS views.py class automatic generated
I have a question I have created a form with an automatically generated class using javascript and now I have to add a views.py in DjangoCMS or Python with that automatically generated class so that it sends the form with extra options that are in the screenshot. I hope you guys can help me and that I have been clear. This is the code from views.py, Sorry its Dutch: def lxbox(request): if request.method == 'POST': name = request.POST.get('name') surname = request.POST.get('surname') company = request.POST.get('company') reference = request.POST.get('reference') email = request.POST.get('email') remarks = request.POST.get('remarks') typeFixture = request.POST.get('typeFixture') numberFixture = request.POST.get('numberFixture') groundFault = request.POST.get('groundFault') numberInput = request.POST.get('numberInput') numberControl = request.POST.get('numberControl') numberGroup = request.POST.get('numberGroup') numberLight = request.POST.get('numberLight') groundFaultextra = request.POST.get('groundFaultextra') numberInputextra = request.POST.get('numberInputextra') numberControlextra = request.POST.get('numberControlextra') numberGroupextra = request.POST.get('numberGroupextra') numberLightextra = request.POST.get('numberLightextra') writeroot = request.POST.get('writeroot') data = { 'name': name, 'surname': surname, 'company': company, 'reference': reference, 'email': email, 'remarks': remarks, 'typeFixture': typeFixture, 'numberFixture': numberFixture, 'groundFault': groundFault, 'numberInput': numberInput, 'numberControl': numberControl, 'numberGroup': numberGroup, 'numberLight': numberLight, 'groundFaultextra': groundFaultextra, 'numberInputextra': numberInputextra, 'numberControlextra': numberControlextra, 'numberGroupextra': numberGroupextra, 'numberLightextra': numberLightextra, 'writeroot': writeroot, } writeroot = ''' Naam: {} Achternaam: {} Bedrijf: {} Referentienummer: {} Email: {} Opmerkingen: {} Type Armatuur: {} Aantal Armaturen per groep: {} Aardlek: {} Extra … -
i want to save my host to database and also create a shortlink using hashlib django
My problem i am facing is that first i cannot save my urls to database, second i cannot generate shorl links for my urls(i,e. my local host) and third, i want to display both on the templates. I used hashlib md5 to short the url, but i am not able to do that. URLS.py path('SaveURL/', views.SaveURL, name='SaveURL'), path('create_short_url/', views.create_short_url, name='create_short_url'), VIEWS.py def SaveURL(request): full_url = request.get_host() obj = URL.create_short_url('full_url') url = URL(full_url=full_url, obj=obj) url.save() return render(request, 'link.html', {"full_url": obj.full_url, "short_url": request.get_host()+'/'+obj.short_url}) #generating short link def create_short_url(self, request, full_url): temp_url = md5(full_url.encode()).hexdigest()[:8] try: obj = self.objects.create(full_url=full_url, short_url=temp_url) except: obj = self.objects.create(full_url=full_url) return render(request, 'link.html', {"obj": obj}) MODELS.py #Model to save url of the pages class URL(models.Model): full_url = models.CharField(unique=True, max_length=400) short_url = models.CharField(unique=True, max_length=20) This is where I want to display my localhost URL and generated shortlink. <!-- Copy to Clipboard --> <center><label for="text_copy" class="text-primary">Link to be shared</label> <input type="text" class="form-control border-0 d-block bg-dark text-white" id="text_copy" value="http://127.0.0.1:8000/product/product_view/{{ results.uid }}"/> </center><center><div class="container"> <button onclick="copyToClipboard('#text_copy')" type="button" class="col mr-3 btn btn-light btn-rounded" data-mdb-ripple-color="dark">Copy</button> </center> </div> <!-- Copy to Clipboard --> <center><label for="text_copy" class="text-primary"> Short Link to be shared</label> <input type="text" class="form-control border-0 d-block bg-dark text-white" id="text_copy1" value="http://127.0.0.1:8000/product/product_view/{{ results.user_id }}"/> </center><center><div class="container"> <button onclick="copyToClipboard('#text_copy1')" type="button" … -
Django serializers usage with data transfer objects
I am from Java background and I am getting a bit confused with the serialization in Django Let's say I have this requirement I need to fetch the results of stocks from an exchange. So the request will be like { "exchange" : ["exchange1", "exchange2"], "stock_name" : ["stock1", "stock2"] } In Spring I would write a RequestDto like this, class StockResultRequestDto{ List<String> exchange; List<String> stockName; } and In the controller method getMethod(@RequestBody StockResultRequestDto request) and Jackson library behind the scenes would take care of the serialization. In Django Rest as well, I was thinking to have it similar @dataclass class StockResultRequestDto: exchange: List[str] stock_name: List[str] But since we don't have a builtin serializer in python, I understand, I will need to write serializer as well. class StockMarketRequestSerializer(serializers.Serializer): exchange = serializers.CharField(max_length=100, many=True) stock_name = serializers.CharField(max_length=200, many=True) @api_view(['POST']) def get_stock_result(request): serializer = StockMarketRequestSerializer(data=request.data, many=True) serializer.is_valid(raiseException=False) stockMarketDto = StockResultRequestDto(**serializer.validated_data) <--- Is it advised to create a dto when I can pass around serializer.validated_data? Coming to output considering I don't have a database involved, I fetch the results from a different server class StockResult: stockName: str netProfit: float revenue: float I do business logic and finally, I will have something like stock_result_response = [list … -
How to add UserCreationForm to HTML/Bootstrap template in Django
I am creating a registration page for my website. I am following this tutorial. I have a bootstrap/html template with a form (Down Bellow), and I want to replace the html form with a UserCreationForm that I have already made in my forms.py file. The tutorial says to replace the html input fields with my user creation fields, but then bootstrap cannot style them. Can someone please help me so the default form fields have my python usercreationform? My code is down bellow. Register.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:400,700"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="{% static "registerstyles.css" %}"> <title>GoodDeed - Register</title> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> </head> <body> <div class="signup-form"> <form action="" method="post"> {% csrf_token %} <h2>Sign Up</h2> <p>Please fill in this form to create an account!</p> <hr> <div class="form-group"> <div class="row"> <div class="col"> <input type="text" class="form-control" name="first_name" placeholder="First Name" required="required" ></div> <div class="col"><input type="text" class="form-control" name="last_name" placeholder="Last Name" required="required"></div> </div> </div> <div class="form-group"> <input type="email" class="form-control" name="email" placeholder="Email" required="required"> </div> <div class="form-group"> <input type="password" class="form-control" name="password" placeholder="Password" required="required"> </div> <div class="form-group"> <input type="password" class="form-control" name="confirm_password" placeholder="Confirm Password" required="required"> </div> <div class="form-group"> … -
DJANGO Check if a user is in a group before posting ! If a user is either in that group or not , messages always tells me that I'm not
So I was taking an Udemy Course, and I tried to verify if a user has joined a group, only in that moment he can post something. If not, the user is going to be redirected to a page, with a Django message. But either the user is a member or not, I receive the message that he is not. What do I have to change? I'm desperate. models.py ## MODELS.PY ## from django.db import models from django.urls import reverse from django.conf import settings from groups.models import Group from misaka import html from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): user = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group,related_name='posts',null=True,blank=True,on_delete=models.CASCADE) def __str__(self): return self.message def save(self,*args,**kwargs): self.message_html = misaka.html(self.message) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('posts:single',kwargs={'username':self.user.username, 'pk':self.pk}) class Meta(): ordering = ['-created_at'] unique_together = ['user','message'] views.py ## VIEWS.PY ## #POSTS VIEWS.PY from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from django.views import generic from django.http import Http404 from django.contrib import messages from groups.models import Group,GroupMember from braces.views import SelectRelatedMixin from django.http import HttpResponseRedirect from django.urls import reverse from posts.models import Post from . import models from . import forms from django.contrib.auth import … -
How to fix Django "ModuleNotFoundError: No module named 'application'" on AWS?
I am trying to redeploy a Django web application on AWS. My elastic beanstalk environment has been red a couple of times. When I ran eb logs on the cli, I am getting a "ModuleNotFoundError: No module named 'application' error". I think this has got to do with my wsgi configuration. I have deployed this web app on AWS before. I messed up when I tried deploying a new version then decided to just start over. Here is my wsgi.py configuration: ```import os from django.core.wsgi import get_wsgi_application from django.contrib.staticfiles.handlers import StaticFilesHandler os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = StaticFilesHandler(get_wsgi_application())``` When I deploy the app, it's giving me a 502: Bad gateway error. Let me know if you would like more info on the issue. Any pointers would be greatly appreciated. -
How to access constant with class pointer in python - AUTH_USER_MODEL = 'django_restframework_2fa.User'
I have defined AUTH_USER_MODEL = 'django_restframework_2fa.User' in the settings.py file of Django application. Now, I want to access that User() class using AUTH_USER_MODEL constant. How can this be done? I tried to access it like this settings.AUTH_USER_MODEL(**data) which should be equivalent to User(**data) -
Django lookups - filter charfield that contains a number
I'd like to perform a query on a model with a charfield and I want to filter only the records that have a number contained in that charfield. My model: class LocationCache(models.Model): location_name = CharField(primary_key=True, max_length=100, blank=True) longitude = FloatField() latitude = FloatField() def __str__(self): return self.location_name Are there any lookups like this? LocationCache.objects.filter(location_name__is_number=True) -
Column does not exist foreign key table in Django
In django, I created a new model in my application (The app name is quiz) like this: class Score(models.Model): person1 = models.ForeignKey(Personality, on_delete=models.CASCADE, related_name="person1", blank=True, null=True, default=0) person2 = models.ForeignKey(Personality, on_delete=models.CASCADE, related_name="person2", blank=True, null=True, default=0) score = models.DecimalField(default=0, max_digits=5, decimal_places=2) I then proceeded to do makemigrations and migrate, which was successful. I also registered this model with the admin. But whenever I try to open it's page on the admin site, I get this message: P.S. I'm using PostgreSQL as my backend -
Getting Illegal instruction: illegal hardware instruction python manage.py runserver on Apple M1 chip
I am trying to bring up a Django project with the below dep: python 3.6 and django>2.0 All dependencies have been successfully installed but when I try to bring the server up it gives me the below error and exit after that: [1] 3298 illegal hardware instruction python manage.py runserver I am using MacOS Big Sur 11.2.2 with Apple M1 chip. -
How can I prefetch nested tables?
I'm working on an app with a DRF API. Development has been going on for some months, but only now are we running into performance issues when populating the database with actual data. I have done some profiling and found out that many endpoints query the database hundreds of times to fetch the necessary data. This is something that can be solved with select_related and prefetch_related, that much I know, but I'm having a hard time picturing it. Models class LegalFile(models.Model): code = models.CharField(max_length=75) description = models.CharField(max_length=255) contactrole = models.ManyToManyField(LegalFileContactRole, blank=True, related_name='contactroles') class LegalFileContactRole(models.Model): contact = models.ForeignKey(Contact, on_delete=models.DO_NOTHING, blank=True, related_name='legal_file_contact') subtype = models.ForeignKey(ContactSubType, on_delete=models.DO_NOTHING, related_name='legal_file_contact_role', null=True) class Contact(models.Model): name = models.CharField(max_length=150) surname_1 = models.CharField(max_length=50,blank=True, null=True) surname_2 = models.CharField(max_length=50,blank=True, null=True) class ContactSubType(models.Model): pass Say I want to list all the LegalFiles in the database, and fetch the names and both surnames of the contacts associated to each LegalFile through LegalFileContactRole. Is there a DRYer way than using lowercase notation to prefetch like LegalFile.prefetch_related('contactrole__contact__name', 'contactrole__contact__surname_1', 'contactrole__contact__surname_2')? This kind of nested relationship is a recurring thing in the app. -
I have a problem in my Django project when I try to push to heroku a problem occurs
django.db.utils.IntegrityError: column "pinned" of relation "blog_post" contains null values I migrated and did everything in localhost and Heroku server but I don't know how to solve this error.