Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-rest-framwork: AttributeError, 'Response' object has no attribute 'title'
AttributeError: Got AttributeError when attempting to get a value for field title on serializer QuestionSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Response instance. Original exception text was: 'Response' object has no attribute 'title'. models.py class Question(models.Model): title = models.TextField(null=False,blank=False) status = models.CharField(default='inactive',max_length=10) created_by = models.ForeignKey(User,null=True,blank=True,on_delete=models.SET_NULL) def __str__(self): return self.title class Meta: ordering = ('id',) urls.py urlpatterns = [ path('poll/<int:id>/', PollDetailsAPIView.as_view()), ] serializers.py class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields =[ 'id', 'title', 'status', 'created_by' ] views.py class PollDetailsAPIView(APIView): def get_object(self, id): try: return Question.objects.get(id=id) except Question.DoesNotExist: return Response({"error": "Question does not exist"}, status=status.HTTP_404_NOT_FOUND) def get(self, request, id): question = self.get_object(id) serializer = QuestionSerializer(question) return Response(serializer.data) on postman, i am trying to get an id that doesnt exist but instead of getting this response "error": "Question does not exist" and an Error: 404, i keep getting error 500 Internal server error. -
Hi trying to figure out the apscheduler library. Please help me figure it out
I need to get the last week of products and send email to subscribers using apscheduler it`s only for test class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category') tags = models.ManyToManyField(Tag) seller = models.ForeignKey(Seller, on_delete=models.CASCADE) title = models.CharField(max_length=150) slug = models.SlugField(max_length=150, unique=True) description = models.TextField(default=True) price = models.DecimalField(max_digits=10, decimal_places=2) is_active = models.BooleanField(default=True) create_date = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('product_detail', kwargs={'pk': self.pk}) -
ImportError: cannot import name 'create_new_ref_number' from 'utils' in Django Rest Framework
I tried to create a random unique string in a charfield using create_new_ref_number() but it is giving me above error. I have already installed utils==1.0.1 and my django version is 2.2, as utils package are only allowed in lower django version. The full error is : ImportError: cannot import name 'create_new_ref_number' from 'utils' (C:\Users\User\Desktop\RupseOnline\rupseonline\myvenv\lib\site-packages\utils_init_.py) My model is: from utils import create_new_ref_number class OrderItem(models.Model): #user = models.ForeignKey(User,on_delete=models.CASCADE, blank=True orderItem_ID = models.CharField(max_length=12,unique=True,default=create_new_ref_number()) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants,on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) total_item_price = models.PositiveIntegerField(blank=True,null=True,) The issue arises when I try to run makemigrations. -
Preview image before upload with js
I am building a BlogApp and I am stuck on a Problem. What i am trying to do:- I am trying to preview image before upload. I am using cropping feature to crop the Image but I also want to preview cropped image before Upload too. template.html <form method="post" enctype="multipart/form-data" id="formUpload"> {% csrf_token %} <label for="id_file" class="mr-3 btn"><i class='fas fa-camera-retro'></i> Photo</label> <input type="file" name="file" id="id_file" style='display:none;'> <div class="modal fade" id="modalCrop"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title">Crop the photo</h4> </div> <div class="modal-body"> <img src="" id="image" style="max-width: 100%;"> </div> <div class="modal-footer"> <div class="btn-group pull-left" role="group"> <button type="button" class="btn btn-default js-zoom-in"> <span class="glyphicon glyphicon-zoom-in"></span> </button> <button type="button" class="btn btn-default js-zoom-out"> <span class="glyphicon glyphicon-zoom-out"></span> </button> </div> <button type="button" class="btn btn-default" data-dismiss="modal">Go Back</button> <button type="button" class="btn btn-primary js-crop-and-upload">Crop and upload</button> <button type="button" class="btn btn-primary js-crop-only">Select this image</button> <script defer src="https://use.fontawesome.com/releases/v5.0.8/js/all.js" integrity="sha384-SlE991lGASHoBfWbelyBPLsUlwY1GwNDJo3jSJO04KZ33K2bwfV9YBauFfnzvynJ" crossorigin="anonymous"></script> </div> </div> </div> What have i tried:- I saw many answers and found many answers but they didn't work for me. I also tried this :- document.getElementById("files").onchange = function () { var reader = new FileReader(); reader.onload = function (e) { // get loaded data and render thumbnail. document.getElementById("image").src = e.target.result; }; // … -
What is the best methode for check if only one dataset field is true
I have in Django this model: class CustomerAddresses(models.Model): ID = models.AutoField(primary_key=True) ... Is_Default_Shipping_address = models.BooleanField(default=True, blank=True, null=True) Is_Default_Billing_address = models.BooleanField(default=True, blank=True, null=True) ... def __str__(self): return str(self.ID) How can I check if I add another address that is just one entry is Is_Default_Shipping_address or/and Is_Default_Billing_address is true? The customer may have two or more addresses, but he has in the most scenarios just one billing address which is always default. The best way is if customer adds another address which has the flag default and set the new also as default, the flag from the other entry will be removed. regards. -
Django: How to store mathematical expressions in mysql and then use them
I am using Django and want users to be able to store mathematical expressions like the following in a mysql database following the BODMAS rule: (A / B) * C + D / (E - D) + J^2 Then I want to be able to use these expressions later on in my views. Much like MS Excel. I could build some models that stores as their objects, the variables and operators and build a function to implement BODMAS but it sounds like a lot of complication for a simple task. Is there a simpler, shorter way to do both these steps? -
Unable to makemigrations while using postgres
I am new to pgsql, did not configure this error while I'm trying to makemigration in the Django-rest app. what should I install? I've installed the requirements.txt which consists of : PyJWT==1.7.1 pytz==2021.1 sqlparse==0.4.1 psycopg2>=2.8 psycopg2-binary>=2.8 python_dotenv==0.16 the error: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? -
Best way to copy an attachment file from other's server to your server in Django
I'm importing data from another platform to mine via API they provide. They provide me attachment file URL in response and now I want to save that file on my Django server and use that Django media file URL in my application. So I wanted to know, what is the best way to do this task?? Thanks in advance :) -
Django get other fields value with aggregate function in result
I have query like which is given below todayData = User.objects.filter(log__created_at__date=curDate,og_type='credit').annotate( max_price=Sum('log__bits')).exclude(log__bits=300).order_by('-max_price') through this query i am getting the user which have max count of credit amount after this through this query i am getting the total count of match and user total price newList = [] for user in todayData: highCredit = Log.objects.filter(user_id=user.id,log_type='credit',created_at__date=curDate).exclude( bits=300).aggregate(credit=Sum('price'),match_count=Count('match')) result : print(highCredit) [{'credit': 200, 'match_count': 1}, {'credit': 300, 'match_count': 2}] this is correct but the thing is that i want log table other fields in this variable like log table id with match id how can i get this . i am not getting these values with aggregate. can anyone have any idea please suggest me -
django annotation max min AND first last
From a datatable that stores the BTC price each minute, I'am trying to get an queryset objet that aggregate values by hours (need min, max, first and last). It works well for the max and min class BTCDayDataCandles(APIView): authentification_classes = [] permission_classes = [] def get(self, request, format=None): now = datetime.now() BTCData = BTCminute.objects\ .annotate(test = Trunc('dateTimeEntry', 'hour'))\ .order_by('-test')\ .values('test')\ .annotate(Max('price'), Min('price')) data = { 'BTCData': BTCData, } print(BTCData) return Response(data) How can I add the fist and last price value for each hour in the queryset Object? -
Chained dropdown in Django is not storing data to database(Postgresql)
I am trying to create a chained drop-down in Django that is on selecting country only those states who belongs to the country should come in the drop-down to select.I have used J-Query for drop-down and is working fine. But after sending data from form the form data is coming to console as i have print the form values into the console for better understanding, but is not saving the data to the database and form.is_valid is giving False even if data is correct. Why it is not storing to the database even if the form data s correct models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser,AbstractUser class Country_Model(models.Model): country = models.CharField(max_length=50) def __str__(self): return self.country class State(models.Model): country = models.ForeignKey(Country_Model,on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return self.name class StudentsRegistrationModel(AbstractUser): GENDER = (('F', 'Female',),('M', 'Male',),('O', 'Other',)) email = models.EmailField(unique=True) fathers_name = models.CharField(max_length=25) gender = models.CharField(max_length=1,choices=GENDER,default=None) address = models.CharField(max_length=50) country = models.ForeignKey(Country_Model,on_delete=models.CASCADE) state = models.ForeignKey(State,on_delete=models.CASCADE) phone_number = models.CharField(verbose_name="Phone Number",max_length=10) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS=[] form.py from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from app1.models import StudentsRegistrationModel,State class … -
How to get the Verification code from Django GraphQL Auth
how can I get verification token from this message that prints on the CLI after registering on Django GraphQL Auth? <h3>localhost:8000</h3> <p>Hello a!</p> <p>Please activate your account on the link:</p> <p>http://localhost:8000/activate/{ verification token }</p> -
Django forms with stored procedure in MySQL
I am trying to invoke a stored procedure within a django form. This will fill a select in the template. Apparently it can be called with cursor.execute (), but I can't get it to work. I leave part of the code: class FormX(forms.ModelForm): fieldX = forms.ModelChoiceField(queryset=cursor.execute('SELECT * FROM table'), required=True) -
Can anyone explain How to encrypt a url in Django?
I am going to develop a application in Django. I need to encrypt the url which needs to be decrypted again in business logic. Which module should I need to use.Can any one help me out please.... -
Adding multiple many_to_many from query
I'm going crazy with this problem. So I have a model Template which basically is a template of permissions (when you create a user it will automatically give the good permissions). My model looks like this: class PermissionTemplate(models.Model): name = models.CharField(max_length=100) company = models.ForeignKey(Company, on_delete=models.CASCADE) permissions = models.ManyToManyField(Permission, blank=True, related_name='templates') class Meta: default_permissions = () permissions = ( ("can_delete_template", "Can delete a permission template"), ("can_create_template", "Can create a permission template"), ("can_edit_template", "Can create a permission template"), ) constraints = [ UniqueConstraint(fields=['company', 'name'], name='Unique_template_name_per_company') ] def __str__(self): return self.name I'm now writing the tests so in my setupTestData I do this: @classmethod def setUpTestData(cls): templateperms = PermissionTemplate.objects.create(name="Administrators", company=company) perms = Permission.objects.filter( content_type__app_label__in=['authentication', 'company']) templateperms.permissions.add(*perms) print(perms) print(templateperms.permissions) But the result is not as expected the first print will return my queryset well: <QuerySet [<Permission: authentication | permission template | Can create a permission template>, <Permission: authentication | permission template | Can delete a permission template> .... ] But my second print: auth.Permission.None And I don't have the permissions saved in my template If someone have an idea it would be much appreciated -
<embed?> element not able to show pdf preview on safari
My embed element is able to show pdf preview in chrome but not in safari. Can anyone advise on how I can render the embed PDF Preview element on safari? I have tried some of the methods but none worked. Recommended way to embed PDF in HTML? Thank you! <embed src="" type="application/pdf"> -
unable to get groups and permissions working for auth0 user in django admin
I am using Auth0 authentication and allowing the users to login to admin site. How ever, I am not able to get the django groups and permissions to work with these users. The users are getting saved to auth_user table. I am using social_django with auth0. here is a brief of the authentication backends, login, logout urls . # declaring authentication backends for auth0 users AUTHENTICATION_BACKENDS = { 'django.contrib.auth.backends.ModelBackend', 'core.authentication.auth0.Auth0' } ##### Login and Logout Urls and Redirections LOGIN_URL = '/login/auth0' LOGIN_REDIRECT_URL = '/admin' LOGOUT_REDIRECT_URL = '/login/auth0' # social auth pipeline SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'core.authentication.authorization.process_roles', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) if I disable superuser status, staff users are not able to access anything in the admin site, even after assigning to a group. I would like to add users to a group and allow access based on that. Also I haven't created any custom user model on django side to read the users. Should I use a custom user model for auth0 authentication? Any guidance on this front would be really helpful. -
Filter many to many objects from parent queryset
I have 2 models like this class A(models.Model): x = models.CharField(blank=True, null=True, max_length=256) y = models.CharField(blank=True, null=True, max_length=256) class B(models.Model): m = models.ManyToManyField(to=A, blank=True) #other fields class C(models.Model): p = models.ManyToManyField(to=A, blank=True) #other fileds now when i query the objects of model 'B' using query_b = models.B.objects.all() i want to exclude those objects from many to many field 'm' if they exist in models.C.objects.all() and return query_b -
Django - Add block inside an included html
In Django, can we add block content in a included html page? Is it feasible? base.html {% block title %} <p>This is title base.html</p> {% endblock title %} {% include "head.html" %} head.html {% block subtitle %} <p>This is subtitle head.html</p> {% endblock subtitle %} index.html {% extends 'base.html' %} {% block title %} <p>This is title index.html</p> {% endblock title %} {% block subtitle %} <p>This is subtitle index.html</p> {% endblock subtitle %} Final result <p>This is title dashboard.html</p> <p>This is subtitle head.html</p> Meaning, that when we are rendering index.html, it will not find the subtitle block on head.html Thanks! -
How to extract the data from the uploaded file using filesystemstorage in django?
Hi I am learning python I tried uploading a file using FileSystemStorage defualt class that is defualt class in django and the file is uploading but I want to extract the data from the uploaded file that is being stored media folder like name: "soso" age: "so" the code which I tried so far is as below views.py: from django.shortcuts import render from django.conf import settings from django.core.files.storage import FileSystemStorage def index(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'index.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'index.html') index.html: {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> {% if uploaded_file_url %} <p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p> {% endif %} <p><a href="{% url 'home' %}">Return to home</a></p> {% endblock %} -
Django - How access the value of an instance in views.py
I have this model class Post(models.Model): title = models.CharField(max_length=100) title2 = models.CharField( max_length=100) content = models.TextField(default=timezone.now) content2 = models.TextField(default=timezone.now) post_image = models.ImageField(upload_to='post_pics') post_image2 = models.ImageField(upload_to='post2_pics') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) Then I have this simple view function that allows me to access each of its field in my HTML: def home(request): postings = { 'listings' : Post.objects.all(), } return render(request, 'front/front.html', postings) {% for listings in listings%} <h1>{{listings.content}}</h1> {% endfor %} With this, I'm able to access the content field for every instance of that model and display it My question is how can I access the content field in my view function and change it. The content field holds a zipcode and I want to use an API to display the city of that zipcode(which I already know how to do) and pass it back to the h1 tag. Each instance holds a unique zipcode so I need it to apply for each instance. How would I approach this? -
How to use object.id to make another object, creator of the current object?
I have two models in my django application 'Client' and 'Installment'. Below is my models.py: models.py rom django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class Client(models.Model): name = models.CharField(max_length = 100) dob = models.SlugField(max_length = 100) CNIC = models.SlugField(max_length = 100) property_type = models.CharField(max_length = 100) down_payment = models.IntegerField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.name def get_absolute_url(self): return reverse('client_details',kwargs={ 'pk' : self.pk}) class Installment(models.Model): client = models.ForeignKey(Client, null=True, on_delete=models.CASCADE) installment_month = models.CharField(max_length = 100) installment_amount = models.IntegerField() installment_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.installment_month def get_absolute_url(self): return reverse('installment_confirmation') and my views.py view.py # To create new client class ClientCreateView(CreateView): model = Client fields = ['name', 'dob', 'CNIC', 'property_type', 'down_payment'] # To add new installment class AddInstallmentView(CreateView): model = Installment #template_name = "property_details/addinstallment_form.html" fields = ['installment_month', 'installment_amount'] And the URL that I have to add a new installment is below: urlpatterns = [ path('', ClientListView.as_view(), name='client_list'), path('new/', ClientCreateView.as_view(), name='add_client'), path('<int:pk>/', ClientDetailView.as_view(), name='client_details'), path('<int:pk>/Add-Installment', AddInstallmentView.as_view(), name='add_installment'), path('confirmation/', views.installment_added, name='installment_confirmation'), ] You can see that the URL for adding new installment is unique. For example, /<local_server_addr>/<client.id>/Add-Installment (because of <int:pk> above) I can create a new client and also I can add installment. But … -
How to obtain geo co-ordinates of a remote user in group video chat?
I am building a group video chat application in Django with the help of Agora where I want to show the user their geo distance from every other user. To a given user, the UI would look something like this (along with the video of course) User A - (User A's remote video) - 5 miles away from you User B - (User B's remote video) - 100 miles away from you User C - (User C's remote video) - 10 miles away from you User D (local user - you) Now in the video chat, a user can log off & a new user can join the call any time. To compute the geo distance of a remote user with the local user, I need geo-coordinates of both the parties. I can obtain the geo-location of the local user by integrating with some location library. I am confused on how to obtain the geo-coordinates of the remote user? My django code flow looks something like renders links to views.py ----> video.html -------> agora.js Video.html renders the video chat room. I am using Agora to power the group video chat whose code is defined in agora.js. Any time a new … -
Is there a way to show Django messages in Django admin site?
I need to display a Django message on the Django admin index site. I am looking for a way to add certain conditions for the message to be displayed and pass it to Django index site. Is there a way to achieve that? -
how do i seed some data in to my table , that i have fetched from a specific extrernal api in Django?
so my requirment is i need to fetch some data from a github api and seed it into the table in my django api application. so while the app is running it should always be seeded with that data.. And then i need to make a REST api using that Table data which is already seeded with github api data. im a beginner and i have searched a lot but couldnt find what to do ? i have already created mmy fuction to fetch data and also i have created a model based on my requirment. all i need to know where should i put that code so that it seeds my table when the application runs so that i can create a rest api using that table data .. this is the data fetching code(which i currently have put in view as a function to see if its working) def apiOverview(request): mainarr=[] url = 'https://api.github.com/repos/afhammk/components/contents' try: r = requests.get(url, auth=("afhammk","token")) fish = r.json() for ele in fish: try: desc=requests.get("https://api.github.com/repos/afhammk/components/contents/"+ele["name"]+"/description.txt?ref=main" ,auth=("afhammk","token")).json() content=str(base64.b64decode(desc["content"])) name=content.split("'")[1::2][0] description=content.split("'")[1::2][1] y=Task(component=ele["name"],url=ele["html_url"],owner=name,description=description) y.save() except: mainarr=["cant fetch second url"] except: mainarr=["cant fetch first url"] below is the model i created class Task(models.Model): component=models.CharField(max_length=200) owner=models.CharField(max_length=200) description=models.CharField(max_length=200) url=models.CharField(max_length=200) def __str__(self): …