Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django forms vs HTML forms
when i use the Django {{ forms }} the forms i rendered with the build in functionalities, if user submits and fields are invalid the invalid fields are cleaned but rest of the information in the form is not cleaned, this provides the user to change only the fileds where error is raised. When i use HTML forms on submit if there is a error all the fields are cleaned and the user has to write all the information over again from scratch. How can i accomplish the same fuctionality in a html form as in Django {{ forms }} -
Best Way to integrate React with Django
My Question is that What will be the best way to integrate React App into Django project. React => Front-end Django => Backend i see there are 2 Options to do this: Keep Front-end and Back-end Separate and use API between them. Put front-end code into Django Project and link this projects template and static files in my_project/settings.py file. and run command "npm run build" every time when I made changes. What will be the best way?? -
What is the purpose of sending instance.title as second argument in validated_data.get function in DRF serializer update function
def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.author = validated_data.get('author', instance.author) instance.date = validated_data.get('date', instance.date) instance.save() return instance What is the purpose of sharing instance.title etc in second argument of "validated_data.get" function instance.title = validated_data.get('title', instance.title) -
Django CSRF error on file upload view (CSRF verification failed. Request aborted.)
I'm trying to build a page with an upload form in Django and the GET request works fine but when I send the file I get the following error: CSRF verification failed. Request aborted. My view is very simple: class ImportView(generic.FormView): template_name = 'assignments/import.html' form_class = ImportForm success_url = reverse_lazy('assignment_import') def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): # handle upload here assignments = pd.read_excel(request.FILES['file'].file) for i, assignment in assignments.iterrows(): assignment_obj = Assignment() assignment_obj.name = assignment['name'] assignment_obj.save() return self.form_valid(form) else: return self.form_invalid(form) And the form template (assignments/import.html): <h2>Import assignments</h2> {{ form.non_field_errors }} {{ form.source.errors }} {{ form.source }} <form class="post-form assignments-import" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="row flexibel" style="clear: left;"> <div class="col">{{ form.file|add_class:form.file.name|as_crispy_field }}</div> </div> <button class="save btn btn-success" type="submit">Assignment</button> </form> In my settings.py I have (the relevant parts): BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.getenv('DJANGO_SECRET', default='...') DEBUG = True ALLOWED_HOSTS = ['localhost', '127.0.0.1', '.example.com'] MAPS_URL = os.getenv('MAPS_URL', default="https://www.example.com") DOMAIN_NAME = os.getenv('DOMAIN_NAME', default=".example.com") # Production settings CSRF_USE_SESSIONS = True CSRF_COOKIE_SECURE = True CSRF_TRUSTED_ORIGINS = True DATA_UPLOAD_MAX_MEMORY_SIZE = True DATA_UPLOAD_MAX_NUMBER_FIELDS = True FILE_UPLOAD_MAX_MEMORY_SIZE = True SECURE_BROWSER_XSS_FILTER = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_DOMAIN = DOMAIN_NAME SECURE_REDIRECT_EXEMPT = DOMAIN_NAME SESSION_COOKIE_DOMAIN = DOMAIN_NAME … -
How to upload multiple different images in django with their associated names, basically creating a database of images associated with their names
I need to upload various images with their associated names and display them in django. I am doing this manually using admin window but its a nightmare since the number of image is huge. Is their any other way of uploading multiple images all at once using some python code? I already have a file containing all of the images that i need to upload. -
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 %}