Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Best Hosting platform [closed]
I am building a website and I am using tailwind css templates and django in backend. Which will be the easiest and most suitable platform for hosting website in cheap rates? I want SSL certificate too... What are the best options for hosting as well as for buying a good domain? -
FlatList in combination with Axios
I already saw many questions regarding Axios and Flatlist, but none of them helped me to be honest. What I am trying to do: I am fetching a url using axios, which is working fine. I can see the response from the server side as well as when logging the response from the React Native client. Then I was trying to use Flatlist in order to list the favorites (from the response) into the app. I am fetching a url of a server using axios: useEffect(() => { axios.get(`app/appGetFavorites`) .then(res => { //setting favorites as the stringified response of "res" setFavorites(JSON.stringify(res.data)) //string to JSON (works fine) setJson(JSON.parse([favorites])) }) .catch(error => { console.warn('Parse (e): ' + error) }) }, []) the variable favorites is the following when logged (typeof String): [{"id":"2182","name":"Smithfield Foods Inc 2","address":{"street":"Friedhofstraße","street_number":"100","postal":"41472","city":"Neuss","latlng":{"latitude":"51.1609417","longitude":"6.6619322"}},"logo":"192.168.2.109:8000/static/logos/2101.jpg"},{"id":"2344","name":"Weatherford International Inc 2","address":{"street":"Heisterbacher Str.","street_number":"","postal":"47139","city":"DU","latlng":{"latitude":"51.4747044","longitude":"6.6986361"}},"logo":"192.168.2.109:8000/static/logos/2263.jpg"},{"id":"3539","name":"Webwork Innovations GmbH","address":{"street":"Witzelstraße","street_number":"18","postal":"40225","city":"Düsseldorf","latlng":{"latitude":"51.2030737","longitude":"6.7836779"}},"logo":"192.168.2.109:8000/static/companyFiles/2329/logo/logo_1611569379.png"}] This is the view, which is including the FlatList component: return ( <View> <FlatList ListHeaderComponent={renderHeader} data={json} renderItem={renderItem} keyExtractor={item => item.id} /> </View> ) This is the renderItem component, which is used to render an individual favorite item. The properties are sent to an individual component, which is located in another class: const renderItem = ({ item }) => ( <SingleFavorite item={item} … -
Django url path converter not working in production
I'm using path converter in my django app like so: # urls.py from . import views from django.urls import path urlpatterns = [ path('articles/<str:collection>', views.ArticleView), ] # views.py @login_required def ArticleView(request, collection): print(collection) if collection == "None": articles_query = ArticleModel.objects.all() ... This works fine in development for a url suck as : http://localhost:8000/articles/My Collection which gets encoded to http://localhost:8000/articles/My%20Collection, and is decoded properly in the ArticleView. However, in development, I have to edit the view like so to get it to work: # views.py import urllib.parse @login_required def ArticleView(request, collection): collection = urllib.parse.unquote(collection) print(collection) if collection == "None": articles_query = ArticleModel.objects.all() ... Otherwise, the print(collection) shows My%20Collection and the whole logic in the rest of the view fails. This happens in the admin interface as well. requirements.txt asgiref==3.2.10 Django==3.1.1 django-crispy-forms==1.9.2 django-floppyforms==1.9.0 django-widget-tweaks==1.4.8 lxml==4.5.2 Pillow==7.2.0 python-pptx==0.6.18 pytz==2020.1 sqlparse==0.3.1 XlsxWriter==1.3.3 pymysql What am I doing wrong here? Thanks in advance! -
I am trying to run cookiecutter on https://github.com/chopdgd/cookiecutter-django-reactjs and I cannot figure out how to use it
I am new to this and trying to learn, If possible someone please explain to me how to run react with Django using this cookiecutter. I am always getting this error - FileNotFoundError: [Errno 2] No such file or directory: '/app/frontend/build/static'. Thank you for your attention. -
Connecting React JS Front End with Django REST API using axios/fetch
So I have my REST api in Django REST Framework with the following endpoints: app/shipments/create/ app/shipments/list/ app/shipments/retrieve/<str:id> app/shipments/update/<str:id>/ app/shipments/delete/ I installed and configured Django CORS I am using React JS for my frontend and axios for fetching the API URLs. For the frontend: Here is my React Code, which is a form that the user fills and then clicks on submit button: class ShippingRequest extends React.Component{ constructor(){ super(); this.state = { shipments:[], }; //we want to get the shipments everytime the app loads, have them displayed when the application first starts this.getShipments(); } getShipments = async () =>{ try{ let data = await axios.get('http://127.0.0.1:8000/app/shipments/list/') .then(({data}) => data) this.setState({shipments: data}); }catch(error){ console.log(`Shipment Retrieval Error:\n ${error}`); } } createShipments = async () =>{ try{ let response = await axios.post('http://127.0.0.1:8000/app/shipments/create/'); console.log(response); this.getShipments(); }catch(error){ console.log(`Shipment(s) Creation Error:\n ${error}`); } } componentDidMount(){ this.getShipments(); } retrieveShipment = async () =>{ try{ let response = await axios.get("http://localhost:8000/app/shipments/retrieve/"); console.log(response); this.getShipments(); }catch(error){ console.log(error); } } deleteShipments = async () =>{ try{ let data =await axios.delete(`http://localhost:8000/app/shipments/delete/`); this.getShipments(); }catch(error){ console.log(`Shipment(s) Deletion Error: ${error}`); } } updateShipments = async (id, val) =>{ try{ let data = await axios.put(`http://localhost:8000/app/shipments/update/`); this.getShipments(); //to see shipments after updating }catch(error){ console.log(`Shipment(s) Update Error: ${error}`); } } submitHandler … -
Remplir automatiquement un champ avec des données d'autres champs Django
Bonjour ! C'est la première fois que je poste quelque chose, désolé si c'est mal fait ou maladroit. Je travaille sous django en python sur l'une des dernières versions. J'aimerais qu'un de mes champs de mon formulaire (KEY) soit rempli automatiquement avec la concaténation de mes autres champs tel que : KEY = avec 'SENT_' + search_categories + '_' + '001' et que le '001' s'autoincrement. Je ne peux pas vous montrer le model car c'est le code mon entreprise, je ne suis donc pas sûr de la légalité de la chose si je vous fournis le code mais la KEY est définie comme ça dans mon model : key = models.CharField(max_length=30, blank=False, null=False, unique=True) J'espère que vous allez pouvoir m'aider. Merci beaucoup ! -
How to redirect an UpdateView upon success?
I created a small Django application to manage data that fits a simple a model. For now I only need two views: one to list all records and another to edit a record with a generic form. Everything functions as expected, except the redirection from the edit view upon a successful update. In urls.py are the following contents: from django.urls import path from . import views app_name = 'reqs' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.ReqUpdateView.as_view(), name='update'), ] In forms.py: from django.forms import ModelForm from .models import Requirement class RequirementForm(ModelForm): class Meta: model = Requirement fields = ['name', 'priority', 'source' , 'rationale'] And the templeate requirement_form.html: <h1>{{ requirement.id }} - {{ requirement.name }}</h1> <form method="post" novalidate> {% csrf_token %} <table> {{ form.as_table }} <tr><td></td><td><button type="submit">Save</button></td></tr> </table> </form> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <br><br> <a href="{% url 'reqs:index' %}">Back to list</a> Finally views.py, on a first attempt to redirect the update to the list: from django.views.generic import ListView, UpdateView from django.urls import reverse_lazy from .models import Requirement from .forms import RequirementForm class IndexView(ListView): template_name = 'reqs/index.html' context_object_name = 'requirements_list' def get_queryset(self): return Requirement.objects.order_by('subject') class ReqUpdateView(UpdateView): model = Requirement form_class = RequirementForm success_url = reverse_lazy('/') With this formulation … -
Assign a simple HTML site with django
I want to assign/add a simple static HTML site to my django site. I know that's not what django is for but at the beginning I just want to create a simple site with a href to the other directories on the project. For e.g. index.html <html> <head></head> <body> <a href="/speiseplan">anzeige</a><br /> <a href="/speiseplanEdit">Speiseplan </a><br /> <a href="/speiseplan">Menu1</a><br /> <a href="/speiseplan">Menu2</a><br /> <a href="/speiseplan">Menu3</a><br /> </body> </html> Now I want to add this site to urls.py. I read that it shoud be possible with TemplateView. I already tried this: urlpatterns = [ path('', TemplateView.as_view(template_name="/templates/speiseleitsystem/index.html")), path('speiseplan/', views.speiseplan_Anzeige, name='speiseplan_Anzeige'), path('speiseplanEdit/', views.speiseplan_Eintragen, name='speiseplan_Eintragen'), path('menu1/', views.speiseplan_menu1, name='speiseplan_menu1'), path('menu2/', views.speiseplan_Anzeige, name='speiseplan_menu2'), path('menu3/', views.speiseplan_Anzeige, name='speiseplan_menu3'), ] Did I missed something? -
Is it possible to add/remove HTML Attributes for every formfield in Django
My goal is to remove the required tag from every formfield in my django app. The problem is that I've installed some 3rd party libraries and I want to remove it from their forms either. I thought about creating a custom Formrenderer, but I'm not shure how or maybe you have another idea. -
button on list_display django admin
I want to create a button called check Issues for each instance of my Scenario class. But the button it doesn't work. I am going to show you the code: class Scenario(TemporalObject): ... def def issues_button(self): return format_html( '''<form action="issue/" method="POST"> <button type="submit">Check Issues</button> </form>''') class ScenarioAdmin(admin.ModelAdmin): list_display = ("name", "user", "start", "end", "nb_hours","issues_button") ... def get_urls(self): urls = super().get_urls() my_urls = [ django.urls.path('issue/', self.gen_issues), django.urls.path('duplicate/', self.gen_duplicate), ] return my_urls + urls def gen_issues(self, request): if len(request.user.username) > 0: queryset=self.get_queryset(request) if len(queryset) > 0: for i in range(len(queryset)): sv = ScenarioVerifier(queryset[i]) sv.verify() return HttpResponseRedirect("../") else: self.message_user(request,"The queryset is empty" ,level=messages.ERROR) return HttpResponseRedirect("../") What I have to change??