Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Assigning a Class for a label in the Django forms
I am trying to add a class for label in a custom django form. I am able to add class to the input but for the labels I have been struggling for a while: Here is the form: class infoForm(ModelForm): class Meta: model = Info fields = ['businessName'] widgets={ 'businessName':forms.TextInput(attrs={"class": 'form-control'}), } labels = { 'businessName': 'Business Name', } Here is the model class Info(models.Model): businessName = models.CharField(max_length=100) My question: How to add the class form-label inside the label of every input? Thank you -
raise validation error if there is two president for the same club?
in my model, I don't want two presidents for the same club. I have 6 clubs so I will have 6 presidents too no more. I'm new to validation I tried to use the clean method but the error won't get raised. my model: class MyUser(AbstractUser): STUDENT = 1 INSTRUCTOR = 2 ADMIN = 3 ROLE_CHOICES = ( (STUDENT, 'student'), (INSTRUCTOR, 'instructor'), (ADMIN, 'admin'), ) club_name = ( (0, 'ISOM'), (1, 'Accounting'), (2, 'PA'), (3, 'Finance'), (4, 'Management & Marketing'), (5, 'Economics'), ) is_president = models.BooleanField(default=False) club_name = models.IntegerField(choices=club_name, default=0, verbose_name='Club/Department') roles = models.PositiveSmallIntegerField(choices=ROLE_CHOICES) the validation I used: def clean(self): club = MyUser.objects.all() president = MyUser.objects.all() try: club.objects.get(club_name__iexact=club_name) president.objects.get(is_president__iexact=is_president) except club.DoesNotExist: return club_name, is_president raise ValidationError(_("A president for this club already existed.")) -
How do fix OperationalError: no such column: "something" in django?
I have a model in models.py called location with a field named "something" and whenever I use the manage.py migrate command after the makemigrations command I get the "django.db.utils.OperationalError: no such column: "something"" error. I've seen other people ask questions like this but none of the answers help me, can someone heko me out -
Running into Redis Connection error when adding a second queue to django-RQ
This issue is most likely because of my misunderstanding of how django-RQ/redis works. I've been using django-rq with great results to run/cache long running processes. However, we're now in a position where we need to split up some of these processes into different queues. The docs make this seem easy enough. However, I get the following error when trying to send a task to the pro queue: Could not resolve a Redis connection I was thinking it was possibly because I'm using the same connection info for both queues, but I've seen other examples that do the same thing (https://newbedev.com/how-to-create-multiple-workers-in-python-rq). Where did I go wrong? (I included the local and heroku settings as the same issue exists in both). if(on_heroku): RQ_QUEUES = { 'default': { 'URL': os.getenv('REDISTOGO_URL', 'redis://localhost:6379/0'), # If you're on Heroku 'DEFAULT_TIMEOUT': 500, }, 'pro': { 'URL': os.getenv('REDISTOGO_URL', 'redis://localhost:6379/0'), # If you're on Heroku 'DEFAULT_TIMEOUT': 500, } } else: RQ_QUEUES = { 'default': { 'HOST': 'localhost', 'PORT': 6379, 'DB': 0, 'DEFAULT_TIMEOUT': 500, }, 'pro': { 'HOST': 'localhost', 'PORT': 6379, 'DB': 0, 'DEFAULT_TIMEOUT': 500, } } -
Listen to mqtt topics with django channels and celery
I would like a way to integrate django with mqtt and for that the first thing that came in my mind was using django-channels and an mqtt broker that supports mqtt over web sockets, so I could communicate directly between the broker and django-channels. However, I did not found a way to start a websocket client from django, and acording to this link it's not possible. Since I'm also starting to study task queues I wonder if it would be a good practice to start an mqtt client using paho-mqtt and then run that in a separate process using celery. This process would then forward the messages receives by the broker to django channels through websockets, this way I could also communicate with the client process, to publish data or stop the mqtt client when needed, and all that directly from django. I'm a little skeptical about this idea since I also read that process run in celery should not take too long to complete, and in this case that's exactly what I want to do. So my question is, how much of a bad idea that is? Is there any other option to directly integrate django with mqtt? *Note: … -
Add a download functionality in django change view
I already added a button alongside the save buttons for my django change view: {% extends 'admin/change_form.html' %} {% load static %} {% load i18n %} {% block submit_buttons_bottom %} <div class="submit-row"> <input type="submit" value="Download" id="download_profile" name="_continue"> <input type="submit" value="{% trans 'Save' %}" class="default" name="_save"> <input type="submit" value="{% trans 'Save and add another' %}" name="_addanother"> <input type="submit" value="{% trans 'Save and continue editing' %}" name="_continue"> <!-- inmport script --> <script src="{% static '/js/downloadData.js' %}"></script> <script src="{% static '/js/collapsibleSection.js' %}"></script> <script src="{% static '/js/investmentAdminScript.js' %}"></script> {% endblock %} and I already started adding the script to retrieve individual data per row to download them. 'use strict'; window.addEventListener('load', () => { const downloadButton = document.querySelector('#download_profile'); downloadButton.addEventListener('click', e => { if (!confirm('Data will be saved before downloading. Are you sure you want to continue?')) { e.preventDefault(); return; } // get module const fieldsets = document.querySelectorAll('fieldset'); fieldsets.forEach(thisFieldset => { const dataRows = thisFieldset.querySelectorAll('.form-row'); dataRows.forEach(dataRow => { // retrieve each input field and add a download to .xlsx function }); }); }); }); However, it gets complicated very fast. Is there a better way to do this? -
Django Rest Framework Serializing Custom Field
I am trying to serialize a custom field that is not on my model. The queryset code groups the model on the item1 field and generates a count column. There is no count field on my Data model. views.py class GetDataGroups(generics.ListAPIView): serializer_class = DataSerializer def get_queryset(self): queryset = ( Data.objects.values("item1") .annotate(count=Count("item1")) .order_by() ) return queryset serializers.py class DataSerializer(serializers.ModelSerializer): count = serializers.CharField(write_only=True) class Meta: model = Data fields = ["item1", "count"] How do I also get the count field to show up in my rest api? -
django restrict value to a foreign key of a foreign key
I have three models Address: Representing an address Itinerary: Representing a set of addresses. It has ManyToManyField relation with Address Appointment: Representing Address within the itinerary. It has a Foreign key to Itinerary and a Foreign Key to Address. What I am trying to understand is what's the best way to establish a relationship between Appointments and Itinerary/Address so that when selecting an address for an appointment, users can only chose among the addresses associated with the Itinerary to which the appointment is associated. Basically I am trying to limit the choices of the field app_location within the Appointment model to only have as selection-able options Address present in the location field of Itinerary model (associated with appointment) class Address(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) address1 = models.CharField("Address line 1", max_length=1024,) zip_code = models.CharField("ZIP / Postal code", max_length=12, blank=True, null=True) class Itinerary(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title=models.CharField(max_length=40) location=models.ManyToManyField(Address, related_name='location') class Appointment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) app_location=models.CharField(max_length=20) contact=models.ForeignKey(Contact, on_delete=models.CASCADE, blank=True, null=True) itinerary=models.ForeignKey(Itinerary, on_delete=models.CASCADE, blank=True, null=True) -
How to create two models with required ForeignKey fields to eachother?
I have two models, both of them with a ForeignKey field to eachother. from django.db import models class County(models.Model): capital = models.ForeignKey("Municipality", on_delete=models.PROTECT, related_name="capital_of") class Municipality(models.Model): county = models.ForeignKey(County, on_delete=models.CASCADE, related_name="municipalities") With these models, I'm unable to create nor an instance of County or Municipality. What should I do to fix it? -
Django + Dockerfile + Cron
I have been working on a task for a few days. Building a separate Dockerfile (not using docker-compose just a stand alone Dockerfile) that is supposed to produce an image and run a cron job which I have not done before. I believe I am almost there, but running into a config/settings issue when running the script. I have a short Dockerfile here... FROM python:3.7.8-alpine RUN apk update RUN apk add --no-cache libpq postgresql-contrib python3-dev RUN apk add --no-cache supervisor postgresql-dev RUN python3 -m pip install --upgrade pip ADD ./app/requirements.txt /files/requirements.txt ADD ./app/reqs/ /files/reqs/ RUN python3 -m pip install -r /files/requirements.txt RUN touch /var/log/cron.log ADD cronjobs/crontab.txt /crontab.txt ADD cronjobs/cron_script.sh /cron_script.sh ADD ./script.py /script.py COPY cronjobs/entry.sh /entry.sh ADD ./script.py /app COPY ./script.py /app RUN chmod +x /script.py RUN chmod 755 /script.sh /entry.sh RUN /usr/bin/crontab /crontab.txt COPY . /cron_app CMD ["/entry.sh"] crontab.txt file here.. * * * * * /cron_script.sh > /dev/stdout entry.sh file here. #!/bin/sh echo "Docker container running....." /usr/sbin/crond -f -l 8 Script which calls the main python script. #!/bin/sh echo "Python script running..." cd /cron_app python3 send_email.py echo "python script has finished..." The script sends an email, which uses django's settings, and email config in my settings file which … -
Unable to create using .object.create() in DJANGO 3.5+
I am having trouble creating objects using '.objects.create()' in Django v3.5+ here is my create function - order = Order.objects.create( txn_id = txn_id, user = request.user, payment_id = pay_id, gateway_order_id = str(gateway_order_id), gateway_signature = str(signature), amount = basket.get_total_price(), payment_option = "Wallet", order_status = True,) Here are they values captured and trying to populate - 9 teddy pay_HbkHTcQsUzT0Rb order_HbkH3jmcvfhQR8 53fa5704b595832d472ccc08e193d2b686078d78ca7fa7e403f763c753568433 90.00 Wallet True and here is the corresponding model class Order(models.Model): txn_id = models.ForeignKey(Transaction, on_delete=models.CASCADE, related_name="order_txn") user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="order_user") payment_id = models.CharField(max_length=100, null=True, blank=True) gateway_order_id = models.CharField(max_length=100, null=True, blank=True) gateway_signature = models.CharField(max_length=100, null=True, blank=True) amount = models.DecimalField(max_digits=5, decimal_places=2) payment_option = models.CharField(max_length=200, blank=True) order_status = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ("-created",) def __str__(self): return str(self.created) any assitance would be appreciated. Many Thanks in Advance! -
Django OAuth Toolkit refresh token using okta workflow API Connector
I have successfully created an oauth provider and can verify that I am able to get a token and refresh token using django-oauth-toolkit. While using [okta workflow api connector][1] OAUTH option, it is able to get the token after going through the initial setup. However, once that initial token expires, it is not getting a refreshed token as expected. The scope that the connector is setup with is an additional scope that I added to the settings.py of my django project via the SCOPES setting similar to how the doc's show in [this link][2]. As I am new to django-oauth-toolkit. My first question is does a new scope added via this method need to have additional configuration in order to allow an oauth2 connection to get a refresh token? I am using django-oauth-toolkit 1.5.0 [1]: https://help.okta.com/wf/en-us/Content/Topics/Workflows/function-reference/HTTP/http_authorization.htm [2]: https://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html -
Applying and managing Django migrations in Skaffold development environment
I'm not satisfied with my current workflow related to managing Django migrations and it really feels like there should be a better way. As part of my environment setup shell script, it creates a .venv and adds env vars to it for DB connection strings and the such. When I work on models and need to migrate this gives me the ability to run ./manage.py migrate in the local environment to apply them. This is really the only purpose it serves. It also adds the same env vars to Kubernetes secrets for the cluster. I came across this where someone had a similar issue, but was kubectl exec into the Pod: How to keep Django 2.2 migrations on Kubernets while developing? That would mitigate the need to run ./manage.py locally and thus have the env vars, but kubectl exec into the Pod just to run ./manage.py migrate seems like an even bigger hassle. It seems like there should be a better way. Suggestions? -
Django Rest Framework URL filter only specific fields from Database
I did try to search my problem in StockOverflow or Google, but I can find only how to make Search results and how to make search on specific fields, but I need API output with specific fields with URL request. I have DB with those fields: date = models.DateField(['%Y-%m-%d']) channel = models.CharField(max_length=255) country = models.CharField(max_length=255) os = models.CharField(max_length=255) impressions = models.IntegerField() clicks = models.IntegerField() installs = models.IntegerField() spend = models.FloatField() revenue = models.FloatField() I did create different filters which can be used to GroupBy, ordering and another good features. The problem is: for example I have task to: Show the number of impressions and clicks that occurred before the 1st of June 2017, broken down by channel and country, sorted by clicks in descending order. If I use this: http://127.0.0.1:8000/api/stock?date_to=2017-05-19&groupby=channel&groupby=country&ordering=-clicks It will give me this result: "results": [ { "channel": "adcolony", "country": "US", "impressions": 101292, "clicks": 2479, "installs": 445, "spend": 743.6999999999999, "revenue": 965.12, "CPI": "1.67" }, It was Grouped by "channel" and "country" for specific date in DESC order. But how to make additional URL inputs (like show only "impressions" and "clicks")to show ONLY those: "results": [ { "channel": "adcolony", "country": "US", "impressions": 101292, "clicks": 2479, }, This is my … -
sudo apt install python3-dev for windows
I'm trying django-oscars demo and I'm wanted to test it out but I'm literally stuck on the first part lol. I need help since I can't use sudo for windows what should I do then? "sudo apt install python3-dev" djang-oscar -
KeyError at /home 'assets', using webpack loader
I'm working on a small project using Django and VueJS, i just install django-webpack-loader and "webpack-bundle-tracker": "^0.4.3", and i got an error while rendreding : KeyError at /home 'assets' This is my code : {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Hello</title> </head> <body class="sidebar-enable vertical-collpsed"> <!--<h1>Vue JS</h1>--> <div id="app"></div> {% render_bundle 'app' %} </body> </html> -
Page not found, request method: get using Django when all pages correctly in urls.py
I know there are many similar posts, but having tried: Page not found (404) Request Method: GET Django -Page not found (404) Request Method: GET Method Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/about I'm still not able to solve this problem. This is a practice sample from cs50w. I get this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in airline.urls, Django tried these URL patterns, in this order: admin/ flights/ users/ The empty path didn’t match any of these. I have a main urls.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path("flights/", include("flights.urls")), path("users/", include("users.urls")) ] urls.py in flights: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<int:flight_id>", views.flight, name="flight"), path("<int:flight_id>/book", views.book, name="book") ] and in users, url.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout") ] My settings.py: """ Django settings for airline project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os … -
Django with dropzone multiple images do not upload in CBV
Im working on bulletin board for sporting shoes with django. For now my goal is to give an opportunity for users create and post their own bboards with information from models through model.Forms. And the biggest problem is upload propely multiple images using dropzone.js, i spend lots of time for this problem. The first part on 'addpage.html' is usual forms with text and selected inputs, but the second one is the dropzone js div class, cause i know i cannot affort to use 2 forms straight on current page. My question is how am i have to organize my CreateView at views.py for uploading images on server. For now i have only traceback 'AddCardCreateView' object has no attribute 'object!!! And dictionary of images is empty So let's see my code. We will start from models.py (ImagePhoto fk to Card) class Card(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, verbose_name='Пользователь') category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категория') brand = models.ForeignKey(Brand, on_delete=models.PROTECT, verbose_name='Бренд') boots_model = models.CharField(max_length=100, db_index=True, verbose_name='Модель бутс') description = models.TextField(verbose_name='Описание') slug = AutoSlugField('URL', max_length=70, db_index=True, unique_with=('created', 'boots_model', 'size', 'color', 'price'), populate_from=instance_boots_model, slugify=slugify_value) price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='Цена') created = models.DateTimeField(auto_now_add=True, db_index=True) updated = models.DateTimeField(auto_now=True) size = models.DecimalField(max_digits=4, decimal_places=1, verbose_name='Размер') NEW = 'new' USED = … -
Django ModelForm Widget attributes generation in HTML
What is the proper way to have Django rendering widgets to html elements with correct attributes? Following the documentation I did the following for my class: CLASS: class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='TravelsApp/profile_pics',blank=True) phone_number = models.CharField() credits = models.PositiveIntegerField(default=10) exp_date = models.DateField(default = timezone.now) ..... FORM class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ('profile_pic', 'phone_number', 'exp_date') widgets = { 'profile_pic': forms.ClearableFileInput(attrs={'class': "w3-btn w3-blue w3-center"}), 'phone_number': forms.TextInput(attrs={'class': "w3-input", 'required':'True'}), 'exp_date': forms.DateInput(attrs={'class': "w3-input", 'required':'False', 'disabled': 'True'}), } ....... VIEW: def register(request): ....... # GET: Just render the forms as blank. user_form = UserForm() profile_form = UserProfileInfoForm() return render(request,'TravelsApp/registration.html', {'user_form':user_form, 'profile_form':profile_form, }) When register() gets called and the code after #GET is executed the 'exp_date' UserProfileInfoForm is not rendered properly : HTML: <p><label for="id_exp_date">Exp date:</label> <input type="text" name="exp_date" value="2021-07-21" class="w3-input" disabled="True" required id="id_exp_date"> <input type="hidden" name="initial-exp_date" value="2021-07-21 20:06:53+00:00" id="initial-id_exp_date"></p> The attribute 'required' is present (hence meaning required = true) while it should be set to false (It also generates this 'initial-exp-date' which is hidden and I think it's added just for security reasons) I tried to play around for one long evening then I noticed that if I change the form definition removing the 'exp_date' from the 'fields' … -
Add a button along save buttons in Django Admin Change Form
I have this code for a custom change_form: {% extends 'admin/change_form.html' %} {% load static %} {% load i18n %} {% block after_related_objects %} <button>Another button</button> {% endblock %} {% block submit_buttons_bottom %} {{ block.super }} <!-- import script --> <script src="{% static '/js/collapsibleSection.js' %}"></script> <script src="{% static '/js/investmentAdminScript.js' %}"></script> {% endblock %} which produces this view: It works fine but I wanted to add it inside the button row below: I tried to change the code to: {% extends 'admin/change_form.html' %} {% load static %} {% load i18n %} {% block submit_buttons_bottom %} <button>Another button</button> {% endblock %} {{ block.super }} <!-- import script --> <script src="{% static '/js/collapsibleSection.js' %}"></script> <script src="{% static '/js/investmentAdminScript.js' %}"></script> {% endblock %} but it's giving me an invalid block error. How do I add the button element to produce the result in the image above? -
Django custom user error when registering: get_session_auth_hash() missing 1 required positional argument: 'self' (new user can otherwise log in)
I am aware of this answer: TypeError: get_session_auth_hash() missing 1 required positional argument: 'self', but I am not using a custom backend and the error in question happens when registering a new user through a Django form, not when logging in. Further, whilst the user does not remain logged in when registering and is not automatically redirected to the main page as intended, logging in from the log in form seems to function normally. The error happens on this line in my registration view: login(request, User) And traces back to this line in django.contrib.auth: if user is None: user = request.user if hasattr(user, 'get_session_auth_hash'): session_auth_hash = user.get_session_auth_hash() <<<<<<<<< This line I think because I'm using a custom user, there's something else I need to modify in the default code, but I'm not sure what this should be. I think the custom user model should be interchangeable with the default user model, but it isn't and I'd welcome someone with more experience than me pointing me in the right direction. My code as follows: Custom user model and manager in models.py: from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, password = None, active = True, staff = False, superuser … -
Django get all objects whose many to many filed contains a filter
I have 3 models: City: indicating a city Titles: indicating job titles Contacts: indicating people. A person can have multiple titles and multiple cities Now, given an city object and a title object, I want to query for all people that have those objects in their instance. Basically something like "All Lawyers in NY". class City(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name=models.CharField(max_length=40) state=models.CharField(max_length=15) class Title(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title_name=models.CharField(max_length=40) class Contact(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name_surname = models.CharField(max_length=60) title = models.ManyToManyField(Title) city = models.ManyToManyField(City) -
Django models create multiple choices field with status
I have a question about my models, I need to create a post request in which I select a couple of people for one POST and I want to add a status to each of them assigned to a given person my models.py class Daily(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) team = models.CharField(choices=utils.TEAM, max_length=8, default=None, blank=False) person1 = models.CharField(choices=utils.PERSONS, max_length=15, default=None, blank=True) person2 = models.CharField(choices=utils.PERSONS, max_length=15, default=None, blank=True) person3 = models.CharField(choices=utils.PERSONS, max_length=15, default=None, blank=True) date = models.DateField() class Meta: ordering = ('-date',) constraints = [ models.UniqueConstraint(fields=['user', 'date'], name='name of constraint') ] so my question is how to optimize it, for every record will be choices 2 or 3 person, but now i wanna add status choices for each of them and be unique for choices person -
How to reformat a Nigerian phone number in Javascript or Python function [closed]
I received phone numbers in different formats and I will like to convert them to a particular format before using them.These are the following formats users will always submit: +234 816 312 1111 234 816 312 1111 +2348163121111 2348163121111 0816 312 1111 08163121111 I will like to always reformat the number to No 6. i.e 08163121111. The implications of this are: '+' signs are removed spaces between the numbers are removed. country code (234) are removed. '0' are added at the beginning of the numbers after removing country code. How do I achieve this in javascript or using a python function. -
How can I create submit form in Django with dropping down list?
I am just starting to work with Django and I have some problems with forms and dropping lists. So, let me explain my problem: I have a model with two attributes, I want to display one of the attributes in a dropping down list (This one will be unchangeable) and another one in a text field (This one will be changeable). Also, I have a submit button, so I want to change a second attribute in a text field and by pressing on the button. I have no idea how to do this, can somebody type examples? Thank you!