Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement encryption decrypttion using cryptography in Django
I am trying generate the order and send to someone and i want to use encrypt and decrypt method using crypto library like bitcoin, Ethereum, but i don't know how can i implement this. -
No migrations to apply for Heroku
I've added a field in my clients model. Here's the model: class Client(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=20) mobile_number = models.CharField(max_length=12) email = models.EmailField(null=True, blank=True) position = models.CharField(max_length=30) organization = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.CASCADE) agent = models.ForeignKey("Agent", related_name="clients", null=True, blank=True, on_delete=models.SET_NULL) category = models.ForeignKey("Category", related_name="clients", null=True, blank=True, default=6, on_delete=models.SET_NULL) company_name = models.CharField(max_length=50 , default=None) street_address = models.CharField(max_length=50 , default=None) baranggay = models.CharField(max_length=50 , default=None) city = models.CharField(max_length=50 , default=None) region = models.CharField(max_length=50 , default=None) date_added = models.DateTimeField(auto_now_add=True) phoned = models.BooleanField(default=False) special_files = models.FileField(blank=True , null=True) def __str__(self): return self.company_name Before I've added the position field the program runs smoothly. Now I've got: ProgrammingError: column clients_client.position does not exist At Heroku Bash, when I run python manage.py makemigrations, it detects the changes, but when I migrate it says, no migrations to apply. Please help. -
How to add several classes using django forms and widget?
I need to add two classes into a field in my page using django forms and widget. I can add one one class according to instructed in this link [http://www.learningaboutelectronics.com/Articles/How-to-add-a-class-or-id-attribute-to-a-Django-form-field.php#:~:text=and%20id%20attributes.-,In%20order%20to%20add%20a%20class%20or%20id%20attribute%20to,%3D%7B'class'%3A'some_class'%7D.] But when I add two classes technical_name = forms.CharField(widget=forms.TextInput( attrs={ 'class':'readonly_able', 'class':'tn' } )) I can see only the last class ('tn' in this case) in my web page. -
Why Django serves static files using the wrong MIME type?
On a new installation of windows 10, right after installing python v3.9.5, I do: >pip install django >django-admin startproject test1 >cd test1 >python manage.py migrate And then I edit test1/settings.py only to set the STATIC_ROOT and disable DEBUG mode settings.py import os ... DEBUG = False ALLOWED_HOSTS = ['127.0.0.1'] ... STATIC_ROOT = os.path.join(BASE_DIR, 'static') And then: >python manage.py collectstatic >python manage.py runserver And finally, I navigate to http://127.0.0.1:8000/admin/ and I see this: -
failed to start gunicorn daemon error in digital ocean
i am trying to deploy my django project on digital ocean, and this error stoping me from doing that first let me show my directory structure MY gunicorn.socket file [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target my gunicorn.service file [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=developer Group=www-data WorkingDirectory=/home/developer/myprojectdir ExecStart=/home/developer/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ bharathwajan.wsgi:application [Install] WantedBy=multi-user.target when i try to check the status of gunicorn it throws me error like this -
DRF How to filter relational data?
In drf you can install djanog-filter and do url/?id=1&username=jack but in the following data what if I want to filter the dates. For example dates.title=interview. [{ "id": 1, "password": "pbkdf2_sha256$260000$xkkKjiHK3ddS1fbGwpt7bQ$EZOhxwywEWGL+0JfzSIEgWFXPPN/f8JelGX2RrjplQM=", "last_login": "2021-06-02T13:25:51Z", "username": "jack", "email": "x@x.com", "secon_email": "", "first_name": null, "last_name": null, "middle_name": null, "is_active": true, "is_staff": true, "is_superuser": true, "is_email_verified": true, "is_role_verified": true, "date_joined": "2021-06-02T13:24:36Z", "receive_newsletter": false, "birth_date": null, "city": null, "about_me": "", "phone_number": "", "second_phone_number": "", "imageUrl": null, "age": "", "address": null, "dates": [{ "id": 1, "deleted": null, "title": "apoentment", "description": "", "start": null, "end": null, "from_time": null, "to_time": null, "date_created": "2021-06-03T06:49:50.929466Z", "recurrence": [], "priority": "", "date_type": 1, "created_by": 1, "users": [1] }, { "id": 2, "deleted": null, "title": "interview", "description": "", "start": null, "end": null, "from_time": null, "to_time": null, "date_created": "2021-06-03T06:49:50.929466Z", "recurrence": [], "priority": "", "date_type": 2, "created_by": 1, "users": [1] } ] }] class UsersSerializer(DynamicSerializer): # dates is relational data ( it is another other model) class Meta: model = User fields = [*[x.name for x in User._meta.fields], 'dates'] depth = 1 -
Connecting django restframework with kivy
I have created Todo list api using django restframework. Now I want to connect api to mobile using kivy mobile framework for frontend. Can somebody tell me how we can connect django rest framework with kivy. Thankyou. -
Django. Add new property ForeignKey to User model existing model: OperationalError
I have existing model which was created before, and I would like to add ForeignKey property to User model, when I run migrations command, I take following errors (fragment of the errors): sqlite3.OperationalError: no such column: patientapp_patient.author_id django.db.utils.OperationalError: no such column: patientapp_patient.author_id The model: class Patient(models.Model): number = models.IntegerField() last_name = models.CharField(max_length=30) first_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=30) birthday = models.DateField(default=datetime.date.today) age = models.IntegerField(null=True) fromdate = models.DateField(default=datetime.date.today) appdate = models.DateField(default=datetime.date.today) district = models.ForeignKey(District, on_delete = models.CASCADE) address = models.TextField(default='') gender = models.BooleanField(default=True) occupation = models.ForeignKey(Occupation, on_delete = models.CASCADE) # it is extra field for patient to prevent from deleting them status = models.BooleanField(default=True) author = models.ForeignKey( User, on_delete=models.CASCADE, ) In addition, in an another project, I have done the same action without facing any difficulties. -
How should I implement email verification using restframework-simple-JWT?
I have been working on custom API token logic, that would allow me to verify users using just their email, but not username and password. How I see it: One user send me credentials (just an email address); Django SMTP server sends an email with verification code; User sends its email address and verification code to the server and then gets access and refresh tokens; I read approximately the same question, but I did not find the answer concrete enough, so I would be glad to hear any suggestion how to solve it. -
Error 'You have not defined a default connection` while connecting multiple database using mongoengine connect()
I have two apps which connects to the same mongodb database using mongoengine. one of the Apps is working fine but when I open the second App it throws an error "A different connection with alias 'default' was already registered. Use disconnect() first". Then I changed the alias in the connect function of one Apps as connect(alias='default2', db='variome'). now it throws the error You have not defined a default connection Can someone please help to fix this -
Django Admin now showing model list in iframe — what changed?
I have built a Django application with a custom interface. It hasn't been changed in a couple of years. These (previous) servers are running Django 3.0.8. Recently I set up a new server, and the Django Admin interface now shows the model list in a scrolling iframe, and long tables on the right side are also scrolled independently of the page. This server is running Django 3.2.3. I don't like the new interface, but it more importantly it will require an extensive rewrite of our custom admin css. Can anyone point me to information about the change, or tell me if there is a setting to disable it? -
Do i really need to learn DJANGO?
I'm not an expert in python , But if i want to make an app all by myself , Do i really need to learn Django ? OR learning React is better for a beginner level project ? -
How to assign ranking on objects based on a value in a queryset
I have a queryset that returns a list of menus that and I want to assign each Menu a rank based on the number of votes accumulated is there a way I can achieve this using django Query Expressions? I'm also open to any other suggestions. The queryset is as follows: qs = Menu.objects.filter(Q(created_at__date__iexact=todays_date)).order_by('-votes') And the Menu class model is shown below: class Menu(models.Model): """Represents menu class model""" restaurant = models.ForeignKey(Restaurant,null=True,blank=True,on_delete=models.CASCADE) file = models.FileField(upload_to='menus/') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) uploaded_by = models.CharField(max_length=50, null=True, blank=True) votes = models.IntegerField(default=0) After serializing the queryset returns the following data: [ { "id": 10, "file": "https://res.cloudinary.com/dw9bllelz/raw/upload/v1/media/menus/index_ah660c.jpeg", "restaurant": "Burger King", "votes": 10, "created_at": "2021-06-03T09:33:05.505482+03:00" }, { "id": 9, "file": "https://res.cloudinary.com/dw9bllelz/raw/upload/v1/media/menus/index_ah660c.jpeg", "restaurant": "Texas Plates", "votes": 2, "created_at": "2021-06-03T09:33:05.505482+03:00" }, { "id": 8, "file": "https://res.cloudinary.com/dw9bllelz/raw/upload/v1/media/menus/index_ah660c.jpeg", "restaurant": "Carlito Dishes", "votes": 2, "created_at": "2021-06-03T09:33:05.505482+03:00" }, { "id": 7, "file": "https://res.cloudinary.com/dw9bllelz/raw/upload/v1/media/menus/index_ah660c.jpeg", "restaurant": "Kram Dishes", "votes": 1, "created_at": "2021-06-03T09:33:05.505482+03:00" }, ] -
How to set selected text from database into populated cascading dropdown List with JSON Data
I follow this tutorial with title Cascading Dropdown List using JSON Data - Learn Infinity https://www.youtube.com/watch?v=T79I5jOJlGU&t=11s I have 4 select tags ( -region -province -municipality -barangay ) First I populate the dropdown list from JSON DATA I achieve the first one that I have to select a specific region first before the province gets populate. What I want to achieve next is to set selected text from the database into cascading dropdown. HTML CODE: <form name="addressForm"> <select name="region" id="region"> <option value="">Select Region</option> </select> <select name="province" id="province"> <option value="">Select Province</option> </select> <select name="municipality" id="municipality"> <option value="">Select Municipality</option> </select> <select name="barangay" id="barangay"> <option value="">Select Barangay</option> </select> </form> JS CODE $(document).ready(function(e){ function get_json_data(code,region) { //alert("a " + code) var html_code = ""; $.getJSON('/templates/ph_API/CombineAddress.json', function(data){ ListName = code.substr(0, 1).toUpperCase() + code.substr(1); html_code += '<option value="">Select ' + ListName + '</option>'; $.each(data, function(key, value) { if(value.region == region) { html_code += '<option value="' + value.code + '">' + value.name + '</option>'; } }); $('#' + code).html(html_code); }); } get_json_data('region', 0); $(document).on('change', '#region', function() { var region_id = $(this).val(); if (region_id != '') { get_json_data('province', region_id); } else { $('#province').html('<option value="">Select Province</option>'); } $('#municipality').html('<option value="">Select Municipality</option>'); $('#barangay').html('<option value="">Select Barangay</option>'); }); $(document).on('change', '#province', function() { var province_id … -
django error: ValueError: invalid literal for int() with base 10: [closed]
I make a djagno project Why this code is error?? views.py def HomePageView(request): model = Post.objects.all() today = datetime.now(timezone('Asia/seoul')) yesterday = today - timedelta(days=1) today_post = Post.objects.filter(dt_created=today) yesterday_post = Post.objects.filter(dt_created=yesterday) context = { 'todayPost': today_post, 'yesteerdayPost': yesterday_post, 'model':model, } return render(request, 'math_note/home.html', context=context) error: ValueError: invalid literal for int() with base 10: b'02 08:59:09.459625' -
Django can send "reset password" mail but cannot use the "send_mail"
I want to send a "greetings" mail, when people sign up for my webpage. I can send a "reset password" email using the built in auth_views.PasswordResetView but when I try use the django.core.mail.send_mail I get an Username and Password not accepted. My settings.py . . #Email config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_PORT = 587 DEFAULT_FROM_EMAIL = "My Name <no-reply@my_site.com>" EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_PASSWORD = app_cred EMAIL_HOST_USER = app_email and views.py def register(request): if request.method=="POST": #post request form = UserRegisterForm(request.POST) agree_form = AgreeForm(request.POST) if form.is_valid() and agree_form.is_valid(): user = form.save(commit=False) user.email = form.cleaned_data["email"] user.save() send_mail(subject = "Welcome to my-site.com", message = "Welcome!", from_email = None, recipient_list = [user.email]) return redirect("login") else: form = UserRegisterForm() agree_form = AgreeForm() return render(request,"users/register.html",context= {"form":form,"agree_form":agree_form}) As far as I understand, Django uses the credentials specified in the settings, so I wonder why I can send a password-reset mail but cannot use the send_mail method using the same credentials? -
Python program to check Date of birth is greater then 18 or not?
What should I use here to check if a person inputs the dob is greater than 18 or not please try to solve this problem, so please try to find out the solution of this DOB problem? views.py def register(request): if request.method == "POST": # Get the post parameters username = request.POST['username'] email = request.POST['email'] First_name = request.POST['First_name'] Last_name = request.POST['Last_name'] dob = request.POST['dob'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] # check for errorneous input if User.objects.filter(username=username).exists(): messages.error(request, 'This Aadhaar is Already Used') return redirect('home') if User.objects.filter(email=email).exists(): messages.error(request, 'This Email is already Used') return redirect('home') if (pass1 != pass2): messages.error(request, " Passwords do not match") return redirect('home') # Create the user myuser = User.objects.create_user(username, email, pass1) myuser.first_name = First_name myuser.last_name = Last_name myuser.save() extendedregister = Registration(user=myuser, First_name=First_name, Last_name=Last_name, dob=dob) extendedregister.save() messages.success(request, "You are successfully registered") return redirect('home') else: return HttpResponse("404 - Not found") -
Heroku No migrations to apply
I'm having trouble with my database at Heroku: I've added some models for my App and whenever I run makemigrations it detects those changes. However when I run migrate it only says no migrations to apply. Please help! -
AttributeError: 'tuple' object has no attribute 'product'
When I go to the url:http://127.0.0.1:8000/addToCart/1/ , it should add the product to the Cart. But it is showing >AttributeError: 'tuple' object has no attribute 'product' Maybe I've made a mistake. models.py: class Cart(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) session_key = models.CharField(max_length=200, blank=True) product = models.ManyToManyField(Product, related_name='product_items') views.py: @api_view(['GET']) def addToCart(request, pk): product = Product.objects.get(id=pk) if request.user.is_authenticated: #user is authenticated mycart = Cart.objects.get_or_create(user=request.user) mycart.product.add(product) # <--- here is the problem else: print(request.session.session_key) return Response({'response':'ok'}) urls.py: path('addToCart/<str:pk>/', views.addToCart, name='addToCart'), What I need to change to add the product to the cart? -
How to group two items with two dates and get durations in pandas?
I usually work with data look like this {'id': '1', 'start_date': '2012-04-8', 'end_date': '2012-08-06'} but now I have something very different. I have items of items where each two-element represents the one item data = [ {'id': '1', 'field': 'end_tmie', 'value': '2012-08-06'}, {'id': '1', 'field': 'start_date', 'value': '2012-04-8'}, {'id': '2', 'field': 'end_tmie', 'value': '2012-01-06'}, {'id': '2', 'field': 'start_date', 'value': '2012-03-8'}, ] Goal how to get the duration end_time -start_time for each two data points with the same id in pandas data Goal df = [ {'id': '1', 'durations': '2012-08-06 - 2012-04-8'}, {'id': '2', 'durations': '2012-01-06 - 2012-03-8'}, ] 2 data Goal how to resample data to look like tihs df = [ {'id':'1', 'start':'2012-04-8', 'end':'2012-08-06'}, {'id':'2', 'start':'2012-03-8', 'end':'2012-01-06'}, ] -
django getting error :Refused to display 'http://127.0.0.1:8000/' in a frame because it set 'X-Frame-Options' to 'deny'
i have set X-Frame-Options: SAMEORIGIN but still getting error :Refused to display 'http://127.0.0.1:8000/' in a frame because it set 'X-Frame-Options' to 'deny'. -
Django starts becoming slow after add my app to INSTALLED_APPS
After adding a new feature(with a new Django app) to My Django site last month it started acting slow, I found that by adding my new app let's say "ABC" to the INSTALLED_APPS the site starts to become slow. But now I couldn't figure out what is causing the slowness. I have commented out my codes from "ABC" app from admin.py urls.py and even models.py. But the slowness still persists, only by removing the "ABC" app from INSTALLED_APPS is making the site work as intended. And the only thing I haven't commented out from "ABC app is the @shared_task function used by celery. -
How to download a HTML div as PDF?
I have a report page in my Django project I have to create a download button for downloading this report. The report is inside the div named generate-pdf. I just want to make this part available for user download. How can I do this in Django? details.html <div class="col-md-12 generate-pdf" id="generate-pdf"> {% for approval_item in approval_items_list %} <ul class="timeline"> <li {% if forloop.counter0|divisibleby:2 %} {% else %}class="timeline-inverted" {% endif %}> <div class="timeline-badge" </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4 class="timeline-title">Step {{ forloop.counter }}</h4> <hr> </div> <div class="timeline-body"> <div class="row"> <div class="col"> <img src="{{ approval_item.starter.image.url }}" width="150px" height="150px" alt="userprofile"/> </div> <div class="col"> <p> Username: {{ approval_item.starter }}</p> <p> First Name: {{ approval_item.starter.first_name }}</p> <p> Last Name: {{ approval_item.starter.last_name }}</p> <p style="font-weight: bold">Rank: {{ approval_item.starter.rank }}</p> </div> </div> </div> <hr> <p style="float: right">Date: {{ approval_item.start_time }}</p> </li> <br> <li> </li> </ul> {% endfor %} <div class="card-secondary"> .... <table class="table table-head-bg-primary mt-4"> <thead> <tr> <th scope="col">Role</th> <th scope="col">Uploaded Date</th> <th scope="col">Uploader / Role</th> <th scope="col">File</th> </tr> </thead> <tbody> {% for doc in approval_documents %} <tr> <td> {{ doc.rank }} </td> <td> {{ doc.created_date }} </td> <td> {{ doc.user.first_name }} {{ doc.user.last_name }} | {{ doc.user.rank.rank_name }}</td> <td> <a href="{{ doc.file.url }}" download="">View</a> </td> </tr> … -
how save and clean method works in django model class and how they are invoked? Also, how super is helping in this code?
from django.db import models from django.core.exceptions import ValidationError from rest_framework import serializers import re class UserModel(models.Model): name = models.CharField(max_length=50, blank=False, default='') email = models.CharField(max_length=50, blank=False, default='') #phone = models.IntegerField(blank=False, default='') phone = models.CharField(max_length=10,blank=True, default='') company = models.CharField(max_length=50, blank=True, default='') def __str__(self): return self.name class Meta: ordering = ('id',) **def save(self, **kwargs): self.clean() return super(UserModel, self).save(**kwargs)** **def clean(self): super(UserModel, self).clean()** errors = {} valphone = self.phone valmail = self.email regex = '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9_-]+\.\w{2,3}$' if not (valphone.isdigit() and len(valphone) == 10): errors['phone'] = (f"{valphone} must`enter code here` be 10 digits and shouldn't contain any string") if not (re.search(regex, valmail)): errors['email'] = ('Invalid email id format') if errors: raise serializers.ValidationError(errors) -
Create Affiliate system for my e-commerce website in Django
As, I am building a Django based e-commerce website and now I want to add the affiliate system setup to my website, like as the users or any influencers can generate affiliate links for any products on my website and if someone purchase through that URL then the commission is added to that influencer affiliate account. Can anyone help me out in this situation?