Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send a POST to Django Rest passing only ID on relationships, instead of whole dictionary after using Serializers for related fields?
I'm doing a little tutorial on Django Rest Framework, as I never used it before even though I have some experience with Django using templates. So I'm diverging a little from the tutorial class as I think I learn better this way, so I got to a point where in a Movie Rating simple application, when you do a GET from the Ratings serializer, you get just the FK IDs and the "stars" rating I added: [ { "id": 1, "user": 1, "movie": 1, "stars": 5 }, { "id": 2, "user": 1, "movie": 4, "stars": 4 } ] As I learned in a previous lesson from the said course, I know you can specify a serializer for each field, so instead on a GET request you get the dictionary with the whole data. class RatingSerializer(serializers.ModelSerializer): movie = MovieSerializer(many=False) user = UserSerializer(many=False) class Meta: model = Rating fields = ('id', 'user', 'movie', 'stars') That way the return from the GET to the Ratings route shows relational data instead of only the IDs: [ { "id": 1, "user": { "id": 1, "username": "admin", "email": "admin@admin.com" }, "movie": { "id": 1, "title": "Matrix 2", "synopsis": "Neo is back." }, "stars": 5 }, { … -
Trouble understanding the task of Django and Django rest framework?
Here I have trouble understanding the above question. I have a task given as above. It says I have to make an api (get api) in Django which contains the above four fields id, name, latitude and longitude. It is simple to make a get api, if I can save the data to the database from Django-admin. But here, I suppose it says to use google map apis. Ok, somehow I can get the data from the google apis ( I am not so sure which python package is best for this), but how to save that data to the db, and later show it while calling get api?? -
Django rest framework valid related field not found by serializer but present in request
I have 2 related models and I am trying to perform an ajax 'multipart/form' post request. But it seems like data regarding the related model is not identified by the serializer for some reason. I have tried editing the 'create' method of the viewset, to understand why the data is not passed, but to no avail. I think the issue is related to json serialization, but i do not know how to fix it Here are some things i tried: models.py class Dream(models.Model): # Some fields ... class Milestone(models.Model): title = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) description = models.TextField(max_length=500) dream = models.ForeignKey( Dream, on_delete=models.CASCADE, related_name='milestones') serializers.py class DreamSerializer(TaggitSerializer, serializers.ModelSerializer): milestones = MilestoneSerializer(many=True, read_only=False) class Meta: model = Dream fields = (..., 'milestones') class MilestoneSerializer(serializers.ModelSerializer): class Meta: model = Milestone fields = ('id', 'title', 'user', 'date', 'description', 'dream') read_only_fields = ('user', 'dream', 'date') views.py class DreamViewSet(viewsets.ModelViewSet): queryset = Dream.objects.prefetch_related('user').all() serializer_class = DreamSerializer permission_classes = [permissions.IsAuthenticated] # Tried to manually override the create function to fix the error def create(self, request, *args, **kwargs): print(request.data) # <QueryDict: {'title': ['test'], 'image':[<InMemoryUploadedFile: somePhoto.jpg (image/jpeg)>], ... , 'milestones': ['[{"title":"test1","description":"test1"}]']}> # seems like it is evaluating to string literal '[{"title":"test1","description":"test1"}]' print(request.data['milestones']) # [{"title":"test1","description":"test1"}] print(type(request.data['milestones'])) … -
How to navigate to a new link from the search box results in Django template with ajax?
I am creating a chat application in Django. I am using ajax to get search results to show up after each character is typed in the input box. It works fine. But now I am trying to add a link to the search results(which are just a name) so that if I click on one of the search results it goes to that link and views.chat_from_search is called where I handle all the logic of creating a chat and the rendering the page. I tried to add an event listener and then redirect to the new link (the code I tried to add the link is inside ** ** tags) but it results in this error Reverse for 'chatSearch' with arguments '('',)' not found. 1 pattern(s) tried: ['chat/search/(?P<chat_user_name>[^/]+)/\Z'] My code for the ajax search and where I create the div that holds the search results (and my failed attempt to add a link) is inside sendSearchData (which is below). the ajax returns an array of objects which only has a username attribute. This is the structure of the objects (I am creating this and appending it to a list which I return) indiv_user = { 'name': user.username, } const sendSearchData … -
Django get_or_create | update_or_create
I'm trying to implement get_or_create | update_or_create but I'm receiving the following error message: TypeError: Field 'id' expected a number but got <SimpleLazyObject: <User: admin>>. MORE DETAILS: File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/models/query.py", line 657, in get_or_create return self.get(**kwargs), False File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/models/query.py", line 496, in get raise self.model.DoesNotExist( wallet.models.SelectedWallet.DoesNotExist: SelectedWallet matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/models/fields/init.py", line 1988, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'SimpleLazyObject' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Volumes/HDD/Allan/django/venv/project_onefinance/onefinance/views.py", line 43, in select_wallet obj, created = SelectedWallet.objects.update_or_create( File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) class SelectedWallet(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) wallet = models.name = models.ForeignKey(Wallet, default=1, on_delete=models.CASCADE) created = models.DateField(verbose_name='Created', auto_now_add=True) modified = models.DateField(verbose_name='Modified', auto_now=True) created_by = models.ForeignKey('auth.User', related_name='selected_wallet_created_by', blank=True, null=True, default=None, on_delete=models.SET_DEFAULT) modified_by = models.ForeignKey('auth.User', related_name='selected_wallet_modified_by', blank=True, null=True, default=None, on_delete=models.SET_DEFAULT) class Meta: db_table = 'myapp_selected_wallet' ordering = ['wallet__name'] verbose_name = 'Selected_Wallet' verbose_name_plural = 'Selected_Wallets' def __str__(self): """String for representing … -
CORS is not activating my POST request. CSRF Cookie 'not set'
I am attempting to replicate this project using Vue instead of React. My goal is to authenticate a Django user from my Vue frontend. I am using the django-cors-headers package with the following settings. INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ ..., 'django.contrib.messages.middleware.MessageMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:9000" ] CSRF_TRUSTED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:9000" ] CORS_ALLOW_HEADERS = [ ... 'x-csrftoken', 'csrfmiddlewaretoken', 'credentials' ] CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False Right now, the initial request to obtain the CSRF cookie is working and seems to be returning a proper CSRF token which I can include in my request: const login = async () => { const cookie = getCookie("csrftoken"); console.log(cookie) const data = new FormData(); data.append("username", username); data.append("password", password); const headers = new Headers() headers.append('X-CSRFToken', cookie) const response = await fetch("http://localhost:8000/auth/", { method: "POST", // cookies: { // "X-CSRFToken": cookie ? cookie : "" // }, headers: headers, credentials: "same-origin", body: data, }); return response.ok; }; However, things still keep getting tripped up in the CORS process, because the request never makes it to the view: [21/May/2022 14:26:18] "OPTIONS /auth/ HTTP/1.1" 200 0 Forbidden (CSRF cookie not set.): /auth/ [21/May/2022 14:26:18] "POST … -
"detail": "Method \"GET\" not allowed." and JSON parse error Expecting property name enclosed in double quote
So I made a POST method but everytime I try to send a request I get this error. This is my method @api_view(['POST']) def CreateCustomService(request): x=CustomService.objects.create( Title=request.data['Title'], Description=request.data['Description'], PreConditions=request.data['PreConditions'], Duration=request.data['Duration'], HomeSampling=request.data['HomeSampling'], HomeSamplingPrice=request.data['HomeSamplingPrice'], Communication=request.data['Communication'], CommunicationPrice=request.data['CommunicationPrice'], ServicePrice=request.data['ServicePrice'], ) jsonobject=CustomServiceSerializer(x) return Response("DATA STORED") And this is the request that I am trying to send POST http://127.0.0.1:8000/Inventory/CreateCustomService HTTP/1.1 Content-Type: application/json { "Title": "TbGold", "Description": "Done to detect TB", "PreConditions": ["Drink water"], "Duration":"30 mins", "HomeSampling": "True", "HomeSamplingPrice": 200, "Communication": "True", "CommunicationPrice": 100, "ServicePrice": 18000, } This is my Model class CustomService(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Title = models.CharField(max_length=100) Description = models.TextField() PreConditions = ArrayField(models.CharField( max_length=100), blank=True, null=True) Duration = models.DurationField() HomeSampling = models.BooleanField(default=False) HomeSamplingPrice = models.IntegerField(default=0) Communication = models.BooleanField(default=False) CommunicationPrice = models.IntegerField(default=0) ServicePrice = models.IntegerField(default=0) def __str__(self): return self.Title Error when I open url Error when I send request through test.http file -
Django - uploading data to a model with pandas ".to_sql()" causes problems for the foreign key field
I identified a problem that ".select_related()" doesn't work if the table with a foreign key was uploaded using pandas. Uploading data the alternative way using a loop is not an option because the table is too big. Here's an example: Set up #Models class Magazine(models.Model): name = models.CharField(max_length=20, unique=True, primary_key=True) founded = models.CharField(max_length=20, unique=True, primary_key=True) def __str__(self): return self.name class Issue(models.Model): name = models.ForeignKey(Magazine, on_delete=models.CASCADE, db_column="name") week = models.CharField(max_length=10, unique=False) def __str__(self): return self.week #Admin from mainsite.models import Magazine, Issue admin.site.register(Magazine) admin.site.register(Issue) #Migrated python ../manage.py makemigrations python ../manage.py migrate Fill first table import os import sys import pandas as pd import django sys.path.append(os.path.dirname(os.getcwd())) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') #configures the settings for the project. Need to do this before manipulating models django.setup() from mainsite.models import Magazine, Issue magazineNames = ['journal science', 'naughty mag', 'funny cartoons', 'comic fans', 'lawncare', 'NEVERISSUED'] magazineFounded = ['1901', '1995', '2005', '2011', '1993', '1900'] Magazine.objects.bulk_create([Magazine(name=i, founded=j) for i,j in zip(magazineNames, magazineFounded)]) Fill second table 1.) THIS WORKS for Issue.objects.select_related("name"), but uses a loop. It works because I can specify the names being a Magazine() instance. issueNames = ['journal science', 'journal science', 'naughty mag', 'funny cartoons', 'comic fans', 'lawncare', 'lawncare'] issueWeeks = ['1', '2', '3', '4', '5', '6', '7'] Issue.objects.bulk_create([Issue(name=Magazine(name=i), week=j) … -
Invalid signature Django rest framework simple_jwt token
Hiii i am faced with a problem of invalid token. I am testing simple_jwt with django rest framework When i log on the endpoint of TokenObtainPairView i receive refresh and access token but when i verify that token on jwt.io, I have invalid signature. It is obvious that my simple_jwt deliver me the wrong token. I don't know where the problem come from. After research I am thinking may be I need to Change 'SIGNING_KEY': SECRET_KEY,but I don't know how. I mentioned that I am using the pure TokenObtainPairView whithout any customization. If someone can help me. I am new here -
Max occurrences of a foreign key inside query
I'm trying to get an item with the most occurrences of a foreign key (votes), inside of a queryset (Questions, Choices). I.E. I need to get the most popular vote to set the 'winner' attribute in the JsonResponse. Any help on how I can figure this out? Here is my view. allchoices = [{ 'id':i.id, 'question':i.question.id, 'choice_text':i.choice_text, 'votes':i.voter_set.all().count() } for i in poll_choices] return JsonResponse({ "votes":choice.voter_set.all().count(), 'winner':True, 'success':True, 'allchoices':allchoices },safe=False,) These are my models: class Voter(models.Model): # Authentication of anonymous users choice = models.ForeignKey('PollChoice', on_delete=models.CASCADE) question = models.ForeignKey('PollQuestion', on_delete=models.CASCADE) class PollChoice(models.Model): question = models.ForeignKey('PollQuestion', on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) def __str__(self): return self.choice_text class PollQuestion(models.Model): question = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) creator = models.ForeignKey('poll_creator',/\ on_delete=models.CASCADE, null=False, blank=False) uuid = ShortUUIDField(length=8, max_length=12) def poll_choices(self): return self.pollchoice_set.all().annotate(voters=/\ models.Count(models.F('voter'))).order_by('-voters') def choices(self): return self.pollchoice_set.all() def __str__(self): return f'{self.question}' -
Django - how to see ALL column results of a join using .select_related()?
I am having difficulty seeing the foreign table's field from a resulting join using select_related(). Any idea what my issue is here? Define models class Magazine(models.Model): name = models.CharField(max_length=20, unique=True, primary_key=True) founded = models.CharField(max_length=20, unique=True, primary_key=True) def __str__(self): return self.name class Issue(models.Model): name = models.ForeignKey(Magazine, on_delete=models.CASCADE, db_column="name") week = models.CharField(max_length=10, unique=False) def __str__(self): return self.week Register from mainsite.models import Magazine, Issue admin.site.register(Magazine) admin.site.register(Issue) Migrate python ../manage.py makemigrations python ../manage.py migrate Loading data import os import sys import django sys.path.append(os.path.dirname(os.getcwd())) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mags.settings') #configures the settings for the project. Need to do this before manipulating models django.setup() from mainsite.models import Magazine, Issue magazineNames = ['journal science', 'naughty mag', 'funny cartoons', 'comic fans', 'lawncare', 'NEVERISSUED'] magazineFounded = ['1901', '1995', '2005', '2011', '1993', '1900'] Magazine.objects.bulk_create([Magazine(name=i, founded=j) for i,j in zip(magazineNames, magazineFounded)]) issueNames = ['journal science', 'journal science', 'naughty mag', 'funny cartoons', 'comic fans', 'lawncare', 'lawncare'] issueWeeks = ['1', '2', '3', '4', '5', '6', '7'] Issue.objects.bulk_create([Issue(name=Magazine(name=i), week=j) for i,j in zip(issueNames, issueWeeks)]) #QUERY Issue.objects.select_related("name").values_list() <QuerySet [(1, 'journal science', '1'), (2, 'journal science', '2'), (3, 'naughty mag', '3'), (4, 'funny cartoons', '4'), (5, 'comic fans', '5'), (6, 'lawncare', '6'), (7, 'lawncare', '7')]> -
AttributeError at /app/ 'numpy.ndarray' object has no attribute 'read'
I am making a wep app for face recognition by django and face_recogntion api, I don't how to solve this error from django.http import HttpResponse from django.shortcuts import redirect, render from .models import * import face_recognition import cv2 import urllib.request import numpy as np import dlib def Home(request): print(f'request method is {request.method}') if(request.method=='GET'): return render(request, "app.html") elif(request.method=='POST'): print(f'printing req body {request.POST["imageURL"]}') imageURL = urllib.request.urlopen(request.POST["imageURL"]) imageURL = face_recognition.load_image_file(imageURL) image = face_recognition.load_image_file(imageURL) image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB) imgLoc = face_recognition.face_locations(image); print(f'Image imagLoc {imgLoc}') cv2.imshow(image) cv2.waitKey(3000) return redirect('/app/') I am asking question on stackoverflow for the first time so sorry for any mistakes. -
How to check if there was a call of service function from APIView?
I'm trying to implement the service layer in my API. Now im trying to test create function with unittest lib. I dont really figure out, how to code it right. views.py class AuthorListApi(APIView): class InputSerializer(serializers.Serializer): name = serializers.CharField() def post(self, request): serializer = self.InputSerializer(data=request.data) serializer.is_valid(raise_exception=True) create_author(**serializer.validated_data) return Response(serializer.data, status=status.HTTP_201_CREATED) services.py def create_author(name: str) -> Author: """ Create a Author model object. """ author = Author(name=name) author.full_clean() author.save() return author test_view.py @mock.patch('books.views.AuthorListApi.create_author') def test_view_calls_service(self, service_mock): self.client.post(self.url, data=self.data) service_mock.assert_called_once_with(**self.data) Assertion error is: AttributeError: <class 'books.views.AuthorListApi'> does not have the attribute 'create_author' -
unsupported operand type(s) for -: 'DateField' and 'DateField'
I am working on creating a contract model with Django and I came cross on how to get the time duration from the start_date to the end_date?? class Contract(models.Model): name = models.CharField(max_length=100) price = models.IntegerField(max_length=10) start_date = models.DateField(auto_now_add=True) end_date = models.DateField(auto_now_add=True) duration = models.IntegerField(end_date - start_date) # how get the duration by hours created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name -
I cant figure out how to post angular's input form data in database (mongodb) using Django Rest API
I cant figure out how to post angular's input form data in database (mongodb) using Django Rest API. There are not enough tutorials and documentations on the internet regarding the set of django and angular along with mongodb. or maybe im tunnel visioned now. If anyone has a link which might solve my problem it would be great. Below is my angular's html file where you can see the form <form (ngSubmit)="onSubmit()"> <div class="form-group"> <label for="InputAttackTitle">Attack Title</label> <input ngModel type="text" class="form-control" name="AttackTitle" id="InputAttackTitle" placeholder="Enter Attack Title"> </div> <div class="form-group"> <label for="InputAttackDescripton">Attack Description</label> <textarea ngModel class="form-control" name="AttackDescription" id="InputAttackDescripton" placeholder="Enter Attack Description" ></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> <br> </div> Here you can see component.ts file export class IconsComponent implements OnInit { form: FormGroup; constructor(config: NgbModalConfig, private modalService: NgbModal,private http:HttpClient, public fb:FormBuilder) { config.backdrop = 'static'; config.keyboard = false; this.form = this.fb.group({ AttackTitle: [''], AttackDescription: [null] }) } AttackTitle:any; AttackDescription:any; onSubmit(){ var formData:any = new FormData(); formData.append("AttackTitle",this.form.get('AttackTitle').value); formData.append("AttackDescription",this.form.get('AttackDescription').value); this.http.post('http://127.0.0.1:8000/attackinfo', formData).subscribe( (response) => { return console.log(response); }, (error) => console.log(error) ) Below is the django's models class class AttackInfo(models.Model): AttackTitle=models.CharField(max_length=70, blank=False) AttackDescription = models.TextField(default='',blank=False) And Below is the view file @csrf_exempt def AttackInfoAPI(request,id=0): if request.method=='GET': attackinfo = AttackInfo.objects.all() attackinfo_serializer=AttackInfoSerializer(attackinfo,many=True) return JsonResponse(attackinfo_serializer.data,safe=False) elif … -
error when I push my project django to heroku
I want to deploying my project in heroku so I run heroku login heroku create heroku git:remote -a frozen-ravine-47377 heroku config:set DISABLE_COLLECTSTATIC=1 it's done and when i run git push heroku master I got error: $ git push heroku master Enumerating objects: 278, done. Counting objects: 100% (278/278), done. Delta compression using up to 4 threads Compressing objects: 100% (272/272), done. Writing objects: 100% (278/278), 694.38 KiB | 5.99 MiB/s, done. Total 278 (delta 126), reused 0 (delta 0), pack-reused 0 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: -----> Using Python version specified in runtime.txt remote: Traceback (most recent call last): remote: File "/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/runtime-fixer", line 8, in <module> remote: r = f.read().strip() remote: File "/usr/lib/python3.8/codecs.py", line 322, in decode remote: (result, consumed) = self._buffer_decode(data, self.errors, final) remote: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte remote: /tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/steps/python: line 5: warning: command substitution: ignored null byte in input remote: ) is not available for this stack (heroku-20). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python … -
How to check mime type for urls without extension in django
I am trying to find mime type of video urls without extension- I am using mimetypes.guess_type(video_url) for finding mime type if video url has extension .mp4 then I am getting a response video/mp4 otherwise it's returning null. is there a way to find mime type of a video url without extension ? -
How should i make DetailView in Django, gives 404
in file "views.py" i added next code: from django.views.generic import DetailView class NewsDetailView(DetailView): model = Articles template_name = "news/details_view.html" context_object_name = 'article' then in the file urls.py I added to urlpatterns next: path('<int:pk>', views.NewsDetailView.as_view(), name="news_detail"), and created the template "details_view.html". When i write to browser: http://127.0.0.1:8000/news/1 it gives 404 error 404 error in DetailView -
Serving Django static admin files with debug off in Elastic Beanstalk
Per other posts on this subject, I followed the advice at https://bestprogrammingblogs.blogspot.com/2021/03/django-static-files-not-working-when-debug-is-false.html to serve static files when debug is false. The site advises to make changes to Settings and URLs respectively STATIC_URL = '/static/' MEDIA_URL = '/media/' if DEBUG: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] else: STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and in URLs re_path(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}), re_path(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}), path('admin/', admin.site.urls), For some reason, my local admin works but the AWS admin site does not. Do I need to tune anything on the AWS side to get this working? My environment variables don't explicitly have any static settings at the moment. -
Bootstap DataTable showing No matching records found Django
I am developing a project in Django where users can share files. I retrieve data(files) from the database and show it in a table on the template and use bootstrap DataTable to implement search functionality in my table But when I search any record from DataTable it shows me No matching records found. Bootstrap CSS CDN <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css"> <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap4.min.css"> Javascript CDN <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap4.min.js"></script> Tamplate <table id="datatable" class="table table-striped table-bordered" style="width:100%"> <thead style="background-color : #607d8b;"> <tr> <th>S.No</th> <th>Uploading Date</th> <th>Branch</th> <th>Subject</th> <th>Download Notes</th> <th>File Type</th> <th>Description</th> <th>Status</th> <th>Action</th> </tr> </th -
Django radio button values in views
I'm using Radio buttons in django forms to record gender fields of object Person, as below. Person Model class Person(models.Model): GENDER = [ ('MALE','Male'), ('FEMALE','Female') ] first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) gender = models.CharField(choices=GENDER, null=True, blank=True, max_length=30) My PersonForm class PersonForm(forms.ModelForm): GENDER = [ ('MALE','Male'), ('FEMALE','Female') ] first_name = forms.CharField(label="First Name") last_name = forms.CharField(label="Last Name") email= forms.CharField(label="Email") gender = forms.ChoiceField( label='Gender', choices=GENDER, widget=forms.RadioSelect(),) class Meta: model = Client fields = ['first_name', 'last_name','email','gender'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def clean(self, *args, **kwargs): cleaned_data = super(PersonForm, self).clean() return cleaned_data Then my create_person_view(() def create_person_view(request): if request.method == 'POST': form = PersonForm(request.POST) if form.is_valid(): form.save(): return render(request, 'person/view_persons.html') else: form = PersonForm() return render(request, "person/create_person.html", {"person_form": form}) Now, I save the form and saves fine. The problem comes in when getting the saved data from database and passing to templates. Specifically when I do Gender: {{person.gender}} It gives: Gender: <django.forms.fields.ChoiceField object at 0x7fd82ae866a0> I wanna display the real value of gender. Any help? Will be really appreciated. -
How to modify a Django Model field on `.save()` whose value depends on the incoming changes?
I have fields in multiple related models whose values are fully derived from other fields both in the model being saved and from fields in related models. I wanted to automate their value maintenance so that they are always current/valid, so I wrote a base class that each model inherits from. It overrides the .save() and .delete(). It pretty much works except for when multiple updates are triggered via changes to a through model of a M:M relationship. So for example, I have a test that creates 2 through model records, which triggers updates to a model named Infusate: glu_t = Tracer.objects.create(compound=glu) c16_t = Tracer.objects.create(compound=c16) io = Infusate.objects.create(short_name="ti") InfusateTracer.objects.create(infusate=io, tracer=glu_t, concentration=1.0) InfusateTracer.objects.create(infusate=io, tracer=c16_t, concentration=2.0) print(f"Name: {infusate.name}") Infusate.objects.get(name="ti{C16:0-[5,6-13C5,17O1];glucose-[2,3-13C5,4-17O1]}") The save() override looks like this: def save(self, *args, **kwargs): # Set the changed value triggering this update so that the derived value of the automatically updated field reflects the new values: super().save(*args, **kwargs) # Update the fields that change due to the above change (if any) self.update_decorated_fields() # Note, I cannot call save again because I get a duplicate exception: # super().save(*args, **kwargs) # Percolate changes up to the parents (if any) self.call_parent_updaters() The automatically maintained field updates are performed here. Note … -
Facing relation "base_post" does not exist LINE 1: ..., "base_post"."featured", "base_post"."slug" FROM "base_post... issue. Can anybody help me?
Recently, I'm working with my Django Portfolio and after successfully deploying on Heroku I faced this error LINE 1: ..., "base_post"."featured", "base_post"."slug" FROM "base_post... So, this is how complete error is looking like Request Method: GET Request URL: https://shubhajeet-pradhan.herokuapp.com/ Django Version: 3.0.8 Python Version: 3.10.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shubhajeet_portfolio', 'base.apps.BaseConfig', 'crispy_forms', 'django_filters', 'ckeditor', 'ckeditor_uploader', 'storages', 'cloudinary_storage'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Template error: In template /app/base/templates/base/index.html, error at line 171 relation "base_post" does not exist LINE 1: ..., "base_post"."featured", "base_post"."slug" FROM "base_post... ^ 161 : </div> 162 : </section> 163 : 164 : <section class="s1"> 165 : <div class="main-container"> 166 : <div class="greeting-wrapper"> 167 : <h3 style="text-align: center;">Projects</h3> 168 : <div class="blog-wrapper"> 169 : {% include 'base/navbar_blog.html' %} 170 : <div class="post-wrapper"> 171 : {% for post in posts %} 172 : <div> 173 : <div class="post"> 174 : <img class="thumbnail" src="{{post.thumbnail.url}}"> 175 : <div class="post-preview"> 176 : <h6 class="post-title">{{post.headline}}</h6> 177 : <p class="post-intro">{{post.sub_headline}}</p> 178 : <a href="{% url 'post' post.slug %}">Read More</a> 179 : </div> 180 : </div> 181 : </div> Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) The above exception … -
drf-spectacular define request schema as JSON Array (like Serializer(many=True))
Is it possible to define "many" serializer schema in drf-spectacular? The request should take this data (JSONArray): MonthlyIncomeSerializer(many=True) Which is a list of objects/dictionaries: [ {'year':..., 'month':..., 'amount': ...}, {'year':..., 'month':..., 'amount': ...}, {'year':..., 'month':..., 'amount': ...}, ] I tried: class PartialDTIPrenajomView(APIView): @extend_schema(parameters=[MonthlyIncomeSerializer(many=True)]) def post(self, request, **kwargs): which doesn't render anything in Swagger. -
Django/Docker: web container not up-to-date code
I use Django docker app and do not manage to apply code update to my web container. I've tried to delete all containers (docker rm -f ID ; docker system prune) and images (docker rmi -f ID ; docker image prune) related to my app and re-build with docker-compose -f docker-comose.preprod.yml build Then I run docker-compose -f docker-comose.preprod.yml up but for some reasons when I connect to my web running container (docker exec -it web sh) and read my updated files, I observe that update are not applied... How should I do to make my update applied?