Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - My parent id is setting as 0 for every class
My state id is also storing the parent id as 0. I want my country to store parent id as 0 and parent id of state should be the id of country like this: Idk whats wrong i tried every possible solution i knew. models.py class customer_location(models.Model): parent_id=models.IntegerField(max_length=100) name=models.CharField(max_length=100) status=models.CharField(max_length=100, default='nil') added_by=models.CharField(max_length=100, default=1) updated_by=models.CharField(max_length=100, default=1) class Meta: db_table="customer_location" def __str__(self): return self.name class Country(customer_location): class Meta: proxy = True def save(self, *args, **kwargs): self.created_on = get_current_datetime_str() self.updated_on = get_current_datetime_str() self.parent_id = 0 super().save(*args, **kwargs) class State(customer_location): class Meta: proxy = True def save(self, *args, **kwargs): self.created_on = get_current_datetime_str() self.updated_on = get_current_datetime_str() super().save(*args, **kwargs) views.py def add_customer_location(request): if request.method == 'POST': form = CustomerLocationForm(request.POST) if form.is_valid(): country = form.cleaned_data['country'] state = form.cleaned_data['state'] country_obj = Country(name=country) country_obj.save() state_obj = State(name=state, parent_id=country_obj.id) state_obj.save() return redirect('success') else: form = CustomerLocationForm() return render(request, 'add_customer_location.html', {'form': form}) def success_view(request): return render(request, 'success.html') -
migration error django.db.utils.DatabaseError
File "D:\kice\flask\venv\lib\site-packages\djongo\sql2mongo\query.py", line 62, in __init__ self.parse() File "D:\kice\flask\venv\lib\site-packages\djongo\sql2mongo\query.py", line 441, in parse self._alter(statement) File "D:\kice\flask\venv\lib\site-packages\djongo\sql2mongo\query.py", line 500, in _alter raise SQLDecodeError(f'Unknown token: {tok}') djongo.exceptions.SQLDecodeError: Keyword: Unknown token: TYPE Sub SQL: None FAILED SQL: ('ALTER TABLE "corsheaders_corsmodel" ALTER COLUMN "id" TYPE long',) Params: ([],) Version: 1.3.6 The above exception was the direct cause of the following exception: return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "D:\kice\flask\venv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "D:\kice\flask\venv\lib\site-packages\django\db\backends\utils.py", line 79, in _execute with self.db.wrap_database_errors: File "D:\kice\flask\venv\lib\site-packages\django\db\utils.py", line 90, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "D:\kice\flask\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "D:\kice\flask\venv\lib\site-packages\djongo\cursor.py", line 59, in execute raise db_exe from e django.db.utils.DatabaseError -
How to update the front-end automatically if the back-end API data value changes in Django/Flask
If there is a field value 10 and after 20 mins it is updated to become 11. Below is the link I found a solution using Vue.js but is there a way to achieve this in Django/Flask.? Tried using Vue.js but need a solution in Django. -
How to load images from django views to a html template using loops
I've just started learning django and have a problem loading images using loops. In models.py I created a class called Pictures In views.py I created 3 instance of the class(Pictures) where img attribute is set to 3 different image names stored in the static folder. Now, I got stuck in loading the images in the template using for loop. apart from img attribute, I also created other attributes. These are the name and image description both of type string and they load just fine when rendered in the template using for loop. My question is what should I put in inside the img html tag to load these 3 different images using for loop? Initially, I was using the syntax below to load images directly from the static folder. <img src="{% static 'img/image-name.jpg' %}" alt="" width="250" height="250"> Now, I want to load the names from the img attribute and for each iteration, I want each of the three different images to load in the template each loop. Now I am not sure what to put inside the src="???". what i have so far and its working: {% for image in images %} <li> <img src="{{image.img}}" alt="" width="250" height="250"> <!-- I … -
TemplateDoesNotExist at/index.html
enter image description here i have tried so many options but my error not resolved please Help -
How to customize `bootstrap_form` fields
Given the form below from django import forms from django.forms import Form class SettingsForm(Form): first_name = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'First name'} ), label='', ) last_name = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'Last name'} ), label='', ) username = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'Username'} ), label='', ) email = forms.EmailField( widget=forms.EmailInput( attrs={'placeholder': 'Email'} ), label='', ) which is rendered using: <form method="post"> {% csrf_token %} {% bootstrap_form form %} <button class="btn btn-success">{{ form_title }}</button> </form> What do I need to change to have first name, last name on the same line? So far I tried: <form method="post"> {% csrf_token %} {% bootstrap_field form.first_name %} {% bootstrap_field form.last_name %} <button class="btn btn-success">Update</button> </form> but when I submit the form using the button, it looks like it doesn't link it to the form. The view is obtained through a FormView subclass SettingsView. When the submit button is clicked, SettingsView.form_valid is never called unless the form is invoked as bootstrap_form form. -
ERD to django models ? Many to many relatioship with attribut
How to get django models of this ER diagram ? I don't understand how to write a model for this ER diagram View ER diagram -
502 gateway error | sentence-transformer package not working correctly
Hello I'm trying to solve this problem from last 5days if anyone know the solution please reply. My website is working properly but one page giving 502 gateway error on post request where i used sentence transformer package the code is working properly on local server but not working on nginx live server Nginx error.log file giving this error For that page 2022/12/26 07:21:57 [error] 2197#2197: *2 upstream prematurely closed connection while reading response header from upstream, client: 106.211.97.247, server: 54.199.217.173, request: "POST /admin/scaning_signature HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/admin/scaning_signature", host: "54.199.217.173", referrer: "http://54.199.217.173/admin/get_signature" -
Django I cannot send the data to the database
I wanna create a appointment system but its not working now. I'dont have a error actually i just have a error and it's coming from views.py (messages.warning(request,"ERROR!")). When i opened the page its coming anyway i just wanna send my informations. models.py: I created models but im not sure for policlinic and doctor because it doesn't seems like charfield text. It's a option field in HTML. class Randevu(models.Model): STATUS = ( ('New', 'Yeni'), ('True', 'Evet'), ('False', 'Hayır'), ) policlinic=models.ForeignKey(Policlinic,on_delete=models.CASCADE) user=models.ForeignKey(User,on_delete=models.CASCADE) doctor=models.ForeignKey(Doctors,on_delete=models.CASCADE) phone = models.CharField(max_length=15) email = models.CharField(max_length=50) date=models.DateField(null=True) time=models.TimeField(null=True) payment= models.CharField(max_length=50) insurance= models.CharField(max_length=50) note=models.TextField(max_length=200) status = models.CharField(max_length=10, choices=STATUS,default='New') ip=models.CharField(max_length=20,blank=True) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def str(self): return self.user.username class AppointmentForm(ModelForm): class Meta: model=Randevu fields=['phone','email','date','time','payment','insurance','note'] views.py: def randevu(request): setting=Setting.objects.get(pk=1) policlinic=Policlinic.objects.all() doctor=Doctors.objects.all() context={'setting':setting ,'doctor':doctor,'policlinic':policlinic} if request.method=='POST': form=AppointmentForm(request.POST) if form.is_valid(): current_user=request.user data=Randevu() data.user_id=current_user.id data.phone=form.cleaned_data['phone'] data.email=form.cleaned_data['email'] data.date=form.cleaned_data['date'] data.time=form.cleaned_data['time'] data.payment=form.cleaned_data['payment'] data.insurance=form.cleaned_data['insurance'] data.note=form.cleaned_data['note'] data.ip=request.META.get('REMOTE_ADDR') data.save() messages.success(request,"DONE! :)") return render(request,'randevu.html',context) messages.warning(request,"ERROR!") return render(request,'randevu.html',context) urls.py urlpatterns = [ path('randevu',views.randevu,name='randevu') ] randevu.html <!-- MAKE AN APPOINTMENT --> <section id="appointment" data-stellar-background-ratio="3"> <div class="container"> <div class="row"> <div class="col-md-6 col-sm-6"> <img src="{% static 'images/appointment-image.jpg' %}" class="img-responsive" alt=""> </div> <div class="col-md-6 col-sm-6"> <!-- CONTACT FORM HERE --> <form id="appointment-form" role="form" action="{% url 'randevu' %}" method="post"> <!-- SECTION TITLE --> <div class="section-title wow … -
Page not found (404) No MenuCategories matches the given query
I created a Django application, the essence is this: data is added through the admin panel, which is then displayed on the main page. I added the data, but they are not displayed on the page; instead an error is displayed: Page not found (404). No MenuCategories match the given query. How can this be fixed? Here is my code in models.py: from django.db import models class MenuCategories(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) explicit_url = models.CharField(max_length=100, blank=True, null=True, unique=True) def __str__(self): return self.name def children(self): return self.menucategories_set.all() def get_elder_ids(self): if self.parent: return self.parent.get_elder_ids() + [self.parent.id] else: return [] -
Django: No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model in django?
after updating some fields in my model and hit the update button, i get this error that says No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model. I have am redirecting too after the update is done, but it seem not to be redirecting to that url anylonger, NOTE: the url still exists and works fine what could the problem be here? class ProductInline(): form_class = PredictionForm model = Predictions template_name = "core/create/create_bet.html" def form_valid(self, form): named_formsets = self.get_named_formsets() if not all((x.is_valid() for x in named_formsets.values())): return self.render_to_response(self.get_context_data(form=form)) self.object = form.save(commit=False) self.object.user = self.request.user self.object.current_amount = self.object.amount self.object.save() for name, formset in named_formsets.items(): formset_save_func = getattr(self, 'formset_{0}_valid'.format(name), None) if formset_save_func is not None: formset_save_func(formset) else: formset.save() messages.success(self.request, "Your bet have been created.") return redirect('core:dashboard') def formset_variants_valid(self, formset): """ Hook for custom formset saving.. useful if you have multiple formsets """ variants = formset.save(commit=False) # self.save_formset(formset, contact) # add this, if you have can_delete=True parameter set in inlineformset_factory func for obj in formset.deleted_objects: obj.delete() for variant in variants: variant.predictions = self.object variant.save() class PredictionUpdate(ProductInline, UpdateView): def get_context_data(self, **kwargs): ctx = super(PredictionUpdate, self).get_context_data(**kwargs) ctx['named_formsets'] = self.get_named_formsets() return ctx def get_current_object(self, id): prediction = Predictions.objects.get(id=id) … -
Django Docker ElasticBeanstalk fails
I'm new to docker and eb deployment, I want to deploy django with docker on eb here's what I did so far created a Dockerfile # Pull base image FROM python:3.9.16-slim-buster # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apt-get update &&\ apt-get install -y binutils libproj-dev gdal-bin python-gdal python3-gdal libpq-dev python-dev libcurl4-openssl-dev libssl-dev gcc # install dependencies COPY . /code WORKDIR /code/ RUN pip install -r requirements.txt # set work directory WORKDIR /code/app then in docker-compose.yml version: '3.7' services: web: build: . command: python /code/hike/manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 volumes: - .:/code it runs locally, but on deployment it fails and when I get to logs, it says pg_config is required to build psycopg2 from source. like it's not using the Dockerfile, I read somewhere I should set Dockerrunder.aws.json but I've no idea what to write in it! -
Django: How to populate model field value using another field in django model?
I want to auto-populate a Model field with data from another field, according to the value of that field, i will then auto add a new value the empty field. class Predictions(models.Model): amount = models.DecimalField(max_digits=999999999, decimal_places=2, default=0.00) current_amount = models.DecimalField(max_digits=999999999, decimal_places=2, default=0.00) def save(self, *args, **kwargs): if self.amount: self.current_amount = self.current_amount super(Predictions, self).save(*args, **kwargs) As you can see i have overridden the save method and assigned the value of current_amount to amount, Now the problem is this, when a user want to update this model, i don't want the current_amount to still be set to the amount, some calculation would be done on the curren_amount, so i want the new values for current_amount to remain. So I thought of doing this in the create view and not override the save method This is what i came up with NOTE: I am peforming some other operations in the code, so it might be a little long (the code). class ProductInline(): form_class = PredictionForm model = Predictions template_name = "core/create/create_bet.html" def form_valid(self, form): named_formsets = self.get_named_formsets() if not all((x.is_valid() for x in named_formsets.values())): return self.render_to_response(self.get_context_data(form=form)) # self.object = form.save() # new_form = form.save(commit=False) # new_form.user = self.request.user # self.object = new_form.save() self.object … -
ValueError at /state/ Field 'id' expected a number but got 'None'
I am getting this error and i have tried typecasting to change it to an integer but it still gives an error. I don't know what's wrong with the code and i am stuck here from past 30 minutes. Can someone help? urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', cview.Insertrecord), path('country/', lview.Insertrecord), path('state/', lview.Insertrecord_state), ] models.py class customer_state(models.Model): parent_id=models.ForeignKey(customer_location, on_delete=models.CASCADE) name=models.CharField(max_length=100) status=models.CharField(max_length=100, default='nil') added_by=models.CharField(max_length=100, default=1) updated_by=models.CharField(max_length=100, default=1) created_on=models.CharField(max_length=100) updated_on=models.CharField(max_length=100) class Meta: db_table="customer_state" def __str__(self): return self.name def save(self, *args, **kwargs): self.created_on = get_current_datetime_str() self.updated_on = get_current_datetime_str() super().save(*args, **kwargs) views.py def Insertrecord_state(request): # Define the parent_id variable parent_id = None if request.method=='POST': if request.POST.get('parent_id')...... and request.POST.get('updated_on'): parent_id = request.POST.get('parent_id') parent_location = customer_location.objects.get(id=parent_id) saverecord=customer_state() saverecord.parent_id=parent_location saverecord.name=request.POST.get('name') saverecord.save() messages.success(request,"Record Saved Successfully..!") return render(request, 'state.html', {'parent_id': parent_id}) else: # Return the form with the parent_id variable return render(request,'state.html', {'parent_id': parent_id}) state.html <div class="container-sm"> <form method = "POST"> {% csrf_token %} <div class="row mb-3" style="display:none"> <label for="inputEmail3" class="col-sm-2 col-form-label">Parent ID</label> <div class="col-sm-10"> <input type="text" value="{{ parent_id }}" name="parent_id" class="form-control" id="inputEmail3" required/> </div> </div> . . </form> -
How to check if the user already rated through template or view function django
So In my list_detail.html I have included the create_starr.html file where my star rating form is placed. Now I can Rate a post with a user only once (which I want). But if a user already rated then it goes to the else condition (goes to the create_starr.html file) But the thing I wanna do is if a user already rated. in post_detail.html I want it to show for example if a user rated 5, I want to show 5 stars in the place of postable star rating form(non editable) in list_detail.html page. But dont know how can I approach that. NOOB HERE. in my models class List(models.Model): title = models.CharField(max_length=120) genre = models.ManyToManyField('Genre') creator = models.ForeignKey(User,on_delete=models.SET_NULL,blank=True, null=True) posted = models.DateTimeField(auto_now_add=True) content = RichTextField(null=True,default=' ') type = models.CharField(max_length=10,default="Movie") spoiler_choices = [(False, 'No'),(True, 'Yes')] spoiler = models.BooleanField(default=False,null=True, choices = spoiler_choices) slug = models.SlugField(max_length= 300,null=True, blank = True, unique=True) def __str__(self): return f'{self.title}|{self.creator}' def save(self, *args, **kwargs): self.slug = slugify(self.title + str(self.posted)) super(List,self).save(*args, **kwargs) class Starr(models.Model): user = models.ForeignKey(User,models.CASCADE) list = models.ForeignKey(List,models.CASCADE) rate = models.PositiveIntegerField(default=0) class Meta: unique_together = ["user", "list"] def __str__(self): return self.user.username + " | " + self.list.title + " | " + str(self.rate) in my views class TheirDetailView(DetailView): … -
Bootstrap modal is not popping up on chrome though working well on microsoft edge
i have used a bootstrap modal in my project .All is working well except modal. when i was using microsoft edge modal is popping up with good manner but something wrong with the google chrome. now how can i get the modal pop up on chrome with best user experience Though it is working while i removed "fade" from the class, it popped up with a dark background, i think this is not a good user experience -
In Django is it possible to add url directory instead of url file
is it possible to use urls directory instead of using url file normaly we do like path("", include("app.urls"), name="") # urls is urls.py but is it possible to add a directory not the urls.py file path("", include("app.folder"), name="") # inside the folder urls.py file lives -
Django static are not getting load on AWS using Nginx
i have a website build on Django. everything is working fine on local machine but the static file are not getting load on production. Django project is running fine on Debug=False I did install whitenoise==6.2.0 the error django settings SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ["*"] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ "http://54.234.143.251", ] CSRF_TRUSTED_ORIGINS = [ "http://54.234.143.251", ] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", # app "applipsync", "store", # packages "whitenoise.runserver_nostatic", "rest_framework", "django_q", "allauth", "allauth.account", "allauth.socialaccount", "crispy_forms", ] CRISPY_TEMPLATE_PACK = "bootstrap4" MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", #add whitenoise "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", ] ROOT_URLCONF = "core.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [BASE_DIR / "templates"], "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" # EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' ACCOUNT_EMAIL_REQUIRED = True # Make email verification mandatory to avoid junk email accounts ACCOUNT_EMAIL_VERIFICATION = "mandatory" EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = "" EMAIL_HOST_PASSWORD = "" AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` … -
ModuleNotFoundError: No module named 'menu'
I'm developing a django application, but when I try to start the server, I get an error: ModuleNotFoundError: No module named 'menu'. Here is my code in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'menu', ]` ``` Here is the project structure: My files I don't understand what I'm doing wrong. -
Django - How to store two different models in a single database table with same column name
I have two models country and state. And the columns which i used for them is as follows: from django.db import models from datetime import datetime # Create your models here. def get_current_datetime_str(): now = datetime.now() return now.strftime("%Y-%m-%d %H:%M:%S") class customer_location(models.Model): parent_id=models.CharField(max_length=100) name=models.CharField(max_length=100) status=models.CharField(max_length=100, default='nil') added_by=models.CharField(max_length=100, default=1) updated_by=models.CharField(max_length=100, default=1) created_on=models.CharField(max_length=100) updated_on=models.CharField(max_length=100) class Meta: db_table="customer_location" def __str__(self): return self.name def save(self, *args, **kwargs): self.created_on = get_current_datetime_str() self.updated_on = get_current_datetime_str() super().save(*args, **kwargs) self.parent_id = 0 super().save(*args, **kwargs) Now i want to set parent id as 0 if a country is entered. And i want to set the parent id as auto incremented id of country if state is entered. The main problem i am facing is to store both of them in single table. How can i do that? Example of Database Schema: -
How can i get 2nd data from requests.post
views.py class Box_Mission_Update(APIView): authentication_classes = [SessionAuthentication , BasicAuthentication] permission_classes = [IsAuthenticated,] def post(self,request,format=None): try: data = request.data update_time = datetime.strftime(datetime.now(),"%Y-%m-%d %H:%M:%S") if data['CEID'] == 203: x=Box_Mission.objects.filter(mission_no=data['CommandID']).latest('created_at') Box_Mission.objects.filter(code=x.code).update(mission_status=2) BoxSubMission.objects.filter(box_mission=x,mission_id='S3').update(end_time=update_time) print('mission_done') return JsonResponse({'code': 0,"description":'mission updated','detail':''}) except Exception as e: event = Error(str(e)) return JsonResponse({"code":event.code,"detail":event.description},status=event.status,safe=False) post requests def update_command_info_203(self, data): try: self.mission_report.clear() self.mission_report={ "CommandID":self.list_Command_Info[index]['CommandID'], "CEID":203, } r = requests.post(f'http://{Mcs["HOST"]}:{Mcs["PORT"]}/api/box_mission/update',data=json.dumps(self.mission_report),auth=HTTPBasicAuth(Mcs["ACCOUNT"],Mcs["PASSWORD"]),headers={'Content-Type': 'application/json'},timeout=1) self.mission_report.clear() except Exception as error: print("203 message fail to update.",error) pass function above will requests.post the data 2 times, the 2nd data will be at 1 min later, how can i only trigger my views.py with the 2nd data i receive? -
issue with configuring django_ace
i'm trying to create a web application that incorporates a light-weight ide but i am having trouble integrating a code editor with syntax highlighting with django. when i try to use the ace widget configurations, none of the settings i add seem to work but the widget is still rendered. views.py from django.shortcuts import render from . import forms # Create your views here def index(request): return render(request, 'main.html', context={'ace_editor': forms.EditorForm}) forms.py from django import forms from django_ace import AceWidget class EditorForm(forms.Form): text = forms.CharField(widget=AceWidget( mode="java", theme="twilight", wordwrap=False, width="5000px", height="300px", minlines=None, maxlines=None, showprintmargin=False, showinvisibles=False, usesofttabs=True, tabsize=None, fontsize=None, toolbar=True, readonly=False, showgutter=True, behaviours=True, )) main.html <p>hi</p> {{ ace_editor }} output -
Why does this Django filter query return empty list?
In my Vechicle table: Vechicle.objects.all().first().tags.slugs() <QuerySet ['car', 'awd']> when I test it in python manage.py shell >>> from django.db.models import Q >>> q_objects = Q(tags__slug='car') >>> q_objects &= Q(tags__slug='awd') >>> q_objects <Q: (AND: ('tags__slug', 'car'), ('tags__slug', 'awd'))> >>> from partpicker.models import Car >>> Car.objects.all().filter(q_objects) <QuerySet []> -
DJANGO RF - Include the SerializerMethodField when nesting a serializer in another serializer
I have a serializer on my UserProfile model. It includes a SerializerMethodField "userGlobalPoints" : class UserProfileSerializer(serializers.ModelSerializer): userGlobalPoints = serializers.SerializerMethodField() def get_userGlobalPoints(self, obj): (*** calculation ***) return userGlobalPoints class Meta: model = UserProfile fields = '__all__' In my Post serializer, I want to nest, for each post, informations about the post's author. So I include fields from the UserProfile model (there is a ForeignKey relation in the Post model). I would like to add the userGlobalPoints field. But I can't figure out how I can nest this field in the serializer. It looks like the usual syntax for nesting a serializer does not work on SerializerMethodField fields. This is my PostSerializer: class PostSerializer(serializers.ModelSerializer): pk = serializers.ReadOnlyField() authorNickname = serializers.CharField(source='postAuthor.userNickname', read_only=True) authorProfileWithGlobalPoints = UserProfileSerializer(many=False, read_only=True) class Meta: model = Post fields = ['pk','authorNickname','postText', 'postTimestamp', 'authorProfileWithGlobalPoints'] Any help on how to achieve this would be apreciated! -
django inline_formset get pk from foreign key item before save to make a form validation
django noob here, well i´ve be dealing with this for over a day and i cant figure out, so decide to post, any help, thanks! have this project and i want to validate this formset, this formset have a select with product list, and quantiy, i need to validate if when saving new data, that the product selected have o not stock enough and raise a form validation error, but i cant figure out how to get the pk from the related model, already read several articles but cant make it work this models.py class Product(models.Model): product_id = models.AutoField(primary_key=True) description = models.CharField(max_length=50) stock = models.IntegerField(default='0') def __str__(self): return self.description + '(' + str(self.stock)+')' def save(self, *args, **kwargs): self.description = self.description.title() super(Product, self).save(*args, **kwargs) class Invoice(models.Model): invoice_id = models.AutoField(primary_key=True) client_id = models.ForeignKey(Client, on_delete=models.CASCADE) date = models.DateTimeField() status = models.BooleanField(default=True) def __str__(self): return str(self.invoice_id) class InvoiceItem(models.Model): invoice_id = models.ForeignKey(Invoice, on_delete=models.CASCADE) product_id = models.ForeignKey(Product, on_delete=models.CASCADE) qty = models.IntegerField(default='0') price = models.DecimalField(max_digits=10, decimal_places=2, default=0) class Meta: constraints = [ models.UniqueConstraint( fields=['invoice_id', 'product_id'], name='unique invoiceitem') ] these are my forms.py class InvoiceForm(forms.ModelForm): class Meta: model = Invoice exclude = ['status'] labels = { 'client_id': ('Cliente'), 'date': ('Fecha'), } widgets = { 'date':forms.DateInput( attrs={'type': 'date'}, ), …