Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why nested serializer in django not working in my code
I am trying to create a nested serializer but code isn't working and I am unable to find out where the problem is. Here are my models class Company(models.Model): name=UniqueCharField("Name",) address=models.TextField("Address",blank=True,null=True,default='',) city=OptionalCharField("City Name",) state=OptionalCharField("State Name",) country=OptionalCharField("Country Name",) phoneno=OptionalCharField("Phone No.",) mobileno=OptionalCharField("Mobile No.",) emailid=OptionalCharField("Email Address",) class Meta: verbose_name="Company" verbose_name_plural="Companies" db_table="MST_Company" class CompanyContacts(models.Model): companyname=models.ForeignKey(Company,models.CASCADE,"contactdetails") contactname=RequiredCharField("Contact Name",) contactno=OptionalCharField("Contact No.") emailid=OptionalCharField("Email ID") class Meta: verbose_name="Company Contact" verbose_name_plural="Company Contacts" db_table="MST_CompanyContacts" and serializers, class CompanyContactsSerializer(serializers.ModelSerializer): def create(self,validated_data): return CompanyContacts.objects.create(**validated_data) class Meta: model=CompanyContacts exclude=('companyname',) class CompanySerializer(serializers.ModelSerializer): contactdetails=CompanyContactsSerializer(required=False,many=True,read_only=False) def create(self, validated_data): contactdetails_data=validated_data.pop('contactdetails',None) mcompany=Company.objects.create(**validated_data) # company.save() if contactdetails_data: for contactdetail in contactdetails_data: CompanyContacts.objects.create(companyname=mcompany,**contactdetail) return mcompany class Meta: model = Company extra_fields=['contactdetails'] fields='__all__' read_only_fields=('date_created','date_modified','user_created','user_modified') Here is my payload: { "id":"", "name":"Test Company", "address":"", "city":"", "state":"", "country":"", "phoneno":"", "mobileno":"", "emailid":"", "contactdetails":[ {"contactname":"Test Name - 1","contactno":"Test Mobile - 1","emailid":"Test Email - 1"}, {"emailid":"Test Email - 2","contactno":"Test Mobile - 2","contactname":"Test Name - 2"} ] } Server response : { "name": [ "This field is required." ] } Code is self explanatory, even then you require to ask anything, Please let me know and I will provide you the detailed explanation .Help would be greatly appreciated. Thanks in advance. -
getting only total number of listings by using django-mptt
i am using django-mptt to list all parent categories in my home page and to display the total count of all items inside off all subcategories related to the main category but i am only getting the display of all items in all categories for example i have only 2 vehicles(cars,motors) and 3 mobiles(2 , 1) here is my model: class Category(MPTTModel): name = models.CharField(max_length=100) image_url = models.CharField(max_length=100,blank=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') tag = models.CharField(max_length=40,blank=True) class MPTTMeta: order_insertion_by = ['name'] def __str__(self): return self.name and in my view i am calling this query: categories = Category.objects.add_related_count(Category.objects.root_nodes(), Ad, 'category', 'ads_counts', cumulative=True) and in the template: {% load mptt_tags %} <ul> {% recursetree categories %} <li class="col-lg-3 col-md-3 col-sm-6 col-xs-12"> <a data-cid="{{ node.id }}" style="font-size: 12px" class="category-list-style" data-toggle="modal" data-target="#subcategorymodal"> {{ node.name }}<span>({{ node.ads_counts }} Ads)</span> <i class="flaticon-transport-9"></i> </a> </li> {% endrecursetree %} but here is what i get is the total count of ads displayed on all categories, instead of getting 0 ads -
How can I use Django model required=False?
I want my required / optional field separate or write description at least. but required=False doesn't work. my user model.py get birthdate field. like: birthdate = models.DateField(blank=True, null=True) and my userform_input.html <div class= "border-b my-2 py-3"> {{field}} {% if field.field.required %} * {% endif %} </div> I tried How to make Django's DateTimeField optional? __init__() got an unexpected keyword argument 'required' but also doesn't work. How can I describe it? -
Remove individual ManyToManyRelationship instances through a Django view
So I have this Assignment model: class Assignment(models.Model): has_applied = models.ManyToManyField('driver.Driver', blank=True, verbose_name=_( "Driver applications"), related_name="driver_applications") Which features a has_applied field with a ManyToMany relationship to the Driver model. I want the front-end user to be able to remove these relationships. I have a normal DetailView from the Assignment model but I use it to only show the candidates: class AssignmentCandidateDetailView(generic.DetailView): model = Assignment context_object_name = 'assignment_candidate_detail' template_name = 'pages/candidate/c.html' With this url: path('assignment/<int:pk>/candidates', views.AssignmentCandidateDetailView.as_view(), name='assignment-candidate-detail'), And in the template I use this to get a list of the candidates that have applied and their information: {% for entry in assignment_candidate_detail.has_applied.all %} ..... stuff {% endfor %} In the template list of candidates I would like to add a "Delete" button per candidate. This button will remove the ManyToMany field relationship of that particular candidate. But I am not sure how to approach this. Can someone help? I supposse it should be something like (pseudo code): def assignment_candidate_delete(request, pk): assignment = get_object_or_404(Assignment, pk=pk) assignment.has_applied.remove(candidate) But how can I pass the correct information so that it removes only the relationship of a particular candidate? -
Django Allauth Messages
I am having problems with Django Allauth messages. When I register two accounts (Peter and John), Peter account is verified and John is not yet verified. When I login Peter's account, I got a displayed message that John account is not verified (email verification). That is the problem, I shouldn't have gotten a displayed message on John when I logged into Peter's account. I use mandatory on email verification. -
I get the following error message: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method'
These enter image description hereare the models, views, and error message: enter image description here enter image description here enter image description here -
What is best practise for password tokens
I have a project where custom user model realised and now i am thinking about implement password reset function passwordResetToken and email confirmation of user during registration UniqueTokenForEmailConfirmation and now i want to understand what is a best practices to locate this kind of tokens. In app's views.py file where password login reset function will be realised and user email confirmation function or i should create separate file token.py what is a best practice -
Django - How to save Google Maps Polygon javascript code to View?
I want to create polygon area on Google maps. User select their area via Google Maps Polygon should be saved. I want to to do calculations on these Polygons. On the other hand, other polygons should be displayed on the map. I want to pass users selected polygon area array into my forms.py, views.py and show their selected area in the template. Model from django.contrib.auth.models import User from django.contrib.gis.db import models class Category(models.Model): name = models.CharField(max_length=250) def __str__(self): return self.name class Property(models.Model): user = models.ForeignKey(User,default=None, null=True, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True) polygon = models.PolygonField() Forms class CreateFrom(forms.Form): category = forms.ModelChoiceField(Category.objects.all(), initial=1) polygon = forms.PolygonField(required=False) def deploy(self, user): category = self.cleaned_data.get('category') polygon = self.cleaned_data.get('polygon') deploy = Property(user=user, category=category, polygon=polygon) deploy.save() return deploy Views def create(request, username): user = get_object_or_404(User, username=username) form = forms.CreateFrom() if request.method == 'POST': form = forms.CreateFrom(request.POST or None) if form.is_valid(): form.deploy(user) return render(request, 'maps/maps.html', {'form': form}) Template From the Create page want to passing the array to my views. I can't input the coordinates array. How I pass the array. <script> var geocoder; var map; var polygonArray = []; function initialize() { map = new google.maps.Map( document.getElementById("map_canvas"), { center: new google.maps.LatLng(37.4419, -122.1419), zoom: 13, mapTypeId: … -
Django showing: OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>'
After I restarted my PC the terminal showed ImportError as follows ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? So i install django. But when i run the command to start the server i got this error. Following some suggestions i have tried force-reinstalling django Making migrations Still hte error persist, i dont know the cause of this error please help me out. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Python38\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Python38\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Python38\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python38\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Python38\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line … -
If user found in a post it returns the username from User database as permalink in the post from models in Django
This is my class models.py I have tried the .split method but keep getting an error that Charfield can not iteriet. I'm trying to make it so that when I call posts in a template if there is a username starting with @ it will have the username link to that users profile. class Status1(models.Model): post = models.CharField(max_length=333) user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(auto_now=True) -
How to deploy a django web site into PlanetHoster
I developed a web site using Django in Python. Everything is working and running perfectly my localhost. I have a hosting space in PlanetHoster and I would like to deploy it. But honestly, I don't know how to do it. I have tried and failed. I asked support from PlanetHoster but they can't help because they are not developers neither webmasters. I am trying to follow the video in the link but it does not work. https://www.youtube.com/watch?v=ffqMZ5IcmSY Please assist me -
DRF filter choices by group name
Let's say I'm making a media library model, and there are these choices in named groups: models.py class MediaLibrary(models.Model): MEDIA_CHOICES = [ ('Audio', ( ('vinyl', 'Vinyl'), ('cd', 'CD'), ) ), ('Video', ( ('vhs', 'VHS Tape'), ('dvd', 'DVD'), ) ) ] media_type = models.CharField(max_length=50, choices=Media_Choices) If I make a request through DRF, it would return all the objects which match either "Audio" and "Video". How can I filter the request so that it only returns objects under the "Audio" group. (Or the "Video" group.) -
Foreign keys error when trying to create a new record in Django
I have two models that are linked in a One-to-Many relationship: Activity and Users. A user can only be connected to 1 activity but an activity can be referenced from multiple User entries. // Activity id | username_id | activity | initial_date | ending_date -- ------------ -------- ------------ ------------ 1 | | test | 2020-01-20 | None 45 | | test45 | 2020-01-25 | None // User username_id | email | username | last_login | date_joined |is_admin | is_active | is_staff | is_superuser ------------ ----------------- ---------- ------------ ----------- --------- --- -------------------------------- 2 | ab@hotmail.com | ab | 2020-01-20 | 2020-01-15| No | No | No | No 3 | xy@hotmail.com | ab | 2020-01-21 | 2020-01-18| No | No | No | No //models.py from django.utils import timezone from django.contrib.auth import get_user_model User = get_user_model() class Activity(models.Model): id = models.AutoField(primary_key=True) username_id = models.ForeignKey(User, on_delete=models.CASCADE) activity = models.CharField(null=False, max_length=140) initial_date = models.DateField(default=timezone.now(), null=False) ending_date = models.DateField(default=timezone.now(), null=False) class User(AbstractBaseUser): username_id = models.AutoField(primary_key=True) email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] //forms.py from … -
How can I define my form such that it's html starts with <div ...>?
Currently, in forms.py, I have: questionToProblemPreview = forms.CharField(label = "Preview", widget = forms.Textarea(attrs={'id' : 'MathOutPut', 'readonly' : 'True', 'cols': 80, 'rows': 10})) The resulting HTML in Django admin looks like this: <div class="form-row field-questionToProblemPreview"> <div> <label class="required" for="MathOutPut">Preview:</label> <textarea name="questionToProblemPreview" cols="80" rows="10" id="MathOutPut" readonly="True" required> </textarea> </div> </div> How can I make it such that <textarea name="questionToProblemPreview" cols="80"...> becomes instead <div name="questionToProblemPreview" cols="80"...>? -
Django Web App Heroku Deployement : No matching distribution found for decouple==0.0.7
I am deploying a web app made in Django on Heroku. I am following a tutorial in which tutor has made a w/s without any CSS / Image input from User. But my app has lot of style and profile pics etc which need ImageField in model. IMP -> I made the project for Django 2.2, but django 3 got launched so I am using that. Please help me... I have done following steps: Installed Anaconda Made Virtual Env & Activated it. Installed pip Installed Dependencies pip freeze > requirements.txt git add . & git push -am "Text" git push heroku master My requirements.txt : asgiref==3.2.3 certifi==2019.11.28 cffi==1.13.2 decouple==0.0.7 dj-database-url==0.5.0 Django==3.0.2 django-appconf==1.0.3 django-bootstrap3==12.0.3 django-heroku==0.3.1 django-mediumeditor==1.0.0 gunicorn==20.0.4 misaka==2.1.1 psycopg2==2.8.4 pycparser==2.19 python-decouple==3.3 pytz==2019.3 six==1.14.0 sqlparse==0.3.0 whitenoise==5.0.1 My Error: Enumerating objects: 18, done. Counting objects: 100% (18/18), done. Delta compression using up to 8 threads Compressing objects: 100% (16/16), done. Writing objects: 100% (16/16), 1.96 KiB | 1.96 MiB/s, done. Total 16 (delta 9), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Need to update SQLite3, clearing cache remote: -----> Installing python-3.6.10 remote: -----> Installing pip remote: -----> Installing SQLite3 remote: … -
Django Many-to-Many relationship with additional columns
I have a model where I store the 'news' articles. I want to create a M2M relationship with Django and to add a 'similarity' score to this relationship. I don't want the similarity to be symmetrical so I set it to False. From my search I found the following code is the way to go. It works, except it requires the 'related_name' to be added to one of 'from_news' or 'to_news'. Although I don't understand exactly why it is required but that's okay. My main question is since the relationship is not symmetrical, how does Django know that it should refer to the 'from_news' column when I query for similar articles? Is it the 'from' or is it because it comes first and 'to_news' comes later? I would guess I should have explicitly state it in the definition of 'similars' in the 'News' class. Please clarify how it works. Thanks! class News(models.Model): title = models.CharField(max_length=150) body = models.TextField() similars = models.ManyToManyField('self', through='Similarity', symmetrical=False) class Similarity(models.Model): from_news = models.ForeignKey(News, on_delete=models.CASCADE) to_news = models.ForeignKey(News, on_delete=models.CASCADE) score = models.DecimalField(max_digits=2, decimal_places=2) -
Django smart selects chained select not working properly on html
I am able to load the data from models however the chained selections are not dependent from one another. I can pick a recipe without selecting a category or a subcategory. i have been reading on smart selects but there is no complete tutorial. so far the admin section is working perfectly. forms.py from django import forms from .models import Recipe, Category, Subcategory #pylint: disable=E1101 class RecipeForm(forms.ModelForm): cat = forms.ModelChoiceField(queryset=Category.objects.all()) subcat = forms.ModelChoiceField(queryset=Subcategory.objects.all()) rec = forms.ModelChoiceField(queryset=Recipe.objects.all()) class Meta: model = Recipe fields = ['cat', 'subcat', 'rec'] views.py from django.http import HttpResponse from django.shortcuts import render from .models import Recipe, RecipeIngredient from .forms import RecipeForm # Create your views here. def recipe_view(request): #pylint: disable=E1101 recipe_form = RecipeForm() return render(request, "home.html", context={'recipe_form':recipe_form}) #pylint: enable=E1101 Home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> {% block content %} <form action="" method="POST"> {% csrf_token %} {{ recipe_form.as_p }} </form> {% endblock %} </body> </html> models.py class Category(models.Model): category = models.CharField(max_length=250) def __str__(self): return self.category class Subcategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) subcategory= models.CharField(max_length=250, default="") def __str__(self): return self.subcategory class Recipe(models.Model): name = models.CharField(max_length=250, default="") category = models.ForeignKey(Category, on_delete=models.CASCADE) subcategory = ChainedForeignKey( Subcategory, chained_field="category", chained_model_field="category", show_all=False, auto_choose=False, … -
Migrating WordPress free website with own developed python or JavaScript website
I want to start an educational website with text material, assignments and video tutorials. And I future I want to extend the same for selling my graphic designs. So to start this I was thinking to start with free WordPress website and slowly migrate this website with my own developed Django (Python) and JavaScript website. I am learning python and JavaScript and doesn't start development yet. So my question is is its fine and in right direction to start free WordPress website for now and then migrate with same domain to my own developed? -
Django EMAIL_PORT in localhost development
I am trying to integrate email verification while a new user registed. I am in the beggining of this feature implementation. For this purposes in settings.py i set the following settings EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'youremail@gmail.com' EMAIL_HOST_PASSWORD = 'yourpassword' EMAIL_PORT = ???? and here is my question which EMAIL_PORT i should specify if i am working on my local computer -
How do I remove duplicate records in an existing database? (no unique constraint defined)
I'm working on a project where improvements to database schema, query speed, and template inheritance are required. As an example, there is a Menu model that lacks a unique constraint (See below). To improve the model's data integrity, I'm planning to add a migration by adding a unique=True constraint to the season field. Before applying the migration, I checked the database for all Menu instances to see if an integrity error could potentially occur. As a result of checking, there are 3 model instances with the same value assigned to season. I want to remove all but 1 of the Menu instances from the existing database in this case, and it doesn't matter which one is kept. What would be some approaches to accomplishing this? class Menu(models.Model): season = models.CharField(max_length=20) items = models.ManyToManyField('Item', related_name='items') created_date = models.DateTimeField( default=timezone.now) expiration_date = models.DateTimeField( blank=True, null=True) def __str__(self): return self.season -
Only allow users to register usernames starting with @ in Django
Hey guys when registering users I only want them to be able to use names starting with @ I have been looking in documentation for Django all day but don't seem to be able to find where I could edit this. Any help would be awesome thank you! -
How to input multiple rows into django database with one submission in django
I have a for loop with hidden input in each. I try to input it into a transaction database with: Models.py class TransDetail(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(max_digits=15,decimal_places=2) amount = models.IntegerField() sumprice = models.DecimalField(max_digits=15,decimal_places=2) no_note = models.CharField(max_length=200) class Transaction(models.Model): no_nota = models.CharField(max_length=200) total_nota = models.DecimalField(max_digits=15,decimal_places=2) tanggal = models.CharField(max_length=200) HTML Template <table> <tbody> <form method="POST" action="{% url 'transactionadd' %}"> {% csrf_token %} {% for name,amount,price,sumprice in x %} <tr> <td>{{name}} <input type="hidden" name="name" value="{{name}}"> </td> <td>{{amount}} <input type="hidden" name="amount" value={{amount}}> </td> <td>{{price}} <input type="hidden" name="price" value={{price}}> </td> <td>{{sumprice}} <input type="hidden" name="sumprice" value={{sumprice}}> <input type="hidden" name="no_note" value={{no_nota}}> </td> </tr> {% endfor %} </tbody> </table> <input type="hidden" name="no_nota" value={{no_nota}}> <input type="hidden" name="total_nota" value={{sumcart}}> <input type="hidden" name="tanggal" value={{now}}> <h3> Your cart total is {{sumcart}}</h3> <hr/> <button type="submit" class="btn-success">Confirm</button> </form> Views.py def transactionadd(request): form1 = TransForm(request.POST or None) form2 = TransDetailForm(request.POST or None) if form1.is_valid() and form2.is_valid(): form1.save() form2.save() messages.success(request,"Transaction recorded") Cart.objects.all().delete() return redirect('index') context={ 'form1':form1, 'form2':form2 } return render(request, 'cart.html', context) The problem is everytime I confirm the transaction, only one entry line (the latest object) is being inputed into the database. Let say I put a hamburger and a hot dog into the cart and create a transaction. In the transaction detail … -
Error installing mod_wsgi in windows subsystem for linux
I tried to install mod_wsgi in Microsoft Visual Code and terminal as wsl. Tried updating all the required packages, but no luck. Installed inside Virtual env. Tried pip install mod_wsgi and pip install mod_wsgi == 4.5.24. Tried everything but still getting these errors. Screenshot 1 Screenshot 2 -
Django REST Framework: How to add a foreign primary key to an M2M serializer that uses a through table?
How can I add a primary key from a M2M relationship to my serializer? The examples I have seen only seem to work when a custom through model isn't set. models: class Inventory(models.Model): quantity = models.IntegerField() ... class Order(models.Model): order_items = models.ManyToManyField(Inventory, through='myapp.OrderItem') ... class OrderItem(models.Model): order = models.ForeignKey(Order) inventory = models.ForeignKey(Inventory) sell_price = models.IntegerField() quantity = models.IntegerField() serializers: class InventorySerializer(serializers.ModelSerializer): class Meta: model = Inventory fields = ('id', ) class OrderItemSerializer(serializers.ModelSerializer): inventory_id = serializers.PrimaryKeyRelatedField(source='inventory.id', read_only=True) class Meta: model = OrderItem fields = ('order_id', 'inventory_id', 'sell_price', 'quantity',) class OrderSerializer(serializers.ModelSerializer): order_items = OrderItemSerializer(many=True) inventory_id = serializers.PrimaryKeyRelatedField(source='inventory.id', read_only=True) class Meta: model = Order fields = '__all__' Expected Results: [ { "id": 1, "order_items": [ { "inventory_id": 1, "sell_price": "2.00", "quantity": 12 }, { "inventory_id": 2, "sell_price": "9.50", "quantity": 6 }, { "inventory_id": 3, "sell_price": "77.77", "quantity": 1 } ... <other fields> ], Ive tried various combinations of field names in meta, adding the InventorySerializer directly to the model, etc. but I can't seem to get it to work. What am I missing? -
Django queryset has no attribute when using select related
I'm trying to using select_related to queryset, and it returns queryset has no attribute when using select related. I made two models, and one model has foreignkey column, it is 1:1. models class User(models.Model): name = Charfield() class Item(models.Model): user = models.ForegnKey(User, on_delete=models.CASCADE, related_name='user_item_set', null=True) When I try this queryset, it says queryset does not have select related. users = User.objects.get(id=pk).select_related('user_item_set')