Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a Serial field restart at 1 for every super-item in Django
In my program, there is a structure like so (the items discussed aren't real, but should get the structure across): We have multiple super items, let's call them posts (like a blog). The Post-class has a UUID as its PK. Every Post can have multiple comments. The Comment-class also has a UUID as its PK. However, I'd like to add a SERIAL-like field (let's call it Index) to the Comment class, but not so that every new comment counts on the "same counter", but rather that the Comment's Index starts at 1 for each Post, so Post 1 has three comments with unique UUIDs, and Indices 1, 2 and 3. Post 2 should have other comments, but these should still have indices 1, 2, 3, 4 ... I don't have any code to show, but the problem is more technical than syntactical, so this should suffice. Any ideas? -
Django project Using mod wsgi and apache - ImportError: No module named 'encodings'
I am able to run my django project in development mode using python3.7 manage.py runserver However when tried to run the same project using apache mod wsgi configuration, I am getting the below error: Fatal Python error: initfsencoding: unable to load the file system codec ModuleNotFoundError: No module named 'encodings' Below is the httpd.conf file configuration LoadModule wsgi_module "/TomCatWeb/app/projects/myproj/myenv/lib/python3.7/site-packages/mod_wsgi/server/mod_wsgi-py37.cpython-37m-x86_64-linux-gnu.so" WSGIPythonHome "/TomCatWeb/app/projects/myproj/myenv" WSGIPythonPath /TomCatWeb/app/projects/myproj WSGIScriptAlias /hello /TomCatWeb/app/projects/myproj/proj/wsgi.py DocumentRoot /TomCatWeb/app/projects/myproj/proj/ <Directory /TomCatWeb/app/projects/myproj/proj> <Files wsgi.py> Require all granted </Files> </Directory> -
Which linux distro docker image I can use to connect to MySQL v8.0.12?
I have a redhat server with docker installed I want to create a docker image in which I want to run django with MySQL but the problem is django is unable to connect to MySQL server(remote server). I'm getting following error: Plugin caching_sha2_password could not be loaded: /usr/lib/x86_64-linux-gnu/mariadb19/plugin/caching_sha2_password.so: cannot open shared object file: No such file or directory I googled it and found that libraries does not support 'caching_sha2_password'. Can anyone suggest me which distro have libraries that support 'caching_sha2_password'? Thanks in advance. -
how to create rest API for .py file which connects to MySql
I have already created 2 .py files. one is connecting to MySql (dbconnect.py) and the other (app.py) is calling functions defined in the first file. I have uploaded my files on GitHub repository https://github.com/omkarcpatilgithub/Moneytor. can anyone help me creating a rest API for the 1st file (dbconnect.py) with Django? I have no idea about Django framework, what should I actually do or where I should start? -
How to get all details using filter condition in django?
This is my scenario I have user data in the user database. Example { id:1, email:'her@gmail.com' } filter condition sample = user.objects.filter(email='her@gmail.com') print(sample.id) I tried to print user id.but its throwing error.how to print id in the filter condition? and why its throw error any issue?. -
Is it possible in Django model to update a manually created primary key field using a calculated value during save()
In Django, is it possible to update the manually created primary key field of a model with a calculated value during save() method? For example, in the following model: class Siding(models.Model): siding_doc = models.PositiveIntegerField(primary_key=True, unique=True, default=1000, ...) created_date = models.DateField(default=timezone.now, verbose_name='Date Created') eff_date = models.DateField(verbose_name='Effective From') siding_rate = models.DecimalField(max_digits=5, decimal_places=2, ...) will it be possible for me to .get the last siding_doc number, increment the value by 1 and (kind of) insert the calculated value in the primary key field siding_doc for the new record. And if it is possible, can we do this in model's save() method? -
How to create comment form
I'm Django beginner. I am trying to implement a code on how to implement a comment form in home page. In all tutorials I have come across, it is advisable to pass an ID in views.py. How can I create a form in homepage without an ID? class Comments(models.Model): user=models.ForeignKey(settings.AUTH_USER_MODEL) commented_image=models.ForeignKey(Image,....) comment_post=models.TextField() def home(request): if request.method == 'POST': form=CommentForm(request. POST) if form.is_valid(): comment=form.save(commit=False) comment.user=request.user comment.commented_image=post comment.save() return redirect.... else: form=CommentForm -
how do I add 'id' to model form in Django?
I'm trying to control some input fields with JavaScript in my Django. So I thought I should assign class and id to each field. I've searched a bit and tried myself but didn't work. Below is my code: forms.py class MyInputForm(forms.ModelForm): format_free = forms.CharField(widget=forms.Textarea (attrs={'class':'formats', 'id':'format_free'}) ) format_simple = forms.CharField(widget=forms.CharField (attrs={'class':'formats', 'id':'format_simple'}) ) class Meta: model=MyInput fields=['format_free', 'format_simple'] widgets = {'authuser':forms.HiddenInput()} But this keeps on giving me error that says "TypeError: init() got an unexpected keyword argument 'attrs'" I have no idea on what went wrong. Thanks in advance :) -
Django deployment using pythonanywhere
So, I have deployed my site successfully on pythonanywhere, but when I try loading the site, I get the following error. TemplateDoesNotExist at / base.html Request Method: GET Request URL: http://devchron.pythonanywhere.com/ Django Version: 3.0.3 Exception Type: TemplateDoesNotExist Exception Value: base.html Exception Location: /home/devchron/.virtualenvs/devchron.pythonanywhere.com/lib/python3.7/site-packages/django/template/backends/django.py in reraise, line 84 Python Executable: /usr/local/bin/uwsgi Python Version: 3.7.5 Python Path: ['/home/devchron/devchron.pythonanywhere.com', '/var/www', '.', '', '/var/www', '/home/devchron/.virtualenvs/devchron.pythonanywhere.com/lib/python37.zip', '/home/devchron/.virtualenvs/devchron.pythonanywhere.com/lib/python3.7', '/home/devchron/.virtualenvs/devchron.pythonanywhere.com/lib/python3.7/lib-dynload', '/usr/lib/python3.7', '/home/devchron/.virtualenvs/devchron.pythonanywhere.com/lib/python3.7/site-packages'] Server time: Fri, 27 Mar 2020 07:01:54 +0000 Now, the statement which I use in the child templates is {% extends "base.html" %}. This is where the error happens. The error also states that: Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /home/devchron/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/devchron/.virtualenvs/devchron.pythonanywhere.com/lib/python3.7/site-packages/django/contrib/admin/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/devchron/.virtualenvs/devchron.pythonanywhere.com/lib/python3.7/site-packages/django/contrib/auth/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/devchron/devchron.pythonanywhere.com/blogposts/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/devchron/devchron.pythonanywhere.com/useraccounts/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/devchron/.virtualenvs/devchron.pythonanywhere.com/lib/python3.7/site-packages/markdown_deux/templates/base.html (Source does not exist) This makes sense as the file base.html is not present in any of these folders, instead it is present on /home/devchron/devchron.pythonanywhere.com/templates/base.html , django doesn't look here. I want django to look in that folder instead of the others to load the files successfully, any way to resolve this? I saw the file structure on … -
List Index out of range when reading an Excel File
When I'm reading the excel file I get this "List index out of range" error. views.py a_list= studentData list_iterator= iter(a_list) next(list_iterator) for detail in list_iterator: stuname= detail[0] print(stuname) student_batch = Batch.objects.get(name=stuname) email = detail[1] rs_id = detail[2] phone_number = str(detail[3]) dob = detail[4] address = detail[5] age = detail[6] firstName = detail[7] lastName = detail[8] username = detail[9] password = detail[10] print(type(phone_number)) user=User.objects.create( firstName = firstName, lastName = lastName, username = username, ) user.set_password(password) user.is_student = True user.school = request.user.school user.save() user_ins = User.objects.get(username=username) student=Student.objects.create( user = user_ins, email = email, rs_id = rs_id, dob = dob, address = address, age = age, ) It actually works and I tried to print the data and it prints the right data too. I don't know where is the error. Note: studentData is a list containing the data of user. Then I used next() to skip the first iteration and start from 2nd row. -
How to test a view that creates a new Organization(entity) in database in Django?
I'm new to Unit Testing. I have a view which takes an AJAX request and creates a new Organization to my database. How do I test it? Here is my view: @csrf_exempt def newOrg(request): if request.method == 'POST': param = json.loads(request.body) org = param.get('org') Organization.objects.create(orgname=org) return JsonResponse({'status':200}) The url used: ('ajax/newOrg/', views_admin.newOrg, name='ajax_newOrg'), -
How I can insert my django model data in fields for edit a record
I want to edit my product which all data is already in django model. When i add press the "edit" button in option a new form is open to edit a product but I don't know who to insert data in fields. Kindly give me guidance how i display me data in fields there is the image of my product and that is edit form if you see before the edit button data is displaying but i want that data in form fields views.py class EditProduct(TemplateView): template_name = 'stock/editproduct.html' def get(self, request, product_id): productedit = get_object_or_404(Product, pk=product_id) form = EditProductForm() args = {'form':form, 'productedit':productedit} return render(request, self.template_name, args) template.html {% extends 'base.html' %} {% block content %} <div> <h4>Edit Product!</h4> <hr/> <form method="post" enctype="multipart/form-data" > {% csrf_token %} {{ form.as_p }} <h4>{{productedit.pro_name}}</h4> <p>{{productedit.companyName}}</p> <p>{{productedit.Sale_Price}}</p> <p>{{productedit.Quantity}}</p> <button type="submit" class="btn btn-success" >Edit</button> </form> </div> {% endblock %} form.py class EditProductForm(forms.ModelForm): class Meta: model = Product fields = ('companyName', 'pro_name', 'Purchase_Price', 'Sale_Price', 'Quantity', 'Picture' ) def __init__(self, *args, **kwargs): super(EditProductForm, self).__init__(*args, **kwargs) self.fields['companyName'].label = 'Company Name' self.fields['pro_name'].label = 'Product Name' self.fields['Purchase_Price'].label = 'Purchase Price' self.fields['Sale_Price'].label = 'Sale Price' -
How to create a special function when a model instance is created?
I'm making a system wherein when the user creates a log he gains points from how it. How do I go about in trying to make this? I tried making a signal.py function but it's giving me an error of 'DPRLog' object has no attribute 'Points'. Am I doing it right? I just want to add points whenever I create a log so I placed it as signal.py class. Can anyone help me out? Thanks Heres my models.py: from django.db import models from profiles.models import User from django.urls import reverse # Create your models here. class Points(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(default=0, null=False) def __str__(self): return self.user.username class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' class Manager(models.Model): manager = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.manager.full_name class Member(models.Model): manager = models.ForeignKey(Manager, on_delete=models.CASCADE) member = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=30, null=True) def __str__(self): return self.member.full_name class Job(models.Model): manager = models.ForeignKey(Manager, on_delete=models.CASCADE) member = models.ForeignKey(Member, on_delete=models.CASCADE) title = models.CharField(max_length=30, blank=False, null=False) description = models.TextField() datePosted = models.DateTimeField(auto_now=True) file = models.FileField(null=True, blank=True, upload_to='job_files') def __str__(self): return self.title def get_absolute_url(self): return reverse('job-detail', kwargs={'pk': self.pk}) class DPRLog(models.Model): STATUS_CHOICES = ( ('PENDING', 'PENDING'), ('CANCELLED', 'CANCELLED'), ('COMPLETED', 'COMPLETED'), ) … -
How to give suggestions in the field entry form value from DB
I am doing basic project for small school in small town as charity non-profit (i am not professional devoloper). It is quite basic web for teacher to find student info ( grades and background). I choiced student code as there are students with exactly the same name and surnames so I thought code would be easier to distinct. This everything works good however i want teacher while typing studentcode in the entry field to get studentfullname as suggestion right in the field entry so they can choice from suggestions ( and click OK button) and avoide choicing wrong student. What i did so far: In models.py class ABC(models.Model): name = models.CharField(max_length=150) class Student(models.Model): studentcode=models.CharField(max_length=200) studentfullname=models.CharField(max_length=500) class Meta: managed=False db_table='class09' in forms.py i have : from django import forms from .models import ABC class ABCForm(forms.ModelForm): name = forms.CharField(max_length=150) class Meta: model = ABC fields = ('name',) in views.py : def index(request): if request.method == "POST": form = ABCForm(request.POST) if form.is_valid(): formps = form.save(commit=False) name = formps.name studbackground=Student.objects.get(studentcode=name) context={'background':studbackground ,} return render(request, 'vasagrad/back.html',context) else: form = ABCForm() return render(request, 'vasagrad/index.html', {'form': form}) index.html i have : <form method="POST" class="ticker_area" > {% csrf_token %} {{ form}} <button class = "ticker_button" type="submit">OK</button> </form> I … -
RecursionError in django
I am trying to save M2M field in my choice model. and it giving me this Error(can't even find where the traceback is! File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related_descriptors.py", line 846 , in __init__ raise ValueError('"%r" needs to have a value for field "%s" before ' File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 518, in __repr__ return '<%s: %s>' % (self.__class__.__name__, self) File "C:\Users\Dell\PycharmProjects\AdmissionSystem\Admission\users\models.py", line 155, in __str__ return self.clg_id File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related_descriptors.py", line 535 , in __get__ return self.related_manager_cls(instance) File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related_descriptors.py", line 846 , in __init__ raise ValueError('"%r" needs to have a value for field "%s" before ' File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 518, in __repr__ return '<%s: %s>' % (self.__class__.__name__, self) File "C:\Users\Dell\PycharmProjects\AdmissionSystem\Admission\users\models.py", line 155, in __str__ return self.clg_id File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related_descriptors.py", line 535 , in __get__ return self.related_manager_cls(instance) RecursionError: maximum recursion depth exceeded models.py class choice(models.Model): stud_id = models.ForeignKey(student, on_delete=models.CASCADE) clg_id = models.ManyToManyField(college) created_at = models.DateTimeField(default=timezone.datetime.now()) updated_at = models.DateTimeField(default=timezone.datetime.now()) isactive = models.BooleanField() def __str__(self): return self.clg_id class student(models.Model): fullname = models.CharField(max_length=50) password = models.CharField(max_length=10) email = models.EmailField(unique=True) class college(models.Model): name = models.CharField(max_length=50) password = models.CharField(max_length=10) it also gives __str__ return non string type(type student) error when i do return self.stud_id instead of return self.clg_id i just want to have each student get choice of each college only once. how … -
name the dict in a list and send as response
I have a result as this [ { "Total": 54063120.8235, "Percentage": 126.1001 }, { "Total": 1464405, "Percentage": 0 } ] but I want a result in the following way [ Income:{ "Total": 54063120.8235, "Percentage": 126.1001 }, taxes:{ "Total": 1464405, "Percentage": 0 } ] What change shall I do? I am saving my list as result = [Income, taxes] -
How to show one is online when he redirects to an URL in Django python?
am trying to show an user online in my django website platform when he redirects to an URL. Can any online tell me the way to write a code for this . -
Django rest_auth token based social authentication
I'm using Django 2.2 and allauth + rest_auth to enable REST based authentication of the user. Also using Angular 8 in front-end. Also using django-oauth2-provider for token generation. As per the rest_auth documentation, I enabled the Google authentication. urlpatterns = [ path('login/google/', GoogleLoginView.as_view()) ] from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter from rest_auth.registration.views import SocialLoginView class GoogleLoginView(SocialLoginView): adapter_class = GoogleOAuth2Adapter The token is generated on frontend using angularx-social-login When I send the token using POST request to the /login/google/ endpoint, it gives error as django.urls.exceptions.NoReverseMatch: Reverse for 'socialaccount_signup' not found. 'socialaccount_signup' is not a valid view function or pattern name. The configuration is like ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_UNIQUE_EMAIL = True SOCIALACCOUNT_AUTO_SIGNUP = True SOCIALACCOUNT_EMAIL_VERIFICATION = ACCOUNT_EMAIL_VERIFICATION -
Importerror from runserver command
(Sorry I'm new at this so I apologize if the question isn't worded well) I tried to run python manage.py runserver after setting up for a project without error, however it wasn't successful and it displayed the following error: ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding'. In response to the error, I tried to use use a separate command to import: from django.utils.encoding import python_unicode_compatible . However, this gave an error as well: from: can't read /var/mail/django.utils.encoding. Might anyone know what this error means and what I may do to fix it? Thank you so much! -
how to add a simple user fillable form in blog post detail page?
I have built a blog application. it has a page that shows the added posts and if you click on each one it will take you to a post detail page. i want to add a small form to the post detail page that users and none users could fill it.so whenever a post is made in the admin page there would be a new fillable name and email submit form for it inside the detail page. please help me with the code -
TabError: inconsistent use of tabs and spaces in indentation (in python Django shell)
*** from django.db import models class post(models.Model): title = models.CharField(max_length=120) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __unicode__(self): return self.title def __str__(self): return self.title -
How do I make a webpage be different for a superuser and a normal user on django?
Let me explain a little, I'm trying to make a website just for practicing, in which you have two sides, customer-side, and admin-side, so I want to make certain pages display certain functions when you are logged in as an admin, and to not display said functions to normal users, such as edits and stuff. How do I do that? I hope I explained it properly. Thanks. -
How to send foreground and background push notification to android using django push notification package
Iam using django-push-notification package in django project , In android it the json response should be in the format : { "data": { "title" : "You have a notification", "body" : "The body of the notification", "id" : 1234, "backgroundImage" : "assets/notifications/background.png", }, "notification" : { "alert" : "You have a notification", "title" : "You have a notification", "body" : "The body of the notification", "sound" : "default", "backgroundImage" : "assets/notifications/background.png", "backgroundImageTextColour" : "#FFFFFF" } } So that only android can get the foreground and background notifications. I tried the code : try: fcm_device = GCMDevice.objects.all() fcm_device.send_message("new-notification-out",title="title-out",\ extra={"data": { "title-data" : "title-in", "body" : "new-notification-in" }, \ "notification" : { "alert" : "You have one new notice", "title" : "title-notify",\ "body" : "new-notification" }}) except: pass But not getting the payload "data","notification" in android side, How can I send the payload accurately from backend side ? -
Django rest framework nested serializer create method
I have created a nested serializer, when I try to post data in it it keeps on displaying either the foreign key value cannot be null or dictionary expected. I have gone through various similar questions and tried the responses but it is not working for me. Here are the models ##CLasses class Classes(models.Model): class_name = models.CharField(max_length=255) class_code = models.CharField(max_length=255) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.class_name class Meta: ordering = ['class_code'] ##Streams class Stream(models.Model): stream_name = models.CharField(max_length=255) classes = models.ForeignKey(Classes,related_name="classes",on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.stream_name class Meta: ordering = ['stream_name'] Here is the view class StreamViewset(viewsets.ModelViewSet): queryset = Stream.objects.all() serializer_class = StreamSerializer Here is the serializer class class StreamSerializer(serializers.ModelSerializer): # classesDetails = serializers.SerializerMethodField() classes = ClassSerializer() class Meta: model = Stream fields = '__all__' def create(self,validated_data): classes = Classes.objects.get(id=validated_data["classes"]) return Stream.objects.create(**validated_data, classes=classes) # def perfom_create(self,serializer): # serializer.save(classes=self.request.classes) #depth = 1 # def get_classesDetails(self, obj): # clas = Classes.objects.get(id=obj.classes) # classesDetails = ClassSerializer(clas).data # return classesDetails I have tried several ways of enabling the create method but like this displays an error {"classes":{"non_field_errors":["Invalid data. Expected a dictionary, but got int."]}}. Any contribution would be deeply appreciated -
How to manage multiple users at server side of system using Django
I am creating a Vehicle Tracking and Management System in Python Django. In my project, there are 3 different users who have different dashboards. How to create a skeleton of this project