Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: AJAX request in generic class-based view does not assign class attribute with new value
I am currently creating a page using Django generic class-based view. However, whenever I made AJAX request, the class attribute is not assigned with the sent data/value. Code example: class CourseView(View): object = None # Other attributes and methods # POST method (AJAX url points to the same path) def post(self, request, *args, *kwargs): if request.is_ajax(): print("prev value:",self.object) self.object = self.POST['object'] print("new value:", self.object) return HttpResponseRedirect(success_url) From the code above, suppose that the value sent during the 1st AJAX request is "one", then the output from the console should be as follow (which is correct AT FIRST) prev value: None new value: one However, when I made the 2nd AJAX request with another value, for example "two", the output from the console shows prev value: None #suppose to be one new value: two Since I have assigned the class attribute with value "one" during the 1st AJAX request, shouldn't the attribute be overwrote and display "one" as the previous value, instead of the initial value None during the 2nd AJAX request? Or is there any other ways to do this. -
The database is not accepting the updated field values in django
I an currently learning django and i am just a beginner. I am making a basic social media app. I have programmed it to create a profile for every user that registers. I am also trying to add an edit profile function. But when a user tries to edit his/her profile pic, status or tries to change his/her account to private account nothing is happening i.e. the database is not saving the editted data. pls help me to rectify my mistakes. Thanks. My views.py(variables- private, status, image are not getting saved) def edit_profile(request): user = request.user user_profile = profile.objects.get(user__username=user) Profile = user_profile myuser = User.objects.get(username=user) follow1 = Follow.objects.filter(follow_user=user) follow2 = Follow.objects.filter(user=user) follow_by = follow1.count() follow_to = follow2.count() try: if request.method == 'POST': username = request.POST['username'] name = request.POST['name'] email = request.POST['email'] private = request.POST['private'] status = request.POST['status'] image = request.FILES.get('img') if private == 'on': paccount = True else: paccount = False if User.objects.filter(username=username).exists() and User.objects.get(username=username) != request.user: messages.error(request, 'username is taken') return redirect('edit_profile') elif User.objects.filter(email=email).exists() and myuser.email != email: messages.error(request, 'An account exists with this Email-id') return redirect('edit_profile') else: myuser.username = username myuser.first_name = name myuser.email = email myuser.save() Profile.user = myuser.username Profile.name = myuser.first_name Profile.private = paccount Profile.save() return … -
django .env EmailMessage auth troubles
im trying to secure my credentials while i want to configure email activation sending. So i have to import my .env values in correct place in settings.py while i do it, it tries to auth to another email mentioned in EmailMessage method. But while i leave it hardcoded in settings.py everything works smoth with credentials from settings.py. Why django tries to authenticate to noreply@sendsite.com in EmailMessage method? #settings.py ACCOUNT_UNIQUE_EMAIL = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') PASSWORD_RESET_TIMEOUT_DAYS = 1 ####################################### #part of views.py if form.is_valid(): user = form.save() user.is_active = False user.save() current_site = get_current_site(request) email_body = { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), } link = reverse('activate', kwargs={ 'uidb64': email_body['uid'], 'token': email_body['token']}) email_subject = 'Activate your account' activate_url = 'http://' + current_site.domain + link email = EmailMessage( email_subject, 'Hi ' + user.username + ', Please the link below to activate your account \n' + activate_url, 'noreply@sendsite.com', [user.email], ) email.send(fail_silently=False) ########### #.env EMAIL_HOST_USER=**********@gmail.com EMAIL_HOST_PASSWORD=****** -
Django annotate NumericRange - AttributeError: 'NumericRange' object has no attribute 'resolve_expression'
I have DRF custom filter and I'm struggling with building query for NumericRange. I need to create NumericRange(or other range for integers) with two calculated values and then use that field to filter it using __overlap. def filter_range(queryset, name, value): queryset = queryset.annotate( number_range=ExpressionWrapper( NumericRange(F(f"{name}_base"), F(f"{name}_base") + F(f"{name}_extend")), output_field=NumericRange(), ), ).filter(number_range__overlap=(value.start, value.end)) When I use this filter, I'm getting: 'NumericRange' object has no attribute 'resolve_expression' I think that maybe I'm using the wrong range field or something but I couldn't find anything better. -
How to change in Django Admin the default form (dropdown list) for a foreignKey model?
I want to change in my django administration page the form of a field. In my model I have the 'user' as foreign key to another model. When I create a new 'programare' in the administration page the default form-field for user it's a dropdown with all entries of 'Cont' model. It's dizzy to search the right one, so I want to change that dropdown with a plain-text input or an autocomplete form. class Programare(models.Model): user = models.ForeignKey(to=Cont, on_delete=models.CASCADE, related_name='programari') ... -
django3.1 error "TypeError: expected str, bytes or os.PathLike object, not NoneType"
welcome I have problem in django 3.1 : TypeError: expected str, bytes or os.PathLike object, not NoneType [27/Aug/2020 14:56:53] "GET /static/js/scripts.js HTTP/1.1" 500 83625 -
Django test set created_at field
I have following model in Django (models.py) from django.db import models # Create your models here. class Session(models.Model): session_token = models.TextField(default="") code = models.CharField(max_length= 5, default="") active = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Now, I have following function to be tested. def get_active_session_older_than_hours(older_than_hours): older_date_time = datetime.datetime.now() - datetime.timedelta(hours=older_than_hours) data = Session.objects\ .filter(active=True, updated_at__lte=older_date_time)\ .values_list('code') return data I want to test it. from django.test import TestCase #Working fine class ActiveSessionsNotPreset(TestCase): def test(self): data = get_active_session_older_than_hours(3) self.assertEqual(len(data), 0) #This is not working. #It is not getting the result. class ActiveSessionPresent(TestCase): def setUp(self): older_date_time = datetime.datetime.now() - datetime.timedelta(hours=4) Session.objects.create(session_token='', code='US', active=True, created_at=older_date_time, updated_at=older_date_time) def test(self): data = get_active_session_older_than_hours(3) print("DEVENDER data " + str(data)) self.assertEqual(len(data), 1) In the second test case, I am not getting any result. What is the correct way to force created_at and updated_at? -
Django singe models show in html
I want to show only body_text, how do I do that? I do not want to use for loop because it adds text to all . For example when I add body1 in Text-1 and then text-2 I want a new one to appear and delete text-1. this is my code . This is models.py # Create your models here. class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=200) email = models.EmailField() def __str__(self): return self.name class Entry(models.Model): blog = models.ForeignKey(Blog,on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() authors = models.ManyToManyField(Author) rating = models.IntegerField() def __str__(self): return self.headline and this is html ```<h2>{{posts.body_text}</h2>``` this is views.py template = 'aries.html' forms = Entry() posts = Author.objects.all() args = {'forms':forms,'posts':posts} return render(request,'Zodiac/aries.html',args)``` -
In Django is it possible to obfuscate or hide client IP from logging on certain pages?
We have a need to allow a user of our internal Django site to send an anonymous email via a contact form to an internal email box. I have all of the framework in place and the messages arrive and are not obviously traceable. However, the Django logs do record the IP address along with a timestamp of all requests. I am curious if it would be possible to some how hide or perhaps proxy the client IP when the form is submitted to help protect their anonymity? I have found many articles on how to get the client IP but my searches have not hit upon anything that does the reverse. I could perhaps alter the Django Logging format to exclude the client IP but it would be good to leave it on for the rest of the site for debugging etc. thank you in advance. -
Best approach to handle large files on django website
Good morning all. I have a generic question about the best approach to handle large files with Django. I created a python project where the user is able to read a binary file (usually the size is between 30-100MB). Once the file is read, the program processes the file and shows relevant metrics to the user. Basically it outputs the max, min, average, std of the data. At the moment, you can only run this project from the cmd line. I'm trying to create a user interface so that anyone can use it. I decided to create a webpage using django. The page is very simple. The user uploads files, he then selects which file he wants to process and it shows the metrics to the user. Working on my local machine I was able to implement it. I upload the files (it saves on the user's laptop and then it processes it). I then created an S3 account, and now the files are all uploaded to S3. The problem that I'm having is that when I try to get the file (I'm using smart_open (https://pypi.org/project/smart-open/)) it is really slow to read the file (for a 30MB file it's taking … -
Facing problem with database models after deploying to heroku
Need Help From Django Developer... Project is deployed on heroku But i was facing problem in data mapping through postgresql to server side(heroku). The data is not being displayed on the html page which is stored in postgresql database. And if you know anything please leave a message for sure... Thankyouenter image description here -
RelatedObjectDoesNotExist at / User has no customer
when I try to create a new user and when I log in using that user it show that error it automatically doesn't create that user as a customer and shows that error views.py from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.http import JsonResponse import json import datetime from .models import * from .utils import cookiesCart, cartData, guestOrder def store(request): data = cartData(request) cartItems = data['cartItems'] products = Product.objects.all() context = {'products': products, 'cartItems': cartItems} return render(request, 'store/store.html', context) def cart(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items': items, 'order': order, 'cartItems': cartItems} return render(request, 'store/cart.html', context) # @login_required def checkout(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items': items, 'order': order, 'cartItems': cartItems} return render(request, 'store/checkout.html', context) def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('Product:', productId) customer = request.user.customer(user=request.uses) product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + 1) elif action == 'remove': orderItem.quantity = (orderItem.quantity - 1) orderItem.save() if orderItem.quantity <= 0: orderItem.delete() return JsonResponse('Item was added', safe=False) def processOrder(request): transaction_id = datetime.datetime.now().timestamp() … -
how to make changes or add column in model for which migration has already been run?
I have already run migration for class Siginingauthlist(models.Model): employee_id = models.AutoField(primary_key=True) employee_name=models.CharField(max_length=500) department_sign=models.CharField(max_length=10) year_validfrom=models.DateField() year_validthrough=models.DateField() def __str__(self): return self.department_sign i forgot to add sign_designation=models.CharField(max_length=50) later class Siginingauthlist(models.Model): employee_id = models.AutoField(primary_key=True) employee_name=models.CharField(max_length=500) department_sign=models.CharField(max_length=10) sign_designation=models.CharField(max_length=50) year_validfrom=models.DateField() year_validthrough=models.DateField() def __str__(self): return self.department_sign makemigrations and migrated again but the column was not added to the table . what can i do -
Python, Django, save files localy with NO ROOT but custom rights
I'm working on a Django app and try to save file with that function def save_entry(title, content): """ Saves an app entry, given its title and Markdown content. If an existing entry with the same title already exists, it is replaced. """ filename = f"entries/{title}.md" if default_storage.exists(filename): default_storage.delete(filename) default_storage.save(filename, ContentFile(content)) and I get saved it as with ROOT rights as: -rw-r--r-- 1 root root 18 Aug 27 12:08 Page_test2.md instead: -rwxrwxrwx 1 1000 1000 136 Aug 24 23:16 Python.md* my app doesn't see them in the list for this reason, I suppose def list_entries(): """ Returns a list of all names of encyclopedia entries. """ _, filenames = default_storage.listdir("entries") return list(sorted(re.sub(r"\.md$", "", filename) for filename in filenames if filename.endswith(".md"))) Please hint me how to solve it -
Django REST Framework "ERR_CONNECTION_REFUSED" on API call
I'm hosting a Django Rest Framework application and a ReactJS website on a Windows 2019 server. The ReactJS communicates to the DRF by API calls. When I browse my website locally (on the server), everything works. However when I access it from my own PC (or any other PC) I'll get the error "ERR_CONNECTION_REFUSED". This is the error I get in my browser when accessing the website from my own PC: I've tried changing the API calls from localhost:8000 to 0.0.0.0:8000, I'll then get a different error saying I can't access the DRF by HTTPS. Django Rest framework console: What's the solution here? -
If the customer wants to add another one product to the previous number of her order list shop in Django
I'm trying to solve a small project. In one section of it, there is a function that will check if status is equal to the shopping and the product already exists in customer's order list and has an amount, try to add a new amount to it. For example john's list has: 3 apple and now wants to add 2 more apples to the list. how we can do it? I did a little bit of it but I'm not sure if it's correct. class Product(models.Model): code = models.CharField(max_length=10) name = models.CharField(max_length=10) price = models.PositiveIntegerField() inventory = models.IntegerField(default=0) class Customer(models.Model): user = models.OneToOneField(to=User, on_delete=models.PROTECT) phone = models.CharField(max_length=20) address = models.TextField() balance = models.PositiveIntegerField(default=20000) class OrderRow(models.Model): product = models.ForeignKey(to=Product, on_delete=models.PROTECT) order = models.ForeignKey("Order", on_delete=models.PROTECT) amount = models.PositiveIntegerField() class Order(models.Model): # Status values. DO NOT EDIT class Status(models.IntegerChoices): STATUS_SHOPPING = 1 STATUS_SUBMITTED = 2 STATUS_CANCELED = 3 STATUS_SENT = 4 customer = models.ForeignKey(to=Customer, on_delete=models.PROTECT) order_time = models.DateTimeField() total_price = models.PositiveIntegerField() status = models.IntegerField(choices=Status.choices) rows = models.ForeignKey(OrderRow, on_delete=models.PROTECT, related_name='order') @staticmethod def initiate(customer): pass def add_product(self, product, amount): self.status = self.status.STATUS_SHOPPING try: if self.orderrow_set.filter(product=product).exists(): pass -
Django - Wrong datetime on server
I've deployed my Django application on DigitalOcean server. Everything works fine, except date. So, hours are displaying different (inside the document time is displaying 4 hour late) on admin dashboard and inside the model instance. During export to excel time also wrong. P.S: I'm using flatpickr for DateTimeField: var d = new Date($.now()); window.addEventListener("DOMContentLoaded", function () { flatpickr(".datetimefield", { enableTime: true, enableSeconds: true, dateFormat: "Y-m-d H:i:S", time_24hr: true, locale: "az", defaultDate: `${d.getFullYear()}-${d.getMonth()+1}-${d.getDate()} ${d.getHours()}:${d.getMinutes()}:00` }); }); -
Can't import 'views' from 'urls' - Django
I'm trying to import 'views' file to my 'urls' so I could map the path to this 'vehicle_validation' function. For some reason, pycharm can't find this file. can someone help me understand what's the problem? urls file: from django.urls import path from vehicule_approver import views # error here urlpatterns = [ path('admin/', admin.site.urls), path('vehicle_validation/', views.vehicle_validation) ] views file: import requests from django.http import HttpResponse import json from pyapi.vehicule_approver.models import Vehicle def vehicle_validation(request): ... project structure: structure image -
How do you populate Django models in an SQLite database in an Asynchronous way?
I have a model that I would like to populate with csv data, I have followed a few tutorials on this and am now trying to do it on my own. This is the code that I have so far; import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings') import django django.setup() #Import models from app_name.models import Instance # Third Party Imports import pandas as pd # Pull csv data into script file = 'path/to/file/filename.csv' collected_data = pd.read_csv(file,index_col='Timestamp') # this is a dataframe with three columns and a datetime index for timestamp, row in collected_data.iterrows(): info1 = row[0] info2 = row[1] info3 = row[2] inst = Instance.objects.get_or_create(timestamp = timestamp, info1 = info1, info2 = info2, info3 = info3)[0] I am getting the following error, which I don't really understand, as I am quite new to Django. SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. Let me know if there is any more information needed for a MCVE -
Django move models classmethod to another file
I have model Order(models.Model): name = models.Charfield() @classmethod do_something(cls): print('do soemthing') What I want to do is to move do_something method from my model to another file.I want to do it because I have several other big methods in this model and want to structure the code, don't like lengh of this file. It's getting big > 700 lines of code. So I want to move my method to another file and import it, so it still can be used like modelmethod like this: Order.do_something() Any ideas? -
django Filter customers in the specific user groups
I want to display Customers from specific groups in the ListView, not able to understand how to get the queryset class CustomerList(ListView): model = Customer queryset = Customer.objects.filter(customer__groups__name__in=['online', 'whatsapp']) template_name = 'staff/customer_list.html' models.py class Customer(models.Model): # Staff customer= models.ForeignKey(User, verbose_name=_("Customer"), on_delete=models.CASCADE, related_name='customer') contact = models.ForeignKey(Contact, verbose_name=_("Contact"), on_delete=models.CASCADE, blank=True, null=True) ... Customers are added to the groups as below: class AddUser(CreateView): def post(self, request, *args, **kwargs): form = UserForm(request.POST) if form.is_valid(): user = form.save(commit=False) group, created = Group.objects.get_or_create(name='online') user.groups.add(group) user.save() -
Sending 2 JSON objects to Django with Ajax
I'm trying to send 2 arrays via Ajax to my Django backend. They are basic lists of dicts like: send_products = [{'product': some_text, 'orden': some_value}, .........] send_categories= [{'category': some_text, 'orden': some_value}, ........] The AJAX call As I researched around the web, I'm trying data = { 'category': send_categories, 'products': send_products, }; data['category'] = JSON.stringify(data['category']); data['send_products'] = JSON.stringify(data['send_products']); $.ajax({ url:'/website/save-catalog-order/', type:'POST', dataType: 'json', contentType: 'application/json', csrfmiddlewaretoken: "{{ csrf_token }}", data: data, success:function(response){ }, error:function(){ }, }); My target Django view @ensure_csrf_cookie @login_required @transaction.atomic def SaveCatalogOrderView(request): category = request.POST['category'] data = {} return JsonResponse(data) Result: I get an "MultiValueDictError: 'category' If I try category = json.loads(request.POST['category']) Result: I get an "MultiValueDictError: 'category' If I try category = json.loads(request.POST) Result: TypeError: the JSON object must be str, bytes or bytearray, not QueryDict I usualy send 1 Json obeject POSTs without any problem But I can;t find the way to send 2. Any clues welcome! -
django automatic login without being logged in
I wanted to talk about a problem I've been having in one of my latest django builds. I want to make the following automatic login script, but when I provide the link, the application fails to log the user in, however, even with debug = True set in settings, it will not provide me with any errors, it simply refuses to log me in. I have created a superuser, which I call "User1" in this case. def automatic_login(request): user = User.objects.get(username="User1" login(request, user, backend=settings.AUTHENTICATION_BACKENDS[0] return HttpResponseRedirect(reverse('student_listing')) I have been tearing hair out as to why this doesn't work, any help would be greatly appriciated! -
ImportError: attempted relative import with no known parent package in context_processor
I have a django-project (version 3.1) with this structure: my_project --my_app --__init__.py --admin.py --asgi.py --context_processors.py --models.py --urls.py --views.py --wsgi.py In my views.py I import a model as follows: from .models import my_table which works perfectly. In my context_processors.py I do exactly the same thing: from .models import my_table but this gives me the error: ImportError: attempted relative import with no known parent package. This does not make sense to me. Can anyone help me out on this? -
Django Drop-down fields for foreign key to another database field
I am a Django beginner and I am having trouble using bootstrap drop-downs for foreign key use. I have an input form for adding Providers (supplier, manufacturer, or both) for my purchasing website that has the following data structure: class Provider(models.Model): provider_id = models.AutoField(primary_key=True) provider_name = models.CharField(max_length=255, unique=True) provider_address = models.CharField(max_length=255, null=True, blank=True) provider_email = models.EmailField(null=True, blank=True) provider_contact_01 = models.CharField(max_length=20, null=True, blank=True) provider_contact_02 = models.CharField(max_length=20, null=True, blank=True) provider_type = models.ForeignKey(ProviderType, on_delete=models.CASCADE) in which provider_type is a foreign key for table ProviderType that has the following data structure: class ProviderType(models.Model): providertype_id = models.AutoField(primary_key=True) providertype_desc = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.providertype_desc Dataset for ProviderType: | providertype_id | providertype_desc | --------------------------------------------- | 1 | Supplier | | 2 | Manufacturer | | 3 | Supplier & Manufacturer | The problem is that I have used providertype_desc as the text in the drop down field, because it is more user friendly and has context, rather than providertype_Id, Code segment in html: <div class="form-group col-md-6"> <label for="provider_type">Type of Provider</label> <select class="custom-select" id="provider_type" name="provider_type" aria-label="Example select with button addon"> <option selected>Choose...</option> {% for prov_types in provider_types %} <option>{{prov_types.providertype_desc}}</option> {% endfor %} </select> </div> But the POST sequence fails because the providertype_id needs to be …