Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UnidentifiedImageError at /login/ cannot identify image file 'C:\\Users\\sudha\\django_project\\media\\default.jpg'
views.py/blog: from django.shortcuts import render, get_object_or_404 from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models import User from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) from .models import Post def home(request): context = { 'posts': Post.objects.all() } return render(request, 'blog/home.html', context) class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class PostDetailView(DetailView): model = Post class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['Your_Name','city','phone','cost'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['title','content','phone'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Post success_url = '/' def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False def about(request): return render(request, 'blog/about.html', {'title': 'About'}) views.py/users: from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') form.save() messages.success(request, f'Your account has … -
How to Sell digital Keys using Django
I'm new to web development and have decided to use Django to work on my digital e-commerce website. I'm mainly going to be selling digital keys. I need it such that. I can add the keys for the product in the admin section. when a product is purchased. I single line(one key) has to be sent via email to the customer. But I haven't been able to find any resources relating to this. Can anyone help me with this? point me in the right direction and Ill carry on from there. Thank you very much. -
Display PostgreSQL tables contents in Django
I'm looking to display the contents of a postgres table in Django. Clearly I'm doing something wrong but can not figure out why the data won't show. Below is what I have so far, the tables headers show but there is no data or any error messages. Checked the table in pgAdmin and there is plenty of data there. # models.py from django.db import models from datetime import datetime # Create your models here. class SensorData(models.Model): device_name = models.TextField() sensor_type = models.TextField() sensor_data = models.SmallIntegerField() sensor_date = models.DateTimeField() def __str__(self): return self.device_name # views.py from django.shortcuts import render from django.http import HttpResponse from django.views.generic import ListView from .models import SensorData # Create your views here. class ErrorView(ListView): model = SensorData template_name = 'errors.html' # urls.py from django.urls import path from .views import ErrorView urlpatterns = [ path('errors/', ErrorView.as_view(), name='errors'), path('', ErrorView.as_view(), name='errors'), ] # errors.html {% extends 'layout.html' %} {%block content %} <section class ='infoContainer'> <div id = 'sensorInfo'> <h2> Error Information </h2> <table id = "deviceTable"> <tr> <th><strong>Device </strong></th> <th><strong>Sensor Type </strong></th> <th><strong>Date</strong></th> <th><strong>Information</strong></th> </tr> {% for error in object_list %} <tr> <td> {{error.device_name}} </td> <td> {{error.sensor_type}} </td> <td> {{error.sensor_date}} </td> <td> {{error.sensor_data}} </td> </tr> {% endfor %} </table> … -
business logic in admin panel
I'm new with python and I create two models (Shoes and Order) I can add record by admin panel but I want each time that I add order record it's check weather the shoes are available or not! where should I put logic? models: -
DRF non-writable nested serializer related field
I'm using Django 3.2 and DRF I have a serializer with nested serializer fields like class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = [ 'id', 'title', ] class QuestionSerializer(serializers.ModelSerializer): category = CategorySerializer() class Meta: model = Question fields = [ 'category', 'title', 'description' ] Where in response the data should be returned like { "category": { "id": 4, "title": "General Knowledge", "created": "2021-05-23T07:12:14.749571Z", "modified": "2021-05-23T07:12:14.749639Z" }, "title": "Where is Delhi?", "description": "" } This is fine, but with the POST method, I don't want to create nested data for the Category because these records are only created from the admin panel. But these fields are required to create the Question record. When passing the id of the category in the payload, it still says the category field is required. How can I assign a related field using the id of the object instead of passing all data to create a nested object? -
All usernames are indicated by the username phrase
admin dashboard: In addition to the admin part, the template is displayed in the same way. Ever since I customized the accounts section, in all the sections where I have used the username, there is a problem that the usernames are displayed without that name and only by displaying the phrase username. settings.py: AUTH_USER_MODEL = 'accounts.CustomUser' models.py(accounts): class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("Users must have an email address.") if not username: raise ValueError("Users must have a username.") user = self.model( email=self.normalize_email(email), username=username ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user def get_profile_image_filepath(self, filepath): return f'images/accounts/profiles/{self.pk}/{"profile.png"}' class CustomUser(AbstractBaseUser, PermissionsMixin): class Meta: permissions = [ ('all', 'all of the permissions') ] first_name = models.CharField(max_length=30, null=True, blank=True) last_name = models.CharField(max_length=30, null=True, blank=True) email = models.EmailField(verbose_name='email', max_length=100, unique=True) username = models.CharField(max_length=55, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=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) profile_image = models.ImageField(null=True, blank=True, upload_to=get_profile_image_filepath, default='images/accounts/profiles/default_image.jpg') objects = MyAccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self): return self.USERNAME_FIELD def get_profile_image_filename(self): return str(self.profile_image)[str(self.profile_image).index(f'images/accounts/profiles/{self.pk}/'):] … -
stop dynamic add field to form when form is invalid
Followed below code to add and display etra fields to forms dynamically with "Add another" button. Code is working but problem is on "Add another" button click (when form in invalid) additional form fields are added to form but not displayed. Want to make sure when form is invalid extra fields are not added to form. Forms class MyForm(forms.Form): original_field = forms.CharField() extra_field_count = forms.CharField(widget=forms.HiddenInput()) def __init__(self, *args, **kwargs): extra_fields = kwargs.pop('extra', 0) super(MyForm, self).__init__(*args, **kwargs) self.fields['extra_field_count'].initial = extra_fields for index in range(int(extra_fields)): # generate extra fields in the number specified via extra_fields self.fields['extra_field_{index}'.format(index=index)] = \ forms.CharField() View def myview(request): if request.method == 'POST': form = MyForm(request.POST, extra=request.POST.get('extra_field_count')) if form.is_valid(): print "valid!" else: form = MyForm() return render(request, "template", { 'form': form }) HTML <form> <div id="forms"> {{ form.as_p }} </div> <button id="add-another">add another</button> <input type="submit" /> </form> JS <script> let form_count = Number($("[name=extra_field_count]").val()); // get extra form count so we know what index to use for the next item. $("#add-another").click(function() { form_count ++; let element = $('<input type="text"/>'); element.attr('name', 'extra_field_' + form_count); $("#forms").append(element); // build element and append it to our forms container $("[name=extra_field_count]").val(form_count); // increment form count so our view knows to populate // that many fields for … -
Sending emails to an email with an attachment
In the django function, I fill in a docx document template doc = DocxTemplate('template.docx') dates = date prices = price tbl_contents = [{'expirationdate': expirationdate, 'price': price} for expirationdate, price in zip(dates, prices)] context = { 'tbl_contents': tbl_contents, 'finalprice': sum(prices), 'startdate': startdate, 'enddate': enddate } doc.render(context) doc.save("static.docx") How do I get a file static.docx and send it to email? I sent ordinary emails via send_mail but how do I send emails with an attachment? -
How much python is needed for web development
How much python is needed for learning web development? Is it necessary to solve very complex coding questions in python before moving towards Flask/Django? -
VueJS + Django Rest Framework in dockers
I have a VueJS front end and a Django Rest Framework Backend which are independant (Django does not serve my VueJS app) In local they work very well together but after using a docker-compose to deploy them on the server they don't want to communicate anymore. I can see my frontend but the axios requests get a TimeOut. How it's made in my docker compose: version: '3' networks: intern: external: false extern: external: true services: backend: image: #from_registry container_name: Backend env_file: - ../.env depends_on: - db networks: - intern volumes: - statics:/app/static_assets/ - medias:/app/media/ expose: - "8000" db: image: "postgres:latest" container_name: Db environment: POSTGRES_PASSWORD: **** networks: - intern volumes: - pgdb:/var/lib/postgresql/data frontend: image: from_registry container_name: Frontend volumes: - statics:/home/app/web/staticfiles - medias:/home/app/web/mediafiles env_file: - ../.env.local depends_on: - backend networks: - intern - extern labels: - traefik.http.routers.site.rule=Host(`dev.x-fantasy.com`) - traefik.http.routers.site.tls=true - traefik.http.routers.site.tls.certresolver=lets-encrypt - traefik.port=80 volumes: pgdb: statics: medias: In my AxiosConfiguration I put: baseURL="http://backend:8000" And my front try to access on this URL but get a timeout error. In the console I have an error xhr.js:177 POST https://backend:8000/api/v1/token/login net::ERR_TIMED_OUT It seems that there is a https in place of the http. Can it come from here? Any idea how to make them communicate? … -
Getting AttribueError by SlugRelatedField despite the object being saved
I am creating an API to save class teachers. Now all the fields in the ClassTeacher model are foreign fields so I am using a SlugRelatedField in the serializer. It looks like SlugRelatedField does not support attribute lookup like this "user__username" and raises attribute error HOWEVER the object is still being saved. models.py class ClassTeacher(models.Model): teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) class_name = models.ForeignKey(Classes, on_delete=models.CASCADE) school_id = models.ForeignKey(School, on_delete=models.CASCADE) serializers.py class ClassTeacherSerializer(ModelSerializer): teacher = SlugRelatedField(slug_field='user__username', queryset=Teacher.objects.all()) <---- this is causing the error class_name = SlugRelatedField(slug_field='class_name', queryset=Classes.objects.all()) school_id = SlugRelatedField(slug_field='school_id__username', queryset=School.objects.all()) <---- and I am assuming that this will too class Meta: model = ClassTeacher fields = '__all__' I tried adding a @property in the Teacher model to retrieve the username and use the property in the slug_field but that did not work too. How can I save the object without getting the error? -
Получение организатора встречи вк VK API, Social_django
Использую django+vk api. Хочу получить организатора встречи вк для дальнейшей рассылки инвайтов. В django авторизуюсь через social_auth_vk, тяну токен и с помощью него авторизуюсь в api. Но для получения организатора встречи, я так понимаю, нужно получить настройки api.groups.getSettings(group_id=id) Но мне выпадает ошибка о том, что у меня нет прав на этот метод, хотя права на groups запрошены. SOCIAL_AUTH_VK_OAUTH2_SCOPE = ['email', 'groups', 'ads'] Я прочитал, что авторизация social_auth не дает токена с полным доступом, а режет его. Подскажите, как решить проблему. -
In django How can i get unchecked checkbox values.currently it returns only checked value
models.py taken = models.BooleanField(default=False) forms.py taken = forms.CheckboxInput() in html this field comes in a loop so when i try to fetch this in views taken = request.POST.getlist('taken') it only returns checked fields as 'on' here i need both 'on' and 'off'. -
erorr manage.py dumpdata > db.json
I have erorr when user manage.py dumpdata > db.json CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u062f' in position 17: character maps to <undefined> -
Unversion files in my django project not getting commited or pushed to Github from Pycharm
I am trying to push my project to Github . But for some reason the unversioned files are not getting commited in pycharm vcs and hence not getting pushed to github The comment button keeps on fading out whenever I check the unversion file option and try to commit them. What is the issue exactly ? -
Can Django ORM's `.first` return `None` for a non-empty queryset?
I have a very simple model called Achievement. In an algorithm, I reach a point in which I have a queryset for this model - named achievements bellow. I got in a situation in which the method .first() applied to this queryset outputs None, even though there is an element in the queryset. In summary, achievements.order_by('-amount')[0] # outputs an achievement achievements.order_by('-amount').first() # None achievements.count() # 1 How can this happen? There is no default ordering for this model. -
Django Updateview html templet with links using current instance object values
I have two models class AccGroup(models.Model): grpid = models.BigAutoField(primary_key=True, editable=False) groupname = models.CharField(max_length=40, default="") class Meta: indexes = [models.Index(fields=['groupname'])] def __str__(self): return "%s" % (self.groupname) class Account(models.Model): accid = models.BigAutoField(primary_key=True, editable=False) shortcut = models.CharField(max_length=10, default="") accname = models.CharField(max_length=100, default="") accgrp = models.ForeignKey(AccGroup, on_delete=models.RESTRICT, default=0) class Meta: indexes = [models.Index(fields=['shortcut']),models.Index(fields=['accname']) ] def __str__(self): return "%s--%s" % (self.shortcut, self.accname) One Update View defined on above model class AccountUpdateForm(UpdateView): model = Account fields = ['shortcut','accname','accgrp'] def get_success_url(self): currid = self.kwargs['pk'] account = Account.objects.get(pk=currid) print(account) return ('/polls/accmst/'+ str(account.accid)) and the corresponding HTML templet <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Update Account</title> </head> <body> <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Save" /> </form> <p> <a class="btn btn-info btn-sm" href="{% url 'polls:accgrpList' %}">Back To Group List</a> </p> <p> <a class="btn btn-info btn-sm" href="{% url 'polls:accgrpList' form.accgrp.grpid %}">Back To Account List</a> </p> </body> </html> so on success the same page is displayed using the current account object primary key there are two more links Link 1 point the a group list <polls:accgrpList> which translates to http://localhost:8000/polls/accgrplist Link 2 my problem is I want to point to url http://localhost:8000/polls/accgrplist/2 where the last part is the grpid of the current account … -
How to access Other Model Field from Serializer related Field?
have following model class Search(models.Model): trip_choice = ( ('O', 'One way'), ('R', 'return') ) booking_id = models.IntegerField(db_index=True, unique=True) trip_type = models.CharField(max_length=20, choices=trip_choice) and Booking Model is Fk with search class Booking(models.Model) flight_search = models.ForeignKey(Search, on_delete=models.CASCADE) flight_id = models.CharField( max_length=100 ) return_id = models.CharField( max_length=100, blank=True, null=True ) I have following rule if trip type is Return 'R' the return id cannot be sent empty in serializer. class AddBookSerializer(BookSerializer): booking_id = serializers.IntegerField(source='flight_search.booking_id') class Meta(BookSerializer.Meta): fields = ( 'booking_id', 'flight_id', 'return_id', ) def validate_booking_id(self, value): print(value.trip_type) Is there any way I can access trip type based on booking id I am really stuck here. -
Success message not showing after deleting the object in Django rest framework
I have a DestroyAPIView in which I am using the perform_delete function to delete an instance. However, I want to send a success message with 200 status. I tried, but in the postman I am getting blank with 204 status. How can I acheive this?? My view: class UpdateOrderView(UpdateAPIView,DestroyAPIView): permission_classes = [AllowAny] #queryset = Order.objects.prefetch_related('order_items').all() #value = self.kwargs['pk'] queryset = Order.objects.all() print(queryset) serializer_class = OrderUpdateSerializer def perform_destroy(self, instance): if instance.delete(): return Response({ "message":"Order deleted successfully" }, status=status.HTTP_200_OK) else: pass The instance is deleted, I have checked the db, but I am not getting success message. -
show django template engine message in javascript pop up box
I have used django2 to develop a web app. I want to make the text in django template engine showing in js pop up box. <ul class="messages"> {% for message in messages %} <li>{% if message.tags %} "{{ message.tags }} "{% endif %} {{ message }}</li> {% endfor %} </ul> I want to show message in the for loop in js pop up box. How to pass this value to js pop up box in each loop in HTML? -
Django-LDAP Authentication on Login Page
I am having a task to implement the LDAP user authentication on a Django Application. I am quite new to Django and hence facing a lot of issues finding the solution to this question as all the available resources or answers on Stackoverflow are either too old or doesn't have the similar approach which I am using. I have made the changes in my views.py , settings.py , installed all the required packages for ldap to run fine. However I am not getting how to link the ldap with my login form which I have made. I will share my all the changes which I did for the LDAP to work. I will appreciate your time, if you will be able to solve my problem. Here is my : settings.py import ldap AUTH_LDAP_SERVER_URI = "ldap://myldapserver.com" AUTH_LDAP_CONNECTION_OPTIONS = {ldap.OPT_REFERRALS : 0} AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s, OU=USERS,dc=myldapserver, dc=com" AUTH_LDAP_START_TLS = True AUTHENTICATION_BACKENDS = ["django_auth_ldap.backend.LDAPBackend"] views.py from django.contrib.auth import authenticate, login import ldap def ldap_auth(username, password): conn = ldap.initialize(myproj.settings.LDAP_AUTH_URI) try: ldap.set_option(ldap.OPT_REFERRALS, 0) #ldap.set_option(ldap.OPT_PROTOCOL_VERSION, 3) conn.simple_bind_s(username, password) except ldap.LDAPError as e: return f'failed to authenticate' conn.unbind_s() #return "Success" return render(request, 'login.html') #not sure if I need to use the above commented line, as it is … -
Pycharm plugin for autocompletion in Django
I am learning Django for a couple of month now and I've noticed that there's some methods/fields and stuff like that (e.g. get_absolute_url), that Pycharm doesn't offer autocomplition for. So I've been wondering are there any plugins or something for pycharm i can install to make autocomplition more thorough? Thanks in advance! -
Gunicorn worker getting timed out even after processing is success and not returning a Http response
I am using a Django application to do some file processing. I am using an Nginx, Gunicorn, and Django setup. My file processing is being done successfully at the backend level, however, my gunicorn worker is timing out. I have increased the timeout parameter both in Nginx and Gunicorn. -
How to implement django framework nested relationships?
I have tried the option as shown on django rest framework docs, but still it wont work properly.when implementing the nested relashionship I only get the primary key of the lesson, I want all the lesson dedails to apear.Meaning A student has many lessons and I want to allow for each student to show his lessons. Thank you!! My code: Models.py from django.db import models from django.contrib.auth.models import User # from django.utils import timezone from datetime import date class Student(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) information = models.TextField(blank=True) objects = models.Manager() # default manager class Meta: ordering = ('-first_name',) def __str__(self): return self.first_name class Lesson(models.Model): options = ( ('paid', 'Paid'), ('not paid', 'Not Paid'), ) student = models.ForeignKey( Student, on_delete=models.CASCADE, related_name='lessons') paid = models.CharField( max_length=10, choices=options, default='not paid') title = models.CharField(max_length=50) task1 = models.CharField(max_length=50) description1 = models.TextField(blank=True) task2 = models.CharField(max_length=50) description2 = models.TextField(blank=True) user = models.ForeignKey( User, null=True, on_delete=models.CASCADE) lesson_date = models.DateField(default=date.today, null=False) objects = models.Manager() # default manager class Meta: ordering = ('-lesson_date',) def __str__(self): return '%s: %s %s %s' % (self.student, self.title, self.lesson_date, self.paid) Serializers.py from rest_framework import serializers, fields from private_models.models import Lesson, Student class LessonSerializer(serializers.ModelSerializer): #student = serializers.SerializerMethodField() class Meta: model = Lesson fields = … -
Downloaded Django project file raises RelatedObjectDoesNotExist
I have this project that runs correctly on my pc. However, when this project file is pulled/downloaded by other people, RelatedObjectDoesNotExist shows up after createsuperuser. Models.py class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name =models.CharField(max_length=100) middle_name =models.CharField(max_length=100) last_name =models.CharField(max_length=100) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_chairperson = models.BooleanField(default=False) is_faculty = models.BooleanField(default=False) is_student = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'middle_name', 'last_name'] class FacultyInfo (models.Model): fac_user = models.OneToOneField(User, on_delete=CASCADE, primary_key=True) @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: if instance.is_faculty == True: FacultyInfo.objects.create(fac_user=instance) instance.facultyinfo.save() Full Traceback Traceback (most recent call last): File "E:\iPLM-master2\iPLM-master\manage.py", line 22, in <module> main() File "E:\iPLM-master2\iPLM-master\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in exe cute return super().execute(*args, **options) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in ha ndle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "E:\iPLM-master2\iPLM-master\CRS\models.py", line 33, in create_superuser user = self.create_user( File "E:\iPLM-master2\iPLM-master\CRS\models.py", line 26, in create_user user.save(using=self._db) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save super().save(*args, **kwargs) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 774, in save_base …