Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
AdminInline and unknown IntegrityError UNIQUE constraint failed
Django Version: 3.0.4 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: store_hoursofoperation.day Hello, I'm trying to resolve this error, but I don't know how to proceed. I want the Store model to contain multiple HoursOfOperation. However, this error occurs whenever I add another weekday on any store -- Store A has Monday hours, Store B will error if I add Monday hours. I am using the default admin to include the HoursOfOperation within the Store model. How do I stop the HoursOfOperation.day from being unique? admin.site.register(HoursOfOperation) class HoursOfOperationInline(admin.TabularInline): model = HoursOfOperation extra = 0 @admin.register(Store) class StoreAdmin(admin.ModelAdmin): inlines = [ HoursOfOperationInline ] WEEKDAYS = [ (1, ("Monday")), (2, ("Tuesday")), (3, ("Wednesday")), (4, ("Thursday")), (5, ("Friday")), (6, ("Saturday")), (7, ("Sunday")), ] class Store(models.Model): name = models.CharField(max_length=250) summary = models.CharField(max_length=250) address_line1 = models.CharField(max_length=100) address_line2 = models.CharField(max_length=50) phone = models.CharField(max_length=12) website = models.CharField(max_length=50) status_storefront = models.BooleanField( help_text="Is the storefront open to customers?" ) status_takeout = models.BooleanField( help_text="Is takeout available for customers?" ) status_delivery = models.BooleanField( help_text="What is the delivery service? [No, Yes, Custom]" ) status_delivery_service = models.CharField( max_length=20, blank=True, null=True ) anchor_id = models.CharField(max_length=30) hours = models.Many @property def storefront(self): return "Yes" if self.status_storefront else "No" @property def takeout(self): return "Yes" if self.status_takeout … -
django cannot access default admin section
I am trying to access the django default admin section and I get a 404 error "not found" I can access the default django splash page that tells me I am in debugging mode If I try to access via nginx, I get a nginx bases 404 error 'not found' in browser but my logs are clean. If I try from command line with links http://127.0.0.1/admin I get 'connection refused' (secret) kermit@tuna:~/www/src/exchange $ cat /etc/nginx/sites-available/default upstream django { server unix:///var/run/uwsgi/exchange.sock; # for a file socket #server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # Default server configuration # server { access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; listen 80 default_server; listen [::]:80 default_server; # SSL configuration # listen 443 ssl default_server; listen [::]:443 ssl default_server; root /home/kermit/www/src/exchange; index index.html index.htm index.php index.nginx-debian.html; server_name tuna.tra.com; location / { try_files $uri $uri/ =404; include /etc/nginx/uwsgi_params; } # pass PHP scripts to FastCGI server # location ~ \.php$ { include snippets/fastcgi-php.conf; } # Django media location /media { alias /home/kermit/www/src/exchange/media; # your Django project's media files - amend as required } location /static { alias /home/kermit/www/src/exchange/static; # your Django project's static files - amend as required } # Finally, send all … -
Trying to make a web app that uses a map matching algorithm with arcpy. Can I use ArcMap or do I need ArcGiS Server?
My client used ArcMap 10.5 to make a map matching algorithm and requested of me to make a web application where users could upload the information necessary to make it work; which in this case is a series of GPS markings, the road network data for the area where the GPS markings come from and a few other user-chosen parameters. I am currently designing the app with Django since I can just take the algorithm as a function and import it to the app. The algorithm itself uses arcpy to locate the GPS points and correlate them to a point on a street by taking previous points and comparing the speed of travel at the instant of measurement with the calculated speed to arrive from said previous point to the correlated point in the selected street. However, a big problem in the design has been the fact that ArcMap 10.5 uses Python 2 for its Arcpy library. On top of that, in the virtual environment I use for coding, I can't import Arcpy successfully; I'm currently using Powershell and pipenv. Investigating I found that there is a way to import arcpy using pipenv... while using ArcGiS Pro. Which uses Python …