Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a Django Graphql Generator?
I am wondering if there a way to automatically generate graphql queries and mutations in Django applications. Using Ariadne + Django + Python 3.9 system i created is here: https://github.com/bastianhilton/Alternate-CMS -
Django sum values of from a for loop in template
I want to show the sum for the values (cals, protein, carbs, etc) of multiple foods in a new table but have no idea how to do it in a django template. Heres what the for loop displays {% for food in meal.foods.all %} <div class='table-container'> <table class='food-table'> <thead> <tr> <th>Name</th> <th>Calories</th> <th>Protein</th> <th>Carbs</th> <th>Fat</th> <th>Sugar</th> <th>Sodium</th> </tr> </thead> <tbody> <tr> <td>{{ food.name }}</td> <td>{{ food.calories }}</td> <td>{{ food.protein }}g</td> <td>{{ food.carbs }}g</td> <td>{{ food.fat }}g</td> <td>{{ food.sugar }}g</td> <td>{{ food.sodium }}mg</td> </tr> </tbody> </table> </div> {% endfor %} The new table would look like this but just display the totals. -
How do I create a delete button in the Image field?
I'm new to programming and I'm taking my first steps, especially in django, in this case I used ImageField to upload images on the site I'm programming, but it only shows the path of the image and I was wondering how I could add a delete button to the page to edit a post...enter image description here enter image description here -
Save a field as hash and compare it in django
I created my own user model: class CustomUser(AbstractBaseUser,PermissionsMixin): phone_number = models.CharField(verbose_name="Mobile Number", max_length=11, unique=True, blank=False, null=False) security_code = models.IntegerField(verbose_name="Security Code",default=create_security_code) security_code_creation = models.DateTimeField(auto_now=True) a user can login with password or security code. I will text them the security code if needed. but I don't want to store security code as plain text in my database. I want to store it like password (hashed). I found from django.contrib.auth.hashers import make_password which I can use to create a hashed version of security code. my question is should I write a separate authentication backend or simply write/use a function like check_password that is implanted in AbstractBaseUser? -
Validating nested dictionaries containing dynamic keys using DRF Serializers
I am working on writing serializers for an existing API for the purpose of auto-generating OpenAPI documentation for the project. One of the issues I'm running into is defining serializers to validate the returned data from some of the views. Here is the structure of the data: { "airmass_data": { "site-A": { "times": ["2021-09-09T09:54","2021-09-09T10:04"], "airmasses": [2.900041850251779, 2.687634707193725] }, "site-B": { "times": ["2021-09-09T09:54","2021-09-09T10:04"], "airmasses": [2.900041850251779, 2.687634707193725] }, ... }, "airmass_limit": 3.19 } There can be an arbitrary number of "site-X" keys, and they are dynamically generated - which is definitely part of my issue. Here is how I've set up my serializers, which I think mostly matches my dictionary structure: class SiteAirmassDatumSerializer(serializers.Serializer): times = serializers.ListField(child=serializers.CharField()) airmasses = serializers.ListField(child=serializers.FloatField()) class SiteAirmassSerializer(serializers.Serializer): site = SiteAirmassDatumSerializer(source='*') class AirmassSerializer(serializers.Serializer): airmass_data = SiteAirmassSerializer(source='*') airmass_limit = serializers.FloatField() However, when passing my dictionary into the the serializer and attempting to validate it, the serializer.errors attribute has: { "airmass_data": { "site": [ "This field is required." ] } } Is there a good way to write a set of serializers such that it deals with dynamically generated keys? I am mostly trying to write this to validate the general structure of the returned dictionary - not necessarily the keys … -
Heroku wont connect to my django database
my database is the default sqlite3 database, I tried with multiple projects but Heroku won't connect to the database, hope u guys will help me I'm new to Heroku i don't know if I'm missing something these are my settings setup for Heroku, I have no static files import django_heroku import dj_database_url ALLOWED_HOSTS = ['*'] DATABASES = { 'default': dj_database_url.config() } django_heroku.settings(locals()) -
In Django template button is not working as expected
In my project, I used the function toggle_follow which is working fine but in my template on the first click nothing changed in the second click it turns to unfollow as expected, and after again clicking it becomes to follow which is also expected. After that, it doesn't work. Though the follow shows in the following tab and update the list but the button stopped working. The problem is, the follow counter is not updating properly and not storing into database as If I follow someone and another user visit the same profile, the user by default see that he is following the user also whom I'm following which is not as expected. However, for first three time the result is expected and working properly. my models.py >>> class Follow(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follow") followed = models.ForeignKey(User, on_delete=models.CASCADE, related_name="followers") class Meta: verbose_name = "following" verbose_name_plural = "followings" unique_together = ["user", "followed"] def str(self): return f"{self.user} is following {self.followed}" def followed_post(self): return self.followed.posts.order_by("-date").all() my views.py >>> @login_required def toggle_follow(request, id): if request.method == "GET": return HttpResponse(status=405) if request.method == "POST": try: follow_obj = Follow.objects.get(user=request.user.id, followed=id) except Follow.DoesNotExist: try: to_follow = User.objects.get(pk=id) except User.DoesNotExist: return HttpResponse(status=404) else: new_follow_obj = Follow(user=request.user, followed … -
How to learn python pandas with django?
Trying to integrate python pandas scripts with django, but it's not working. Is there any good course or book to recommend? -
Django: Is there a way to let Heroku manage js and css files but let images come from S3 bucket?
I am buiding an app with django. I uploaded all my static files to an S3 bucket. Js and css files included. And in DEBUG = False I'm getting my files from that bucket I am hosting my app in Heroku, so I couldn't serve images from there. That's way I'm getting my images from an externar source. But now I'm facing some problems when I have all my files in the S3 bucket. And I also think it's not really necessary to serve js and css from there too. So is there a way to let images come from the S3 bucket but serve my js and css files from the host (heroku)? -
Django filtering ForeignKey
This is view: def post(self, request): author_request = request.data.get("author") queryset = Book.objects.filter(author=author_request) serializer = BookSerializer(queryset, None) return Response(serializer.data, HTTP_200_OK) This is model: class Author(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) full_name = models.CharField(max_length=255, null=True, blank=True) about = models.TextField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.full_name class Meta: verbose_name = 'Author' verbose_name_plural = 'Authors' So, when i try to filter the book by author i get the error. The error tells me that the POST data that i entered which is "Aleksa Petrovic" a name of a author that exists in the database is not an UUID. So when i filter it, it filters by UUID and i want it to filter by "full_name" -
Can AWS SQS be Used in a Django Project with django-celery-results Backend?
Pre-warning: there is A LOT I don't understand My Requirement I need to be able to get the result of a celery task. I need the status to change to 'SUCCESS' when completed successfully. For example: I need to be able to get the result of x + y after executing add.delay(1,2) on the task below. myapp/tasks.py from celery import shared_task from time import sleep @shared_task def add(x, y): sleep(10) return x + y Is AWS SQS the right tool for my needs? I read Celery's Using Amazon SQS and understand at the bottom it says this about the results. Results Multiple products in the Amazon Web Services family could be a good candidate to store or publish results with, but there’s no such result backend included at this point. Question: Does this mean django-celery-results can't be used with AWS SQS? More Context Below What I am doing executionally? I look at my AWS queue (shows messages available as 3) In my local terminal, I do celery -A ebdjango worker --loglevel=INFO (see celery output below) In my PyCharm Python console connected to my Django project, I do r = add.delay(1,2) r is an AsyncResult object: >>> r = add.delay(1,2) >>> … -
Django - How to access POST data in GET method part of a view without saving the data in the database?
I have something like: def my_view(request): if request.method == POST #upload a json file and parse data from it parsed_data = parser.parse() else: #define some forms and variables context = { 'parsed_data' = !what do I put here??! } return render(request, 'file.html', context=context) What shoud I put in the context? If method is GET, parsed_data will not exist, if it is POST, parsed_data will exist but won't go to db. How do I keep its value without storing it in db? -
Remove helper text in Django forms
I have a form in Django for adding an object to an app. On the form I want to remove the helper text from the form. I have done this already in another form, but I can't seem to replicate the removal. Any ideas, my code is below: from django import forms from .models import Node class DateInput(forms.DateInput): input_type = 'date' class NodeCreateForm(forms.ModelForm): class Meta: model = Node fields = ('nickname', 'address', 'date') help_texts = { 'nickname': None, 'address': None, 'date': None } widgets = { 'date': DateInput(), } -
How can I remove "multiple" attribute from django_filters form select field?
Im trying to create a filter form for a table using django-filter. I have the filter working for the fields I want, however for the two ManyToMany fileds in my model, django_filters is creating a select field with the multiple attribute, I do not want that multiple attribute how can I remove it? Here is my model (partial) class Employee(models.Model): ... ... abilities = models.ManyToManyField("capa.CapaType" blank=True) responsibilities = models.ManyToManyField(Responsibilities, blank=True ... ... Class Responsibilities(models.Model): ... title = models.CharField(max_length=30) description = models.CharField(max_length=256) ... capa.CapaType is similar to roles just elsewhere in the project filter.py import django_filters from .models import Employee class EmployeeFilter(django_filters.FilterSet): class Meta: model = Employee fields = ('abilities', 'responsibilities') From what I have read on various other stack overflow questions such as this Django_filters Widget Customize, I should be able to set the widget style in filter.py, but when I tried something similar to the following in the EmployeeFilter class; responsibilities = django_filters.MultipleChoiceFilter(choices=Employee.responsibilities.all(), widget=forms.Select(attrs={'class': 'form-control'})) I get this error in the server console; AttributeError: 'ManyToManyDescriptor' object has no attribute 'all' Removing "all()" gives me this error when I try to load the page 'ManyToManyDescriptor' object is not iterable Any ideas how I can make these fields non multiple? Thanks -
Nginx and Django not acting as expected
I am using Django and have created a custom user model, along with WSGI and Nginx to hand the webserver. All is working well but the user authentication is not working, and the admin login panel does not have any css in it. . -
Auto increment an element value when a URL is hit using API
I am new to DRF, so apologies if it's a trivial question. I want to create an API endpoint to auto-increment the value of a column in the database, whenever a specified URL is hit. For instance--> In the models.py file I have: models.py class User(models.Model): name = models.CharField(null=False, blank=False, max_length=250) error= models.IntegerField(null=False, blank=False) How should I write a view function so that whenever the associated URL hits, the value of error increments by 1? In the URL the ID of the row should also be passed such as: localhost:8000/users/error/2 Upon hitting the above URL the value of the error for user 2 should be increased by one. Thanks, -
How to add Item to cart on ListView Django/
I am making django app, adding items to cart in detail-view work fine but i struggle with implementation the same on ListView. What should I do? views.py class ShopListView(ListView): model = Item template_name = 'shop/home.html' context_object_name = 'items' def post(self, request, *args, **kwargs): pk = self.kwargs.get('pk') item = get_object_or_404(Item, id=pk) orderItem, created = OrderItem.objects.get_or_create(order_item=item) order, created = Order.objects.get_or_create(order_user=request.user) order.save() order.order_items.add(orderItem) return HttpResponse('Items added') Also if i do post(self,request,pk) as in DetailView i get an error one argument is missing 'pk'. class ShopDetailView(DetailView): model = Item template_name = 'shop/detail.html' context_object_name = 'item' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = Comment.objects.filter(item=self.object) context['form'] = CommentCreationForm() return context def post(self, request, pk): if 'buy' in request.POST: item = get_object_or_404(Item, id=pk) orderItem, created = OrderItem.objects.get_or_create(order_item=item) order, created = Order.objects.get_or_create(order_user=request.user) order.save() order.order_items.add(orderItem) return HttpResponse('Items added to the database') if 'comment' in request.POST: form = CommentCreationForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.comment_user = request.user comment.item = Item.objects.get(id=pk) comment.save() return HttpResponse('post-created') else: return HttpResponse('post not created') DetailView works fine. -
BeautifulSoup - reading pages that require wait
quick question, I built a webcrawler class that fetches links from the page, I have problem with specific pages that dont load as a whole html, only load more content when you scroll down (if that makes sense). There's especially one specific page that I need for my project that does that Currently I load links with beatifulsoup in this way: #newurl is url passed into a function newurl = newurl.encode('ascii', 'ignore').decode('ascii') resp = urllib.request.urlopen(newurl) soup = BeautifulSoup(resp, self.parser, from_encoding=resp.info().get_param('charset')) links = [] return links But in result, number of fetched links differs every run! Is there an option for BeautifulSoup to 'wait' while opening url, maybe 10 sec, to get all more content loaded into the page and then fetch links? Or maybe completely different method? Thanks for any suggestions -
Cache router in Django - how to run python manage.py createcachetable properly for the related database
I am using Django for my project. I need to generate a new cache table in the database. The command python manage.py createcachetable doesn't work for db_my_project instead it works for the default one. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'db_my_project': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_db', 'USER': 'my_username', 'PASSWORD': 'my_password',, 'HOST': 'my_host', 'PORT': '3306', }, } I have the following cache settings in the settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'dataframe_cache', } } As you can see above from its location info, it is supposed to generate a the table 'dataframe_cache'. It is generating that table for the default database (db.sqlite3), but not for the db_my_project (mysql). I know that I should implement a cache router class like below. class CacheRouter: """A router to control all database cache operations""" route_app_labels = {'db_my_project'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'db_my_project' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'django_cache': return 'db_my_project' return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'db_my_project' return None My question is that where do I put this CacheRouter class in my Django project so that I can generate … -
Django - how to import sendgrid python library?
I would like to use Sendgrid's python library so I can use their Web API for sending email from Django. I installed the library and their example code says to from sendgrid import SendGridAPIClient. Django does not recognize this module though - import sendgrid could not be resolved. I am running django inside docker, I did docker-compose down and then docker-compose up -d --build after install sendgrid. I feel like I'm missing a fundamental step here. PS C:\Users\Doug\OneDrive\django\smartmark> pipenv install sendgrid Installing sendgrid… Adding sendgrid to Pipfile's [packages]… Pipfile.lock (1e7343) out of date, updating to (4cf710)… Locking [dev-packages] dependencies… Success! Locking [packages] dependencies… Success! Updated Pipfile.lock (1e7343)! Installing dependencies from Pipfile.lock (1e7343)… ================================ 37/37 - 00:00:02 PS C:\Users\Doug\OneDrive\django\smartmark> -
How do I make a button click change the django order_by?
Here's my views.py function. def publications(request): if request.method == 'POST': publications = UserPublications.objects.all().order_by('status_date') else: publications = UserPublications.objects.all().order_by('contributors') context = {'publications': publications} return render(request, 'users/publications.html', context) Here's my publications.html: <button type="submit" method="POST">Filter By Date</button> <ol class="text"> {% for publication in publications %} <div>{{publication.text}}</div> {% endfor %} </ol> I want a button to be clicked on and if someone clicks on it it changes to filter by date instead of by contributors (both attributes of my model). How would I do that? Right now I have no errors but when I click on the button it's not updating the sorting on my objects. Thanks in advance. -
Validation using clean method in models.Model Django
I try to use the clean method to validate fields so if the category equals to "cars" then the x field should't be entered. I tried something like this below, but it doesn't work at all. class Category(models.Model): name = models.CharField(primary_key=True, max_length=100) def __str__(self): return self.name class Product(models.Model): def clean(self): if self.category == "cars" and self.x is not None: raise ValidationError( _('information')) category = models.ForeignKey( Category, on_delete=models.PROTECT, default='cars') x = models.CharField( max_length=10, choices=X_OPTIONS, blank=True) When I am sending category: "cars", x: "sth", it doesn't hangle the error. -
Can't disconnect from Google OAuth2 using social-auth-app-django
I followed the official docs to set up the Disconnection pipeline in a Django project. Following other posts like, this and this I put in a Log out button a POST requisition to disconnect the Google OAuth2 account. So, in summary, I have: settings.py SOCIAL_AUTH_DISCONNECT_PIPELINE = ( # 'social_core.pipeline.disconnect.allowed_to_disconnect', 'social_core.pipeline.disconnect.get_entries', 'social_core.pipeline.disconnect.revoke_tokens', 'social_core.pipeline.disconnect.disconnect', ) template: <form action="{% url 'social:disconnect' 'google-oauth2' %}" method="post"> {% csrf_token %} <button>Sair</button> </form> But doing that, the Google Account is not logged out. The Home page is just refreshed. This is what I get in virtual webserver log: "POST /disconnect/google-oauth2/ HTTP/1.1" 302 0 "GET / HTTP/1.1" 200 4988 If I had another tab with Gmail logged in and refresh the page I keep logged in. Is there anything I'm missing? -
Django cannot resolve the name of the db service
I have a django application dockerized and a postgresql server. I'm using docker compose to put both them together. The problem is that I always get this error: web_1 | django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known This is my docker-compose.yml file: version: '3' services: web: image: "badger-dev" ports: - "8000:8000" volumes: - .:/app links: - db:db depends_on: - db db: image: "badger-postgres" container_name: db ports: - "5432:5432" I have also tried the following config with the same result: version: '2' services: web: image: "badger-dev" ports: - "8000:8000" volumes: - .:/app links: - db:db networks: - djangonetwork db: image: "badger-postgres" container_name: db ports: - "5432:5432" networks: - djangonetwork networks: djangonetwork: driver: bridge These are my settings: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'dbhvu01u3e3fug', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', # Use PgPool } } Any idea why it's not working? -
Django ForeignKey returning id instead of name
Api return Models Serializers And so i want to get the author name instead of id