Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SMTPSenderRefused getting this error while requesting the forget password
Getting the below error when I submit user's email address to get the password reset link the below pic is settings.py file -
How are all serializer errors returned in DRF at once?
I'm testing for multiple validation errors to be raised in(UserRegistrationSerializer). Yet DRF only returns the first error that is raised: {'username': [ErrorDetail(string='Choose a different username', code='invalid')]} I'm expecting: {'username': [ErrorDetail(string='Choose a different username', code='invalid')], 'password2': [ErrorDetail(string='Password confirmation failed', code='invalid')] How can multiple errors be accounted for once a serializer is validated as in the documentation example? https://www.django-rest-framework.org/api-guide/serializers/#validation class TestRegisterationSerializer__002(TestCase): '''Verify that the registeration process fails with respect to selecting an unavailable username and password confirmation''' @classmethod def setUpTestData(cls): User.objects.create_user(username="Python") cls.data = { 'username': "Python", 'password': "#secret#", 'password2': "Secret" } cls.error_messages = [ "Choose a different username", "Password confirmation failed" ] cls.serializer = UserRegisterationSerializer(data=cls.data) def test_user_registeration_invalid_confirmation(self): self.serializer.is_valid() print(self.serializer.errors) import re from django.contrib.auth.models import User from rest_framework import serializers class UsernameSerializer(serializers.ModelSerializer): username = serializers.SlugField(min_length=4, max_length=12) def validate_username(self, value): try: self.Meta.model.objects.get(username__iexact=value) except self.Meta.model.DoesNotExist: return value raise serializers.ValidationError("Choose a different username") class Meta: fields = ['username', ] model = User class LoginSerializer(UsernameSerializer): password = serializers.RegexField( r"[0-9A-Za-z]+", min_length=5, max_length=8 ) def validate(self, data): username, password = [ input.lower() for input in [data['username'], data['password']] ] if all(password[i] == password[i + 1] for i in range(len(password) - 1)) or username == password: raise serializers.ValidationError({ 'password': "Invalid password" }) return data class Meta: fields = ['username', 'password', ] … -
Grouping model field names in Django
I have a complex detail view where a lot of varied data is rendered dynamically. My model has hundreds of fields, many of which are related to one another. I would like to be able to group a number of these fields in order to do queries. Is there are way to do this? In order to cherry-pick specific fields and group them, my current approach has been to use word extensions to the field names that is common for each group. For example, field names like: ampicillin = models.CharField(...) ciprofloxacin = models.CharField(...) ... become: ampicillin_antimicro = models.CharField(...) ciprofloxacin_antimicro = models.CharField(...) ... The idea is then to create a field name list and access specific groups of fields using a substring search. How am I to do this? Below is a summary of my attempts and issues so far. Using _meta I can access the raw model field name information using _meta: all_fields = [] for field in MyModel._meta.fields: all_fields.append(field) This gives a list like: [<django.db.models.fields.CharField: ampicillin_antimicro>, <django.db.models.fields.CharField: ciprofloxacin_antimicro>, ...] but I've not been able to figure out how to extract the information I need from this, however. Using _meta and field.get_attname_column()[0] I can make a list of field name … -
How can I rewrite an average value per datet time interval MySQL query as a Django QuerySet
I have the following MySQL query that displays the average value per 10 minute interval: SELECT FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(date_time) / 600) * 600) AS interval_date_time, AVG(some_value) AS avg_value FROM djangoapp_somemodel GROUP BY interval_date_time ORDER BY interval_date_time; For example, if I have the following 3 records: date_time some_value 2021-11-29 00:11:01 10 2021-11-29 00:16:15 20 2021-11-29 00:24:32 25 The query will output the following: interval_date_time avg_value 2021-11-29 00:10:00 15 2021-11-29 00:20:00 25 I suspect the query isn't that efficient but I want to get the same output using a Django QuerySet. Here's what I have so far: (SomeModel.objects .annotate(interval_date_time=F("date_time")) .values("interval_date_time") .annotate(avg_value=Avg("some_value")) .order_by("interval_date_time") ) I believe I need to make changes to the first annotate method call. Any help would be appreciated. -
How do I import views.py to my project urls file
I am working with Django and trying to do a login system The app is supposed to deliver a simple 'Login System'-view but my_app/urls.py fails to import methods from my_app/views.py. My app name is authentication Here is my-project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('authentication.urls')), ] Here is my_app/urls.py. from django.contrib import admin from django.urls import path, include from authentication import views urlpatterns = [ path('', views.home, name="home"), path("signup", views.signup, name="signup"), path("signin", views.signup, name="signin"), path("signout", views.signup, name="signout"), ] Here is my-app/views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, "authentication/index.html") I have also added this in my-project/settings.py 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR /"templates"], 'APP_DIRS': True, And I get the following error TemplateDoesNotExist at / authentication/index.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.9 Exception Type: TemplateDoesNotExist Exception Value: authentication/index.html Exception Location: C:\Users\julie\Login System\venv\lib\site-packages\django\template\loader.py, line 19, in get_template Python Executable: C:\Users\julie\Login System\venv\Scripts\python.exe Python Version: 3.9.5 Python Path: ['C:\\Users\\julie\\Login System', 'c:\\python39\\python39.zip', 'c:\\python39\\DLLs', 'c:\\python39\\lib', 'c:\\python39', 'C:\\Users\\julie\\Login System\\venv', 'C:\\Users\\julie\\Login System\\venv\\lib\\site-packages'] -
"detail": "Method \"GET\" not allowed." i have not set it as GET so why is it showing this error
i am trying yo create a new item but i am getting "detail": "Method \"GET\" not allowed error on page of django rest framework and 405 (Method Not Allowed) error in console views.py: def create_person(request): serializer = PersonSerializer(data=request.data, many=False) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) urls.py urlpatterns = [ path('', views.getRoutes, name='routes'), path('notes/', views.getNotes, name='notes'), path('notes/create/', views.createNote, name='create-note'), path('notes/<str:pk>/update/', views.updateNote, name='update-note'), path('notes/<str:pk>/delete/', views.deleteNote, name='delete-note'), path('notes/<str:pk>/', views.getNote, name='note'), ] -
Download pd dataframe to csv dynamically with django
Created an django website which scrapes the github repo and show it as table . That table data is dataframe. So, i want that dynamic user data to be downloaded as csv when user clicks the button or url. I have not used any models and all. How it can be done in a simple way ? This is hosted website RepoLoader. I don't know the right method to do that. -
Why am i getting this error when i run python manage.py shell in terminal?
UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 2: character maps to -
Share Models Between Two Different Django Projects
I have two different Django projects which should be using exactly the same db & same models and working on different servers. I don’t want to define same models twice in both apps since the models might change and changes should be done on both sides. What would be the best solution to define models once and use the same models in both projects? -
Django query fail using diacritic
My ListView in Django is: class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username = self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') When User ID contains lettes like č, ć, š, it fails with: GET http://myapp.local/user/ITeri%C4%87 404 (Not Found) How can I fix this? I use same code on my PC and it works. I uploaded the same code to the company server and only this wont work. -
I am getting the date instead of date and time data in a POST request
I have a date range picker on my website. When a user inputs the date and time range, I want to send separately within the form the startDate and the endDate daterangepicker code: $('input[name="datetimes"]').daterangepicker({ timePicker: true, timePickerIncrement: 5, startDate: moment().startOf('hour'), endDate: moment().startOf('hour').add(32, 'hour'), locale: { format: 'YYYY-MM-DD hh:mm' }, opens: 'center', drops: 'auto' }); And this is what I tried: $('#formid').submit(function(e) { e.preventDefault(); let startDate = ($('#datetimes').data('daterangepicker').startDate).format('YYYY-MM-DD hh:mm'); let endDate = ($('#datetimes').data('daterangepicker').endDate).format('YYYY-MM-DD hh:mm'); $(this).append('<input type="hidden" name="start_date" value='+startDate+' /> '); $(this).append('<input type="hidden" name="end_date" value='+endDate+' /> '); this.submit(); }); Before the this.submit(); I did a console.log(startDate) and thi is what I am getting: I am getting the date and the time (as expected), but then if I try doing a print(request.POST) in the view (django back-end), this is what I get: Somehow, during the POST the HH:mm disappeared. How can I keep the values of hh:mm during the POST? -
DJANGO multi db transaction with nested transaction.atomic
I've been searching a good way to implement cross db transaction in DJANGO, but there seem to be no good answer. I did see this post Django transaction using multi-db which suggested using nested trasaction.atomic(using='different_data_base_name'). However I wonder how does this work. With each nested block, django identifies a different connection, and all the checks and operations are performed specific to this connection, so I think the nested transaction.atomic could not guarantee cross-db transaction. Could someone help me understand why the nested transaction.atomic could work? Or if not, any suggestions on how to go about it? -
Automatically generate chatroom when onclick button
I wanna make a chat app that when clients click on the button, they will connect and chat with the admin. Each admin has a button only and he can chat with many clients. Each client can chat with many admin too. 1 chatroom has only 2 users (admin+client). My solution is when clients click the button, it will generate a chatroom and add user_id of admin and client into its. But now I'm struggling to find way to automatically generate a chatroom with random id or name. Hope you guys can help me <3 -
How can I create a unique primary integer key of fixed length?
I want Django to automatically create a unique key of fixed length. This is what I have so far: card_id = models.AutoField(primary_key=True) This method will create keys starting from a very low number and it is not of fixed length. I want to have it a fixed length of 7 chars/digits and have it be composed of integers (a string with number chars is fine as well) e.g. 1543534. I call this from views.py to create a new entry in the database: BORROWER.objects.create(ssn=Ssn, bname=Name, address=Address, phone=Phone) Notice that card_id is not specified, so I want to have Django auto-create it. -
python manage.py takes too much time to run in Django
I am working on Python rest framework and after setting up python 3.8.12 on my mac, when I tried to up the server with python manage.py runserver command for Django, it takes around 2 minutes and in-between it gives some connectionpool logs described as below. 2021-11-26 11:24:04,249 DEBUG urllib3.connectionpool : Starting new HTTP connection (1): 169.254.169.254:80 2021-11-26 11:24:05,252 DEBUG urllib3.connectionpool : Starting new HTTP connection (2): 169.254.169.254:80 2021-11-26 11:24:06,586 DEBUG urllib3.connectionpool : Starting new HTTP connection (3): 169.254.169.254:80 2021-11-26 11:24:07,590 DEBUG urllib3.connectionpool : Starting new HTTP connection (4): 169.254.169.254:80 2021-11-26 11:24:09,527 DEBUG urllib3.connectionpool : Starting new HTTP connection (1): 169.254.169.254:80 2021-11-26 11:24:09,528 DEBUG urllib3.connectionpool : Starting new HTTP connection (2): 169.254.169.254:80 2021-11-26 11:24:09,821 DEBUG urllib3.connectionpool : Starting new HTTP connection (3): 169.254.169.254:80 2021-11-26 11:24:09,822 DEBUG urllib3.connectionpool : Starting new HTTP connection (4): 169.254.169.254:80 2021-11-26 11:24:10,154 DEBUG urllib3.connectionpool : Starting new HTTP connection (5): 169.254.169.254:80 2021-11-26 11:24:10,155 DEBUG urllib3.connectionpool : Starting new HTTP connection (6): 169.254.169.254:80 Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. This is a headache because every time it takes this much time for any change. I can't find any solution over web. Please Help. All solutions are welcomed. Thanks in advance ;) -
Access data from second external SQLite database in Django
This is my project structure I am able to access the default SQLite database db.sqlite3 created by Django, by importing the models directly inside of my views files Like - from basic.models import table1 Now, I have another Database called UTF.db which is created by someone else, and I want to access it's data and perform normal QuerySet operations on the retrieved data The problem is I don't know how to import the tables inside that database, as they are not inside any model file inside my project as it's created by someone else I tried adding the tables inside the UTF.db database to a models.py file by first adding it to the settings.py file like the following DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'otherdb':{ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'UTF.db', } } And then using the inspectdb command to add the tables to an existing models.py file The command I tried out - python manage.py inspectdb > models.py But, that just causes my models.py file to get emptied out Does anyone know how this can be solved? In the end, I wish to import the table data inside of my views files by … -
how to get single query set from three different models using Django..?
I have two models A and B which having many to many relation and form third model E with extra attributes . so i want to perform following sql query using Django ORM : select * from A , B , E where A.id = E.id and B.id = E.id and A.id = '107'; how i can do..? *I try this A.objects().filter(e__aid=107) it gives me only content from A model.* Please Help..! -
upload images issue. While uploading an image taking only image name but not the images how to solve this problem
By using Vuejs, Axios and Django, we're uploading "multiple images" using Vuejs form in one upload/browse attempt. After uploading, the images are getting in a list and then the list of images names are stored into backend in ImageField. The image names are saving into database but not saving into Media Folder. Here is snippet of the code. Vuejs <label> <span>Files</span> <input type="file" multiple @change="handleFileUploads($event)" /> <ul v-if="files.length"> <li v-for="(name, i) in filesNames" :key="i">{{ name }}</li> </ul> </label> <div> <img v-for="image in images" :src="image" /> </div> <br /> <button v-on:click.prevent="submitForm">Submit</button> Axiox <script> new Vue({ el: '#app', data() { return { files: [], images: [], } }, computed: { filesNames() { const fn = [] for (let i = 0; i < this.files.length; ++i) { fn.push(this.files.item(i).name) } return fn } }, methods: { handleFileUploads(event) { this.files = event.target.files; this.images = [...this.files].map(URL.createObjectURL); }, submitFile() { let formData = new FormData(); for (var i = 0; i < this.files.length; i++) { let file = this.files[i]; formData.append('files[' + i + ']', file); } submitForm: function(){ let formData = new FormData(); const fna = [] for (let i = 0; i < this.files.length; ++i) { fna.push(this.files.item(i).name) } console.log('fna'); console.log(fna); axios({ method : "POST", url: "{% … -
Django form validation failing for formset with choicefield
My formset consists of choice field with initial data populated from Views.py, Formset is generated properly with initial data but when I submit the form the form.is_valid is failing. I'm not sure what I'm missing here however tried in different ways but couldn't resolve. forms.py class RelServiceForm2(forms.Form): ebsapp = forms.CharField(widget=forms.TextInput(attrs=dict(required=True)), label=_("")) code_version = forms.ChoiceField(widget=forms.Select(), label=_(""), required=False) mscv = forms.ChoiceField(widget=forms.Select(), label=_(""), required=False) views.py mscv_versions_tup = [] mscv_versions_tup = [('9.11.041', '9.11.041'), ('9.11.040', '9.11.040')] print('mscvversions', mscv_versions_tup) my_config = update_my_config(region='us-east-1', account='prod') client = session.client('elasticbeanstalk', config=my_config) _beanstalk_apps = _ebsstageapps.filter(ebsapp__type='beanstalk') _beanstalk_apps_list = list(_ebsstageapps.values_list('ebsapp__name', flat=True)) print('_ebsstageapps : _beanstalk_apps', _beanstalk_apps_list) _response = client.describe_applications(ApplicationNames=_beanstalk_apps_list)['Applications'] RelServiceFormSet = formset_factory(RelServiceForm2, extra=0, ) formset = RelServiceFormSet(initial=[{'ebsapp': x} for x in _beanstalk_apps_list]) for _beanstalk_app in _response: code_versions = _beanstalk_app['Versions'] code_versions_tup = [] for v in code_versions: code_versions_tup.append((v, v)) for form in formset: if form['ebsapp'].value() == _beanstalk_app['ApplicationName']: print(' Form sec Matched') form.fields['code_version'].choices = code_versions_tup form.fields['mscv'].choices = mscv_versions_tup if request.method == 'POST': formset = RelServiceFormSet(request.POST,) # initial=[{'ebsapp': x} for x in _beanstalk_apps_list]) for _beanstalk_app in _response: code_versions = _beanstalk_app['Versions'] code_versions_tup = [] for v in code_versions: code_versions_tup.append((v, v)) for form in formset: if form['ebsapp'].value() == _beanstalk_app['ApplicationName']: form.fields['code_version'].choices = code_versions_tup form.fields['mscv'].choices = mscv_versions_tup else: print('unmatched') form = formset print('print form before valid', form) print('\n\n print') if form.is_valid(): … -
increase geo corrdinates such that nearest points can be found
I am working on a project which uses external API for fetching nearby shops for given Geo coordinates now the problem, if in case there is now shop available for given coordinates we should still be able to retrieve any of its nearest locations for shops that means we possibly have to increase coordinates periodically until we find such shops or locations(shops) which also means we're increasing the (GPS radius), now my question is whether there any such algorithm available which does such thing, also is my approach correct in this case because i am increasing the amount of API hits def get_nearby_stores(member_id,lat,lon): api = B2C response , status_code = api.get_nearest_location_shop( member_id=member_id, lat=lat, -
Django Save Occasionally Fails
We have a code like below and when executing process_something, sometimes the fields failed to be updated after process_something3 successfully executed. Most of the time it works normally but sometimes it just failed to update all mentioned field in the functions from django.db import models class DjangoObject(models.Model): field1 = models.PositiveSmallIntegerField() field2 = models.DateField() field3 = models.PositiveSmallIntegerField() def process_something(self): # Do something here self.save(update_fields=['field1']) self.process_something2() def process_something2(self): # Do asynchronous process self.process_something3() def process_something3(self): # Do another thing here self.save(update_fields=['field2', 'field3']) As far as i know it only happens here, so i suspect it caused by race condition by saving on same object. Is it really that or there is other cause and how to fix it ? Django version is 3.2.9 Postgresql version is psql (PostgreSQL) 12.7 (Ubuntu 12.7-0ubuntu0.20.04.1) Asynchronous process using [django-rq](https://github.com/rq/django-rq) -
How to break multiple if statements?
I have a permission class for my viewset. But it has multiple if statements and the if statements can be added others as well if some action added inside viewset. So how can I optimize my code here for better performance ? def has_permission(self, request, view): if view.action in ["update", "partial_update"]: return some_user if view.action == "create": return some_user if view.action in ["list", "retrieve"]: return some_user if view.action == "destroy": return some_user return False -
Django: I am unable to get Django to autocreate an autofield
I am calling BORROWER.objects.create(ssn=Ssn, bname=Name, address=Address, phone=Phone) from views.py to create an entry in my sqlite database. This is my models.py file with the relevant function. class BORROWER(models.Model): card_id = models.AutoField(primary_key=True, max_length=7), ssn = models.CharField(max_length=11) bname = models.CharField(max_length=71) address = models.CharField(max_length=79) phone = models.CharField(max_length=15) def __str__(self): return str(self.card_id) The database entry is successfully created. However, since I am not specifying a value for the card_id field, the value stays as (<django.db.models.fields.AutoField>,) instead of an actual key. When I try to specify a value for card_id it says something about unexpected argument. Am I calling the create function incorrectly? -
How do I make a calculation appear from models in my HTML template?
hello I am trying to do a multiplication in Django from models multiplying the quantity by the unit_price and reflecting the result in total_price) but I see that it is not reflected in my HTML template (I have some inputs and in the input where I want to reflect the result of the multiplication, it does not appear), does anyone know what is missing for me? [![Here neither the input of total_price appears][1]][1] I should also mention that it is a form and a formset to which I want to apply that models.py class Parte(models.Model): codigo=models.IntegerField() quantity=models.IntegerField() unit_price=models.IntegerField() total_price=models.IntegerField() tax_free=models.BooleanField() descripcion=models.CharField(max_length=255,blank=True, null=True) descuento=models.IntegerField() total=models.IntegerField() @property def total_prices(self): return self.quantity*self.unit_price def __str__(self): return f'{self.codigo}: {self.descripcion} {self.quantity} {self.unit_price} {self.total_prices} {self.tax_free}{self.descuento}{self.total}' presupuestos-forms.html <table class="table table-bordered table-nowrap align-middle"> <thead class="table-info"> <tr> <th scope="col">Código</th> <th scope="col">Descripción</th> <th scope="col">Cantidad</th> <th scope="col">Precio Unitario</th> <th scope="col">Precio Total</th> <th scope="col">Libre de Impuestos</th> <th scope="col">Agrega Fila</th> </tr> </thead> <tbody> <tr> <td> {{presupuestosparteform.codigo}} </td> <td> {{presupuestosparteform.descripcion}} </td> <td> {{presupuestosparteform.quantity}} </td> <td> {{presupuestosparteform.unit_price}} </td> <td> {{presupuestosparteform.total_prices}} </td> <td> <div> {{presupuestosparteform.tax_free}} </div> </td> <td> <input type="button" class="btn btn-block btn-default" id="add_more" value="+" /> </td> </tr> {{ formset.management_form }} {% for form in formset %} <tr id="formset" class="form-row"> <td> {% render_field form.codigo class="form-control" %} </td> … -
Ajax call to update sort criteria of product list in a Django template
I'm trying to make an Ajax call to update the sort criteria of a product list that is being displayed on the store page, depending on the drop-down option. The store page template extends from the main template. However, the sort isn't working. I took the liberty of removing all views that are not relevant to the question, except the store page view which is receiving the ajax call. I am wondering if there is a conflict issue since the store page is also receiving the cart total from the front end via the CartData function. Any insight would be helpful. main.html <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1"/> <title>MyShop</title> {# Bootstrap stylesheet#} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> {# Custom CSS#} <link rel="stylesheet" href="{% static 'css/ecomsite.css' %}"> {# Google Fonts import#} <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap" rel="stylesheet"> <script type="text/javascript"> var user = '{{request.user}}' /* getToken function creates a CSRF token so that the cart.js script can communicate with the updateItem view */ function getToken(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; …