Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I use JWT tokens in Django Rest Framework?
I'm new to django and DRF, I'm trying to build an authentification system using JWT, I want to login the user directly after registering, I read the documentation and I managed to create a token manually and return it in my serializer, but my questions are this: 1) How can I use this token to see if the user is logged in or not? 2) Can I use the {% if user.is_authenticated %} in my templates? if so how? 3) How can I get the user logged in informations in another view? 4) Is there a more efficient way of dealing with authentifications with DRF? -
Parse /proc/net/route output in Django template
I have the following python script to parse the output of the /proc/net/route file and it works fine when I run it in the shell. The code return a separate list for each routing entry in the table I need to display the output of this script in a table in the django template. I tried to use a for loop but it does not display anything. def routes(request): with open("/proc/net/route") as fh: next(fh) for line in fh: routes = line.strip().split() destination = socket.inet_ntoa(struct.pack("<L", int(routes[1], 16))) gateway = socket.inet_ntoa(struct.pack("<L", int(routes[2], 16))) mask = socket.inet_ntoa(struct.pack("<L", int(routes[7], 16))) metric = routes[6] interface = routes[0] context_routes = {'routes': routes } return render(request, 'lwp_admin/routes.html', context_routes ) CLI output of the script: 0.0.0.0 192.168.1.1 0.0.0.0 100 enp1s0 172.17.0.0 0.0.0.0 255.255.0.0 0 docker0 192.168.1.0 0.0.0.0 255.255.255.0 100 enp1s0 192.168.34.0 0.0.0.0 255.255.255.0 0 vmnet1 192.168.64.0 0.0.0.0 255.255.255.0 0 vmnet8 192.168.122.0 0.0.0.0 255.255.255.0 0 virbr0 I want this output to be displayed in the django template in a table. Django template code: <table class="table table-bordered table-responsive table-striped table-condensed"> <thead class="bg-maroon-gradient"> <tr> <th scope="col" class="col-xs-1 text-center">Destination</th> <th scope="col" class="col-xs-1 text-center">Subnet mask</th> <th scope="col" class="col-xs-1 text-center">Gateway</th> <th scope="col" class="col-xs-1 text-center">Metric</th> <th scope="col" class="col-xs-1 text-center">Interface</th> </tr> </thead> <tbody> {% for route … -
Unable to display serializer to update model details - Django-Rest-Framework
I am trying to update my team model using a serializer. The page is rendering but it is not including the serializer to update the data. I am also trying to auto populate the serializer based on the pk the user selects from the edit button on the teams.html page. urls.py path('teams/', views.TeamInfo.as_view(), name='teams'), path('delete_team/<int:pk>/', views.delete_team, name='delete_team'), path('edit_team/<int:pk>/', views.edit_team, name='edit_team'), teams.html <div class="team"> <h3>Team Details</h3> <p> {% csrf_token %} {% for info in teams %} <li>{{ info.club_id }}</li> <li>{{ info.team_name }}</li> <li>{{ info.manager_name }}</li> <form action="{% url 'clubs:delete_team' info.pk %}"> <input type="submit" value="Delete"> </form> <form action="{% url 'clubs:edit_team' info.pk %}"> <input type="submit" value="Edit"> </form> edit_teams.html {% extends 'club_main_page.html' %} {% load rest_framework %} {% load staticfiles %} {% block body_block %} <div class="editteam"> <h3>Edit Team</h3> <form action="{% url 'clubs:edit_team' pk=instance.pk %}" method="POST"> {% csrf_token %} {% render_form serializer %} <input type="submit" name="" value="Update"> </form> </div> {% endblock %} views.py: def delete_team(request, pk): team = Team.objects.filter(pk=pk) team.delete() return redirect('clubs:teams') def edit_team(request, pk): instance = Team.objects.filter(pk=pk) if request.method == 'POST': serializer = TeamSerializer(request.POST, instance=instance) if serializer.is_valid(): serializer.save() return redirect('/') else: return redirect('/') else: serializer = TeamSerializer(instance=instance) return render(request, 'edit_club.html', {'serializer': serializer}) -
Django Test what form a formset uses
If I have a form like: class MyForm(modelForm): # Form stuff And a formset like: MyFormSet = modelformset_factory( MyModel, form=MyForm, max_num=6, validate_max=True, ) Is there a way to test that form=MyForm? def test_formset(self): formset = MyFormSet() self.assertEqual(formset.max_num, 6) self.assertTrue(formset.validate_max) # Tried this but it didn't work self.assertIsInstance(formset.form, MyForm) -
Avoiding "DoesNotExist at /"
I made a log in view, which works perfectly. The issue is that I want to avoid the Django's default template message: DoesNotExist at / Usuario matching query does not exist. Request Method: POST Request URL: http://localhost:8000/ Django Version: 2.1.5 Exception Type: DoesNotExist Exception Value: Usuario matching query does not exist. Instead of that I'm trying to send my own login error message, my code is like this: def login(request): if request.method == "POST": print('Form is post.') form = LoginForm(request.POST) if form.is_valid(): print('Form is valid.') loginUser = form.cleaned_data.get('nombreUsuario') loginPass = form.cleaned_data.get('password') loginEmp = form.cleaned_data.get('nombreEmpresa') encontroUsuario = Usuario.objects.get(nombre=loginUser, password=loginPass) encontroEmpresa = Empresa.objects.get(nombre=loginEmp) if encontroUsuario and encontroEmpresa: return HttpResponse('Logueado con éxito.') if encontroUsuario.DoesNotExist or encontroEmpresa.DoesNotExist: return render(request, "loginError.html", {"form": form}) else: form = LoginForm return render(request, "login.html", {"form": form}) -
Sending emails with django
I am building an app with django and i have build a contact form on the app which allows users to contact by just sending an email. Everything works fine but the problem is, in the received email the senders email is not displayed in the From:sender_email, instead the email in apps settings.EMAIL_HOST_USER is displayed in From:shopvoomhelpdesk@gmail.com, and To:shopvoomhelpdesk@gmail.com. I have tried to debug the problem but can't understand what is causing the problem. here is my code in views.py def contact(request): if request.method == 'POST': form = EmailForm(request.POST) if form.is_valid(): try: names = form.cleaned_data['names'] email = form.cleaned_data['email'] print(email) subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] message_body = f'Names: {names} \n {message}' send_mail( subject, message_body, email, [settings.EMAIL_HOST_USER], fail_silently=True ) return render(request, 'sunyata/success.html') except Exception as e: context['form'] = EmailForm(request.POST) context['error'] = 'Unable to send message, it might be due to spelling error in\ email check your email and resend again' return render(request, 'sunyata/success.html', context) else: form = EmailForm(request.POST) context['form'] = form return render(request, 'sunyata/contact.html', context) else: context['form'] = EmailForm() return render(request, 'sunyata/contact.html', context) forms.py from django import forms class EmailForm(forms.Form): names = forms.CharField(label='Names',widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':"Enter your names"})) email = forms.EmailField(label='Email', widget=forms.EmailInput(attrs={'class':'form-control', 'placeholder':'Enter your email'})) subject = forms.CharField(label='Subject',widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':"Enter email subject"})) message = … -
raise exception in django oauth toolkit
I'm using Django 2.x and django-oauth-toolkit to generate access token. I have written a custom token view to run a few checks on the account and then generate access token to the user. If custom check fails, I want to raise an exception with 400 status code. class CustomTokenView(TokenView): def create_token_response(self, request): login = request.POST.pop('username', None) username = get_user_model().objects.filter( email=login[0] ).last() if not username.verified: raise HttpResponse(content='User not verified', status=status.HTTP_400_BAD_REQUEST) request.POST._mutable = mutable return super(TokenView, self).create_token_response(request) But this gives error as TypeError: exceptions must derive from BaseException I also tried with from rest_framework.response import Response raise Response('User not verified', status=status.HTTP_400_BAD_REQUEST) But none is working. -
Django User's DetailVew affects authentificated User
I tried to display information about User (profile page) using DetailView. It works but when I open a DetailView of User for some reason Django thinks that I am authenticated as this user. For an example if I log out, open some User's DetailView, Django starts to think that I am logged in and logged in as this User. I can see problems as base.html shows currently logged user and changes if user is not authenticated. Any ideas what is wrong? Thanks! views.py class ProfileView(DetailView): model = User template_name = 'users/profile.html' urls.py urlpatterns = [ path('profile/<int:pk>/<str:username>', ProfileView.as_view(), name='profile'), ] profile.html {% extends 'base.html' %} {% block content %} <article class = 'media content-section'> <div class="media"> <img class="avatar-image rounded-circle" src="{{ user.profile.image.url }}"> </div> <div class = 'media-body'> <div class='article-metadata'> <h3>Профиль {{user.username}}</h3> </div> <div class="article-content"> <p>{{user.first_name}}</p> <p>{{user.email}}</p> <p>{{user.profile.birthdate}}</p> <p>{{user.date_joined}}</p> </div> </div> </article> {% endblock %} base.html <div class="navbar-nav"> {% if user.is_authenticated %} <div class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="far fa-user-circle" title="Пользователь"> {{user.username}}</i></a> ... -
Sort by ascending and descending using django-filter
I have the following code for few filterings: from .models import ProductLaptop import django_filters class ProductLaptopFilter(django_filters.FilterSet): laptops_name = django_filters.CharFilter(lookup_expr='icontains') laptops_price = django_filters.NumberFilter() laptops_price__gt = django_filters.NumberFilter(field_name='laptops_price', lookup_expr='gt') laptops_price__lt = django_filters.NumberFilter(field_name='laptops_price', lookup_expr='lt') class Meta: model = ProductLaptop fields = ['laptops_name', 'laptops_price', 'brand_name'] The html codes for this: {% load widget_tweaks %} {% block content %} <form method="get"> <div class="well"> <h4 style="margin-top: 0">Filter</h4> <div class="row"> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.laptops_name.label_tag }} {% render_field filter.form.laptops_name class="form-control" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.laptops_price.label_tag }} {% render_field filter.form.laptops_price class="form-control" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.brand_name.label_tag }} {% render_field filter.form.brand_name class="form-control" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.laptops_price__gt.label_tag }} {% render_field filter.form.laptops_price__gt class="form-control" %} </div> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.laptops_price__lt.label_tag }} {% render_field filter.form.laptops_price__lt class="form-control" %} </div> </div> <button type="submit" class="btn btn-primary"> <span class="glyphicon glyphicon-search"></span> Search </button> </div> </form> Which gives me a view like below: Here I want to add an option where people can sort the items in ascending and descending order. Can anyone give me some suggestions how can I implement this? -
LEFT OUTER JOIN in subquery
Consider a simple User and Content models setup. I would like to get the distribution of content per user, including 0 for users without content: per_user | count ----------+------- 0 | 89 1 | 15 2 | 14 One way to do this in pure SQL is: SELECT per_user, count(per_user) count FROM ( SELECT COUNT(c.id) per_user FROM app_user u LEFT JOIN app_content c ON (c.user_id = u.id) GROUP BY u.id ) AS sub GROUP BY per_user ORDER BY per_user DESC; I can do this to get the per_user count: User.objects.annotate(per_user=Count("content")).values("per_user") Unfortunately I cannot stick another .annotate(c=Count("per_user")) at the end of this: FieldError: Cannot compute Count('per_user'): 'per_user' is an aggregate -
nested query filter _ Django
I keep it simple. I have 3 models. class C(models.model): some_field = models.BooleanField(default=False) class B(models.model): b = models.ForeignKey(C) class A(models.model): a = models.ForeignKey(B) I need a query filter that gets A.a.b.some_field = True. how can I achieve this ? -
how to solve "cannot find installed version of python-django or python3-django." on ubuntu 18.0.4
i tried installing pip and everything worked like this $ sudo pip3 install django==2.1.5 requirement already satisfied: django in /usr/local/lib/python3.6/dist-packages then i tried to run $ django-admin --version and it gives me Cannot find installed version of python-django or python3-django i tried running $ sudo apt install python-django-common but didn't work then i tried to run $ sudo pip install django $ django-admin --version but it shows 1.11.11 i want the newest version 2.1.5 and it wouldn't let me use it -
how to create a link to a different template's id using Django template tags?
I have a button and I want that button take me to a different template's HTML id. How can I do that using Django template tags? This is nav.html <navbar class="name"> <a href="{% url 'main' %}" class="name">Home</a> <a href="{% url 'ministries' %}" class="name">Login</a> <a href="{% url 'areas' %}" class="name">Areas</a> <a href="{% url 'about' %}" class="name">About Us</a> </navbar> This is index.html and it has an id called #Ministries <!-- Ministries Section --> <div class="w3-container w3-padding-32" id="Ministries"> <h3 class="w3-border-bottom w3-border-light-grey w3-padding-16">Ministries</h3> </div> I want Minitries button take to index.html's #Ministries id section -
How can I create the views for a form in Django where the form includes many select widget?
I am a beginner in Django/ Python and have to make a select chain on a website. I am not sure if the forms that I have written are correct as well as the views. This is the model that I am using: from django.db import models from physics_Quizzes.choices import * # Create your models here. class questions(models.Model): questions_type = models. IntegerField( choices = questions_type_choices, default = 0) question_topic = models.IntegerField( choices = question_topic_name_choices, default = 0) question_description = models.TextField() question_answer = models.ForeignKey( 'answers', on_delete=models.CASCADE, blank=True, null=True) question_image = models.ForeignKey( 'images', on_delete=models.CASCADE, blank=True, null=True) question_number = models.IntegerField( choices = question_number_choices, default = 0) def __str__(self): return self.question_description class answers(models.Model): answer_description = models.TextField() answer_image = models.ForeignKey( 'images', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.answer_description class images (models.Model): image_blob = models.ImageField() def __str__(self): return self.image_blob This is the forms.py from django import forms from django.forms import widgets from .models import * class questions_selection_form(forms.Form): question_topic = forms.ChoiceField( label = 'Topic', required = True, widget = forms.SelectMultiple( choices=(question_topic_name_choices), attrs={ "class": "home-topic-selection" } ) ) questions_type = forms.ChoiceField( label = "Questions' Type" required = True, widget = forms.Select( choices=(questions_type_choices), attrs={ "class": "home-questionType-selection" } ) ) question_number = forms.ChoiceField( label = "Questions' Type" required = True, … -
django deconstruct decorator staticmethod
Below is the source code of the deconstruct class decorator, I am a little confused about the use of the staticmethod within the class, because if I change the code klass.__new__ = staticmethod(__new__) to klass.__new__ = __new__ it still works as expected, can anyone explain me why this line of code was added, what is the purpose or use cases? from importlib import import_module def deconstructible(*args, path=None): """ Class decorator that allows the decorated class to be serialized by the migrations subsystem. The `path` kwarg specifies the import path. """ def decorator(klass): def __new__(cls, *args, **kwargs): # We capture the arguments to make returning them trivial obj = super(klass, cls).__new__(cls) obj._constructor_args = (args, kwargs) return obj def deconstruct(obj): """ Return a 3-tuple of class import path, positional arguments, and keyword arguments. """ # Fallback version if path: module_name, _, name = path.rpartition('.') else: module_name = obj.__module__ name = obj.__class__.__name__ # Make sure it's actually there and not an inner class module = import_module(module_name) if not hasattr(module, name): raise ValueError( "Could not find object %s in %s.\n" "Please note that you cannot serialize things like inner " "classes. Please move the object into the main module " "body to use migrations.\n" … -
How to fix this ,I am storing a record of student from frontend
Storing data from frontend in models,But it is not saved in models when I saw in admin the table where it is created...... I dont want to use inbuilt form to sotre data anyone explain how to create database and store and retreive without using inbuilt form ..like that #models.py ` from django.db import models class Details(models.Model): name=models.CharField(max_length=30,unique=True) branch=models.CharField(max_length=50) def __str__(self): return self.name #views.py from django.shortcuts import render from .models import Details def index(request): return render(request,'basic_app/data.html') def details(request): if request.method=="POST": post=POST() post.name=request.POST.get('name') post.branch=request.POST.get('branch') post.save() #urls.py from djang#o.contrib import admin from django.urls import path from django.conf.urls import url from basic_app import views urlpatterns = [ url(r'^$',views.index,name='index'), path('admin/', admin.site.urls), ] ##data.html <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body><center> <h1>enter data here</h1> <form method="POST"> {% csrf_token %} <label for="">Name:</label> <inputype="text" name="name" value=""placeholder="name"> <br> <label for="">Branch</label> <input type="text" name="branch" value=""placeholder="enter branch"> <br> <br> <input type="submit" name="submit" value="post"> </form></center </body> </html> -
Deleting inline item fails due to None id
I have a quote model that has quoteitems as a related field. class BusinessQuote(models.Model): id = models.AutoField(primary_key=True) client = models.ForeignKey(BusinessClient, null=True, on_delete=models.SET_NULL) site = models.ForeignKey(BusinessSite, null=True, on_delete=models.SET_NULL) ... and class BusinessQuoteitem(models.Model): id = models.AutoField(primary_key=True) quote = models.ForeignKey(BusinessQuote, null=True, on_delete=models.CASCADE) job = models.ForeignKey(BusinessJobtask, blank=True, null=True, on_delete=models.SET_NULL) ordered = models.IntegerField(default=0) ... They are displayed in admin as inlines class InlineQuoteItems(admin.TabularInline): model = BusinessQuoteitem extra = 0 formfield_overrides = { ... } class QuoteAdmin(admin.ModelAdmin): list_display = ['id', 'date', 'client', 'site', 'tradename', 'total', 'converted'] list_filter = ['tradename', 'client', ] inlines = [InlineQuoteItems] admin.site.register(BusinessQuote,QuoteAdmin) when I try and delete an inline item I'm getting the following error: Exception Type: TypeError Exception Value: %d format: a number is required, not NoneType Exception Location: /home/.../business/models.py in __str__, line 237 Line 237 relates to: def __str__(self): return "%d" % (self.id) Whats confusing is that this has normally worked out the box so I'm at a loss as to what could cause the inline delete to fail. I am doing some javascript on the fields prior to submitting which totals the inline items and updates the invoice total but it doesn't touch id fields and as its client-side I cannot see it being an influence. -
How to bind rich text from Django admin in the Vue.js SPA web application?
I am trying to create a blog with Django and vue.js And would like to know how blog content which might consist of heading, several subheadings, ul and li s: can be bonded in Vue.js front end? I found some libraries which add rich text feature in Django admin but have no idea how then it will be binded in Vue? -
Django annotate several same objects in QuerySet by different related object
I got: # models class Building(models.Model): ... class Flat(models.Model): building = models.ForeignKey(Building) class Profile(models.Model): flats = models.ManyToManyField(Flat) # logic building = Building.objects.create() flat_1 = Flat.objects.create(building=building) flat_2 = Flat.objects.create(building=building) profile = Profile.objects.create() profile.flats.add(flat_1) profile.flats.add(flat_2) profiles = Profile.objects.filter(flats__building=building) I got in profiles 2 same profiles. How i can annotate each of them by different flat? Maybe Subquery() but how? -
Celery workers failing in aws elastic beanstalk [exited: celeryd-worker (exit status 1; not expected)]
I've been trying to follow this thorough explanation on how to deploy a django app with celery worker to aws elastic beanstalk: How to run a celery worker with Django app scalable by AWS Elastic Beanstalk? I had some problems installing pycurl but solved it with the comment in: Pip Requirements.txt --global-option causing installation errors with other packages. "option not recognized" Then i got: [2019-01-26T06:43:04.865Z] INFO [12249] - [Application update app-190126_134200@28/AppDeployStage0/EbExtensionPostBuild/Infra-EmbeddedPostBuild/postbuild_1_raiseflags/Command 05_celery_tasks_run] : Activity execution failed, because: /usr/bin/env: bash : No such file or directory (ElasticBeanstalk::ExternalInvocationError) But also solved it: it turns out I had to convert "celery_configuration.txt" file to UNIX EOL (i'm using Windows, and Notepad++ automatically converted it to Windows EOL). With all these modifications I can successfully deploy the project. But the problem is that the periodic tasks are not running. I get: 2019-01-26 09:12:57,337 INFO exited: celeryd-beat (exit status 1; not expected) 2019-01-26 09:12:58,583 INFO spawned: 'celeryd-worker' with pid 25691 2019-01-26 09:12:59,453 INFO spawned: 'celeryd-beat' with pid 25695 2019-01-26 09:12:59,666 INFO exited: celeryd-worker (exit status 1; not expected) 2019-01-26 09:13:00,790 INFO spawned: 'celeryd-worker' with pid 25705 2019-01-26 09:13:00,791 INFO exited: celeryd-beat (exit status 1; not expected) 2019-01-26 09:13:01,915 INFO exited: celeryd-worker (exit status 1; not expected) … -
Problem in saving extended User Model. type object 'UserProfile' has no attribute 'USERNAME_FIELD'?
I am trying to create a model UserProfile by extending it from Django's built in User model. After filling out the form the data should be saved in UserProfile model. It's just not happening Initially, the data was only saved in User model but not in UserProfile model. I applied some recommended solutions from the web but now I cannot even fill up the form. On prompting to/register, I get an error saying, type object 'UserProfile' has no attribute 'USERNAME_FIELD' #models.py from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField( max_length=254) country = models.CharField( max_length=50) #forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import UserProfile class RegistrationForm(UserCreationForm): class Meta: model = UserProfile fields = ['email', 'country'] #views.py from django.shortcuts import render,redirect from django.http import HttpResponse from .forms import RegistrationForm from .models import UserProfile from django.contrib.auth.models import User def home(request): return render(request , 'guide/index.html') def register(request): if request.method=='POST': form = RegistrationForm(request.POST) if form.is_valid(): u= form.save(commit=False) u.user = request.user u.save() return redirect('home') else: form=RegistrationForm() return render(request, 'guide/register.html', {'form':form}) I want the code to run and save the data to UserProfile model, but the page says that UserProfile … -
How to link fields in two tables in django==2.1? (NOT foreign key)
I have created two models Event and Student. I then created another table EventParticipants with one field being a foreign key of the Event table (containing the event name). I now want another field in the EventParticipants table that is updated with the details of the student from the table Student when he clicks on a button to participate in an event. How can I make such a field? The nodels: from django.db import models from django.urls import reverse from students.models import Student class EventType(models.Model): type_of_event = models.CharField(max_length=100, unique=True) def __str__(self): return self.type_of_event def get_absolute_url(self): return reverse('dashboard') class Event(models.Model): type_of_event = models.ForeignKey(EventType, on_delete=models.CASCADE) name = models.CharField(max_length=100) description = models.TextField() event_date = models.DateField() venue = models.CharField(max_length=200) entry_fee = models.FloatField() def __str__(self): return self.name def get_absolute_url(self): return reverse('dashboard') class EventParticipants(models.Model): event_name = models.ForeignKey(Event, on_delete=models.CASCADE) The Student model: class Student(AbstractUser): email = models.EmailField(unique=True) roll = models.CharField(max_length=200, blank=False) contact_no = models.DecimalField( max_digits=10, decimal_places=0, blank=False, unique=True) objects = UserManager() -
How to build a list of objects returned from querysets in Django
I am trying to return a list of objects which are returned in queryset for each id. managers = Managers.objects.filter(project_id=project.id).extra(order_by=('id',)) manager_ids = [manager.id for manager in managers] --> ['0', '1', '2'] members = Staff.objects.filter(manager_id=manager_ids[0]).extra(order_by=('id',)) ... return render( 'project': project, 'managers': managers, 'members': members <!-- this has to be a list of Member objects The Managers queryset returns a list of managers related to the project and the Staff queryset will return the team members to each manager. The team members to each member has to be passed to render. How can I implement this? -
Saving file field as None but reflects empty string in the database
I'm trying to submit a form with a file field. There are instances when the file is not yet available so the user will have to submit the form without the file first. My field now looks like this file_attachment_pdf = models.FileField(blank= True,null = True, unique=True) I'm able to save 1 record with blank fields. When adding the 2nd record with blank file upload, it doesn't work anymore since there is an existing record with the file value. Upon checking, it's an empty string. So I tried to override the clean function in models.py def clean(self): if not self.file_attachment_doc: print('doc is blank, will tag as Null') self.file_attachment_doc = None But for some reason, when I check in the DB it still stores as an empty string. (I'm using DB Browser for SQLite, it says the field of data is Text with 0 chars) When I try to submit, here is the error that is returned to me File with this File attachment pdf already exists. If this question was already asked and answered before, please do let me know. -
How to reduces number of sqls generating Django restful services
I need help to improve API performance. Below is my approach also i have tried to do other combination of fields with select_related or prefetch_related but still i am getting like 400sqls. model.py class VisVisits(models.Model): visit_id = models.IntegerField(primary_key=True) null=True) class Meta: managed = False db_table = 'vis_visits' def __str__(self): return str(self.visit_id) class VisVisitData(models.Model): vdata_id = models.IntegerField(primary_key=True) app_local_id = models.IntegerField(blank=True, null=True) visit = models.ForeignKey('VisVisits', models.DO_NOTHING, blank=True, null=True, related_name='data') class Meta: managed = False db_table = 'vis_visit_data' def __str__(self): return str(self.vdata_id) Serializer class VisVisitDataSerializer(serializers.ModelSerializer): class Meta: model = VisVisitData field = '__all__' class VisVisitsSerializer(serializers.ModelSerializer): data = VisVisitDataSerializer(many=True) class Meta: model = VisVisits fields = ('visit_id','data') views.py visit_data = VisVisits.objects.filter(is_valid=1,user_id=u).prefetch_related('school_program__school') visit_data_serializer = VisVisitsSerializer(visit_data,context={'request':request},many=True)