Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Keeping the latest row for rows that have the same value in a column
So right now I have a table that is similar to: | ID | NAME | Date| |---------|------|---| | 1 | BOB | 2007| | 2 | BOB | 2007| | 3 | BOB | 2008| and I want to remove the first two and keep the third row. I've tried using distinct() with order_by() but it only seems to remove one one of the first two rows. -
DRF - How do you include foreign data within a Serializer?
I have a Model that looks a bit like this: class Foo(models.Model): data = models.ForeignKey(Data, on_delete=models.CASCADE) source = models.ForeignKey(Source, on_delete=models.CASCADE) # other fields... In this case I'd like to show the full models for data and source, rather than just their IDs. I also need data to be read-only as it's generated automatically. My Serializer looks like this: class FooSerializer(serializers.ModelSerializer): data = DataSerializer(read_only=True) source = SourceSerializer() class Meta: model = Foo fields = ["data", "source"] read_only_fields = ["data"] What I don't quite understand is: Why isn't data read-only, like it would be if it were a "normal" serializer field? How can I say "save a new source if an identical one doesn't exist already?" -
Celery unregistered task with Django and RabbitMq
I am getting the following message when implementing Celery with Django and RabbitMq [2022-04-07 00:05:10,310: ERROR/MainProcess] Received unregistered task of type 'callservices.celery.send_user_mail'. The message has been ignored and discarded. I have followed all the configuration steps, which I show below in each file within the Django directory, but I have not been able to find the problem. Why does it mention that the task is not registered? celery.py from celery import Celery from django.core.mail import EmailMultiAlternatives, send_mail os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'callserviceapp.settings') app = Celery('callserviceapp') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task() def send_user_mail(randomNumber, email): print("hola") subject = 'Some subject' body="Some body" send_mail(subject, body,'xxxxx.ssmtp@gmail.com', [email],fail_silently = False) return 1 init.py # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from celery import app as celery_app __all__ = ('celery_app',) setting.py INSTALLED_APPS = [ 'sslserver', 'rest_framework', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'callserviceapp.apps.CallserviceappConfig', ] CELERY_BROKER_URL = 'amqp://localhost' -
How many database calls does Django make with foreign key relations?
I have a model "Model_A" with foreign key field "fk" to model "Model_B". When serializing model "Model_A", I am trying to get 2 fields from model "Model_B" but I want to make 1 database call. class Model_B(models.Model): f1 = models.Charfield() f2 = models.Charfield() f3 = models.Charfield() class Model_A(models.Model): fk = models.Foreignkey(Model_B, on_delete=models.CASCADE) Does the following code make 1 or 2 database calls? ma = Model_A.objects.get(pk=1) return { 'f1': ma.fk.f1, 'f2': ma.fk.f2, } Or would the following make more sense? mb = Model_A.objects.get(pk=1).fk return { 'f1': mb.f1, 'f2': mb.f2, } -
Django: How to convert indexed QueryDict into array of QueryDicts?
I am handling a POST request and I receive in request.data the following data structure: <QueryDict: {'document[0]name': ['sample-0.pdf'], 'document[0]folder': ['folder-0'], 'document[1]name': ['sample-1.pdf'], 'document[1]category': ['file'], 'document[1]folder': ['folder-1']}> How can I convert this to the following data structure: [<QueryDict: {'name': ['sample-0.pdf'], 'folder': ['folder-0']}>, <QueryDict: {'name': ['sample-1.pdf'], 'category': ['file'], 'folder': ['folder-1']}>] -
How to add column with drop-down list on Django admin change list template?
I have a TaskRequest model that contains column named 'owner'. This column contains users from group named 'owners'. I want to have an option to select users directly from change list view without clicking on task name. How can I implement a drop-down list so it is visible in the table in my TaskRequest app. Do I really need to overwrite admin template or there is another way to do that? -
Using React with Django to render stars on the page
I am developing manga website which has star rating for each manga. I am using React (which I'm very very new to) with Django. I render div with class stars with id which corresponds to number of stars this manga has. After that Corresponding number of stars must be rendered on webpage with react code. {% block script %} <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> {% endblock %} {% for manga, rating in mangas %} <script type="text/babel"> function Apicall(props) { console.log((props.value)) return Render_rating(props.value) }; function Render_rating(props) { for (var i = 0; i = parseInt(Math.round(props)); i++) { return Render_stars() } } function Render_stars() { return ( <img src="static/mangas/fullstar.png"/> ) } console.log(document.querySelector(".stars").id) ReactDOM.render(<Apicall value={document.querySelector(".stars").id} />, document.getElementById('app')) </script> <div id="manga"> <a href="{% url 'manga' manga.id %}"> <div class="stars" id="{{ rating }}"></div> <div id="app"></div> <h1>{{ manga.title }}</h1> <img src="{{ manga.image.url }}"> <br/>{% for genre in manga.genre.all %}{{ genre }}<br/>{% endfor %} {{ manga.Description }} </a> </div> {% endfor %} I understand that there are many issues with my react code. document.querySelector(".stars").id always renders number 0. Also I want to know about more elegant way to structure react code with Django. I am very new to it so... -
Updating profile picture through serializer
I cannot update a profile image on my extended user model. Here is my serializers.py: class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=False) city = serializers.CharField(source='profile.city', allow_blank=True, required=False) country = serializers.CharField(source='profile.country', allow_blank=True, required=False) profile_pic = serializers.ImageField(source='profile.profile_pic', use_url=True, required=False) class Meta: model = User #, 'city', 'country', 'bio' fields = ['username', 'email', 'password', 'first_name', 'last_name', 'city', 'country', 'profile_pic'] # fields = UserDetailsSerializer.Meta.fields + ('city', 'country') extra_kwargs = {'username': {'required': False}, 'email': {'required': False}, 'password': {'required': False}, 'first_name': {'required': False}, 'last_name': {'required': False}, 'city': {'required': False}, 'country': {'required': False}, 'profile_pic': {'required': False} } def update(self, instance, validated_data): profile_data = validated_data.pop('profile', {}) city = profile_data.get('city') country = profile_data.get('country') profile_pic = profile_data.get('profile_pic') instance = super(UpdateUserSerializer, self).update(instance, validated_data) profile = instance.profile if profile_data: if city: profile.city = city if country: profile.country = country if profile_pic: profile.profile_pic = profile.profile_pic profile.save() return instance When I try to update this image with a new image I do not get any error messages however the image is not updated (image remains the same). -
makemigrations results in django.db.utils.OperationalError: no such column: (Python 3.10 and Django 4.0.3)
First, and this is really important, this error is being returned WHEN I run python manage.py makemigrations (Python 3.10 and Django 4.0.3) In my research of the many instances of this error I've seen that as the first suggestion for this particular error message. I repeat, this issue is NOT going to be solved with the answer, just run python manage.py makemigrations The error I get when adding a new field and running makemigrations is: django.db.utils.OperationalError: no such column: events_eventsetting.timezone_aware_venues OK, now for some additional details. This is not my first Django project. I've been building some solid apps and am very comfortable with adding fields to models. Many, many times, I've done the following without a hitch...until a few days ago Add a new syntactically correct field run 'python manage.py makemigrations' run 'python manage.py migrate' And that's being going very well until a couple of days ago. For additional context, I have not changed the virtual environment in anyway - the requirements.txt file has the exact same contents. I have also added no apps or made any changes to settings.py. When working on a project with about 10 tables and over 200 columns across the DB a few days … -
Any simple alternative to default_if_none that can also handle '0' value?
I am running the following command to filter out empty values in my template: {{ product.error_value1|default_if_none:"--" }} This works well for Null Values but doesn't work if the value entered is "0". I wish the command 'default_if_null' existed. This way it would only check for null. Any suggestions on an alternative? -
calculating percentages on a field in Django
I have the model below and I am trying to calculate the percentages of product quantities. Any help would be greatly appreciated. Thanks model.py class Stock(models.Model): date = models.DateField(default=now) product = models.CharField(max_length=100, null=True, unique=True) quantity = models.IntegerField(default='0') view.py total= Stock.objects.aggregate(total_vote=Sum('quantity')) per = Stock.objects.values('quantity') percentage = [ {'quantity': p['quantity'], 'percentage': p['quantity'] * 100 /total} for p in per ] -
How to add multiple attachments in mail in django
i have multiple file fields form and i want to send all field file to one email in django. kindly suggest. email code: def sendEmail(request): message = "hello world" subject = "Test" mail_id = "customer@example.com" email = EmailMessage(subject, message, EMAIL_HOST_USER, [mail_id]) email.content_subtype = 'html' doc1 = request.FILES['detail_sheet'] doc2 = request.FILES['photo'] doc3 = request.FILES['id_proof'] doc4 = request.FILES['address_proof'] doc5 = request.FILES['company_id_card'] doc = [doc1,doc2,doc3,doc4,doc5] for f in doc: file = f email.attach(file.name, file.read(), file.content_type) email.send() -
Django - Input boxes not styling properly when inheriting from base.html
I am creating a simple login page using Django & Tailwind.css. My form was styling fine until I inherited a <nav> from base.html. When I did so, gray borders started appearing around my input boxes and the input boxes got slightly bigger. The original layout: The new layout (with base.html being inherited): I'm not sure why this is occurring, because all of the code remains the same, I am just {% extends "base.html" %} at the top of my login.html Here is my base.html code (contains the navar & responsive navbar): <!DOCTYPE html> <html class="screen-top"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>{% block title %}{% endblock %}</title> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://shuffle.dev/vendor/icons/css/fontello.css?v=h7b" id="bs-base-css"> <style type="text/css" href="https://shuffle.dev/vendor/tailwind-flex/css/tailwind.min.css?v=bd4"></style> <style type="text/css" href="https://shuffle.dev/vendor/tailwind-flex/css/tailwind.min.css?v=bd4"></style> <style type="text/css" href="css2?family=Poppins:wght@400;500;600;700&display=swap"></style> <link rel="stylesheet" href="https://shuffle.dev/static/build/css/shuffle-preview.3a553ecf.css"> <link rel="stylesheet" href="https://unpkg.com/flowbite@latest/dist/flowbite.min.css" /> <script src="https://shuffle.dev/vendor/tailwind-flex/js/main.js"></script> <script src="https://cdn.tailwindcss.com"></script> {% block css %} {% endblock %} </head> <body id="page" class="antialiased font-body bg-body text-body bg-[rgb(248,250,251)]"> <!-- NAVBAR --> <div class="" id="content"> <section class="relative overflow-hidden"> <nav class="flex justify-between p-6 px-4" data-config-id="toggle-mobile" data-config-target=".navbar-menu" data-config-class="hidden" style="background-color: #2a3342;"> <div class="flex justify-between items-center w-full"> <div class="w-1/2 xl:w-1/3"> <a class="block max-w-max" href="{% url 'home' %}"> <img class="h-8" src="https://i.ibb.co/LRCrLTF/Screenshot-2022-04-03-140946-removebg-preview.png" alt="LOGO" data-config-id="auto-img-1-2" style="transform: scale(2); padding-left: 30px"> </a> </div> <div … -
Type checking between Python classes and JavaScript objects (Django with Vue)
I have a project that has a Python (django) backend and a (mostly) Vue frontend. I render forms with Django html templates instead of Vue, but would like to migrate the forms so that everything frontend is Vue. I want to implement some sort of type checking system that could throw linting errors if I try to create object properties in the frontend that don't match the form data object that exists in the backend. However, I have no idea how to do this given I'm going from Python to Javascript - or if it's even possible to typecheck a JS object from a Python class. I've seen this in Typescript + React, where the props object used to persist the controlled form's state is typed with the backend object. That way, if you tried to add a property to the object in the frontend that wasn't included in the backend model, you'd immediately get a linting error. But that works bc you're working in the same language. Any ideas on how to do this between languages? Maybe an intermediate step with a script to build JS models from the Python classes? -
How can I pass an id to route in Django?
I'm new with Django. Started learning it for 4 days now. I have an issue and I don't know how to solve it. I've searched high and low on Google, but I couldn't understand much from the solutions provided. Here is the issue: I've created models and views for the app I've created the database with all tables needed. In them I have 2 foreign keys which link between two tables In the html, I need to show only the information linked to the foreign key.(eg. I have a webpage in which I have all the countries. When I click on Argentina, I want only Argentina's provinces to be shown) Where and what do I need to do in order for it? Again, I've searched high and low on Google, because I don't think is something that complicated. But everything I found didn't solve my request. -
i'm getting this following error what should i do
Error during template rendering In template C:\Django-Project\resume\core\templates\core\home.html, error at line 1 core/base.html 1 {%extends 'core/base.html'%} -
A single field not showing up when using inlineformset_factory for multiple forms
I'm writing a django webapp that allows me to create orders for customers. I've used inlineformset_factory so that I can create multiple forms in my bootstrap template. Everything loads well, I get 10 forms I can fill out, however the ONLY field it is not loading is the customer field to choose from the drop down menu. Before I changed it to using the inlineformset_factory, the single form loaded fine with all the fields. So i dunno why this is happening. But then even when I submit the form regardless of the customer field appearing I get an error Anyone know why? createOrder from views.py As you can see the fields I want are 'date', 'client', 'customer', 'country', 'product' but only the customer is not showing up! Iget 10 forms but all without customer. def createOrder(request): OrderFormSet = inlineformset_factory(Customer, Order, fields=('date', 'client', 'customer', 'location', 'product'), extra=10 ) formset = OrderFormSet() #form = OrderForm() if request.method == 'POST': formset = OrderFormSet(request.POST) if formset.is_valid(): formset.save() return redirect('/') context = {'form':formset} return render(request, 'accounts/order.html', context) Customer model from models.py: class Customer(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) location= models.CharField(max_length=200, null=True, choices=LOCATION) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): … -
Django user authentication fails in selenium tests
I'm writing tests for my djangocms app, first time using selenium to replicate the browser/user. I'm trying to test the login page, user simply fills out the username & password, but I can't get authenticate to work in the selenium tests. I can log in via the website myself & can even use authenticate in the test code block, but selenium isn't working, any tips? Anything i've read so far just involved the user password not being hashed on save, which mine is, so i don't have a clue here. I know the credentials are correct, the user exists, & the password is hashed in the db. This is also the only test i'm running, so no chance of any other tests affecting it. I also know from turning off 'headless' that the input fields are being filled out properly by selenium, it just won't authenticate. Here is where I create the user in setup def create_user(role='competitor', username=None, email='test@yahoo.com', password='password', superuser=False): # if not given a username, we generate a random string since username's have to be unique random_string = string.ascii_letters + string.digits if not username: username = 'username_' + (''.join( (random.choice(random_string) for i in range(10)) )) group, created = … -
rest_framework.request.WrappedAttributeError: 'AccountManager' object has no attribute 'get'
I am working on my Django project, I am getting this error but i don't really know how to fix it exactly, i have created my custom user model and the user manager class AccountManager(BaseManager): def create_user(self, email, fullname=None, birthday=None,zipcode=None, password=None): if not email: raise ValueError('Users must have an email address') user = self.model(Email_Address=self.normalize_email(email), name=self.normalize_email(email), Date_of_Birth=birthday, zipcode=zipcode ) user.set_password(password) user.save(using='self._db') return user def create_superuser(self, Email_Address, username, password): user=self.create_user(Email_Address=self.normalize_email(Email_Address), password=password,) user.is_admin = True user.is_active = True user.is_staff = True user.is_superuser = True user.save(using='self._db') class User(AbstractUser): Email_Address = models.EmailField(verbose_name='email', unique=True, blank=True, null=True) Date_of_Birth = models.CharField(max_length=30, blank=True, null=True, default=None) name = models.CharField(max_length=30, blank=True, null=True) username= models.CharField(max_length=30,unique=True, blank=True, null=True) zipcode = models.CharField(max_length=30, blank=True, null=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'Email_Address' objects = AccountManager() REQUIRED_FIELDS = ['username'] def __str__(self): return self.username because i am using rest_framework_simplejwt for authentication i am getting this error when i try to log in rest_framework.request.WrappedAttributeError: 'AccountManager' object has no attribute 'get' can anyone please help me with this -
What is index in load static?
please tell me what is the index in {% load static index %}? This came across to me in someone else's code. I didn't find anything like this in the documentation -
Error while trying to integrate keycloak with django
I'm trying to integrate keycloak with my django app using Djanog Keycloak and following the tutorial, but I'm getting the following error: File "/home/enzo/.local/lib/python3.10/site- packages/django_keycloak/admin/__init__.py", line 3, in <module> from django_keycloak.admin.realm import RealmAdmin File "/home/enzo/.local/lib/python3.10/site-packages/django_keycloak/admin/realm.py", line 2, in <module> from keycloak.exceptions import KeycloakClientError ImportError: cannot import name 'KeycloakClientError' from 'keycloak.exceptions' (/home/enzo/.local/lib/python3.10/site-packages/keycloak/exceptions.py) Does someone know how to solve? -
Azure Python SDK - connecting to USGov with CLI Credentials fails?
I've tried using AzureCliCredential() as noted in previous questions/the documentation - this works great in the normal azure cloud. If I'm using the USGov cloud (portal.azure.us), the same code just returns nothing; I've tried http tracing and it looks like it's still pointing at management.azure.com and not management.core.usgovcloudapi.net - but it doesn't say anything. Pretty much all things that require a subscription scope are telling me the subscription doesn't exist, and yet 'az account list' shows all of the subscriptions correctly. I've got all the python modules updated to the latest.. not sure what's wrong at this point, any ideas? just to sum up, procedure is: login with az login --use-device-code go to microsoft.com/deviceloginus (usgov device login) and put in code shell is authenticated az account list shows all of my subscriptions Run test code to list subscriptions - get no results. Trace shows that things still point at management.azure.com - if I force base_url to https://management.usgovcloudapi.net, I get an InvalidAuthenticationTokenAudience exception. Code I'm using: import logging from azure.identity import AzureCliCredential from azure.mgmt.subscription import SubscriptionClient credential = AzureCliCredential() client = SubscriptionClient(credential=credential, logging_enable=True, base_url="https://management.usgovcloudapi.net/") logging.basicConfig(filename='test_sub_debug.log', level=logging.DEBUG) aba_logger = logging.getLogger('azure.mgmt.subscription') aba_logger.setLevel(logging.DEBUG) sub_list = client.subscriptions.list() for subscription in sub_list: print(subscription) # (obviously remove … -
Django i18n does not work with Nginx. Keep redirecting to homepage
Right now I have a django + gunicorn + nginx setup. Everything works: able to switch between the two language set the cookies add the lang prefix in the middle: projurl.com/lang_code/other_dir able to redirect/stay on the page where language switch happened But ... All 1,2,3,4 are working with django dev server (python manage.py runserver) and gunicorn proj.wsgi:application --bind 0.0.0.0:8000 Only 1,2,3 work with nginx. It keeps redirecting to homepage with the right language, but unable to stay on the page where language switch happened. proj/urls.py: urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += i18n_patterns( re_path(r'^admin/', admin.site.urls), re_path(r'', include('app1.urls')), ) In template I have exact example from django i18n translation: link {% load i18n %} <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go"> </form> nginx.conf upstream proj { server web:8000; } server { listen 80; location /static/ { alias /static/; … -
How to assign new value to a ModelForm field which form edits user data, to test if the data will be edited Django test TestCase
I'm testing Django forms handling and trying to test a ModelForm, which form edits the user's data. I tried to write the test in several ways, but each one throws different mistakes. And all the mistakes are related to the data, that I try to assign to the form. I create a user and profile because in my app the user model is extended and trying to change profile.first_name from 'Test' to 'Edited'. This is the test: class ProfileEditFormTests(TestCase): def test_if_form__can_change_passed_data__expect_success(self): """ Test ProfileEditForm if can edit a valid data: -Change profile.first_name from 'Test' to 'Edited' """ user, profile = self.__create_valid_user_and_profile() form_data = { 'first_name': profile.first_name, 'last_name': profile.last_name, 'image': profile.image, 'description': profile.description, 'phone_number': profile.phone_number, 'email': profile.email, } updated_form_data = { 'first_name': 'Edited', } form = ProfileEditForm(data=updated_form_data, instance=profile) # Error: # self.assertTrue(form.is_valid()) # AssertionError: False is not true # on debug, the form have only data.first_name = 'Edited' # and the another fields are empty self.assertTrue(form.is_valid()) form.save() self.assertEqual(updated_form_data['first_name'], profile.first_name) This is the error that occurs when I try to assign a form_data to the form instance. form = ProfileEditForm(data=updated_form_data, instance=form_data) # Error # Traceback (most recent call last): # object_data = model_to_dict(instance, opts.fields, opts.exclude) # opts = instance._meta # AttributeError: 'dict' … -
show all user purchased products in django-oscar
I am trying to render all user purchased products on django-oscar and i am having some problems. I can print all orders by user in order.order OrderProduct.objects.filter(user=user) but it doesn't print each product by itself if order include few products (which saved on order.line) I can also print all products in orders.line LineProduct.objects.all() but i can't filter them by user since there is no user field in order.line. I can add user field on order.line and copy from order each time order is placed but I don't think this is the best solution. Anyone have any idea for a solution? Thanks in advance