Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom "business" logic using pure Django
I am set on building a small website using django. What i am trying to do right now is using a CreateView based on a Model "Order", which one of its fields is another model "Customer". The form itself works to create Orders, but im trying to find out how i can validate that the Customer that was selected is "enabled" (there is a status in the Customer model). I was trying using the clean method but it doesnt even seem to be executing. I tried just raising the error on the clean, without validating anything, and still doesnt work. Any clue what might be wrong? My Form: class OrderForm(ModelForm): def clean_customer(self, *args, **kwargs): raise forms.ValidationError("This customer is banned.") class Meta: model = Order fields = '__all__' Relevant Models: class Order(models.Model): ORDER_STATUS = (('Pending Delivery', 'Pending Delivery'), ('Book on Customer', 'Book on Customer'), ('Overdue', 'Overdue'), ('Completed','Completed')) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) book = models.ForeignKey(Book, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True) date_due = models.DateTimeField(null=True) date_completed = models.DateTimeField(null=True, blank=True) status = models.CharField(max_length=100, choices=ORDER_STATUS, null=True) def get_absolute_url(self): return reverse('orders') class Customer(models.Model): status = models.CharField(max_length=10, null = True, choices=STATUS_CHOICES) name = models.CharField(max_length=200, null=True) username = models.CharField(max_length=25, null = True) email = models.EmailField(null=True) def __str__(self): return … -
wagtail snippets Add all snippet entity by snippet choose panel in one shot not one by one
I m using wagtail 2.8 I have article as snippet and i want to create articles page add all in easy way with out need to add them one by one (i have 400 ) i am using stream Field with StructBlock class NewsListBlock(blocks.StructBlock): slug = blocks.CharBlock(help_text='Block Slug') items = blocks.ListBlock(SnippetChooserBlock(News)) class Meta: label = 'News' icon = 'doc-full' -
ModuleNotFoundError: No module named 'gunicorn'
I followed a [DigitalOcean guide]((https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-debian-10) to set up my Django site. It usually works fine but lately I keep running into this. root@localhost:/usr/bin# sudo systemctl status gunicorn Jun 13 21:27:43 localhost systemd[1]: Started gunicorn daemon. Jun 13 21:27:43 localhost gunicorn[20611]: Traceback (most recent call last): Jun 13 21:27:43 localhost gunicorn[20611]: File "/usr/bin/gunicorn", line 6, in <module> Jun 13 21:27:43 localhost gunicorn[20611]: from gunicorn.app.wsgiapp import run Jun 13 21:27:43 localhost gunicorn[20611]: ModuleNotFoundError: No module named 'gunicorn' Jun 13 21:27:43 localhost systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Jun 13 21:27:43 localhost systemd[1]: gunicorn.service: Failed with result 'exit-code'. Jun 13 21:27:43 localhost systemd[1]: gunicorn.service: Start request repeated too quickly. Jun 13 21:27:43 localhost systemd[1]: gunicorn.service: Failed with result 'exit-code'. Jun 13 21:27:43 localhost systemd[1]: Failed to start gunicorn daemon. root@localhost:/home/development/django# which gunicorn /usr/bin/gunicorn /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/development/django/ ExecStart=/usr/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ app.wsgi:application [Install] WantedBy=multi-user.target -
How to add a row in table and submit form post data
I am trying to add a row of elements in the table , the jQuery code is working, I can add row as many as I want, but the problem is when I submit the rows data, I get only the first elements (first row), so what I am missing here? html <form method="POST" action="{% url 'step2_ach'%}" > {% csrf_token %} <button id="done" class="btn btn-primary disabled" name="submit" type="submit">Ajouter</button> <tr> <td name="nadjib1"> <select required="true" name="article" id="article" class="form-control"> <option selected></option> {% for obj in art %} <option value="{{obj}}">{{obj}}</option> {%endfor%} </select> </td> <td> <input class="na" required="true" min="0" step="0.01" type="number" id="prix" name="prix" placeholder="0.00"> </td> <td> <input class="qu l" required="true" pattern="\d+" type="number" id="quantite" name="quantite"> </td> </tr> </form> jQuery : $(document).ready(function() { $("#add").click(function() { $('#book-table tbody>tr:last').clone(true).insertAfter('#book-table tbody>tr:last'); return false; }); }); views.py ef step2_ach(request): ach = Achats.objects.latest('id') Art = Article.objects.all() if request.method == 'POST': if request.POST['article'] and request.POST['prix'] and request.POST['quantite']: prix = float(request.POST['prix'] ) prix = str(round(prix ,2)) artt = get_object_or_404(Article,Description = request.POST['article']) for article in request.POST.getlist('quantite'): na = AssociationForm({'Id_Article' :artt ,'Id_Achats':Achats.objects.latest('id'),'Prix_Unitaire':prix,'Quantite':request.POST['quantite']},instance=Association()) na.save() return redirect('view') else: error = 'please check your inputs ! ' return render(request, 'step2.html', { 'art': Art , 'er': error }) return render(request, 'step2.html', {'id_achat':ach , 'art': Art}) -
Am getting an error while using the django framework
So basically, I am trying to create a Local Library as part of a course I am doing based around Django. My resource: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Generic_Views. I am currently on the part where I have to create my own Author. Here is my models.py code for Authors: class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField(null=True, blank=True) date_of_death = models.DateField('Died', null=True, blank=True) def get_absolute_url(self): return reverse('author-detail', args=[str(self.id)]) def __str__(self): return f'{self.last_name}, {self.first_name} The message I am recieving in my command prompt is this: catalog.Book.author: (fields.E300) Field defines a relation with model 'Author', which is either not installed, or is abstract. If you require any additional information, please just tell me. Thank you. -
Django customizing widget to CharField breaks
According to the docs, you should be able to add a "widgets" dictionary and overwrite individual widgets. However this gets me the error 'CharField' object has no attribute 'is_hidden'. Note that the name is a TextField but I would like the widget to be a CharField. Shouldn't this work according to this? In my models.py class Todo(TimeStampedModel): name = models.TextField() notes = models.TextField(blank=True) url = models.URLField(blank=True) In my views.py class TodoCreateForm(forms.ModelForm): class Meta: model = Todo fields = ['name', 'notes', 'url'] widgets = { 'name': forms.CharField() } I realize I can manually declare name = forms.CharField() but the pattern above seems to follow the docs and should work -
Django rest framework, delete an extra action object
I have the following View: class MessagesViewSet(ModelViewSet): """ A simple ViewSet for viewing and editing the messages associated with the user. """ authentication_classes = [TokenAuthentication, ] permission_classes = [IsAuthenticated] serializer_class = MessageSerializer filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_fields = FILTERS.FILTER_SET search_fields = FILTERS.SEARCH_FIELDS ordering_fields = FILTERS.ORDERING_FIELDS @action(detail=False, methods=[METHODS.GET, METHODS.DELETE, METHODS.PATCH, METHODS.PUT]) def newest_msg(self, request): """ Return the latest message the user received. """ data = self.get_queryset().order_by(f'-{MessageFields.ID}')[0] data.mark_read = True data.save(update_fields=[MessageFields.MARK_READ]) serialized_data = MessageSerializer(data, many=False) return Response(serialized_data.data, status=HTTP_200_OK) Calling either of the methods specified in the action (except get), just returns the object like the get request. I've also tried something like this but failed. @action(detail=False, methods=[METHODS.GET, METHODS.DELETE, METHODS.PATCH, METHODS.PUT]) def newest_msg(self, request): """ Return the latest message the user received. """ data = self.get_queryset().order_by(f'-{MessageFields.ID}')[0] if self.request.method == METHODS.GET.upper(): data.mark_read = True data.save(update_fields=[MessageFields.MARK_READ]) serialized_data = MessageSerializer(data, many=False) return Response(serialized_data.data, status=HTTP_200_OK) elif self.request.method == METHODS.DELETE.upper(): return self.destroy(self.get_object()) elif self.request.method == METHODS.PATCH.upper(): return self.partial_update(self.request) Which raised the following error: Expected view MessagesViewSet to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. -
deploy django app using Pyaudion libraray
I built a Django app for speech recognition, the app uses the user microphone to record audion the convert it to text, the app work well locally, but when I try to deploy it in Heroku it giving an error that Pyaudio can not install and command 'gcc' failed with exit status 1 I am using Python 3.6 and window 7. so how to deploy it ?? -
What is a remote Docker interpreter when you make a container?
For example, if you're making a container for a Django project, is a remote interpreter a python interpreter that is stored in the Docker cloud and not on your PC? So when someone runs the container on another PC, it will use the same remote interpreter designated for this project from the Docker cloud? -
Add Leading zeros in Django form
In my models I have an integer field that is supposed to be national I'd which is formed normally of 15 digits, if the costumer's national id is less than 15 chars and he inserted it like that, I want to automatically add zeros to the left till it become 15 chars. How do I do it in django. Any help please, it's urgent I searched internet slot, but I didn't find anything. I'm using django to create the form for the class containing the national I'd... Thanks for ur help! -
Django annotate relation with specific object
I have two models in my Django database: class Member(models.Model): signed_up_to=models.ManyToManyField(Piece) class Piece(models.Model): title = models.CharField(max_length=200,null=True,blank=True) When I pull Piece objects from my database, I would like to annotate (Bool or Integer) whether or not the Piece appears in signed_up_to of a specific Member. I've looked around for an answer all over the internet, but with no success. Hope there's anyone who can help me! -
Autodoc Error when using Sphinx with Django
I am attempting to use sphinx autodoc in a Django project, but keep recieving the same error. My project is structured somewhat like so: |project |---app |------models.py |---docs |------build |------source |---------conf.py |etc the top of my conf.py file looks like this: import os import sys sys.path.insert(0, os.path.abspath('../..')) from django.conf import settings settings.configure() and my models.rst file looks like this: Models ====== .. automodule:: project.app.models :members: However, whenever I run make html, I get the one line error: WARNING: autodoc: failed to import module 'app.models' from module 'project'; the following exception was raised: No module named 'project.app' Any suggestions? Is this an issue with my sphinx configuration, or an issue with the django project? -
label of realtion between model and user in django
I am working on a project where user chooses which relation it wants to have to a Post, for example: A user can choose to be from a set of different options to a Post, such as: a sibling, or a parent, of a friend to a Post instance. What is the best way to apply make this? I was thinking of using a models.foreignkey(Post) and maybe adding some sort of label to the field. But would I be able to access this label in the template? Would this be the right implementation? Thanks in advance! -
Python, Django: Populate Widget(Select) with a dynamic list
Good evening, I'm wondering, if there's a solution to populate a "django.form" with an dynamic list from my "views.py"? I'm aware that I can populate it inside the form itself, but what if my list has to be dynamic (let's say it contains unique names created from a database table)? models.py: class Example(models.Model): name = models.Charfield(max_length=255, null=False, blank=False) company = models.Charfield(max_length=255, null=False, blank=False) date_created = models.DateField(auto_now_add=True) forms.py: class ExampleForm(ModelForm): class Meta: model = Example exclude = [ 'date_created' ] views.py: def examplePage(request): form = ExampleForm() coworkers = Example.objects.all() # this list could be generated dynamically via database-query list = ['Company A', 'Company B', 'Company C'] if request.method == 'POST': form = ExampleForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('ExamplePage') context = {'form': form, 'coworkers': coworkers, 'list': list} return render(request, 'app/examplepage.html', context) Hopefully there's a solution and someone could help me!? -
How to update same django application hosted on multiple servers all at once
We have developed a django application which has been sold to many clients. We have deployed the application on different server for different clients (as per their budget and requirement). Whenever there are some new features developed, We need to update the django app on all the servers so that each client get the latest update. I want to know whether it is possible to update the django app on all the servers all at once ? -
display label of crispy form after input in tamplet
i'm using django-crispy-forms the default of crispy layout when i use {{ form.module_name|as_crispy_field }}: <div id="div_id_module_name" class="form-group"> <label for="module name" class=" requiredField"> Module name<span class="asteriskField">*</span> </label> <div class=""> <input type="text" name="module_name" id="module name" tabindex="2" class="textinput textInput form-control form-control" required=""> </div> </div> how can i chang layout to the following <div class="md-form"> <input type="text" name="module_name" id="module name" tabindex="2" class="textinput textInput form-control form-control" required=""> <label for="module name" class=" requiredField"> Module name<span class="asteriskField">*</span> </label> </div> => goal of this i want to label Go Up On focus Input Field -
how to display predicted price of stock with Bokeh in django
I m using linear regression to predict the closing price of a stock on the current day. This works fine. I m using Django. I need to add graphs(time-series and a candlestick). after searching I found that Bokeh is best for what I want to achieve. Question: I want to add time-series and candlestick graph in my Django project. Code This is how I m predicting stocks closing price on the current day. stockprediction.py def get_stock_data(name): try: if model_check(name) == False: data_path = os.getcwd()+"\\StockPrediction\\data\\HISTORICAL_DATA\\" df = pd.read_csv(data_path + name + '_data.csv') df.fillna(df.mean(), inplace=True) X = df.iloc[:, [1, 2, 3]] Y = df.iloc[:, [4]] reg = linear_model.LinearRegression() reg.fit(X,Y) y_today = reg.predict([get_nse_data(name)]) model_path = os.getcwd() + "\\StockPrediction\\data\\saved_data\\" file = model_path + name + ".pkl" joblib.dump(reg, file) return y_today[0][0] else: model_path = os.getcwd()+"\\StockPrediction\\data\\saved_data\\" file = model_path + name+".pkl" model = joblib.load(file) y_today = model.predict([get_nse_data(name)]) return y_today except: return ("Error") def get_nse_data(name): data = nse.get_quote(name) current = [data['open'], data['dayHigh'], data['dayLow']] return current Bonus Question: I need graphs which are best for showing stocks price like candlestick and time-series(can you suggest more.) -
Django function that checking new alerts in DB
I will start my first django project in my collage and I want to know how can I make a function that checking every x time or when I have a new row in the "alerts" table DB and after send email or sms to the user. My project is web system monitor. -
Can I use django and connect to a Websocket server as a client?
I'm developing a project in Django and due to some business needs I've to continuously pull data from a Websocket server can I achieve this functionality via Django? -
Django multiple image upload to S3 Bucket
I have made a simple ecommerce site in Django where user is allowed to upload multiple images of a product. These multiple images are required to save in bucket S3. Here models.py: class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.CharField(max_length=200, null=True) posted_date = models.DateTimeField(default=datetime.now, blank=True) size_chart= models.FileField(upload_to='images/', null=True, verbose_name="") class Product_Pictures(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) file = models.FileField(upload_to='images/', null=True, verbose_name="", default="null") Here views.py: def add_product(request): try: files = request.FILES.getlist('pro-image') size_chart = request.FILES.get('size_chart', False) product = Product.objects.create(user = user, title = request.POST.get('title'), description = request.POST.get('description'), size_chart= size_chart) except Product.DoesNotExist: raise Http500() product = Product.objects.latest('id') for photo in files: add_product_pictures(dress, files) return redirect('/ads') def add_product_pictures(dress, photo): photo = 'images/'+str(photo) Dress_Pictures.objects.create(dress = dress, file = photo) So when I try to add a new product with multiple images, only one image gets upload to S3 bucket none else gets upload. Though entry gets save in database and system throws no error. I have tried many ways to manage it but nothing is working it. I am not getting why all files are not getting upload to bucket. Do suggest me some way out. -
Django Rest Framework: URL endpoint to add 'Favorite/Like/Rate' functionality when using Viewsets?
I created a "Recipe" viewset and I would like the functionality of people to be able to favorite different recipes. My Viewset is very simple and it looks something like this: class RecipeViewset(ListModelMixin, RetrieveModelMixin, GenericViewSet): queryset = Recipe.objects.filter(enabled=True) serializer_class = RoutineSerializer This creates 2 endpoints for the list and detail: www.example.com/recipes www.example.com/recipes/1 I have several options in mind of how the endpoint to favorite the recipe could look like: www.example.com/recipes/1/favorite www.example.com/recipes/favorite/1 www.example.com/favorite/recipes/1 www.example.com/recipes-favorite/1 Which would be the best approach and does Django provide an easy way to achieve this? PS: The user will send the Auth Token in the headers so its not required to be sent in the URL. -
How to use JWT with both RESTful and GraphQL in Django
I have a Django project with both restful and GraphQL APIs exposed: /summary/ : restful api powered by django REST framework path('summary/', views.SummaryView.as_view(), name="summary"), /graphql/ : graphql api powered by graphene-django path('graphql/', GraphQLView.as_view(graphiql=True)), I'd like to add JWT to both APIs, but I could only find tutorials for adding JWT for either restful or GraphQL APIs. Is there a way to add JWT auth to both RESTful and GraphQL APIs? -
RetrieveAPIView generated a error 'function' object has no attribute 'get_extra_actions'
I want to get an only object , I don't need an API rest full so I decided use generics.RetrieveAPIView and read the documentation of DRF, but generated an error extra_actions = viewset.get_extra_actions(), AttributeError: 'function' object has no attribute 'get_extra_actions' I dont understand why a mention appears of viewset. from rest_framework.generics import RetrieveAPIView from ..models import * from .serializers import * class DespachoDetail(RetrieveAPIView): queryset = Despacho.objects.all() serializer_class = DespachoSerializer() well here this is the routes file from django.urls import include, path from rest_framework import routers from .views import * router = routers.DefaultRouter() router.register(r'^despacho/<int:pk>', DespachoDetail.as_view(), basename='despacho-detail') urlpatterns = router.urls -
counting blocked users' entries in a title
Block Model: class Block(models.Model): blocker= models.OneToOneField("auth.user",on_delete= models.CASCADE,related_name="blocker") blocked= models.ManyToManyField("auth.user",blank= True, symmetrical=False) Title Model: class Title(models.Model): first_author = models.CharField(max_length = 150) title = models.CharField(max_length = 150, unique = True) created_date = models.DateTimeField(auto_now=True) title_url= models.CharField(max_length = 150) def __str__(self): return self.title def __unicode__(self): return self.title Entry Model: class Entry(models.Model): title = models.ForeignKey("titles.title", on_delete= models.CASCADE) user = models.ForeignKey("auth.user", on_delete= models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) content = models.TextField(max_length=10000,) def get_likes(self): return self.likes.likers.count() def __str__(self): return self.content def __unicode__(self): return self.title I am trying to get the count of a title's entries that belong to users blocked by "request.user". I tried the query below but it didn't work: blocked_count= Entry.objects.filter(user__blocker__blocked=request.user,title=title.title,created_date__gte=date_from).count I know the one below would work if "blocked" was one to one field and "blocker" was many to many field: blocked_count= Entry.objects.filter(user__blocked__blocker=request.user,title=title.title,created_date__gte=date_from).count But I do not want to change the model. So I need to find a solution for my current situation. -
Returning a Profile with associated Products with Django Rest Framework
I'm building a sample iOS app where users would buy and sell products, and I'm trying to design a page where the upper section will have basic profile details and the lower section will have the products that they're currently selling, something like this: Sample Frontend Image So I'm trying to create a Serializer / API endpoint which would give me the Profile, with the products that they are currently selling. My Product model has a ForeignKey relationship to User: class Product(models.Model): def __str__(self): return self.name name = models.CharField(max_length=200) seller = models.ForeignKey(User, on_delete=models.CASCADE, related_name="product_seller") category = models.ForeignKey("Category", on_delete=models.CASCADE) (...) And I have a Profile model which has a one-to-one relationship with the default Django user. As this view will be based on Profiles, I think it would make more sense to serialize the User or the Profile model and get the products where they are the "seller". So the JSON response that I want is something like this: { "id": 1, "username": “some username”, "profile_image": "http://192.168.1.101:8000/images/profile_pictures/732339C5-E419-4A3D-9022-A314416F5F02.png", "description": “Some description for this particular profile.” “products”: [ { “id”: 1, “image” = http://192.168.1.101:8000/images/abc.jpg, }, { “id”: 2, “image” = http://192.168.1.101:8000/images/abc.jpg, }, { “id”: 3, “image” = http://192.168.1.101:8000/images/abc.jpg, } ] } What would …