Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is the inline formset not validating
I have two models with foreign key relation models.py from django.db import models # Create your models here. class Project(models.Model): STATUSES = ( ('Ongoing', 'Ongoing'), ('Completed', 'Completed') ) YEARS = ( (2019, 2019), (2020, 2020), (2021, 2021), (2022, 2022) ) name = models.CharField(max_length=200) client = models.CharField(max_length=100) year = models.SmallIntegerField(choices=YEARS) status = models.CharField(max_length=10, choices=STATUSES) picture = models.ImageField(blank=True, null=True) description = models.TextField(blank=True, null=True) def __str__(self): return self.name class Photo(models.Model): project = models.ForeignKey("Project", on_delete=models.CASCADE, related_name="images", blank=True, null=True) image = models.ImageField() description = models.CharField(max_length=100, blank=True, null=True) slide = models.BooleanField(default=False) I want photos and project to be created on the same form so I've used inline_formset_factory forms.py from django.forms import inlineformset_factory from projects.models import Photo, Project from django.forms import ModelForm class ProjectModelForm(ModelForm): class Meta: model = Project fields = ( 'name', 'client', 'year', 'picture', 'status', 'description', ) class PhotoModelForm(ModelForm): class Meta: model = Photo fields = ( 'image', 'slide', 'description' ) PhotoFormset = inlineformset_factory(Project, Photo, form=PhotoModelForm, extra=1) I used the generic CreateView views.py from django.contrib.auth.mixins import LoginRequiredMixin from projects.forms import PhotoFormset, ProjectModelForm from django.shortcuts import redirect, reverse, render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Photo, Project # Create your views here. class ProjectCreateView(LoginRequiredMixin, CreateView): template_name = 'projects/project_create.html' form_class = ProjectModelForm … -
How can i color change a <div> in a django template depending on a model field?
i have a model in models.py containing a field which indicate its default color (green) and with a method its supposed to change to amber if the future date(another field) is equal to timezone.now(). However whenever i run the webapp, all objects display green even if the dates are the same. what can i change or {% for prestamo in prestamos %} <style> .activo{ text-align: center; background-color: {{prestamo.color_id}}; margin: 50px; padding: 20px; border-radius: 25px; } </style> <div class="activo"> <ul style="list-style-type:none;"> <li>{{prestamo.item}}</li> <li>numID: {{prestamo.num_serie}}</li> <li>Equipo: {{prestamo.nom_equipo}}</li> <li>Nombre: {{prestamo.empleado}}</li> <li>Departamento: {{prestamo.departamento}}</li> <li>{{prestamo.correo}}</li> <li>Engrega: {{prestamo.fecha}}</li> <li>Expira: {{prestamo.entrega}}</li> </ul> </div> {% endfor %} def return_date_time(): now = timezone.now() return now + timedelta(days=15) class prestamo(models.Model): item = models.CharField(max_length=100) num_serie = models.CharField(max_length=100, default='') nom_equipo = models.CharField(max_length=100, default='') empleado = models.CharField(max_length=100) correo = models.CharField(max_length=100,default='') departamento = models.CharField(max_length=100) fecha = models.DateField(auto_now_add=True) entrega = models.DateField(default=return_date_time) color_id = models.CharField(max_length=100, default='#1DB03C', editable=False) def prestamoExpirado(): if prestamo.entrega != timezone.now(): prestamo.color_id ='#1DB03C' elif prestamo.entrega == timezone.now(): prestamo.color_id = '#FFBF00' return prestamo.color_id def __str__(self): return self.item -
Django - Add form validation to inlineformset_factory
So, I'm trying to validate some fields from an inlineformset_factory object, but I don't see how to do that in a clean way from this view (not using a Form class). Would it be possible to override the .is_valid() method in this case? Any help would be appreciated. def tenant(request, id): tenant = Tenant.objects.get(id=id) DealerFormset = inlineformset_factory(Tenant, Dealer, fields=('name', 'phone_number'), extra=0) formset = DealerFormset(instance=tenant) if request.method == 'POST': formset = DealerFormset(request.POST, instance=tenant) if formset.is_valid(): # <--- How to add custom validations here? formset.save() return redirect('tenant_details', id=tenant.id) context = { 'formset': formset, } return render(request, 'tenant_details.html', context) -
Django - social_auth - How could I separate social_auth_facebook_scope to request different scope
I am a new web developer using django framework and I try to set multiple scope for social_auth_facebook_scope in the django framework. What I have done is ref from this link : How can I ask for different permissions from facebook at different times? But I didn't know how to do it so First,I put the FACEBOOK_SCOPE and FACEBOOK_CUSTOM_SCOPE in the setting.py file SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', 'user_link'] SOCIAL_AUTH_FACEBOOK_CUSTOM_SCOPE = ['instragram_basic'] Second, I don't know where to put this code in. class CustomFacebookOAuth2(FacebookOAuth2) : name = 'facebook-custom' Is it have to use in views.py or apps.py, I don't have any ideas. Next I want my 2 button separate each request First button is to log in with Facebook only Second button is to request a permission for Instagram business account so how do I config in my html file Now what I am config is set the url to call Facebook-custom to request different scope but it doesn't work and return Error pages not found http://localhost:8000/social-auth/login/facebook-custom/ Instagram business Account html class="nav-link" href="{% url 'social:begin' 'facebook-custom' %}">Instragram business account How can I fix it , Anyone have an idea. -
How to use PostgreSQL's stored procedures or functions in Django project
I am working on one Django project. And I decided to write logic code in PostgreSQL instead of writing in Python. So, I created a stored procedure in PostgreSQL. For example, a stored procedure looks like this: create or replace procedure close_credit(id_loan int) language plpgsql as $$ begin update public.loan_loan set sum = 0 where id = id_loan; commit; end;$$ Then in settings.py, I made the following changes: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'pawnshop', 'USER': 'admin', 'PASSWORD': password.database_password, 'HOST': 'localhost', 'PORT': '', } } So the question is, How can I call this stored procedure in views.py? p.s. Maybe it sounds like a dumb question, but I really couldn't find any solution in Django. -
How to generate a download link for a file stored in the flask server rather than directly downloading the file?
I have built a flask app wherein the user uploads a file, it gets processed and thereafter, gets stored in a particular folder on the flask server itself. Now, I wanted to generate a download link for this file (a link I would be emailing to the user) instead of directly allowing the user to download the file. Any ideas how I should go about it? Thank You. -
How to set class of OrderingFilter's widget in Django?
I want to set class of OrderingFilter's in Django framework. I can add class to ModelChoiceFilter like that: from django_filters import OrderingFilter, ModelChoiceFilter user_status_filter = ModelChoiceFilter(queryset=UserStatus.objects.all(), label="Status", widget=Select(attrs={'class': 'form-control'})) But adding class to OrderingFilter results in error: 'ChoiceExactField.widget' must be a widget class, not <django.forms.widgets.Select object at 0x000001FA0C6BCA48>' order_by_filter = OrderingFilter( fields=( ('score', 'Score'), ('money', 'Money'), ), label="Sort by", widget=Select(attrs={'class': 'form-control'}) ) What is the proper solution to set class of this widget? -
Implementing case-insensitive username and email with class base view in Django 3
I'm trying to implement a registration mechanism with class base view in a Django project. I tried many methods but none of them worked. Anybody Has A Solution?? views.py: class RegisterView(FormView): template_name = 'users/user_register.html' form_class = UserRegistrationForm redirect_authenticated_user = True success_url = reverse_lazy('index') def form_valid(self, form): user = form.save() if user is not None: login(self.request, user) return super(RegisterView, self).form_valid(form) def get(self, *args, **kwargs): if self.request.user.is_authenticated: return redirect('index') return super(RegisterView, self).get(*args, **kwargs) forms.py: class UserRegistrationForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] -
Render Variable Form Fields
I'm attempting to created a vehicle project and when I select a brand I would like it to only list the models associated with that brand within my form. Currently, if I select a Make, all models from all other Makes also appear. I would like to filter the options down to only the Models associated with that Make. class CarMake(models.Model): name = models.CharField(max_length=100) country_of_origin = CountryField(null=True) slug = models.SlugField(null=True, blank=True) class Meta: ordering = ['name'] def __str__(self): return self.name def get_absolute_url(self): return reverse('make-profile', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) return super().save(*args, **kwargs) class CarModel(models.Model): name = models.CharField(max_length=100) make = models.ForeignKey('CarMake', on_delete=models.CASCADE) slug = models.SlugField(null=True, blank=True) class Meta: ordering = ['name'] def __str__(self): return self.name def get_absolute_url(self): return reverse('model-profile', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify('%s %s' % (self.make, self.name)) return super().save(*args, **kwargs) -
How to pass dict info to plotlyjs pie chart?
From my views I have {{data}} which is [1, 1, 2, 1, 1] and {{labels}} which is ['CONTAINERSHIP', 'TANKER', 'TUGBOAT', 'FISHING BOAT', 'CHEMICAL TANKER'], but when adding to plotly.js pie chart, it does not read the labels, my code is: {% block content %} <div id="myDiv" style="width:600px;height:250px;"></div> <script> var data = [{ values: {{data}}, labels: {{ data }} , type: 'pie' }]; var layout = { height: 500, width: 500, }; Plotly.newPlot('myDiv', data, layout); </script> {% endblock %} I am pretty sure my problem is on how to pass this info to plotlyjs, but I have no idea what is the proper way? Any assistance is deeply appreciated. -
Django modeling - need advise on Guest, Host, Invitations relation model
I have the following case, which I can't turn into Django models on my own, hence asking the community: A party Host sends out invitations for an Event to multiple Guests and wants to track whom they send Invitations. A Host may host different Events and send out an invitation for each Event to the same Guest. Guest needs to track his invites too. I.e. can ignore or accept an invitation, and be able to see their history of invitations. Host needs to track down responses too, i.e. view who responded for each Event. So, I have so far the following model (simplified here): class Host(models.Model): name = models.CharField(max_length=20) class Guest(models.Model): name = models.CharField(max_length=20) class Event(models. Model): name = models.CharField(max_length=20) one) date = models.DateField() host = models.ForeignKey(Host, related_name="invatations" ) invitations = models.ManyToManyField(Guest, related_name="invatations", ) So this gives me: Host can access a list of invited Guests. Guest can access their invitations via a related name. But I can't figure out how to make invite management by Guest and Host separately. I.e. they should have their own lists, it seems. I.e. if a guest may trash an invite, a Host still needs to see this invite as sent out on his … -
pycharm django install mysqlclient failed
I start a Django project by Pycharm and require to use the Mysql as database, there is somthing wrong with installing the mysqlclient package.I have searched the info and downloaded the package from www.lfd.uci.edu.When I pip install the .whl file,it told me not match the platform. But I use the same package to pip install in cmd sucessfully. I wonder there is something different between the venv and local? the detail screenshot as below: my venv Python version: Python 3.8.8 (default, Apr 13 2021, 15:08:03) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32 I have try some different version mysqlclient pip install mysqlclient-1.4.6-cp38-cp38-win32.whl pip install mysqlclient-1.4.6-cp38-cp38-win_amd64.whl both of above are wrong as below: mysqlclient-1.4.6-cp38-cp38-win_amd64.whl is not a supported wheel on this platform. I don`t have the enough reputation to post the image,I just can let them as a tags.I hope someone can help me out.Thanks for reading this question. -
django Inherit from base Model form and add extra fields (doesn't exist in model fields) is not working
I'm trying to Inherit from BaseModelForm and add extra fields doesn't exist in the Model fields but it doesn't work. # forms.py class BaseConditionForm(forms.ModelForm): class Meta: model = Condition fields = ['nid', 'amount', 'donation'] class ConditionForm(BaseConditionForm): date_type = forms.ChoiceField(choices=ConditionChoices.DATE_TYPE_CHOICES) save_type = forms.ChoiceField(choices=ConditionChoices.SAVE_TYPE_CHOICES) class Meta(BaseConditionForm.Meta): fields = BaseConditionForm.Meta.fields + ['data_type', 'save_type'] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super().__init__(*args, **kwargs) def clean(self): cleaned_data = super(ConditionForm, self).clean() print(cleaned_data['cchi']) pass and models.py class Condition(models.Model): def __str__(self): return str(self.id) # .zfill(10) nid = models.CharField(max_length=10, null=False, blank=False, db_index=True) amount = models.IntegerField(null=True, blank=True) donation = models.IntegerField(default=0, null=True, blank=True) but I got this error . . . File "/mnt/data/programming/projects/lean/shefa/condition/forms.py", line 74, in <module> class ConditionForm(BaseConditionForm): File "/mnt/data/programming/projects/lean/shefa/venv/lib/python3.8/site-packages/django/forms/models.py", line 266, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (data_type) specified for Condition if it is not applicable please suggest me another solution. thanks in advance for you all. -
Websocket Connection Failed on AWS EC2 Ubuntu Instance(Django Channels)
I am trying to deploy my django chammels asgi app in ubuntu aws ec2 instance, my wsgi app is working fine also the asgi on ubuntu is working fine (tested with python websocket library) there is no error in code and daphne is running perfectly I enabled all ports in the security group of EC2 as well There is no error on the codebase and also daphne is running on localhost of EC2 ubuntu Instance perfectly server { listen 80; server_name MY_SERVER_IP; location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /ws/{ proxy_pass http://0.0.0.0:4001; proxy_buffering off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } [Unit] Description=project Daphne Service After=network.target [Service] User=root Type=simple WorkingDirectory=/home/ubuntu/myproject ExecStart=/home/ubuntu/myproject/venv/bin/python /home/ubuntu/myproject/venv/bin/d> [Install] WantedBy=multi-user.target I created this python script to determine if my daphne is working or not, it is providing me the perfect result, no error import asyncio import websockets import json async def hello(): uri = "ws://127.0.0.1:4001/ws/chat/person/?token=<CHAT_TOKEN> async with websockets.connect(uri) as websocket: await websocket.send(json.dumps({"message":"Hey there"})) g = await websocket.recv() print(g) asyncio.get_event_loop().run_until_complete(hello()) This following script returns { "id": 1, "message": "Hey There", "time_stamp": "TIME", "receiver": { "username": "John Doe", "id": … -
How to separate nav bar from the rest of the page
I am new to web development and I am working on Django framework in VSCode. I have been trying to make a user interface for the web application which has a menu on the left side of the screen and a nav bar on top which says "home page" (the image is below). There I need all the texts and photos to be in the rest part of the page, and when I scroll down I want only that part to move, like in a real web application. But I don't know how to do it, do I have to use JavaScript for that or can I just do it within HTML/CSS? As you can see in the picture the paragraph covers the nav bar. Thank you! -
How Should i store Error logs into mysql in Django
For example i want to store errors like this. this is how i want to store all error logs -
Django suddenly gives "No module named "Django""
Been making a blog and I've been busy/ill for 2 weeks, I have came back to it today and go to start my virtual environment, fine so I type python manage.py runserver and just get from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' I tried installing django again but that didn't fix the problem I dont know if it's because my postgres isn't running but when i type psql into my CLI I get psql: error: FATAL: role "toad" does not exist which I can find literally nothing about when I google it At this rate I'll be starting a new project and copy pasting everything across -
Use different view depending on whether slug refers to user or group
I would like to create pages for individual users and groups with vanity URLs following the pattern example.com/<user_or_group_name>. Usernames and group names don't conflict. I set up the following URL pattern: path(route="<str:entity_name>", view=...) I have two distinct views for user pages and group pages. I would like to use either view depending on whether user_or_group_name in the URL is a Group or a User. class GroupPage(DetailView): template_name = "userprofile/group_page.html" model = Group class UserPage(DetailView): template_name = "userprofile/user_page.html" model = User I understand that it is not possible to have to views on the same URL pattern. I could build a unified view and choose object and template depending on whether user_or_group_name is a User or a Group. Yet that feels forced. I thought about routing the URL to a dispatch function (below) but that returns AttributeError: 'function' object has no attribute 'get' raised by the clickjacking middleware. def page_dispatch(request, entity_name): try: User.objects.get(username=entity_name) return UserPage.as_view except User.DoesNotExist: return InstitutionPage.as_view How can I select the view based on whether the URL refers to a user or a group? Thank you for your help. -
Got AttributeError when attempting to get a value for field `gpa` on serializer `SubjectSerializer`
This question seems a kind of repeated one but I am not able to fix it for whole day. Problem is I have following model: class Result(BaseModel): user = models.ForeignKey(User, on_delete=models.CASCADE) registration_number = models.CharField(null=True,blank=True,max_length=20) gpa = models.CharField(max_length=20) subject = models.CharField(max_length=50) I want to get result of single student so I tried filtering based on user_instance and I want data in this format. [ "user":"daneil", [ {"gpa":"A","subject":"maths"}, {"gpa":"B","subject":"science"} ] ] So I tried this in my serializers.py class ResultSerializer(serializers.ModelSerializer): class Meta: model = Result fields = '__all__' class ListResultSerializer(ResultSerializer): subject = SubjectSerializer(many=True, read_only=True) class Meta(ResultSerializer.Meta): fields = ( 'user', 'subject', ) and at the end the nested serializer for field subject was as below class SubjectSerializer(ResultSerializer): class Meta(ResultSerializer.Meta): fields = ( 'gpa', 'subject', ) I dont know What I did wrong as It gives me error stating: Got AttributeError when attempting to get a value for field `gpa` on serializer `SubjectSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. Original exception text was: 'str' object has no attribute 'gpa'. I dont know where I made mistake any help will be helpful. -
Integrate Jaeger open tracing in my django project
In my Django project i would to integrate open tracing tecnique using Jaeger. I installed a Jaeger operator on my kubernetes cluster: So in my django project i install some packages as: django-opentracing jaeger-client opentracing then in my django settings.py i do: MIDDLEWARE = [ 'django_opentracing.OpenTracingMiddleware', ... and at the end of setting i do: import django_opentracing OPENTRACING_TRACE_ALL = True config = Config( config={ # usually read from some yaml config 'sampler': { 'type': 'const', 'param': 1, }, 'local_agent': { 'reporting_host': '10.128.33.41', #My k8s Service Cluster IP endpoint 'reporting_port': '8383', }, 'logging': True, }, service_name='jaeger-operator-metrics', validate=True, ) # this call also sets opentracing.tracer tracer = config.initialize_tracer() OPENTRACING_TRACING = django_opentracing.DjangoTracing(tracer) So i started my application , no errors all seems domìne but the question is: How can i see my jaeger dashboard for look at captured events, logging etc? There is something i have not doing? So many thanks in advance Manuel -
How to create PDF files and open them with django
hey i m working with django to create an OCR app and i m saving the OCR result into a pdf file,however whenever i try to open the file i get we can't open this file and i can't view it unless i m on vscode. if i change to files format to text then i m able to open them, i don't really know the problem exactly so any help ? here i m checking if an image is uploaded to create a file and the create pdf is just a function that runs pytesseract on the image if self.id : File.objects.create( file=(ContentFile(Create_Pdf(self.image),name='file.pdf') )) enter image description here -
Django website hosted on AWS suddenly only shows 'Index of /'
We have a Django app that is hosted on AWS. From one day on another, the website shows 'Index of /' instead of our usual landing page. We haven't changed the source code. Nobody did anything with the source code or AWS and the source code is working in our local test environment. We checked the requirements.txt file, which was suggested in a SO thread with the same issue, but there is nothing wrong with the requirements. On AWS we can see that the DB-instance is running and healthy. The AWS environment is also healthy. The only clue that we have is that there is a message on our AWS 'Personal Health Dashboard' which says that there was a 'RDS operational issue' which has been solved. There is no further info in the message that gives us insight into what might be the issue for us. Does anyone know what might be the issue? -
Updating M2M Model after save
I have two models class Item(models.Model): name = models.CharField(max_length=50) sku = models.CharField(max_length=50) description = models.TextField(max_length=100, blank=True) status = models.IntegerField(choices=TRUE_FALSE_CHOICES, default='1') def __str__(self): return self.name class Location(models.Model): name = models.CharField(max_length=50) description = models.TextField(max_length=100) items = models.ManyToManyField(Item, blank=True) def __str__(self): return self.name so what im trying to achieve is when you save a location all items assigned to that location should change status to 0. Any ideas on how can I do that ? -
Get all defined field choices from Django app
isn't there some util or function, which would iterate through all models in a django app and return something like Model.field: { key->String } values for every choice field defined on a model? Or do I have to write it myself? :) -
KeyError while makeing migrations to the files
C:\Users\SHRIYADAV\Desktop\Django\Roman\Apple\funsite>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\SHRIYADAV\anaconda3\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\SHRIYADAV\anaconda3\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\SHRIYADAV\anaconda3\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\SHRIYADAV\anaconda3\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\SHRIYADAV\anaconda3\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\SHRIYADAV\anaconda3\lib\site-packages\django\core\management\commands\makemigrations.py", line 149, in handle loader.project_state(), File "C:\Users\SHRIYADAV\anaconda3\lib\site-packages\django\db\migrations\loader.py", line 335, in project_state return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps)) File "C:\Users\SHRIYADAV\anaconda3\lib\site-packages\django\db\migrations\graph.py", line 315, in make_state project_state = self.nodes[node].mutate_state(project_state, preserve=False) File "C:\Users\SHRIYADAV\anaconda3\lib\site-packages\django\db\migrations\migration.py", line 89, in mutate_state operation.state_forwards(self.app_label, new_state) File "C:\Users\SHRIYADAV\anaconda3\lib\site-packages\django\db\migrations\operations\models.py", line 318, in state_forwards renamed_model = state.models[app_label, self.old_name_lower].clone() KeyError: ('apple', 'items') when i started project i didn't got any error after making 80% of my project and than i try to check that my migration file are working properly i execute that line of code python manage.py makemigrations and i have the KeyError