Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Do we need to use on_delete argument in ManyToManyField in django?
While designing Models do we need to add on_delete attribute in Manytomanyfield in django just like the foreign key. -
Why am I getting an error at admin (django version 1.11) Incorrect Padding?
Receiving the following error while accessing admin through my website and I am not able to understand why this is occuring. -
Why are my bootstrap cards aligned on top of each other and not aligned side by side?
My bootstrap cards are not aligning side by side and I can't seem to find my mistake. I am using django and html. {% extends 'base.html' %} <div> {% block content %} <h1>Players<h1> {% for player in players %} <div class="row"> <div class="column"> <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{{ player.image_url }}"> <div class="card-body"> <h5 class="card-title">{{ player.name }}</h5> <p class="card-text">{{ player.position }}</p> <a href="#" class="btn btn-primary">Know More!</a> </div> </div> </div> </div> {% endfor %} {% endblock %} </div> -
Site authorization (django) via session + cookies via a third-party API to an external server where login, password data is stored
I can not understand any need to write views in order to do so in the form of authorization by user and login through the api of a third-party service where users with passwords lie. I understand that you need to make a request on the APIs that are available and in post send the login and password. How to implement this in views and form -
Unable to Align the Label under other Label
Sorry I am very very new to CSS I am trying to align "Low" under "Work", but no luck. Could anyone suggest me. Please refer screenshot.enter image description here -
VSCode Django Virtualenvwrapper
Hi i have my django project with use Virtualenvwrapper. I use VSCode and works for me workon etc in terminal. I have 3 files settings to run project in local server and in VPS server. I remove from settings my SECRET_KEY and all files with codes to json files. and run project like this: workon env_name (env_name) workon my_project python manage.py runserver --settings setings.local2 and this works good with file like this: like this: from my_project.settings import * import json import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) with open('keys_my_project.json') as config_file: config = json.load(config_file) SECRET_KEY = config['SECRET_KEY'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config['NAME'], 'USER': config['USER'], 'PASSWORD': config['PASSWORD'], 'HOST': config['HOST'], 'PORT': '5432', } } DEBUG = True ALLOWED_HOSTS = [] STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') and now i have a problem with using VSCode debbuger: { "name": "my_project django", "type": "python", "request": "launch", "program": "my_project/manage.py", "args": ["runserver --settings settings.local2"], "django": true } MY ERROR: Exception has occurred: ImproperlyConfigured The SECRET_KEY setting must not be empty. File "my_project\manage.py", line 18, in main execute_from_command_line(sys.argv) File "my_project\manage.py", line 22, in <module> main() why my VSCode debbuger dont read json in settings file ? -
User Session in Django
Problem: I would like to assign a bank statement for each user. Each user will log in using their username and password, and access their document. At the moment, one user can see the statement of all users. If I would like to assign a document for each user, is adding a ForeignKey to the model is enough? user = models.ForeignKey(User) models.py class BankStatement(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=20) date_created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) Many Thanks -
Django with Gunicorn Serves Only One Request at a Time
I have deployed my Django project to Google Cloud. It has a RAM of 1.7GB and 1 shared core, running on Ubuntu 20.0.4. I have used Nginx as reverse proxy and to serve static files and Gunicorn behind it to serve as WSGI handler. I have run some performance tests using Apache Bench. Now it seems that Gunicorn is serving only one request at a time. I had turned off Nginx and run Gunicorn in port 80 to see if Nginx was the bottleneck, and it wasn't. I have checked with python manage.py server and it serves 3.16 requests per second with nearly 316ms response time. The problem is when I run it with Gunicorn it shows almost the same result or sometimes even worse. I am developing an e-commerce website which performs database I/O. I have used gevent as worker class. I have run the following command- /var/www/grocery-app/g_env/bin/gunicorn grocery.wsgi --workers 3 --worker-class gevent --worker-connections 100 --bind 127.0.0.1:8000 Nginx reads the server from local port 8000. I have run the test from Apache Bench with 100 requests in 100 connections, 50 requests in 50 connections, 50 request in 10 connections. No matter what combination I choose the result always seems … -
How to add values from another model and export it to csv when selecting the School Object from django admin?
How do i add the values and field names of all books (author, year and grade) and teachers (full_name and subject) related to the School when trying to export to csv? Csv example: expecting something like fields for School in db = id, name, address, location, website, about_us, school_book_id fields for Books in db = id, author, year, grade fields for Teachers in db = id, full_name, subject admin.py the django admin is displaying correctly! class SchoolAdmin(admin.ModelAdmin, CsvAdminMixin): list_display = ("name", "address",) model = TechPartner inlines = [ SchoolBooks, SchoolTeachers ] actions = ["export_to_csv",] admin.site.register(School, SchoolAdmin) model.py class SchoolModel: name = models.TextField(verbose_name=_(u"name"), default="", blank=True) address = models.TextField( verbose_name=_(u"address"), default="", blank=True ) website = models.URLField(verbose_name=_(u"website"), blank=True, null=True) class Meta: abstract = True class School(SchoolModel): type = models.ManyToManyField( to=SchoolType, verbose_name=_(u"Type"), blank=True ) class Meta: verbose_name = _(u"school") mixins.py class CsvAdminMixin(object): def export_to_csv(self, request, queryset): meta = self.model._meta fields = meta.get_fields() field_names = [field.name for field in fields] resp = HttpResponse(content_type='text/csv') resp['Content-Disposition'] = 'attachment; filename={}.csv'.format( meta ) writer = csv.writer(resp) writer.writerow(field_names) for obj in queryset: writer.writerow([getattr(obj, field_name) for field_name in field_names ]) return resp export_csv.short_description = "CSV export selected items." when printing queryset: <QuerySet [{'id': UUID('2342342'), 'name': 'Austin High school', 'address': 'There', 'about_us': … -
How can get the data from the foreign key in django
I am trying to get the vendor information against the category id,means when someone select the category all vendor's information against the category should be display,but when i call the url it show the error ' Cannot use QuerySet for "VendorCategory": Use a QuerySet for "Vendor" '. how can i get the vendor information Model.py class Vendor(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=40) Contact_No = models.IntegerField(unique=True) email = models.CharField(max_length=30, unique=True) def __str__(self): return self.name class VendorCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) View.py class All_Vendor(TemplateView): template_name = 'purchase/allVendor.html' def get(self, request, *args, **kwargs): categories = categoryModel.objects.all() categoryId = self.request.GET.get('SelectCategory') vendorselect = VendorCategory.objects.filter(category_id=categoryId) vendor_id = VendorCategory.objects.filter(vendor_id=vendorselect) vendors = vendorModel.objects.get(id=vendor_id) args = {'categories': categories, 'selectedCategory': categoryId, 'vendorselect': vendorselect, 'vendors': vendors} return render(request, self.template_name, args) Template {% block content%} <form method="get"> <label> <select name="SelectCategory"> <option disabled="disabled" selected> Select Category</option> {% for category in categories %} <option value={{ category.id }}> {{ category.name }} </option> {% endfor %} </select> </label> <input type="submit" value="Select"> </form> {% for vendor in vendorselect %} {{ vendor.id }} {% endfor %} {% endblock %} -
How do i access a function i defined in my django view, inside the template (for UTF Encoding)
I have installed django-simple-gravatar and added that in my installed apps in the project. Then i tried using it in my template as: {% load gravatar %} {% gravatar_url user.email 40 %} But i got the following error: Unicode-objects must be encoded before hashing So i made the "Profile" View Accordingly: def Profile(request, pk): template = 'events/profile.html' user = User.objects.get(id=pk) posts = Post.objects.filter(owner=user) liked_posts = Fav.objects.filter(user=user) def email_for_gravatar(self): return self.user.email.lower().encode("utf-8") ctx = {'user': user, 'posts': posts, 'liked_posts': liked_posts} return render(request, template, ctx) And This is how i am trying to access the "email_for_gravtar" function inside my template, i may be wrong here: {% gravatar_url user.profile.email_for_gravatar 40 %} But the error message is still the same. What am i doing wrong here? -
Can get_queryset return 403 or any custom response
I have no idea if This is the good way to do this. I have an endpoint, it should retrieve a specific instance of system. Before being worried about permissions my view lookeds like this: class SystemDetail(generics.RetrieveAPIView): """ Get a system detail """ queryset = System.objects.all() serializer_class = SystemSerializer I want to update this because I want user to be able to see only systems they own. So I update my view like so: class SystemDetail(generics.RetrieveAPIView): def get_queryset(self): user_groups = self.request.user.groups.all().values_list('name') if 'all_rights' not in user_groups[0]: if len(user_groups) == 1: # For now we say that 1 user is only in 1 group dealer_name: str = user_groups[0][0].capitalize() # Group name are creating progammatically, it is using the same enum than the dealer name on the system return System.objects.filter(dealer__name=dealer_name) else: raise AttributeError('User in 2 groups, endpoint can not manage it') else: return System.objects.all() """ Get a system detail """ serializer_class = SystemSerializer So basically it works, when I try to access a system that I should not be able to see I got this message: {"detail":"Not found."} but What I'd like is to set a custom message with a 403 status saying to the user he is trying to access a … -
I can't send form with attachment in Django
I have problem with forms. I have few on my site and they works but i have one form with attachment and when i press 'send' on site nothing happened (site is only refreshing). Thats do immediately so I supposed Django don't even try send this form. And second, how can I set format file for only jpg,png and pdf? forms.py class PayBackForm(forms.Form): subject = forms.CharField(required=True) signature_number = forms.CharField(required=True) email = forms.EmailField(required=False) file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) message = forms.CharField(widget=forms.Textarea, required=False) views.py from aplikacja.settings import EMAIL_HOST_USER from .models import News from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse from django.shortcuts import render, redirect from .forms import ContactFormForDebtor, ContactFormForClient, PayBackForm from django.contrib import messages ... from django.core.mail import EmailMessage def splata(request): if request.method == 'GET': form = PayBackForm() else: form = PayBackForm(request.POST) if form.is_valid(): messages.success(request, 'Form submission successful') subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] email = form.cleaned_data['email'] file = request.FILES['file'] try: mail = EmailMessage(subject, message, EMAIL_HOST_USER, [email]) mail.attach(file.name, file.read(), file.content_type) mail.send() return render(request, "splata.html", {'email_form': form, 'error_message': 'Sent email to %s'%email}) except BadHeaderError: return render(request, "splata.html", {'email_form': form, 'error_message': 'Either the attachment is too big or corrupt'}) return render(request, "splata.html", {'form': form}) html <form enctype="multipart/form-data" method="post"> {% csrf_token %} {% if … -
How can I set an attribute on a functools.partialmethod?
I have ported the following code from Django 2.2 to Django 3.1, and replaced django.utils.functional.curry with functools.partialmethod: class CurrencyField(models.DecimalField): description = 'Currency amount' def __init__(self, *args, **kwargs): kwargs.setdefault('max_digits', 9) kwargs.setdefault('decimal_places', 2) super().__init__(*args, **kwargs) def contribute_to_class(self, cls, name): super().contribute_to_class(cls, name) if hasattr(cls, '_get_value_as_currency'): curried = partialmethod(cls._get_value_as_currency, field=self) curried.admin_order_field = self.name curried.short_description = self.verbose_name setattr(cls, f'get_{self.name}_as_currency', curried) The method works correctly, however the admin_order_field and short_description attributes don't "stick" to the method like they did when I used curry. Is it possible to set attributes on a partialmethod, or will I need to replace this with some other mechanism? -
How to query a list django
def get_queryset(self): result = Tenants.objects.all() filters = self.request.GET.get('filter') if filters is not None: filters = filters[1] if filters[1] == ',' else filters filters_list = filters.split(',') filter_result = Tenants.objects.none() for value in filters_list: filter_result = filter_result | result.filter(Q(business_type__icontains=value) |Q(category__icontains=value)) return filter_result return result.all() here i want the query parameters to be business_type and category when using get method and checking the data i am only able to filter one field either business_type or category when using filter twice like /?page=1&filter=business_type&filter=category then i am getting the data i want but i need the data when the url is like /?page=1&filter=business_type,category -
relation does not exist Django Postgresql Dokku
I created a new model on my already existing Django app.When i updated my git I did these: git pull git push dokku main Then i did these: python3 manage.py makemigrations python3 manage.py migrate But i get this error whenever i try to do an operation: relation "accounts_articleimageshared" does not exist Why?? I don't want to dump my already existing database because i would have to dump it everytime i try to update my app.How can i solve this? -
How to get instance of model in UpdateAPIView django REST?
I have a model Request is below class Request(models.Model): PENDING = 1 APPROVE = 2 REJECT = 3 STATUS_CHOICES = ( (PENDING, 'Pending'), (APPROVE, 'Approve'), (REJECT, 'Reject') ) seller = models.ForeignKey( Seller, on_delete=models.CASCADE, related_name='requests', ) owner = models.OneToOneField( UserProfile, on_delete=models.CASCADE, related_name='request', ) reject_reason = models.TextField(default='') status = models.PositiveSmallIntegerField(STATUS_CHOICES, default=1) created_at = models.DateField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) And an UpdateAPIView class RequestDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Request.objects.all() serializer_class = RequestUpdateSerializer permission_classes = (IsAuthenticated, IsAdminOrRequestOwner) name = 'request-detail' # TODO: send an email inform user that the request have been approve or reject def update(self, request, *args, **kwargs): if self.request.user.profile.role != 3: raise serializers.ValidationError( {'detail': 'You do not have permission to perform this action'}) return super().update(request, *args, **kwargs) What I need is to send an email to the owner of that Request instance. I have written a function to do that but it has to be called in update() method of UpdateAPIView In order to send an email, it required the data from the Request instance that is being updated. The request data only contains information about status My question is what is the proper way to get the Request instance inside the UpdateAPIView. My approach is to get the id from kwargs params and … -
Backend problem in running someone else's Django project | error: 'form 1 is invalid'
I have downloaded the following project from GitHub-https://github.com/sanjaysupanch/Online-Company-Management-Website and run it on my Windows 10 system through the cmd prompt. After creating the virtual environment and running makemigrations, migrate and runserver, the login page opens up. When I proceed to create a new user by clicking on 'Register', there two options 'Employee' and 'Company'. After choosing 'Company', I fill in the details and click on 'Register' but then, receive the error 'form 1 is invalid'. I tried to register as an Employee and that option gave me the same error as well. I am new to Django Python Web Development and this project isn't my own. I suspect this problem has something to do with the backend database but can't figure what the problem might be. Please help me. (A thing to note- When I create a superuser through the cmd prompt, I am able to log into the website through that username and password.) (PS- I wasn't able to attach any screenshots due to the size limit. If something is unclear, please let me know and I'll clarify. Thanks and cheers!) -
How to list messages in order in Django
SO I have been trying to implement a basic one to one chat system in Django. So far, I have created a model that takes in two foreign keys( sender, recipient) and a Charfield by the name of message. class message(models.Model): sender=models.ForeignKey(User,related_name='sender2',on_delete=models.CASCADE) receiver=models.ForeignKey(User,related_name='reciever2',on_delete=models.CASCADE) message1=models.CharField(max_length=10000000) Now, I am able to create message objects but what I want to do is display in a back-and forth conversation on one single page. I have so far been able to fetch all messages for a particular "sender-receiver" combination. def view_message(request,pk): client1=User.objects.get(id=pk) client2=request.user message1=message.objects.filter(sender=client1,receiver=client2).all() return render(request,'message.html',{'messages':message1}) Now the above view just shows all messages for the single user who logged in, sent to the other user whose Primary key is being used/clicked on, But I also want to show are "replies" they receive in a conversation-style manner and in order. Hopefully, You guys understand what I am saying here. A one-to-one private messaging system (not asynchronous), so the page can refresh and reload all messages sent and received but in order. Thank you :) -
Convert string to User pk after posting a form with Django Rest Framework
I am trying to build a feature with AJAX and DRF whereby a user can follow another user. However when I initiate it, the POSTed data does not appear to be hitting the DRF endpoint so I am getting no errors beyond: {user: ["Incorrect type. Expected pk value, received str."],…} following_user: ["Incorrect type. Expected pk value, received str."] user: ["Incorrect type. Expected pk value, received str."] When I hardcode in a couple of integers to the AJAX call it works, so I just need to convert the usernames which are passed as strings to their relevant IDs, I don't know how to do this, however. Here is my js function: const followUser = function(followedUser){ var pathArray = window.location.pathname.split('/'); var currentUser = 'ben' console.log(followedUser); console.log(currentUser) $.ajax({ type: 'POST', url: '/api/userconnections/', data: { csrfmiddlewaretoken: document.querySelector('input[name="csrfmiddlewaretoken"]').value, 'user': currentUser, 'following_user': followedUser }, success: function(data) { alert('Successfully Followed') }, error: function (jqXhr, textStatus, errorThrown) { console.log('ERROR') console.log(jqXhr) }, }); } Here is my serializer: class UserConnectionListSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField() following_user = serializers.StringRelatedField() class Meta: model = UserConnections fields = ['user','following_user'] class UserConnectionSerializer(serializers.ModelSerializer): class Meta: model = UserConnections fields = '__all__' Here is my models.py file class UserConnections(models.Model): user = models.ForeignKey(User, related_name="following", on_delete=models.CASCADE) following_user = models.ForeignKey(User, … -
Change database cached data django while model is updated
I have a model that has a mapping to external API data. For example class Local(models.Model): external_mapping_id = models.IntegerField() name = models.CharField(max_length=255) url = models.UrlField() when I change the name or URL of this model it sends a patch request to the external API and changes the object there too. And I have an endpoint that I cache for 1 hour which shows a list of external objects. The problem is that I can't see updated external objects while I change url or name. Because of cache. How can I change cached data to fit updates without removing caching? CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'google_service_cache', } } -
How to send Email in Django using office365
I am working in a project where I need to send the email to the user who is filling the Email in the form. I am able to send email by using my Gmail Account details but while using outlook.365. This is the image with error that I am getting. My requirement is : Once users come in the registration form and fill the details as Name, Email, Mobile Whatever Email is put there in the form, send the email with link to create new password. Here is my code: settings.py: # Using outlook365: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = 'support@academic.com' EMAIL_HOST = 'smtp.outlook.office365.com' # (also tried : smtp.office365.com and outlook.office365.com) EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_PASSWORD = 'My_Password' # Using my gmail account: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = 'admin@gmail.com' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_PASSWORD = 'My_Password' views.py: subject = "Academic - Create New Password" message = "Hi %s! Please create your new Password here : http://127.0.0.1:8000/api/create-password" % firstname send_mail( subject, # Subject of the email message, # Body or Message of the email 'support@academic.com', # from@gmail.com (admin@gmail.com for gmail account) [email], # to@gmail.com # email that is filled in the form ) Please guide … -
Nginx serving Django static files must have folder with same name as URL
I am serving static files using Nginx. My config looks like this: # django settings STATIC_URL = '/static_folder/' STATIC_ROOT = '/app_data/' # nginx config location /static_folder/ { root /app_data/; } It does not work like this. I need to change the STATIC_ROOT to include the static_folder part. Like this: # django settings STATIC_URL = '/static_folder/' STATIC_ROOT = '/app_data/static_folder/' # <-- here # nginx config location /static_folder/ { root /app_data/; } I want to be able to serve like this: /app_data/logo.png instead of this: /app_data/static_folder/logo.png It is not a big deal if you have one URL part in STATIC_URL but if I use nested URLs, I need to repeat it in STATIC_ROOT too. It gets too deep. For example: # django settings STATIC_URL = '/static_folder/and/another/folder' STATIC_ROOT = '/app_data/static_folder/and/another/folder/' # nginx config location /static_folder/ { root /app_data/; } How can I get rid of this and serve files in /app_data/ without including static_url parts in the folder structure. -
ModuleNotFoundError: No module named 'djfilter.wsgi.application'; 'djfilter.wsgi' is not a package
I am trying to deploy Django app on Heroku ModuleNotFoundError: No module named 'djfilter.wsgi.application'; 'djfilter.wsgi' is not a package -
Django ModelChoiceField display like charField
the ModelChoiceField that should display a list of some type of user, but instead it displays like a charfield ( figure 1 ) figure1 this is my views.py @login_required def create_appointement(request): user = User() if request.method=='POST': appointment = request.POST['type'] if appointment=='register patient': form_appointment = AppointmentForm_2(request.POST or None) if form_appointment.is_valid(): form_appointment.save(commit=False) form_appointment.user_ho_add = request.user start_time = form_appointment.start_time future_time = dt.datetime(1970, 1, 1, start_time.hour, start_time.minute, start_time.second, start_time.microsecond) + timedelta(minutes=30) form_appointment.end_time = dt.time(future_time.hour, future_time.minute, future_time.second, future_time.microsecond) form_appointment.save() messages.success(request, 'appointment added') else: messages.error(request, 'Error') return render(request, 'appointement/add_appointement2.html', {'user_form':form_appointment, } and this my forms.py class AppointmentForm_2(forms.ModelForm): doctor = forms.ModelChoiceField(queryset=User.objects.filter(type_of_user=TypeOfUser.DOCTOR)) patient = forms.ModelChoiceField(queryset=User.objects.filter(type_of_user=TypeOfUser.PATIENT)) date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), input_formats=settings.DATE_INPUT_FORMATS) start_time = forms.DateField(widget=forms.DateInput(attrs={'type': 'time'}), input_formats=settings.TIME_INPUT_FORMATS) class Meta: model = Appointment fields = ('patient', 'doctor', 'date', 'start_time') the doctor field work perfectly but the patient field dont work and this is my models.py class Appointment(models.Model): user_ho_add = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_ho_add_appointment') patient = models.CharField(null=True,max_length = 200, default=defaultTitle) doctor = models.ForeignKey(User, on_delete=models.CASCADE, related_name='doctor_app') date = models.DateField(null=False, blank=False, default=timezone.now) start_time = models.TimeField(null=True, blank=True, default=timezone.now) end_time = models.TimeField(null=True, blank=True, default=timezone.now) is there a way to make the patient field display a choice field?