Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ModelChoiceField passes None
I'm very new to Django. I'm making form to add timetable to specific branch. So I have 'Branch' model and 'Timetable' model. 'Branch' model is in 'branches' app and 'Timetable' model is in 'schedules' app. What I'm expecting is when users fill in the form to add timetable, they can choose which branch to add it from select box. Here is my codes branches/models.py from django.core.validators import RegexValidator from django.db import models from django.urls import reverse # Create your models here. phone_validator = RegexValidator( regex="\d{2,4}-?\d{3,4}(-?\d{4})?", message="It's not correct phone number format.", ) class Branch(models.Model): srl = models.BigAutoField(primary_key=True, verbose_name="Serial") name = models.TextField(verbose_name="Branch name") postcode = models.CharField(max_length=5, verbose_name="Postcode") address1 = models.TextField(verbose_name="Road address") address2 = models.TextField(verbose_name="Detail address", blank=True) phone1 = models.CharField(max_length=13, validators=[phone_validator], verbose_name="Phone 1") phone2 = models.CharField(max_length=13, validators=[phone_validator], verbose_name="Phone 2", blank=True) is_opened = models.BooleanField(default=True, verbose_name="Is opened?") class Meta: verbose_name = "Branch" verbose_name_plural = "Branches" ordering = ["srl"] def __str__(self): return self.name def get_absolute_url(self): return reverse("branches:detail", kwargs={"srl": self.srl}) schedules/models.py import datetime from django.conf import settings from django.db import models class Timetable(models.Model): srl = models.BigAutoField( primary_key=True, verbose_name="Serial", ) branch_srl = models.ForeignKey( "branches.Branch", on_delete=models.CASCADE, verbose_name="Branch Serial", ) period = models.DecimalField( max_digits=2, decimal_places=0, verbose_name="Period", ) period_length = models.DurationField( default=datetime.timedelta(minutes=50), verbose_name="Period Length", ) is_holiday = models.BooleanField( default=False, verbose_name="Is … -
How can I add a "duplicate" button next to the "add another ..." button in djangos admin.StackedInline?
Is there a possibility to add a "copy" or "duplicate" button next to the "add another ..." button in djangos admin.StackedInline (see image)? It should add another object and prepopulate the fields based on the previous object (if that exists). Another fix could be to prepopulate the fields based on the previous object when adding it via "add another ...", but I don't know how to do that. -
how can i get the maximum value of each tag by day in the date range using django
I'am creating ListAPIView using DRF. Here is sample data. DateAndTime column measured per 10 seconds and range is 6/30-8/31. unfortunately, DateAndTime is CharField. Because the database design is like that. I sliced dateandtime field and i got slicedate column using annodate and Substr. The reason I did this was to do group by day. it works fine. I want to get the maximum value of each tag by day in the date range. The maximum value is duplicated, so I want to get the fastest time among them. I think my query is ok, but I get an error. please help me! DateAndTime TagName DataValue 2022-06-30 14:15:40 BW004_GD-4-16 99 2022-06-30 14:15:50 BW004_GD-4-16 25 2022-06-30 14:16:00 BW004_GD-4-16 99 2022-06-30 14:16:10 BW004_GD-4-16 50 2022-06-30 14:16:20 BW004_GD-4-16 99 2022-06-30 14:16:30 BW004_GD-4-16 99 . . . 2022-06-30 14:15:40 BW004_GD-4-17 50 2022-06-30 14:15:50 BW004_GD-4-17 40 2022-06-30 14:16:00 BW004_GD-4-17 25 . . . 2022-06-30 18:20:00 BW004_GD-4-17 50 2022-06-30 18:20:10 BW004_GD-4-17 50 2022-06-30 18:20:20 BW004_GD-4-17 10 . . . 2022-06-30 14:15:40 BW004_GD-4-18 30 2022-06-30 14:15:50 BW004_GD-4-18 40 2022-06-30 14:16:00 BW004_GD-4-18 100 . . . # models.py class EnvAi(models.Model): dateandtime = models.CharField(db_column='DateAndTime', blank=True, null=True) # Field name made lowercase. tagname = models.CharField(db_column='TagName', max_length=50, blank=True, null=True) # Field name … -
what is the best method to initialize or store a lookup dictionary that will be used in django views
I'm reviving an old django 1.2 app. most of the steps have been taken. I have views in my django app that will reference a simple dictionary of only 1300ish key-value pairs. Basically the view will query the dictionary a few hunderd to a few thousand times for user supplied values.The dictionary data may change twice a year or so. fwiw: django served by gunicorn, db=postgres, apache as proxy, no redis available yet on the server I thought of a few options here: a table in the database that will be queried and let caching do its job (at the expense of a few hundred sql queries) Simply define the dictionary in the settings file (ugly, and how many time is it read? Every time you do an 'from django.conf import settings'? This was the situation how it was coded in the django 1.2 predecessor of this app many years ago read a tab delimited file using Pandas in the django settings and make this available. the advantage is that I can do some pandas magic in the view. (How efficient is this, will the file be read many times for different users or just once during server startup?) prepopulate … -
I want to return multiple objects using django def get_context_data
def get_context_data(self, **kwargs): kcl = self.request.user.kcal men_kcal = 13.8 * kcl.weight context = super().get_context_data(**kwargs) if kcl.goal == 'diet': context['bmr'] = men_kcal - 500 else: context['bmr'] = men_kcal + 500 return context context['fixbmr'] = bmr * 2 I want to represent an object in the template. {{ bmr }} And {{ fixbmr }} I'd like to use. What should I do? -
Using Django 4.1 async orm in FastAPi
In verson 4.1 some async stuff was added to orm part of Django. I want to use Django orm in fastAPi, I created a small setting file for using Django orm like this: import os import sys import django from django.conf import settings BASE_DIR = os.path.dirname(os.path.abspath(__file__)) INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.auth', 'orm', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db', 'USER': 'user', 'PASSWORD': 'pass', 'HOST': '127.0.0.1', 'PORT': '5432', } } settings.configure( DATABASES = DATABASES, INSTALLED_APPS = INSTALLED_APPS, ) django.setup() if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) I want to run a query is main file like this in FastApi: @app.get("/test-orm") async def test_django_orm(): results = await User.objects.filter(username="user0") paginator = Paginator(results, 2) paginated = json.loads(serializers.serialize('json', paginator.page(1))) return {"data": paginated} This code simple doesn't work! If I remove async and await it works perfectly, but I write to use async friendly code! Any help and ideas appreciated :) -
How to make raw text file (to edit robots.txt) editor in Django Wagtail admin
The goal is to create a text file editor within the Wagtail admin site. Specifically for robots.txt file. I want the admin to update the file from the admin. How can I do that? -
Need Solution regarding Django
I have been going through Django-admin. but I am getting this error. Here is views.py from django.http import HttpResponse def Milton(request): print("This is a test page") return("<h1>Index</h1>") urls.py """Medical URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from pathlib import Path from django.contrib import admin from django.urls import path from django.views import Milton urlpatterns = [ path('admin/', admin.site.urls), path('Milton/', Milton.site.urls), ] Here is the Powershell Command Line error: Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. Try the new cross-platform PowerShell https://aka.ms/pscore6 spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + conda activate base + ~~~~~ + CategoryInfo : ObjectNotFound: (conda:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\milto\Desktop\Med\Medical> python -m venv .venv PS C:\Users\milto\Desktop\Med\Medical> python .\manage.py … -
How to remove port number from url in production server in django project?
I am deploying my project in production server but the port number is coming in the url. So is there any way to remove the port number from url in Django http://domain_name:8586/admin/login?next=/ -
django If don't have a model, Redirect to createview. If there is, I would like to do it in detail view
class KcalDetailView(DetailView): model = User context_object_name = 'target_kcal' template_name = 'kcalculatorapp/detail.html' def dispatch(self, request, *args, **kwargs): if not self.request.user.kcal: return HttpResponseRedirect(reverse('kcalculatorapp:create')) return super(KcalDetailView, self).dispatch(request, *args, **kwargs) If you go into the detail view, User has no kcal. error That's what it says What should I do? -
Getting error while creating hitting /admin endpoint
I am trying be build an Token Authentication using DRF AuthToken. I want my own customisation for USER model, and this is how I have done. Now I want to login into Django Admin Panel, but when I hit that endpoint I get an error django.db.utils.ProgrammingError: (1146, "Table 'roadmap.tutor_authuser' doesn't exist") and when I am trying to createsuperuser its asks for my email and after entering that I am getting same error. This is how my custom USER Model is, class AuthUser(AbstractUser): ADMIN = 'A' STUDENT = 'S' TUTOR = 'T' ROLE_CHOICES = ( (ADMIN, 'Superuser'), (STUDENT, 'Student'), (TUTOR, 'Tutor'), ) username = None first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) email = models.EmailField(max_length=254, unique=True) role = models.CharField(max_length=1, choices=ROLE_CHOICES, default=STUDENT) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] I also have done make migration and migrate successfully. And this is how my migration file looks like # Generated by Django 4.1 on 2022-08-09 04:40 import django.contrib.auth.models from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.CreateModel( name='Roadmap', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('course_name', models.CharField(max_length=255)), ('course_title', models.CharField(max_length=255)), ('course_description', models.TextField()), ], ), migrations.CreateModel( name='Section', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, … -
How can I display the added Friends to their respective user friends list?
I am developing a feature same like Facebook. means a user can send a friend request and then that specific user will accept the friend request. so it means they both become friends with each other. Now how can I display them in such a way that user A is a friend of User B and vice versa? That's how I have developed it but can't display both of the users in the friend's list. models.py: class AddToNetwork(models.Model): NETWORK_CHOICES = ( ('ADD', 'Add'), ('ACCEPT', 'Accept'), ('DELETE', 'Delete'), ) id = models.UUIDField( primary_key = True, default = uuid.uuid4,editable = False) add_to = models.ForeignKey(User, on_delete=models.CASCADE, related_name="add_to", null=True, blank=True) added_from = models.ForeignKey(User, on_delete=models.CASCADE, related_name="add_from", null=True, blank=True) network_status = models.CharField(max_length=30, choices = NETWORK_CHOICES) added_at = models.DateTimeField(auto_now_add = True) deleted_at = models.DateTimeField(auto_now = True) def __str__(self): return str(self.add_to) Sending a friend request using the following method/logic: def addToNetwork(request, id): try: add_to = User.objects.get(id = id) current_user = User.objects.get(id = request.user.id) network = AddToNetwork.objects.create(add_to = add_to, added_from=current_user,network_status = 'ADD') messages.success(request,f'Request Sent to {add_to.first_name} {add_to.last_name}') return redirect('userProfileDetail', id) except User.DoesNotExist: add_to = None return render(request,'network/network_userProfile.html') Accepting a friend request using the following logic: def acceptNetworkRequest(request, id): try: # if 'accept_friendRequest' in request.GET: friend_request = AddToNetwork.objects.get(id = id) … -
Getting django.db.utils.DatabaseError
I am using Django==3.1.9 with djongo==1.3.6. When saving user in database I am getting django.db.utils.DatabaseError. I think the issue is with the model file. I have forked the code from GitHub which uses Postgres DB. I have only changed the DB configuration to mongo in settings.py Here is the error log Internal Server Error: /signup/ Traceback (most recent call last): File "C:\Users\webde\Work\Fintract\fraudify_sso\venv\lib\site-packages\djongo\sql2mongo\query.py", line 857, in parse return handler(self, statement) File "C:\Users\webde\Work\Fintract\fraudify_sso\venv\lib\site-packages\djongo\sql2mongo\query.py", line 929, in _insert query.execute() File "C:\Users\webde\Work\Fintract\fraudify_sso\venv\lib\site-packages\djongo\sql2mongo\query.py", line 397, in execute res = self.db[self.left_table].insert_many(docs, ordered=False) File "C:\Users\webde\Work\Fintract\fraudify_sso\venv\lib\site-packages\pymongo\collection.py", line 770, in insert_many blk.execute(write_concern, session=session) File "C:\Users\webde\Work\Fintract\fraudify_sso\venv\lib\site-packages\pymongo\bulk.py", line 533, in execute return self.execute_command(generator, write_concern, session) File "C:\Users\webde\Work\Fintract\fraudify_sso\venv\lib\site-packages\pymongo\bulk.py", line 366, in execute_command _raise_bulk_write_error(full_result) File "C:\Users\webde\Work\Fintract\fraudify_sso\venv\lib\site-packages\pymongo\bulk.py", line 140, in _raise_bulk_write_error raise BulkWriteError(full_result) pymongo.errors.BulkWriteError: batch op errors occurred, full error: {'writeErrors': [{'index': 0, 'code': 11000, 'keyPattern': {'admin_org_id': 1}, 'keyValue': {'admin_org_id': None}, 'errmsg': 'E11000 duplicate key error collection: ssoDB.users_user index: admin_org_id_1 dup key: { admin_org_id: null }', 'op': {'password': 'pbkdf2_sha256$216000$bbg7CWLFi44A$69XZYjuc/T1Unv0f7QXrTRTURDbPT+HhT8A2AH+WE14=', 'last_login': None, 'is_superuser': False, 'id': UUID('a9a2b67b-fb63-4b55-b889-f24676949fa6'), 'email': 'testuser@vigastudios.com', 'avatar': '', 'first_name': 'Abhijit', 'last_name': None, 'nickname': None, 'phone_number': '+919083242266', 'organization_id': None, 'admin_org_id': None, 'is_active': True, 'is_staff': False, 'created_at': datetime.datetime(2022, 8, 9, 5, 9, 37, 236707), '_id': ObjectId('62f1ec11e10c9c015b52dbd6')}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': … -
UNIQUE constraint failed: Worked before now it doesn't
I was trying to create a function that programmatically adds owners to lots based on data from a csv file. It was functional before before but now it displays a UNIQUE constraint failed: valuation_lot.lot_number This is the code from which the error was raised. Please let me know if more information is needed. try: lot_new = Lot.objects.get(pk=lot["lot_number"][index]) lot_new.owner.add(owner_new) lot_new.save() except: lot_new = Lot.objects.create( lot_number=lot["lot_number"][index], lot_description= lot["lot_description"][index], lot_rate = Decimal(float(lot['lot_rate'][index])), ) lot_new.owner.add(owner_new) lot_new.save() -
Slack Login With DJango
I want to implement slack login with django and to do that i am using Django Allouth package but i am facing an error -
How to calculates face recognition distance in VGGFace
I am also interested in facial recognition. I am working on Using VGGFace for Face Recognition. I try to find 2 or 3 people who are similar to that person and what percentage of them are accurate. I'm new to dating.i am use this link https://www.codemag.com/Article/2205081/Implementing-Face-Recognition-Using-Deep-Learning-and-Support-Vector-Machines -
How to go implement custom user Token authentication in DRF?
I am trying to do user Token authentication using DRF and I have done that succesfully, but for default USER Model of django , I am want to properly configure the fields in that like I dont want username and wanna make email & password for login and wanna add more fields like first_name and last_name during signup process. I want to add one more field which will say whether this is a student or teacher or a superuser. during signup the data will get stored accordingly. -
Is there a way to pass in an Form Object in an authenticate method in django
I am trying to pass in an form object in an authenticate() method but it is saying there is no attribute for username and password. Is there a specific way I can authenticate this form or not. I have imported everything already from forms and auth.models MY VIEWS.PY def user_login(request): if request.method == 'POST': login_info = LoginForm(request.POST) user = authenticate(username = login_info.username, password=login_info.password) if user: login(request,user) return HttpResponse(reversed('index')) else: return HttpResponse("Wrong") else: login_info = LoginForm() return render(request,"login.html",{'logininfo':login_info}) MY FORMS.PY class LoginForm(forms.Form): username = forms.CharField(label = 'Your username') password = forms.CharField(label= "Don't tell any but us",widget=forms.PasswordInput()) IS there a different way user = authenticate(username = login_info.username, password=login_info.password) -
How to save two values from options in Django?
Am trying to save dropdown in django without using django forms am directly getting the form values to views. This is my view: try: courses = Course.objects.all() except ObjectDoesNotExist: courses = None form = WelcomeForm() if request.method == 'POST': form = WelcomeForm(request.POST) if form.is_valid(): _process = form.save(commit=False) _process.save() messages.success(request, 'Welcome settings has been added successfully') context = {'courses': courses} return render(request, 'welcome/add_form.html', context) And thus, using courses in my dropdown: <select class="form-select" data-search="on"name="courses" multiple> <option></option> {% for data in courses %} <option value="{{data.name}}">{{data.name}}</option> {% endfor %} </select> From the above, i can save name of the course, but i also need slug of the course to make user clickable ! HOw to save two values from the selected options ? -
Navbar get a ValueError
my nav bar: <form method = "POST">{% csrf_token %} <button class="navbar-brand", name = "next",value="next", href="/app/{{ app.id }}/start/begin">Next</a> </form> my def: def view2(request, app_id): index=0 pdict = {1:2} adict = {1: 'start'} if request.method == 'GET': app = Application.objects.get(id=app_id) ac_id = list(adict.keys())[index] p_id = pdict[anode_id] return show(request=request,app_id=app_id,p_id=p_id) else: if request.POST.get("next"): index += 1 ac_id = list(adict.keys())[index] page_id = pdict[anode_id] request.method ='GET' return show(request=request,app_id=app_id,p_id=p_id) if i press next it gives me a ValueError:didn't return an HttpResponse object. It returned None instead. How can i solve this problem? -
Django Frontend Autho key and refresh key
I would like to separate my Django frontend and backend. Literally creating 2 Django servers. What is the best way to store auth access-token and refresh-token on frontend? What is the best way to validate auth when API is called? Thanks! -
django-filter don't use rawqueryset
i have a sql, SELECT asset.id, region.id as region_id, asset.ip, asset.os_type, asset.status, asset.device_type_id FROM region_info AS region JOIN computer_info AS computer ON region.id = computer.region_id JOIN computer_cabinet_info AS cabinet ON computer.id = cabinet.computer_id JOIN asset_location_info AS location ON cabinet.id = location.cabinet_id JOIN asset_server_info AS asset ON location.asset_id = COALESCE ( asset.parent_id, asset.id ) WHERE asset.del_flag = 0 i can't use django orm, so i use raw sql. but django-filter must use queryset,because rawqueryset no .all() method. this is my viewset: from rest_framework.viewsets import GenericViewSet from rest_framework.mixins import ListModelMixin class RegionAssetViewSet(ListModelMixin, GenericViewSet): serializer_class = AssetServerInfoSerializer filter_backends = [DjangoFilterBackend] filter_class = ServerFilter def get_queryset(self): queryset = RegionAssetListVirtual.objects.raw(region_asset_sql) return queryset Can someone help me. -
Django error NoReverseMatch on remote site but works fine locally
My Django site is working fine locally. I am pushing it to my website but one of the links is not working and I can not for the life of me see why as similar things are working fine. here is my url.py from . import views app_name = 'sitepages' urlpatterns = [ path('', views.greeting_page_def, name='greeting_page_html'), path('home/', views.home_def, name='home_html'), path('specs/', views.specs_def, name='specs_html'), path('about/', views.about_def, name='about_name'), path('faq/', views.faq_def, name='faq_name'), path('howTos/', views.howTos_def, name='howTos_name'), path('howTos/puller', views.howTosPuller_def, name='howTosPuller_name'), path('howTos/conformer', views.howTosConformer_def, name='howTosConformer_name'), path('howTos/general', views.howTosGeneral_def, name='howTosGeneral_name'), path('howTos/submitter', views.howTosSubmitter_def, name='howTosSubmitter_name'), ] and my views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required # Create your views here. def greeting_page_def(request): return render(request, 'sitepages/greeting_page_html.html') def about_def(request): return render(request, 'sitepages/about.html') def faq_def(request): return render(request, 'sitepages/faq.html') def home_def(request): return render(request, 'sitepages/home.html') def specs_def(request): return render(request, 'sitepages/specs.html') def howTos_def(request): return render(request, 'sitepages/howTos.html') def howTosPuller_def(request): return render(request, 'sitepages/howTosPuller.html') def howTosConformer_def(request): return render(request, 'sitepages/howTosConformer.html') def howTosGeneral_def(request): return render(request, 'sitepages/howTosGeneral.html') def howTosSubmitter_def(request): return render(request, 'sitepages/howTosSubmitter.html') and the html template that has the links. {% extends 'base.html' %} {% block content %} {% load static %} <a class="link-primary" href="{% url 'sitepages:howTosPuller_name' %}"} >How Tos - Puller</a> <a class="link-primary" href="{% url 'sitepages:howTosSubmitter_name' %}"} >How Tos - Submitter</a> <a class="link-primary" href="{% url 'sitepages:howTosGeneral_name' %}"} >How Tos - General</a> … -
Problem with Django and MySQL. NotSupportedError( django.db.utils.NotSupportedError: MariaDB 10.3 or later is required (found 5.5.65)
I'm using Django for a project with MySQL. I created a virtual environment and installed mysqlclient to connect to the database. But when I try to start the server I get this error. Here's is my version of MariaDB, I installed using Homebrew. And finally the version of mysqlclient in my virtual environment: -
Pymongo Not inserting full document on update_one
I have a lot of documents to update and I want to write a timestamp initially and then an update timestamp when there are duplicates. So I found this answer and am attempting it for MongoDB 6.0 https://stackoverflow.com/a/17533368/3300927 I also store in my model the variable to use when looking for duplicates as searchable If a query has no searchable then I insert it without checking and add a timestamp, then take the results and add a timestamp: data_inserted = collection.insert_many(results) for doc_id in data_inserted.inserted_ids: collection.update_many( filter={'_id': doc_id}, update={'$set': {'insert_date': now, }, }, upsert=True) No issues there: { "_id": { "$oid": "321654987654" }, "IR NUMBER": "ABC784", "Plate": " ", "Plate State": " ", "Make": "TOYOTA", "Model": "TACOMA", "Style": " ", "Color": "SIL / ", "Year": "2008", "insert_date": { "$date": { "$numberLong": "1660000808176" } } } If there is a searchable I attempt to look for it. What I get in MongoDB is only the searchable field with the timestamp: # q_statement.searchable == 'IR NUMBER' for document in results: collection.update_one( filter={q_statement.searchable: document[q_statement.searchable], }, update={'$setOnInsert': {'insert_date': now, }, '$set': {'update_date': now, }}, upsert=True) result: { "_id": { "$oid": "62f19d981aa321654987" }, "IR NUMBER": "ABC784", "insert_date": { "$date": { "$numberLong": "1660001688126" } } } …