Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Relationship between 2 models in Django
I have two models- Order and Expense. The expense is a crud list respective to the particular Order. How can I make such a relationship between these two models? models.py - Order class Order(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="order",blank=True,null=True) client_name = models.CharField(max_length=100) event_name = models.CharField(max_length=100) contact = models.CharField(max_length=15) event_date = models.DateField(auto_now_add=False,auto_now=False) expenses = models.IntegerField(default=0,null=True,blank=True) Models.py - Expense class ProjectExpense(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="project_expense",null=True,blank=True) order_id = models.IntegerField(default='0') exp = models.CharField(max_length=100) exp_desc = models.TextField(null=True,blank=True) amount = models.IntegerField(default='0') def __str__(self): return self.exp Thoughts - I tried assigning the field Order ID with the current Order. But how will I able to pass the current Order.I'm really stuck in here, Thanks in advance! -
How to control Django model form
Assume that I have this model. class Text(models.Model): name = models.TextField(default="") changed_name = models.TextField(default="") data = JSONField(default=dict) Now I want use django model form to: 1. create input in template, only input for name and file. 2. validate file, extract it (inside is json) and send to model field, best if content can be validate separately for model field, like def clean_ method. 3. validate name, then process it and send to two fields, one original and one after changes. Now I did this all in view with custom template and only send corrected post to form, but I like to move all of it to form if it can be done. -
HTML/CSS input field shrinking
Hi I'm trying to develop a website for an online store using Django. In my checkout form, input fields like address,country, zipcode, phone are shrinking. However, the field for state (which is a field with choices is not shrinking). Even in my login and register forms, the input fields are shrinking. Can anyone please tell me why this is happening? My checkout.html: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> <!-- Custom styles for this template --> <link href="./css/form-validation.css" rel="stylesheet" /> </head> <div class="container"> <div class="row"> <body class="bg-white"> <div class="container"> <div class="py-5 text-center"> <img class="d-block mx-auto mb-4" src="https://getbootstrap.com/assets/brand/bootstrap-solid.svg" alt="" width="" height="" /> <h2>Checkout</h2> </div> <div class="row"> <div class="col-md-4 order-md-2 mb-4"> <h4 class="d-flex justify-content-between align-items-center mb-3"> <span class="text-muted">Your cart</span> <span class="badge badge-secondary badge-pill">{{ request.session.items_total }}</span> </h4> <ul class="list-group mb-3"> {% for item in cart.cartitem_set.all %} <li class="list-group-item d-flex justify-content-between lh-condensed" > <div> <h6 class="my-0">{{ item.product.name }}</h6> <small class="text-muted">Brief description</small> </div> <span class="text-muted">${{ item.product.price }}</span> </li> {% endfor %} <li class="list-group-item d-flex justify-content-between bg-light"> <div class="text-success"> <h6 class="my-0">Promo code</h6> … -
How to add foreign key to a serializer manually in django rest framework?
while creating a branch, I want to add the id of a company(foreign key) according to the company of requested user. Basically I want to add company id at serializer level only. Here is my create function of branchViewset: def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, context=context) if serializer.is_valid(raise_exception=True): serializer.save(company=request.user.owner) and here is my serializer: class CreateBranchSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all()) def validate(self, attrs): try: user = self.context['request'].user except: raise CustomAPIException(status_code=status.HTTP_401_UNAUTHORIZED, error_code='1006') return attrs But while creating branch I get the error: company: field is required How can i solve this? -
Django admin, how to restrict a user to insert records only within his country?
I have this Model title= country = models.CharField(max_length=25) country = models.ForeignKey(Country) city = models.ForeignKey(City) user = country = models.ForeignKey(User) Using the (Add Case +)page in the default Django admin, is there anyway to customise the country and city dropdown lists options depending on the current user? For example: if the current logged in user is from USA, then the country dropdown list will show only one option (USA), and the city dropdown list will show only the cities in USA.Then, this user would be allowed only to add cases related to his/her country. -
Recommended way to provide configuration files to Docker containers
I am moving our web application to docker-compose deployment (Django, DRF, AngularJS). Docker looks solid now and things are going well. I want to: confirm with you that I am following best practices regarding application configuration files know if "volume files" are actually bind mounts, which are not recommended I've managed to use environment variables and docker-compose secrets read from the Django settings.py file and it works. The downside is that environment variables are limited to simple strings and can pose some escape challenges when sending Python lists, dictionaries etc. We also have to define and maintain a lot of environment variables since our web app is installed in many place and it's highly configurable. On frontend side (AngularJS) we have two constants.js files and the nginx conf. I've used a CMD ["/start.sh"] in Dockerfile and have some sed commands. But this looks really hackish and it also means that we have to define and maintain quite a few environment variables. Are Docker volumes a good idea for to use for these configuration files? Does such thing as "volume file" actually exist (briefly mentioned here) or is it actually a bind mount? And bind mounts are less recommendable since they … -
How can I have statistics in django admin panel on User with date filter on related field?
Related model class AbstractTask(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) issued_at = models.DateTimeField(auto_now_add=True) Problem I need to show some User statistics per days the admin panel. Lets say just number of tasks issued for users, being able to filter it by issue date (how many were issued yesterday, the day before yesterday, etc). How I do it I use User proxy models to register ModelAdmin for different statistics pages. I use slightly modified (changed date ranges) DateFieldListFilter on task__issued_at field: list_filter = [ ('task__issued_at', DateFieldListFilter), 'username', ] Filters don't work Filters don't work because they end up generating query similar to this: (queryset = User.objects .annotate( # Different statistics. num_tasks=Count('task'), ) .filter( # DateFieldListFilter. task__issued_at__gte='2020-01-01', task__issued_at__lt='2020-01-02, ) .values('id', 'num_tasks') ) SQL: SELECT "auth_user"."id", COUNT("task"."id") AS "num_tasks" FROM "auth_user" LEFT OUTER JOIN "task" ON ("auth_user"."id" = "task"."user_id") INNER JOIN "task" T3 ON ("auth_user"."id" = T3."user_id") WHERE (T3."issued_at" >= 2020-01-01 00:00:00+03:00 AND T3."issued_at" < 2020-01-02 00:00:00+03:00) GROUP BY "auth_user"."id" The problem is that filter adds second join on table "task" when I need just one. Forcing first inner join by adding .filter(task__isnull=False) doesn't help. It just keeps performing two identical inner joins. It is the same behavior in django 2 and 3. Can It … -
Test POST request for multipart/form-data in Pyresttest
I need to test API for multipart/form-data using pyresttest. I have tried https://github.com/svanoort/pyresttest/issues/158 for my API but it's not working. I have created formdata.txt: ----WebKitFormBoundary7MA4YWxkTrZu0gW Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW ----WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="data"; filename="/D:/File-Upload/movie.json" Content-Type: application/json (data) ----WebKitFormBoundary7MA4YWxkTrZu0gW and my yaml file look like: - test: - group: "Group test" - name: "Test name" - url: "/post_movie/" - method: "POST" - headers: {'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'} - body: {'file':'D:/File-Upload/formdata.txt'} - expected_status: [200] but i'm getting error: UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position 156-157: truncated\UXXXXXXXX escape How can I test multipart/form-data in pyresttest ? -
Django ModelForm - Using ForeignKey for Choices
I'm attempting to build out a rather large "Patient Onboarding" form using ModelForms. I'm having trouble getting the choices within the foreign keys to appear in the admin area or to the rendered form without manually adding them to the Postgres database. There has got to be a more efficient way to be doing this...thanks in advance! #models.py from django.db import models from django.forms import ModelForm from django import forms class Patient(models.Model): first_name = models.CharField(max_length=30, verbose_name='First Name', blank=False) middle_name = models.CharField(max_length=30, verbose_name='Middle Name', blank=False) last_name = models.CharField(max_length=30, verbose_name='Last Name', blank=False) gender = models.ForeignKey('GenderChoices', on_delete=models.CASCADE, verbose_name='Gender', blank=False) date_of_birth = models.DateField(verbose_name='Date of Birth', blank=False) medications = models.ForeignKey('MedicationsYesNo', on_delete=models.CASCADE, verbose_name='Do you currently take any medications?', blank=False) class MedicationsYesNo(models.Model): medications_yes_no = models.CharField( max_length=100, choices = [ ('Yes', 'Yes'), ('No', 'No') ] ) def __str__(self): return self.medications_yes_no class OnboardingForm(ModelForm): class Meta: model = Patient fields = '__all__' -
How do I parse more than 2 argument in my URL Path function in Django
Please Assist me. I have this in my url Pattern of my blog app app_name = 'webpages' path('articles/<int:pk>/<slug:slug>', views.blog_detail, name='articles_detail'), How do I code this in the template? I have tried this <a href="{% url 'webpages:articles_detail' post.pk post.slug %}">{{post.title}}</a> I was able to do this for just one argument. but ran into trouble doing for two arguments. -
passing query to html page as linkes ? django / postgresql
I am trying to pass query to HTML page . I tried (request / loader ) to pass the query but it gives No unit are available but there is 3 unit in the database views.pay. from django.shortcuts import render from django.http import HttpResponse from .models import uints from django.template import loader def index(request): latest_uint = uints.objects.order_by('-listing_date')[:5] context = {'latest_unit' : latest_uint ,} return render(request, 'realstate/index.html', context) models.py. from django.db import models import datetime from django.utils import timezone class uints(models.Model): uint_text = models.CharField(max_length = 200) num_of_room = models.IntegerField(default=2) num_of_bathroom = models.IntegerField( default=1) listing_date = models.DateTimeField('listing date') HTML page. {% if latest_uint %} <ul> {% for uint in latest_uint %} <li><a href="/realstate/{{ uint.id }}/">{{ uint.uint_text }}</a></li> {% endfor %} </ul> {% else %} <p>No unit are available.</p> {% endif %} -
Serving Django with gunicorn after new git pull
After updating Django and testing it on my local machine, I am unable to see my updates on my production server after using git pull origin. I have checked to make sure my production server is on the last commit, which was pushed by my local branch. To restart my server I have tried the following: sudo systemctl daemon-reload sudo systemctl restart gunicorn.socket gunicorn.service sudo systemctl restart gunicorn sudo nginx -t && sudo systemctl restart nginx And none have worked. I have also tried removing the --pycache-- folder in my django app folder and checking: sudo systemctl status gunicron Would much appreciate any help you have. -
django-webpush: not able to find user in the request object
I am using DRF, and have set up the auth middleware using JWT backend. I used a package safwanrahman/django-webpush which enable sending notifications, based on VAPID. I got the package working with all setup in place, The API to save information is called and executed successfully. The only problem right now is that the user information is not saved. My findings say that this is because I am using DRF. The way DRF injects a user into the request is may be different from how traditional Django does. And hence the request.user in the view function of the package in not found. @require_POST @csrf_exempt def save_info(request): ... # the request.user mostly does not exist web_push_form.save_or_delete( subscription=subscription, user=request.user, status_type=status_type, group_name=group_name) ... Right now i am thinking to make a clone of the repo and make changes directly in order to debug and find the exact issue/solution. Would that work? -
Prevent webpage from scrolling to the top when submitting a form
I have created a form that submits via javascript but each time I submit the form the webpage scrolls to the top. How do I stop that from happening?. I have tried preventDefault() but that stops the form from submitting all together. My form: class myform(forms.Form): columns = forms.MultipleChoiceField(required=False, label=False) def __init__(self, columnList, *args, **kwargs): self.columnList = columnList super(myform, self).__init__(*args, **kwargs) self.fields['columns'].widget = forms.SelectMultiple() self.fields['columns'].choices = self.columnList My HTML: <p> Select tables and download as excel file:</p> <form id="myform" method="POST" name="Tables_selected"> {% csrf_token %} {{ form.as_p }} <input id="mybutton" type="button" class="btn btn-info" value="Download excel" onclick="redirect()"> </form>` Javascript: <script type="text/javascript" > $(function(){ $('#id_columns').change(function(){ $('#myform').submit(); return false; }); }); function redirect() { location.href="{% url 'download_excel' %}"; } </script> I have tried this, but it prevents the form from being submitted, as well as the redirect: $(function(){ $('#id_columns').change(function(){ $('#myform').submit(function(e) { e.preventDefault(); ); }); }); -
Django pk is not working properly in anchor tag
Recently I created a model to save IeeeXtreme rank of our college and created another model with it for connecting xtreme version with its team. model.py is: class Xtreme(models.Model): version=models.IntegerField(default=9,primary\_key=True) team\_no=models.IntegerField(default=1) def \_\_str\_\_(self): return str(self.version) class Team(models.Model): version=models.ForeignKey(Xtreme,on\_delete=models.CASCADE) team\_name=models.CharField(max\_length=50) global\_rank=models.IntegerField(default=1) region\_rank=models.IntegerField(default=1) country\_rank=models.IntegerField(default=1) college\_rank=models.IntegerField(default=1) def \_\_str\_\_(self): return str(self.version) and then I created a tamplate xtreme.html to load the specific version data into template. In main index page I loaded all versions of IeeeXtreme for our college and want to connect each version with its data, so I used PrimaryKey to load it through url . url.py is: from django.contrib import admin from django.urls import path,include from . import views # from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('',views.main,name='main'), path('xtreme/<int:pk>/',views.xtreme,name='xtreme') ] views.py is: from django.shortcuts import render,get_object_or_404 from django.utils import timezone from django.http import HttpResponse from .models import * def main(request): xtreme=Xtreme.objects.all().order\_by("-version") context={ "xtreme":xtreme, } return render(request,'index.html',context) def xtreme(request,pk): xtreme=Xtreme.objects.filter(version=pk).order\_by("-version") team=Team.objects.filter(version\_\_version=pk).order\_by("college\_rank") post = get\_object\_or\_404(Xtreme, pk=pk) context={ "team":team, "xtreme":xtreme, "post":post, } return render(request,'xtreme.html',context) index.html {% load static %} <section class="sec4" id="xtreme"> <div class="container"> <div class="row"> <div class="col-sm-12"> <h1> IEEEXtreme</h1> </div> {% for j in xtreme%} <div class="col-sm-12"> <a href="{% url 'xtreme' [pk=post.pk](https://pk=post.pk)%}"><h3>IEEEXtreme {{j.version}} Rank of our college.</h3></a> </div> {% endfor %} </div> </div> … -
Creating a record in django model through a POST request
I'm pretty much new to Django and Rest Framework. So I trust you guys to help me fix my issue here. I'm on Python 2.7 and Django 1.11. My models - class Item(models.Model): title = models.CharField(max_length=140) user = models.ForeignKey(User) created_date = models.DateTimeField(auto_now_add=True) due_date = models.DateTimeField(blank=True, null=True) completed = models.BooleanField() completed_date = models.DateTimeField(blank=True, null=True) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=30, null=True, blank=True) last_name = models.CharField(max_length=30, null=True, blank=True) ... ... ... I'm trying to post a record to Item model which should get the user email from the request headers and should create the foreign key relation for that particular record. My Serializer for the Item model- class ItemSerializer(serializers.ModelSerializer): user = serializers.RelatedField(source='User',read_only=True) class Meta: model = Item fields = '__all__' My Viewset for Item model - class ItemViewset(viewsets.ModelViewSet): serializer_class = ItemSerializer queryset = Item.objects.all() def perform_create(self, serializer): print 'Im in here', self.request.user user_id = User.objects.get(email=self.request.user) serializer.save(user= user_id) I've checked few blogs and other questions on StackOverflow and reached till this point. Now when I try to post a record am getting a TypeError as below Got a `TypeError` when calling `Item.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid … -
Django 3.0.5 runserver not working, no message after executing
I downloaded Django 3.0.5 on Windows, and when I went to start a new project and attempted to use runserver, I got nothing in the command prompt. No message. Just new prompt C:\Users\\Desktop\wordcount>python3 manage.py runserver C:\Users\\Desktop\wordcount> Anyone know what's going one. -
how to check if a sqlite field is available in django
i want to make something like this, select tipe from table_name where username == user.username im using sqlite, what i have already tried is using this method Entry.objects.get(headline__exact="Cat bites dog") that i got from the django documentation, but i cant find where to put the column that i want to print, because i only want to check one column, and if that column field is equal to teacher then i want to do something with it. -
How to wirte queryset for django to get models count
Model.py class InventoryData(models.Model): AssetID = models.CharField('Asset ID', max_length=30, unique=True) SerialNumber = models.CharField('Serial Number', max_length=30, unique=True) Make = models.CharField(max_length=30, blank=True, null=True) Model = models.CharField(max_length=30, blank=True, null=True) class Meta: verbose_name = 'Inventory Data' verbose_name_plural = 'Inventory Data' def __str__(self): return self.AssetID Views.py def home(request) # ----- For Models ----- # stnd = obj.objects.filter(AssetID__startswith='ASPL-LAPT').order_by('Model').values_list('Model', flat=True).distinct() dev = obj.objects.filter(AssetID__startswith='ASPLB-DEV').order_by('Model').values_list('Model', flat=True).distinct() mac = obj.objects.filter(Make__startswith='Apple').order_by('Model').values_list('Model', flat=True).distinct() desk = obj.objects.filter(AssetID__startswith='ASPLB-DSK').order_by('Model').values_list('Model', flat=True).distinct() # ----- For Counts ----- # cnt = obj.objects.filter(Model__in=mac).distinct().count() context = {'stnd': stnd, 'dev': dev, 'mac': mac, 'desk': desk, 'cnt': cnt, } return render(request, 'App/home.html', context) this is output i am getting: in my DB i have Make as Apple, Lenovo and Model as two models [MacBook Pro 13.0", MacBook Pro 15.0", T440, T450, T540p], each model has 10 laptops, but when i count i am getting total count as 20 for Mac Book and count as 30 for Lenovo Laptops, i need count for every model as MacBook Pro 13.0" -- 10 MacBook Pro 15.0" -- 10 T440 -- 10 T450 -- 10 T540p -- 10 with below query i am getting below table, cnt = obj.objects.filter(Model__in=mac).count() please help me how to write query for table 2 Table1 Table2 -
django // How to refresh or reload inside {% include 'need_refresh_template' %}
Environment django 2.2 python 3.6 Question I attached ACE editor in my template and I'm trying to make live preview with ajax in the template. This is Ace editor template <!-- ACE editor --> <div style="width: 100%; height: 300px;"> <div id="editor"></div> </div> <!-- Preview --> <div style="width:100%; height: 300px;> {% include 'terms_include.html' %} </div> <script> var editor = ace.edit("editor"); editor.setTheme("ace/theme/twilight"); editor.session.setMode("ace/mode/css"); editor.setOptions({ enableBasicAutocompletion: true, enableSnippets: true, enableLiveAutocompletion: true }); $('#id_preview').click(function () { var css_data = editor.getValue(); $.ajaxSetup({ headers: { "X-CSRFToken": '{{csrf_token}}' } }); $.ajax({ url: '{% url 'terms_ajax_preview' %}', type: 'POST', data: { css : css_data } }) }); </script> And this is another template which is attached in the first template by include tag <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {{ contexts }} <script> {% if contexts %} alert('{{ contexts }}'); {% endif %} </script> </body> </html> views.py def terms_ajax_preview(request): if request.is_ajax(): get_text = request.POST.get('css', '') print(get_text) context = { 'contexts': get_text } return render_to_response('api/terms_include.html', context) # return render(request, 'api/terms_include.html', context) print(get_text) is working very well. However I don't have any idea how render context data and reload template inside of include tag. How should I return to display the data added to that template? -
Looping over a specific field in a django form
Learning Django by creating an eBay like bidding application. One of my models is a simple bid class that will record every user's bid for a particular listing. models.py class Bid(models.Model): bid = models.DecimalField(max_digits=10, decimal_places=2) user = models.ForeignKey(User, on_delete=models.CASCADE) listing = models.ForeignKey(Listing, on_delete=models.CASCADE) forms.py def listing_view(request, id): form = BidForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.listing_id = id # check bid is higher than starting bid or other bids or flash error message current_bid = instance.bid starting_bid = instance.listing.starting_bid query = Bid.objects.all().filter(listing=id) In forms.py, I am writing a view to validate that the bid the user entered is larger than existing bids. It's incomplete because I am stuck on creating this comparison. The easy way is to loop over the 'query' variable and do the comparison, but is there a more elegant solution? I found a solution using the all() function, something like: all(current_bid > i in my_list) But this only works for comparing against a list, not form objects Is there a way to loop over query (i.e. for each in query) and get check whether current_bid is greater than all of the 'each.bid' in 1 line? Something like this: all(current_bid > i for … -
How to add lines usning '-' in python Requests
I am working with python Requests in Django and I need a similar functionality to the 'quote_plus' module, I need my words to be joined by a '-' instead of '+'. Is there a module for that? If not then how do i do it? -
How to include description in django api for swagger
I am using django in built user api with drf and swagger. How to make display of the description of api in swagger to the right of user module api class UserViewSet(viewsets.ModelViewSet): """ description: Operations about user. --- retrieve: Return a user instance. list: Return all users. create: Create a new user. delete: Remove an existing user. partial_update: Update one or more fields on an existing user. update: Update a user. """ permission_classes = [permissions.DjangoModelPermissions] queryset = User.objects.all() serializer_class = UserSerializer I am not able to get the descrption in side of user module -
django send_mail result format customization
When I send an email, the result is all without spaces. Is there a way to add spaces and/or format it? # Send Email send_mail( 'Inquiry - ' + property + ' - from my website', 'Property - ' + property + 'Client Email' + email + message + '', 'email@gmail.com', ['email@gmail.com'], fail_silently=False ) This is my result now : Property - Cuixach 2Client Emailtofol@gmail.covmessage example I would like something like this: Property - Cuixach 2 Client Email - email@gmail.com message: Lorem ipsum -
is it possible to return a HttpResponseRedirect from signal?
I'm working with an EDX integration so in my company developed a plugin to extend some functionality, one of them was the Auth0 integration. One problem was that when we logged out we just clean the Django session but the Auth0 session was activated cause never touched it. So I tried to solve this problem using signals, user_logged_out, I thought that it could be a nice solution but when I tried to log out from Auth0 it didn't work. I create a view that handles that, was just an API call, return HttpResponseRedirect(logout_url) but when I tried to call from the signal was impossible to do the logout. I tried with redirect(reverse(view_url)), also, I create a class instance and then called the function but I failed. My solution was to modify the frontend code to call the new view to complete the logout but I'm pretty interested on why I failed.