Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the cycle for Django's single Function Based Views(FBV) handling both GET and POST requests for this code?
I have been trying to get my head around the views and web requests but, couldn't understand how the below code works internally and couldn't figure out how the cycle of request-response works for this code. def todos_add(request): form = TodoForm(request.POST or None) #This is Django's in-built Form instance if form.is_valid(): form.save() return redirect('/') #redirects to the homepage context = {"form" : form} return render(request, "main/todos_create.html", context) todos_create.html contains the code for displaying the forms and submitting the data. If the form is valid then it stores it in the database and redirects to the homepage. Any help or link to the references is appreciated. Thanks. -
Filter the parent model instances based on an attribute of the associated model in Django
I am trying to get the Users of a particular city in the userprofile model. My code is as below: models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=250, default='Bengaluru', blank=False, null=False) views.py def home(request): users = User.objects.filter(is_staff=False).prefetch_related( Prefetch('userprofile', queryset = UserProfile.objects.filter(city='Mumbai') ) ) context = { 'users': users } return render(request, 'users/home.html', context) But in the above code, users object contains all the users but the userprofiles only where the city is Mumbai. What I want is do get only the users whose userprofile city is Mumbai. Not all the users. How can I do that? What am I doing wrong here? -
How to clean optional Django Form fields
I have a Django search form with an optional fields. If the field is used, it should be validated in clean_{field_name}. However I keep getting '>' not supported between instances of 'NoneType' and 'datetime.date' Error when the field is left empty. When I do a Request URL:http://localhost:8000/dockets/p_CentralGrocers/ (so no query parameters are passed at all), the cleaned_data parameter still has a blank item for the field name, which leads to a datetime comparison with a blank field which causes the error. What is the best way to handle optional fields in the cleaning process? 1 from django import forms 2 from django.core.exceptions import ValidationError 3 from django.utils.translation import ugettext_lazy as _ 4 import datetime 5 6 class SearchDocketForm(forms.Form): 7 8 from_date = forms.DateField(help_text="Enter start date for search", required=False) 9 to_date = forms.DateField(help_text="Enter to date for search", required=False) 10 11 def clean_from_date(self): 12 data = self.cleaned_data['from_date'] 13 if not data return '' 14 15 # check if date is in the past 16 if data > datetime.date.today(): 17 raise ValidationError(_('Invalid date - from date in the future')) 18 return data -
Django user profile implementation - A foriegn key based profile or inheritance based profile?
I have customized user from AbstractBaseUser. Following are types of users we can have: 1)B2C user - They will have to upload a government authorized id proof. 2)B2B user - They will have to upload company registration details, tax identification details. 3)Employee user - Identification documents, tax identification details, bank account details. 4)Partner user - They can be individual, company or employee. They have to upload government id proof(if individual) company registration details(if company). Tax identification details and bank account details. B2C and B2B user too can become partner. I am thinking about which approach should I take to implement these user profiles. If I take foreign key approach, then I will need a usertype or userrole field in my User model, and different table for each type of user. If I take the inheritance approach, then I will be having different table for each user type and all User model fields will be there in each of these tables. 1) What are the pros and cons for each of these approach? 2) User authentication is done using Custom User model. Would it require a change in authentication system? I think it should not, but I am not sure if … -
Graphene_django Mutatation
I'm trying to make a mutation of user model via graphql (graphene_django). Here is a code sample. class UserMutation(graphene.Mutation): class Arguments: email = graphene.String(required=True) name = graphene.String(required=True) age = graphene.String(required=True) user = graphene.Field(UserType) def mutate(self, info, email, name, age): ok = True user = User.objects.get(pk=id) user.email = email user.name = name user.age = age user.save() return UserMutation(ok=ok, user=user) class Mutation(graphene.ObjectType): create_user = UserMutation.Field() So, the problem is it doesn't work. When I try to make a mutation: mutation CreateUser($email: String!, $name: String!, $age: String!) { createUser(email: $email, name: $name, age: $age) { email name age } } It returns me an error: { "message": "Unknown argument \"email\" on field \"createUser\" of type \"Mutation\".", "locations": [ { "line": 33, "column": 14 } ] } But I specified arguments in mutate function. Does somebody know what I'm doing wrong? Thanks. -
Is it possible to write Python code in a Django field?
I'm beginning to use Django to create a site. Following the tutorials, i created a little app that allow to create questions. I would like to create maths questions with Sympy which use Python variables. The presentation is not a problem because i'm using mathjax. More precisely, i would like to be able to do something like that in a question/answer field : a = random.randint(1,9) f = x**a F = integrate(f,x) print(fr'''$f:x\mapsto {f}.$''') I think i would then be able to compare an answer with what i expect by a comparaison with sympy. Is there a way to do that ? -
How can I integrate sphinx properly with django [closed]
I'm new to sphinx and I want to integrate this one in my django project. I can easily deal with single python file but i want to integrate this one with django project. I tried some of the solutions found on google search result, but unfortunately none of works for me. anyway here is my directory structure. enter image description here -
How to get the user while Logout In django
I'm trying to get the user that logout from django and pass that as argyment to an external python script. Here is my logout view: def logoutUser(request): user = request.user exec = run([sys.executable,'scriptlogout.py', user], shell=False, stdout=PIPE) logout(request) return redirect('beesy:Login') But that dosen't work and i coudldn't retreive the user clicking on logout Thanks for helping me -
With Django @csrf_exempt, request.session is always empty
I am stuck in django and would really appreciate it if someone could help me. I need to have an entry point for a 3rd party API. So I created a view and decorated it with @csrf_exempt Now the problem is I am not able to access any session variables I set before. ppConfirmPaymentProcess is another function that processes the POST data sent by this 3rd party API. Everything is working fine, csrf_exempt is also working fine but I can't do request.session["foo"] with this request. Can someone please help? @csrf_exempt def ppConfirmPayment(request): print(request.session, "=======================================") for key, value in request.session.items(): print('{} => {}'.format(key, value)) return ppConfirmPaymentProcess(request) -
How to fix noreversematch for " '...t' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ...." from an included html file
this is the urlpattern url(r'^(?P\d+)$', views.add_product, name='cart') from my function view, I rendered the template 'cart.html' code for 'cart.html' are given below {% extends 'base.html' %} {% block content %} {% include 'cart/cards.html' %} {% for cart in carts %} {% include 'cart/cards.html' with CART=cart %} {% endfor %} {% endblock content %} In the template 'cart.html' I used an include tag to include an html file 'cart/cards.html' code for 'cart/cards.html' are given below <div class="container"> <div class="row bg-primary" style="border-radius: 10px;"> <div class="col-lg-4"> {% include 'products/cards.html' with product=CART.products %} #### included another html file </div> <div class="col-lg-4"> <h3 style="color:#451e75">{{ CART.user }}</h3> </div> <div class="col-lg-4"> <h3 style="color:#451e75">{{ CART.product_quantity }}</h3> </div> </div> {% if not CART %} <div class="row bg-primar"> <div class="col-lg-4"> <h3>Product</h3> </div> <div class="col-lg-4"> <h3>title</h3> </div> <div class="col-lg-4"> <h3>quantity</h3> </div> </div> {% endif %} </div> again inside 'cart/cards.html' in included another html file 'products/card.html' <a href="{% url 'cart' id=product.id %}">gfhfgh</a> Now, my problem is:- I am getting an error: Reverse for 'cart' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['cart/(?P\d+)$'] Error during template rendering In template /root/Desktop/Projects/e_commerce_2_1/templates/products/cards.html, error at line 1 Reverse for 'cart' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['cart/(?P\d+)$'] 1.<a href="{% … -
Django retrieve get_foo_value within values_list and annotate query
I Have Written A Query that returns (rating, count) result = list(Film.objects.values_list('rating').annotate(count=Count('rating'))) rating is a choice field of rating = ( ("5","Excellent"), ("4","Good"), ("3","Average"), ("2","Bad"), ("1","Very Bad"), ) I currently get the result like this [(5, 10), (4,8), (3,7), (2,1), (1,4)] I wish to get the pairs like this [("Excellent",10),("Good",8)...] Is there anything I can do within the Query to get it ? Whats the best method to get the desired result ? Something like get_foo_display within this one. -
how to make django default user when using formsets
I have this model that i want to make the create_by default for current user class order(models.Model): name = models.CharField(max_length=300, null=True,) description = models.CharField(max_length=300, null=True,blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) created_by = models.CharField(max_length=200,default=None,null=True,blank=True) in Django models I cant use request.user I tried in views.py but i cant do it since i am using modelformsets I tried this def create_order(request): orderformset = modelformset_factory(order, form=orderForm) queryset = order.objects.none() user = request.user formset = orderformset(request.POST or None,queryset=queryset) if formset.is_valid(): created=formset.save(commit=False) created.User = request.user created.save() return redirect('home') How i can give default user to this orders using modelformsets -
Adding a class 'is-invalid' to input form in Django
How to add bootstrap class is-invalid to django input forms (Only if the form/field is not correctly completed). My forms.py class BasicUserDataForm(forms.Form): error_css_class = 'is-invalid' user_name = forms.CharField(max_length=20, widget=forms.TextInput(attrs={'placeholder': 'Username', 'class': 'form-control'})) My templates.html <div class="form-group col-md-6"> <!-- Label --> <label for="id_user_name">Username*</label> <div class="input-group mb-0"> <div class="input-group-prepend"> <div class="input-group-text">@</div> </div> {{ form.user_name }} </div> {% if form.user_name.errors|striptags %}<small class="text-danger"><b>{{ form.user_name.errors|striptags }}</b></small>{% endif %} </div> I try: 1.) class BasicUserDataForm(forms.Form): user_name = forms.CharField(max_length=20, widget=forms.TextInput(attrs={'placeholder': 'Username', 'class': 'form-control'})) 2.) class BasicUserDataForm(forms.Form): user_name = forms.CharField(max_length=20, widget=forms.TextInput(attrs={'placeholder': 'Username', 'class': 'form-control {% if form.user_name.errors %}is-invalid{% endif %}'})) 3.) Acoording with documentation class BasicUserDataForm(forms.Form): error_css_class = 'is-invalid' [...] 4.) .error input, .error select { border: 2px red solid; } It still doesn't give any results. I would like to get the effect that gives: user_name = forms.CharField(max_length=20, widget=forms.TextInput(attrs={'placeholder': 'Username', 'class': 'form-control is-invalid'})) -
Django Celery Beat - How to pass arguments using the Database Scheduler?
I need assistant in terms of how to pass function arguments in the DatabaseScheduler in Django Admin for the Django Celery Beat package https://django-celery-beat.readthedocs.io/en/latest/. I've already read Django Celery Beat - How to pass arguments using the DatabaseScheduler and it did not help me in solving issue. I want to execute the following function using Django Celery Beat: @shared_task def rename_widget(widget_id, name): sleep(20) w = Widget.objects.get(id=widget_id) w.name = name w.save() I have set a periodic task in Django Admin, I am using the task(registered) celapp.tasks.rename_widget, have Cronschedule set to run, and in the arguments section I have tried [2, "change to this text"] and after reading above stackoverflow link I tried ["2", "change to this text"]. Task runs on celery server, but never finishes and widget is never renamed to "change to this text". What am I doing wrong? And at bottom -
How to change the id format of field in a model?
For example I have a field of 'customer' IDs going from 1,2,3,4,5 etc However I want to change the format to 010101, 010102,010103, 010104, 010105. As it display on my database and templates. Is there any way of doing that? -
How to limit the choices of ManyToManyFields to a particular Foreign key only, in Django Model
class Bank(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) class Branch(models.Model): bank = models.ForeignKey(Bank, on_delete=models.CASCADE) class ATM(models.Model): bank = models.ForeignKey(Bank, on_delete=models.CASCADE) branch = models.ManyToManyField( Branch) How can I select the multiple branches while adding atm for the particular Bank only? (I know one ATM can't have two branches but I would like to know how can we select the branches for particular bank only?) -
Create model with its associations in python shell in Django
I am trying to create multiple User objects in the shell in Django. It is associated with UserProfile. Now I have a default value for the city column in Userprofile model. But I would like to pass another value to it while creating. I am creating the models from a for loop like this: 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) city = models.CharField(max_length=250, default='Bengaluru', blank=False, null=False) In shell from django.contrib.auth.models import User from my_app.models import UserProfile for i in range(1, 21): User.objects.create(username=f'User_{i}') In the above line I want to give the value of city parameter of the userprofile instance that will be created as soon as the user is created. How can I give that inside the for loop? -
Using the same form for adding new records and editing existing ones in Django with URL parameter
I'd like to use the same form for both adding new records to the database and editing existing ones. The id of the record to be edited is passed via the URL (is this how I should do it?): urlpatterns = [ path('add-or-edit/<int:id>/', add-or-edit_view, name='edit'), path('add-or-edit/', add-or-edit_view, name='create'), [...] views.py: def add-or-edit_view(request, id): if id is not there: # pseudocode, of course :) form = MyForm(request.POST or None) elif request.method == "POST": obj = get_object_or_404(Event, id=id) form = MyForm(request.POST or None, instance=obj) if form.is_valid(): form.save() context = { 'form':form } return render(request, "templates/add-or-edit.html", context) I other words: if I go to add-or-edit/ then I want my empty form, if I go to add-or-edit/1 I want the form populated with data from the object with id 1. I am already doing this with two different views, one edit_view(request, id) and the other add-or-edit_view(request), which of course is not DRY. -
Django Class view based forms: how to add specific fields validation?
I have used Class view based forms with a nested inlineformset. I don't find in Django docs how to add specific/customized fields validation. For example, how can I add validation for uti_mai field of Application that control email format? Usually, I do this in form I pass in my view function... models.py class Utilisateur(SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE uti_ide = models.AutoField(primary_key = True) pro_ide = models.ForeignKey(Projet, on_delete = models.CASCADE) # related project uti_nom = models.CharField("Nom", max_length=20) uti_pre = models.CharField("Prénom", max_length=20) uti_mai = models.CharField("Email", max_length=40) uti_sit = models.CharField("Equipe", max_length=20, null=True, blank=True) uti_pro = models.CharField("Fonction/profil", max_length=200, null=True, blank=True) uti_dem_dat = models.DateTimeField("Date demande",auto_now_add=True, null=True, blank=True) uti_val = models.IntegerField("Demande validée ?", null=True, blank=True) uti_val_dat = models.DateTimeField("Date validation",null=True, blank=True) uti_log = models.CharField("Log utilisateur", max_length=20, null=True, blank=True) uti_dat = models.DateTimeField("Date log",auto_now_add=True, null=True, blank=True) log = HistoricalRecords() class Meta: db_table = 'tbl_uti' verbose_name_plural = 'Utilisateurs' ordering = ['uti_ide'] views.py: class UtilisateurCreateView(CreateView): model = Utilisateur fields = ['uti_nom','uti_pre','uti_mai','uti_sit','uti_pro'] def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data["utilisateur"] = self.request.user.username # nom de l'utilisateur connecté data["projet"] = get_object_or_404(Projet, pro_ide = self.request.GET['projet']) data["application"] = ApplicationFormset(self.request.POST) data["user_profil"] = self.request.session.get('user_profil') else: data["application"] = ApplicationFormset() return data def form_valid(self, form): context = self.get_context_data() application = context["application"] user_profil = context["user_profil"] self.object = form.save(commit=False) self.object.pro_ide = … -
Cancel button not working in html, Django 3
I'm using Django 3.0.6, and when i try to implement the return function, the cancel button also deletes my file. This is my html code <a href="{% url 'tools:delete_csv' i.id %}" onclick="return confirm('Are you sure you want to delete?')"> <button type="button" class="btn btn-danger btn-sm" title="Delete"> <i class="fa fa-trash"></i> </button> </a> -
POST with Django Rest Framework and DataTables returns a 400 bad request
when I use the browsable API from DRF, I can POST and DELETE. Attempting to replicate this via my tradingbook.html (w/DataTables) delivers for (new/edit/delete): Bad Request: /api/trading/ with "POST /api/trading/?format=datatables&keep=id HTTP/1.1" 400 274. The web inspector delivers {"data": { "trader": [ "This field is required." and this holds true for every field. Django version 3.0.4, DRF 3.11, Python3.7.6 Datatables Editor, and DRF-datatables editor. I have spent so much time on it that I'll ever confess. class TradingBook(models.Model): trader = models.TextField(max_length=10) status = models.TextField(max_length=10) price = models.TextField(max_length=10) volume = models.TextField(max_length=10) index = models.TextField(max_length=10) cpty = models.TextField(max_length=10) class Meta: ordering = ['trader'] def __str__(self): return self.trader serialisers.py class TradingBookSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) class Meta: model = TradingBook fields = "__all__" DT_RowId = serializers.SerializerMethodField() def get_DT_RowId(self, TradingBook): return 'row_%d' % TradingBook.pk views.py @csrf_exempt#@csrf_protect#@ensure_csrf_cookie def tradingsomething(request): return render(request, 'trading/tradingbook.html') @method_decorator(login_required, name="dispatch") class TradingBookViewSet(viewsets.ModelViewSet): queryset = TradingBook.objects.all()#.order_by('trader') permission_classes = [permissions.AllowAny] serializer_class = TradingBookSerializer urls.py path('trading', trading_views.tradingsomething), path('trading/<int:pk>/', trading_views.TradingBookViewSet, name='TradingBook'), path('api/', include(router.urls)), urlpatterns += router.urls and my tradingbook.html <script> $(document).ready(function() { function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); // … -
How to serialize the annotate and foreign key in DRF
I have 2 Django models that consider the below sample models. class Status(models.Model): status = models.CharField(max_length=50) class Resolution(models.Model): resolution_status = models.ForiegnKey(Status) resolver_name = models.CharField(max_length="50") So what I want to do is get the count of distinct status from the Resolution model. so for that, I've written an ORM which looks like this. status_count = Resolution.objects.values('resolution_status').annotate(status_count=Count( 'ci_status')) so from the above ORM, I will fetch the distinct resolution_status with its count from the Resolution model. so the main question is here is now I want to serialize the queryset into JSON. so for that, I've written the serializer class like this. class CountSerializer(serializers.ModelSerializer): status_count = serializers.IntegerField() resolution_status = serializers.CharField(source="resolution_status") class Meta: model = Resolution fields = ["resolution_status", "status_count"] From the above serializer class, I'm getting the JSON output like this Instead of showing the ID of that particular status, I want to display the name. for example it should look like this. [ { resolution_status: "Status Name", count: 100 }, { resolution_status: "Status Name 1", count: 120 }, { resolution_status: "Status Name 3", count: 80 }, { resolution_status: "Status Name 4", count: 10 } ] I googled a lot and went through a few StackOverflow QA but couldn't able to figure … -
Possible to show only traceback in Django error response?
When an error occurs in Django (specifically an HTTP 500 "Internal Server Error"), I get an error dump that looks like the following, which I've truncated for brevity: ValueError at <request_url> invalid literal for int() with base 10: 'jbishop' Request Method: POST Request URL: <request_url> Django Version: 3.0.6 Python Executable: <path_to_python> Python Version: 3.8.2 Python Path: [ ... several lines of output ...] Server time: Fri, 15 May 2020 14:11:14 +0000 Installed Applications: ['base.apps.BaseConfig', 'web.apps.WebConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['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', 'qinspect.middleware.QueryInspectMiddleware'] Traceback (most recent call last): File "<some_path_here>", line 34, in inner response = get_response(request) ... continues ... I never care about all those random variables shown immediately below the first two lines that indicate what error occurred. I always care about the traceback, so I can pinpoint where in my code the problem is occurring. Does Django provide capability to modify the error response in some way so I can show just the error and the traceback? It drives me crazy that I have to scroll many lines down to get to what's important. -
Some dropdown links not working in Django
I've have a one page website coded in Django with a menu and anchor links. I had to modify the menu to add some dropdowns, which normally should direct to some new pages, Products and Team, but they don't. If I'm typing http://127.0.0.1:8000/products/ or http://127.0.0.1:8000/team/, pages are loading properly. How should I write the dropdown links to go to specified pages? The reason might be something like {'page': 'privacy_policy'}) as I've seen in def privacy_policy(request): ? Please let me know how should I fix this. Thank you! Here's the menu from base.html <li class="serviceslink dropdown dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <a class="" href="{% if page != 'home' %}/{% endif %}#services">Services <span class="caret"></span></a> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> <li><a class="" href="{% if page != 'home' %}/{% endif %}#products">Products</a></li> </ul> </li> <li class="aboutlink dropdown dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <a class="" href="{% if page != 'home' %}/{% endif %}#about">About Us <span class="caret"></span></a> <ul class="dropdown-menu" aria-labelledby="dropdownMenu2"> <li><a class="" href="{% if page != 'home' %}/{% endif %}#products">Team</a></li> </ul> </li> <li class="clients"><a class="" href="{% if page != 'home' %}/{% endif %}#clients">Customers</a></li> My urls.py contains: url(r'^team/$', views.team, name='team'), url(r'^products/$', views.products, name='products'), url(r'^$', views.index, name='index'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The views.py contains: def team(request): obj = Team.objects.all().order_by('?') … -
Django admin list filter on reverse relationship
I have two django models: class Order(models.Model): date = models.DateTimeField() customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='orders') shipping_address = models.CharField(max_length=200) phone_number = models.CharField(max_length=9) comment = models.CharField(max_length=100, blank=True, null=True) class OrderStatus(models.Model): STATUS_ACCEPTED = 1 STATUS_PROCESSING = 2 STATUS_DELIVERING = 3 STATUS_COMPLETED = 4 CODE_CHOICES = ( (STATUS_ACCEPTED, 'accepted'), (STATUS_PROCESSING, 'processing'), (STATUS_DELIVERING, 'delivering'), (STATUS_COMPLETED, 'completed'), ) date_created = models.DateTimeField(auto_now_add=True) code = models.PositiveSmallIntegerField(choices=CODE_CHOICES) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='status_list') Normally if I wanted to get all the orders with 'accepted' status I could write Order.objects.filter(orderstatus__code=1). But how can I make django admin to create OrderStatus list filter? I have googled a lot and found only one answer here on stackoverflow, which claims simply adding reverse model ('orderstatus' in my case) to list_filter tuple should work, but I get an error message: The value of 'list_filter[1]' refers to 'orderstatus', which does not refer to a Field. What am I doing wrong?