Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Field 'id' expected a number but got
I try to build follow system in Django, it showed Field 'id' expected a number but got ''. how can i get the pk of the current profile user which I vested. This my view def follow_unfollow_profile(request, **kwargs): if request.method == 'POST': my_account = Account.objects.get(username=request.user) pk = request.POST.get('account_pk') obj = Account.objects.get(pk=pk) if obj.username in my_account.following.all(): my_account.following.remove(obj.username) else: my_account.following.add(obj.username) return redirect(request.META.get('HTTP_REFERER')) This is the urls path('<int:user_id>/', account_view, name="view"), path('follow/', follow_unfollow_profile, name='follow-unfollow-view'), The form Which I try to get the object pk <form action="{% url 'account:follow-unfollow-view'%}" method="POST"> {% csrf_token %} <input type="hidden" name="account_pk" value={{account.pk}}> <button type="submit" class="btn btn-success">Follow</button> </form> -
Why Validation Error is not showing in forms
I am building a Blog App and i am stuck on a problem. The Problem Validation Error is not raising. What i am trying to do I made a feature that if user select past time in DateTimeField in Browser Page then a Validation error will be shown. BUT the error is showing. forms.py from django.core.exceptions import ValidationError class PostForm(forms.ModelForm): date_added = forms.DateTimeField(initial=timezone.now) def clean_date(self): date_added = self.cleaned_data['date_added'] if date_added.date() < datetime.date_added.today(): raise forms.ValidationError("The date cannot be in the past!") return date_added views.py def new__blog_post(request,user_id): if request.method != 'POST': form = PostForm() else: form = PostForm(request.POST,request.FILES) new_post = form.save() new_post.post_owner = request.user new_post.save() return redirect('mains:posts',user_id=user_id) context = {'form':form,'posts':posts} return render(request, 'new_blog_post.html', context) My other question related to this , Question I don't know what i am doing wrong in this. Any help would be Appreciated. Thank You in Advance. -
pylance(reportMissingModuleSource) error in VS Code while using Django
https://github.com/microsoft/pyright/blob/master/docs/configuration.md" The error directs to this GitHub readme, no clarification, and no solution is given for this error The Error Message Shown I reinstall python and Django again still not working. What should I do? -
AttributeError at /admin/imports/import/add: 'NoneType' object has no attribute 'attname' (Django)
I have used embedded approach for constructing django models namely productDetails, ShipmentDetails , Customer and Import. I m using Pycharm IDE and no sql database. This is models.py file from djongo import models from django import forms # Create your models here. class ProductDetail(models.Model): product_name = models.CharField(max_length=70, blank=False) quantity = models.IntegerField(blank=False) net_weight = models.FloatField(max_length=70, default=False) class Meta: abstract = True class ProductDetailForm(forms.ModelForm): class Meta: model = ProductDetail fields = ( 'product_name', 'quantity', 'net_weight' ) class ShipmentDetails(models.Model): bl_no = models.CharField(max_length=100) ship_date = models.DateField() vessel_name = models.CharField(max_length=70) vessel_type = models.CharField(max_length=70) load = models.FloatField() class Meta: abstract = True class ShipmentDetailsForm(forms.ModelForm): class Meta: model = ShipmentDetails fields = ( 'bl_no', 'ship_date', 'vessel_name', 'vessel_type', 'load' ) class Customer(models.Model): customer_name = models.CharField(max_length=70, default="anything", null=True) class Meta: abstract = True class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = ( 'customer_name', ) class Import(models.Model): shipmentDetails = models.EmbeddedField( model_container=ShipmentDetails, model_form_class=ShipmentDetailsForm ) exporter = models.EmbeddedField( model_container=Customer, model_form_class=CustomerForm ) importer = models.EmbeddedField( model_container=Customer, model_form_class=CustomerForm ) indenter = models.EmbeddedField( model_container=Customer, model_form_class=CustomerForm ) productDetails = models.EmbeddedField( model_container=ProductDetail, model_form_class=ProductDetailForm ) Payment_options = ( ('C', 'Cash'), ('CD', 'Card'), ) Status_options = ( ('S', 'Signed'), ('US', 'Unsigned'), ('P', 'Pending'), ) dealDate = models.DateField() departureDate = models.DateField() arrivalDate = models.DateField() paymentTerm = models.IntegerField(choices=Payment_options) status = … -
pycharm does not accept html file
I use the Django authentication system, and for this I created a template, named this file login.html and in the registration directory. I already had a file with this name (login.html), and then I created this file and deleted the previous file, now pycharm does not accept the new file as html, and because of this I can not put Django template in this file and Leave a link. And you know you can't rename the file, because then the Django template authentication system can't find it. And now I do not know what to do. What can I do to make pycharm accept this as html? -
Is it possible to write down django project on colab?
I am a beginner. I have started Django project in Google Colab. But all time I am facing local host connectivity issue after execution of python manage.py runserver. Please help me. -
Django Web App running on local Debian 10 but failing on Azure
I can run my web app on my local machine - no errors. But when porting the directory strcture to Azure, I get the ModuleNotFoundError: No module named 'django'. Here is what I did: My app is publicly available on GitHub. The app runs in a virtual environment (called deploydjango). That is reflected in the tree structure of the repo. I ensured that Python version was correct (3.8 as on my local machine). I posted the code to Azure (using the Azure extension of Visual Studio Code). When browsing to the web app URL, I get the error message: :( Application Error If you are the application administrator, you can access the diagnostic resources. That takes me to Diagnose and solve problems on Azure page for the Web App Service. Here I find Availability and Performance. Herein the tab "Web App Dow" is found. Under Application Logs I am advised, that: Application logs from instance: lw0sdlwk00016P contain an error or a warning Clicking More info, I get a log telling me: 2021-02-18T12:02:07.203140817Z [2021-02-18 12:02:07 +0000] [37] [ERROR] Exception in worker process 2021-02-18T12:02:07.203175518Z Traceback (most recent call last): 2021-02-18T12:02:07.203181819Z File "/opt/python/3.8.6/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2021-02-18T12:02:07.203186419Z worker.init_process() 2021-02-18T12:02:07.203190419Z File "/opt/python/3.8.6/lib/python3.8/site-packages/gunicorn/workers/base.py", line … -
How buid a django architecture for multiple user interfaces working with the same data
(don't judge strictly pls, this is my first question) I have a model like Company. Two user interfaces: an administrator's cabinet(Cabinet) (not native django) and an interface for ordinary users (Main). Let's use the example of a list of companies. On the Cabinet, I want to show the companies that he can edit, on the Main - all public companies. I doubt for how to properly organize this moment on the backend. What I think? Make the base class CompanyListService in the service layer, write general logic in it, and separately each interface has its own class: CabinetCompanyListService(CompanyListService), MainCompanyListService(CompanyListService) Pass the model manager to it during initialization(Company is django Model): class CompanyListService: def __init__(self, manager=Company.main_manager): self.manager = manager then I can get here all the data options needed for the front class MainCompanyListService(CompanyListService): def get_companies(self): return self.manager.get_publish_companies() class CabinetCompanyListService(CompanyListService): def get_companies(self): return self.manager.get_available_companies_where_user_is_staff() class MainManager(TreeManager): def get_available_companies(self): """Includes blocked, rejected etc... Companies that actually exist and are available at least to the creator, admin""" return self.get_queryset().exclude(status='deleted') def get_publish_companies(self): return self.get_queryset(status='active') def get_available_companies_where_user_is_staff(self, user): """Companies where user has CompanyManager role""" self.get_available_companies().filter(company_company_managers__user=user) Not sure if this is good architecture. In general, I don't have enough experience to understand how good or bad … -
How to Create a User in nested serializer using generic ListCreateAPIView?
I am working on genericAPIViews in DRF. I am using a built in user model with UserProfile model having one to one relation with it. But I am unable to create user due to nested serializer. My question is that how I can create my built in User model and Profile User model at the same time as UserProfile model is nested in User model.Here is my code: Models.py USER_CHOICE = ( ('SS', 'SS'), ('SP', 'SP') ) LOGIN_TYPE = ( ('Local', 'Local'), ('Facebook', 'Facebook'), ('Google', 'Google') ) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') cell_phone = models.CharField(max_length=15, blank=True, default="", null=True) country = models.CharField(max_length=50, blank=True, default="", null=True) state = models.CharField(max_length=50, blank=True, default="", null=True) profile_image = models.FileField(upload_to='user_images/', default='', blank=True) postal_code = models.CharField(max_length=50, blank=True, default="", null=True) registration_id = models.CharField(max_length=200, null=True, blank=True, default=None) active = models.BooleanField(default=True) # roles = models.ForeignKey(Role, null=True, on_delete=models.CASCADE, related_name='role', blank=True) user_type = models.CharField(max_length=50, choices=USER_CHOICE, null=True, blank=True) login_type = models.CharField(max_length=40, choices=LOGIN_TYPE, default='local') reset_pass = models.BooleanField(default=False) confirmed_email = models.BooleanField(default=False) remember_me = models.BooleanField(default=False) reset_code = models.CharField(max_length=200, null=True, blank=True, default="") reset_code_time = models.DateTimeField(auto_now_add=True, blank=True) longitude = models.DecimalField(max_digits=80, decimal_places=10, default=0.00) latitude = models.DecimalField(max_digits=80, decimal_places=10, default=0.00) r_code = models.CharField(max_length=15, null=True, blank=True) refer_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="user_refer") referred = models.ManyToManyField(User, related_name="user_referred", null=True, blank=True) otp = … -
Update related object with rest framework
Given the following models:- class User(models.Model): first_name = models.CharField() etc. class Relation(models.Model): user = models.ForeignKey(User, related_name='relations', on_delete=models.CASCADE) is_primary = models.BooleanField(default=False) how would I go about creating a serializer and view that can be used to set a particular user's relation to be the primary one? I was hoping to be able to POST something like:- { 'relation': 6 } and for that to find the Relation with ID of 6 and set it's is_primary to True but I can't figure out how to do it. I've tried the serializer like this:- class SetRelationSerializer(serializers.ModelSerializer): relation = serializers.PrimaryKeyRelatedField(queryset=Relation.objects.all()) class Meta: model = User fields = ['relation'] and a viewset action like this:- @action(['post'], detail=False) def set_primary_relation(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) // what do I need in here? return Response(status=status.HTTP_204_NO_CONTENT) Is the only way to do something like:- self.request.user.relations.get(id=serializer.data['relation']).update(is_primary=True) ? Because that seems a bit unpleasant to me. Surely there's a better way? -
Django QuerySet annotate with Subquery
given the following model class Pizza(Model): pass class Topping(Model): on = ManyToMany(Pizza, related_name='on_pizza') I'm trying to get, my Pizza and the number of toppings, along with the top 3 other pizzas (top in terms of the number of toppings) to get the other top pizzas I'm doing: top = Pizza.objects.all().exclude(pk=self.pk).annotate(tcount=Count('on_pizza')).order_by('-on_pizza') this is in a class function (on the model) What I want is the above query, including the current pizza, this is what I tried: def compared_with_top(self): top = Pizza.objects.all().exclude(pk=self.pk).annotate(tcount=Count('on_pizza')).order_by('-tcount') me_with_top = Pizza.objects\ .filter(pk=self.pk)\ .annotate(tcount=Count('on_pizza'))\ .annotate(other_top_3=Subquery(top[:3])) return me_with_top This gives me an error: FieldError: Cannot resolve expression type, unknown output_field I've noticed all the example of subquery involve 2 separate models, and use OuterRef, my query doesn't have an outer ref (its all the same model) I just want to get 2 queries in one if that makes since. The above error points to 'output_field' but I cant find any information about what that should be. -
The Post could not be created because the data didn't validate - ( When i set past time )
I am building a BlogApp and I am stuck on an Error and I keep getting this error :- The Post could not be created because the data didn't validate. What i am trying to do I made a feature that users cannot insert past date in DateTimeField. AND If user enters the past date in field then a Validation Error should be display. AND i was testing it and suddenly a new error is occured. forms.py class PostForm(forms.ModelForm): date = forms.DateTimeField(initial=timezone.now) def clean_date(self): date = self.cleaned_data['date'] if date.date() < datetime.date.today(): raise forms.ValidationError("The date cannot be in the past!") return date views.py def new__blog_post(request,user_id): if request.method != 'POST': form = PostForm() else: form = PostForm(request.POST,request.FILES) new_post = form.save() new_post.post_owner = request.user new_post.save() return redirect('mains:posts',user_id=user_id) context = {'form':form,'posts':posts} return render(request, 'new_blog_post.html', context) It is showing that the Error is in new_post = form.save() line . It means that there's having problem in saving form. The Problem When i set the time of now ( as timezone.now as default ) in DateTimeField then it is working fine , Post is saving fine. BUT when i change the present time (2021-02-18) into past time (2019-02-18) then it is showing that error The Post … -
Django filter ManyToMany with Q and Or
class State(models.Model): name = models.CharField(max_length=55, unique=True) class City(models.Model): name = models.CharField(max_length=255) states = models.ManyToManyField(State, related_name='cities') parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, related_name='children', blank=True) I have a state and I want to find cities that either have null parent or whose parent states doesn't contain a state. I tried state.cities.filter(Q(parent=None) | ~Q(parent__states=state)) but it doesn't work and I query is strange: `SELECT "city"."id", "city"."name", "city"."parent_id", FROM "city" INNER JOIN "city_states" ON ("city"."id" = "city_states"."city_id") WHERE ("city_states"."state_id" = 7 AND ("city"."parent_id" IS NULL OR NOT ("city"."parent_id" IN (SELECT U2."city_id" FROM "city_states" U2 WHERE (U2."state_id" = 7 AND U2."id" = "city_states"."id")) AND "city"."parent_id" IS NOT NULL))) ORDER BY "city"."name" ASC` In particular what does the code AND U2."id" = "city_states"."id" perform? -
Build a react project in django
I am embedding a react project inside my django app. I am serving the index.html file created by npm run build from django as opposed to just using django as a third party api. I like this approach as it leverages django user authentication/ csrf tokens/ etc. After npm run build I am extracting the head and the scripts on index.html and putting them in my base.html of django, this way, the react scripts will be available wherever I need them and I can use my django templates for my navbar, footer etc. The problem I am having is I have to copy and paste the headers and scripts on every build, so my question is if there is a way to make npm run build build the files with the same name every time, or perhaps another solution, so when I rebuild the react project I don't have to recopy and paste to base.html? Here is a code snippet sample base.html <html> <head> <!-- Copy and pasted header files from react build--> </head> <body> <navbar></navbar> {% block content %} {% endblock %} <script> //copy and pasted scripts from react build - different script names on every build </script> </body> … -
Django is rendering template from the database efficient
This is not a HOWTO question, as it, as such, has been answered before here I am trying to integrate Django with modern frontend framework, and I found that it is possible to store and render Django templates from models. Since it is not a standard, I am wondering what are the advantages (or disadvantages if that's the case) of file based templates. Reading though the documentation, I have seen that it is recommended to actually cache templates and models as much as possible for best performance, so why would it not be recommended to store templates in the database? It seems very convenient to me that in doing so pages can be edited from the admin panel (where you can add a code editor), which, along with the rest framework and a front end framework synergize very well. From my research, the template tags and template language seem to work and the context can be passed in a view as well. the only thing I cannot figure out is the {include .. } tag, as it does not seem to point to a view. (although a costum tag cam be made to have this funtion) Can such a setup … -
Bokeh slider to change plot
I am looking to use a slider to change the line plot being displayed. I currently have a 2D array storing y values for each for each x (e.g. one plot for each value of x as shown bellow.) All the sliders I have seen have been changing elements of the plot rather than a variable like i I can use to change the index so only the selected orange line is shown. This might be fixable through custom JS however I have struggled with understanding how to use it for this. Hope this makes sense thanks for your time. -
Create a model of all subdirectories of a website
I want to display on the index.html site all existing subdirectories of a website. E.g. I have localhost/menu1 localhost/menu2 localhost/menu3 localhost/admin I want to create an object which contains all of this subdirectories, so I can easily pass it as context in my urls.py. Any ideas or is this even possible? -
Using default "timezone.now" method in forms. --- TypeError: __init__() got an unexpected keyword argument 'default'
I am Building a BlogApp and I am working on a Feature BUT i am stuck on a Error. I made date = forms.DateTimeField(default=timezone.now) BUT it is keep showing me :- TypeError: init() got an unexpected keyword argument 'default' in Terminal What i am trying to do I want it to set default time of now in the form field in the Browser. forms.py from django.utils import timezone class PostForm(forms.ModelForm): date = forms.DateTimeField(default=timezone.now) class Meta: model = BlogPost fields = ('post_title','date',) widgets = {'post_title': forms.Textarea(attrs={'cols':50})} models.py class BlogPost(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') date_added = models.DateTimeField(null=True,default=timezone.now) What have i tried I also tried default method in models , it is working fine BUT i want to make a 'Validation Errorwhich i cannot do inmodel` It is only possible in Forms . So i am doing it in Forms. I don't know what to do. Any help would be Appreciated. Thank You in Advance. -
Get total pages of a xhtml2pdf document in view
does anyone knows how to get the total pages of a document generated by xhtml2pdf. I need to store the total pages in a database. In Pypdf2 I could use pdf.getNumPages() for example... -
How to implement case-insensitive search by substring in a string from a model in sqlite in Cyrillic?
I have a model with a CharField: class catalogModel(models.Model): title = models.CharField('Name', max_length = 100, null = True) и мне нужно осуществить поиск по моделям catalogModel с помощью поля title без учёта регистра # search query search = request.GET['search'] catalogModel.objects.filter(title__icontains = search) The only problem is that "__icontains" does not work correctly in "sqlite" with Cyrillic (case-sensitive, although it should not). I was thinking of filtering by title by uppercasing it and a search term like: # search query search = request.GET['search'] catalogModel.objects.filter(title__UPPERCASE__icontains = search.upper()) -
How to globally tell Cloudinary to automatically decide the type of file in Django?
I use cloudinary as the default media storage for my Django project so I just setup it like this: settings.py INSTALLED_APPS = [ 'cloudinary' ] DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' CLOUDINARY_STORAGE = { 'CLOUD_NAME': os.environ.get('CLOUDINARY_STORAGE.CLOUD_NAME'), # env is set right 'API_KEY': os.environ.get('CLOUDINARY_STORAGE.API_KEY'), 'API_SECRET': os.environ.get('CLOUDINARY_STORAGE.API_SECRET'), } so now if I want to setup an ImageField I have no problems with that just with default Django syntax: image = ImageField(upload_to=get_image_upload_path, max_length=255) but when I want to store a file in my way it's video file: video = FileField(upload_to=get_video_upload_path, max_length=255) I get this error: Invalid image file which means that Django using cloudinary storage tries to upload this file as an image what's set as the default behavior to cloudinary. So my questions is if there is anyway to tell cloudinary gloabally to automatically decide what type of the file is? -
how to filter the distance between 1 user and a list of sellers in django rest framework
hello i am trying to have a page where as soon as a buyer or seller navigates to it calculates the distance between that user and other sellers, i have found the calculation to do it and i have found out how to calculate it but i want the user to be able to filter the distance but the thing is that the distance is not a column in my table so it gives an error of TypeError at /marketplace/search/ 'Meta.fields' must not contain non-model field names: distance here is my code below def calc_dist_fixed(lat_a, long_a, lat_b, long_b): """all angles in degrees, result in miles""" lat_a = radians(lat_a) lat_b = radians(lat_b) delta_long = radians(long_a - long_b) cos_x = ( sin(lat_a) * sin(lat_b) + cos(lat_a) * cos(lat_b) * cos(delta_long) ) return acos(cos_x) * EARTH_RADIUS_IN_MILES class Listsellers(generics.ListAPIView): queryset = Seller_account.objects.all() serializer_class = SellerAccountSerializer filter_backends = [DjangoFilterBackend] def calc_dist(self): user = self.request.Users.objects.username seller = Users.objects.filter(seller=True) lat_a = user.latitude long_a = user.longitude lat_b = seller.latitude long_b = seller.longitude distance = calc_dist_fixed(lat_a, long_a, lat_b, long_b) filterset_fields = [ 'distance', 'cuisine', 'delivers', ] is there something i am missing? -
can't compare datetime.datetime to datetime.date in django
I am Building a BlogApp and I am stuck on an Error. I tried many times and tried many answers but nothing solved my error. def validate_date(date_added): if date_added < timezone.now().date(): raise ValidationError("Date cannot be in the past") class BlogPost(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') date_added = models.DateTimeField(null=True,default=timezone.now,validators=[validate_date]) The Work of this Function Work of this function is to prevent past date as a input. The Problem Whenever i try to make a new blogpost and try to add the past date then it is keep showing me :- can't compare datetime.datetime to datetime.date What have i tried I tried many answers like This but nothing worked for me. I don't know what is wrong in this code. Any help would be appreciated. Thank You in Advance. -
React router PrivateRoute keeps redirecting to login
I just implemented token based authentication in my django and react application and I now want to make sure that unauthorized users are unable to access my pages. I tried this by using a PrivateRoute. The annoying thing is that when you reload the page, it keeps sending me to the login page, which then recognizes that I am authorized, and sends me back to home. So for some reason when I refresh the page, the isAuthenticated variable is set to false for a second. I tried to counter this by creating an isLoading variable in my auth.state. This should recognize that authentication is not loaded yet, and that it should wait to check for the isAuthenticated state. However, when I reload the page it still goes to login, and then to home because it takes a while before it recognizes the isAuthenticated variable. Does anyone know why this keeps happening? This is my PrivateRoute file import React, { useState } from 'react'; import { Redirect, Route } from 'react-router-dom' import { connect } from 'react-redux'; const PrivateRoute = ({ component: Component, auth, ...rest }) => ( <Route {...rest} render={(props) => { if (auth.isLoading) { return <h2>Loading...</h2>; } else if … -
Error after changing Django database from SQLite3 to PostgreSQL
I have changed an existing database for a Django project from SQLite3 to PostgreSQL and moved all the data with dumpdata and loaddata commands. When I'm running the server, It's giving me the following error - ContentType 19 for <class 'easy_thumbnails.models.ThumbnailDimensions'> #233 does not point to a subclass! I'm using django-filer which has a dependency on easy_thumbnails. I'm guessing the error is coming from there. I have checked this link and followed teewuane's answer to reorder the django_content_type table but still no luck.