Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django logging missing while testing through the interactive shell
We added the below to show the SQL queries on the console. And, as a proof of concept, we are following the online tutorial to build a testing project. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django.db.backends': { 'level': 'DEBUG', 'handlers': ['console'], } }, } At the step of "Explore the free admin functionality", for example, the console SQL logging works as exacted. So, when clicking on the button, we see sample SQL logs like attached below. However, when using the interactive shell through the command python manage.py shell, and calling python commands like Choice.objects.filter(question__pub_date__year=current_year), we did not see any SQL log. We wonder if we missed anything for the backend logging on the interactive shell. We are testing with Django v3.1.4 and Python v3.7.6. Just let us know if you need more details. Sample Django backend logging records: ... (0.000) SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."expire_date" > '2022-11-21 23:03:45.762894' AND "django_session"."session_key" = 'dd9uy7q873cijz0603l5uu9zl3wujr2f') LIMIT 21; args=('2022-11-21 23:03:45.762894', 'dd9uy7q873cijz0603l5uu9zl3wujr2f') (0.000) SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = 1 LIMIT 21; args=(1,) (0.000) BEGIN; args=None (0.000) SELECT … -
UnboundLocalError - local variable 'emprendedores' referenced before assignment
I can't figure out why am I getting this error message: "UnboundLocalError - local variable 'emprendedores' referenced before assignment" enter image description here Hey fellows, i'm building an app in Django and almost is pretty well. However, I cannot find solution to a problem in my search view. The main idea is allowing the user to indicate the word and to select the desired fields to search into from an form, and returning the registered users that satisfy the criteria. The html file looks like this: enter image description here This is the model: enter image description here and this is the view I'm working on: enter image description here But I can't figure out why am I getting this error message: "UnboundLocalError - local variable 'emprendedores' referenced before assignment" enter image description here I'll be glad if someone can help my out. -
Django login fails because of too many redirect
I have a pretty basic instance of a Django app serving an hybrid React app. I wanted to protected this app behind a login using the default authentification module of Django but when I try to access the app on http://127.0.0.1:8000/ I get redirected to: http://127.0.0.1:8000/accounts/login/?next=/accounts/login/%3Fnext%3D/accounts/login/%253Fnext%253D/accounts/login/%25253Fnext%25253D/accounts/login/[...] And the browser display ERR_TOO_MANY_REDIRECTS. Python 3.11.0 Django 4.1.3 config/urls.py from django.contrib import admin from django.urls import include, path from rest_framework import routers from maapi import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('routers/', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('api/', include('maapi.urls')), path('', include('frontend.urls')), ] frontend/urls.py from django.urls import path from . import views urlpatterns = [ path(r'', views.ReactAppView.as_view(), name='react_app'), path(r'<path:path>', views.ReactAppView.as_view(), name='react_app_with_path'), ] frontend/views.py from django.views.generic import TemplateView from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required # Create your views here. @method_decorator(login_required, name='dispatch') class ReactAppView(TemplateView): template_name = 'app.html' # Get url parameter (Note that removing this doesn't solve the issue) def get_context_data(self, **kwargs): return {'context_variable': 'value'} Can you identify what is wrong or point me to what to test? Thank you. -
Python calling a property from inside a class
I'm trying to call the property protocolo on a new imagefield's upload_to argument What I'm trying to accomplish is to have the saved images use a custom filename. class biopsia(models.Model): paciente = models.CharField(max_length=50) creado = models.DateTimeField(auto_now_add=True) foto = models.ImageField(upload_to=f'fotos_biopsias/%Y/{*protocolo*}', blank=True) def __str__(self): return str(self.protocolo) @property def protocolo(self): return 'BIO' + str(self.creado.year) + '-' + str(biopsia._base_manager.filter( creado__year=self.creado.year, creado__lt=self.creado ).count() + 1) File "C:\Users\LBM\Documents\virtualenviorements\clinico\biopsia\models.py", line 30, in biopsia foto = models.ImageField(upload_to=f'fotos_biopsias/%Y/{protocolo}', blank=True) NameError: name 'protocolo' is not defined* I've tried defining an outside method for upload_to but still I cannot use it inside my class -
How to skip if empty item in column in Django DB
I;m new to learning Django and ran into a small issue: I'm working on a product display page where some products are in a subcategory. I want to be able to display this subcategory when needed but I do not want it to show up when unused. Right now it will show up on my page as 'NONE' which I do not want. How do I fix this? My model looks like this: class Category(models.Model): category_name = models.CharField(max_length=200) sub_category = models.CharField(max_length=200,blank=True,null=True) On my webpage I use the {{category}} in a for loop to display the different categories. Unfortunately is shows 'NONE' when there is no subcategory. -
Form Submitting with Jquery in Django
I wanna submitting form with jquery append. But it doesn't work. I am adding fields but when i click the submit, only original fields sent. Duplicate fields not sending. How can i fix this. And also when i delete the fields, it only delete one field instead of three fields. first image is original fields. Seconda image is clone the fields with jquery Third is datas which are sent with form Here is my codes... models.py from django.db import models # Create your models here. class Contact(models.Model): full_name=models.CharField(max_length=100) email=models.CharField(max_length=200) mesaj=models.CharField(max_length=200) def __str__(self): return self.full_name views.py from django.shortcuts import render from .models import Contact #from django.contrib import messages # Create your views here. def contact(request): if request.method=='POST': full_name=request.POST['full_name'] email=request.POST['email'] mesaj=request.POST['mesaj'] contact=Contact.objects.create(full_name=full_name,email=email,mesaj=mesaj) # messages.success(request,'Data has been submitted') return render(request,'contact.html') contact.html <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> </head> <body> <div class="input_fields_wrap"> <form method="post" action=""> {% csrf_token %} <input type="text" name="full_name" class="field-long" /> <input type="text" name="email" class="field-long" /> <input type="text" name="mesaj" class="field-long" /> <button type="button" class="add_field_button">Add Field</button> <button type="button" class="remove_field_button">Remove Field</button> </div><input type="submit" value="Submit" /></form> </body> <script> var max_fields = 10; var wrapper = $(".input_fields_wrap"); var add_button = $(".add_field_button"); var remove_button = $(".remove_field_button"); $(add_button).click(function(e){ e.preventDefault(); var total_fields = wrapper[0].childNodes.length; if(total_fields < max_fields){ $(wrapper).append('<input type="text" name="full_name" class="field-long" … -
Hi! I need help. I'm trying to figure it out how I can do this and I'm getting frustrated because I know that it will be solve with just little thing
I explain: I have two models called Diagram and Parts respectability. manage.py This is my Diagram Model: from django.db import models import random, string def id_generator(size=10, chars=string.digits): return ''.join(random.choice(chars) for _ in range(size)) class Diagram(models.Model): fuel_type_choices = [('liquid_propane', 'L.P.'), ('natural_gas','N.G.'),] item_type_choices = [ ('conversion_kits','CONVERSION KITS'), ('griddle_parts','GRIDDLE PARTS'), ('grill_parts','GRILL PARTS'), ('kegorator_parts','KEGORATOR PARTS'), ('outdoor_kitchen_parts','OUTDOOR KITCHEN PARTS'), ('pizza_oven_parts','PIZZA OVEN PARTS'), ('power_burner_parts','POWER BURNER PARTS'), ('refrigerator_parts','REFRIGERATOR PARTS'), ('rotisserie_parts','ROTISSERIE PARTS'), ('searing_station_parts','SEARING STATION PARTS'), ] diagram_id = models.CharField(primary_key=True, max_length = 10, blank = True, unique = True) mpn = models.CharField(max_length = 50, blank = False, unique=True) model = models.CharField(max_length = 50, blank = False) name = models.CharField(max_length = 500, blank = False) image = models.ImageField(upload_to = 'img/diagrams/') number_of_references = models.IntegerField(null=True, blank=False) fuel_type = models.CharField(max_length = 15, choices = fuel_type_choices, default = False) item_type = models.CharField(max_length = 25, choices = item_type_choices, default = False) map_area = models.TextField(null=True) def save(self): if not self.diagram_id: # Generate ID once, then check the db. If exists, keep trying. self.diagram_id = id_generator() while Diagram.objects.filter(diagram_id=self.diagram_id).exists(): self.diagram_id = id_generator() super(Diagram, self).save() def __str__(self): return self.name And this is my Part Model: from django.db import models import random, string def id_generator(size=10, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) class Part(models.Model): warranty_choices = ( ('0','0'), … -
How to implement a user customizable and personalized dashboard with django
I've created a django website with user accounts and a database containing data and I would like each user to be able to create their own personalized dashboard to view only the data that they care about. How can this be implemented where each dashboard is connected to the specific user that created it? My question is a little vague because I don't know how to implement a feature that is created by a user, is viewable only by that user, and is persistent. Any help or guidance would be much appreciated! I haven't tried anything yet because I don't know how to get started. Online search results are things like creating a custom admin dashboard or a dashboard that is shared across all users, which is not what I'm looking for. -
Problem with redirecting to login page after successful authorization in django-microsoft-auth
I am using django-microsoft-auth to log in with Microsoft account. The problem I am facing is that I want to use it in my login.html and I've managed to add this button to my html, however it redirects me to admin page. My URL that I added in Azure is default one: https://<mydomain_name>.com/microsoft/auth-callback/ I found this solution on Stackoverflow but it requires changing URL on Azure AD. Is there any other way to change reditect from /admin to /home other than changing URL in Azure AD? I was thinking if I could change it somehow directly in library. -
django does not load CSS file in HTML-file which extends from "base.html"
I have a base.html which my options.html extends from like this //options.html {% extends "webpage/base.html" %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'webpage/options.css' %}"> {% block content %} <div class="test"> foo </div> {% endblock content %} //base.html {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'webpage/base.css' %}"> <!-- jQuery--> <script src="https://code.jquery.com/jquery-3.6.1.slim.js" integrity="sha256-tXm+sa1uzsbFnbXt8GJqsgi2Tw+m4BLGDof6eUPjbtk=" crossorigin="anonymous"></script> <title>:)</title> </head> <body> hello world {% block content %} {% endblock content %} <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </body> </html> the issue is that the CSS is not loaded/applied. In the web-console (when I run python manage.py runserver) and go to the "options" page, then I can see that the webpage/base.css is loaded (i.e GET /static/webpage/base.css is printed), but the webpage/options.css is not. I thought I had something wrong in the static- path, but if I move the <link rel="stylesheet" type="text/css" href="{% static 'webpage/options.css' %}"> into my base.html(and go to my home page) then I see that GET … -
Django - ModelForm(request.POST) is not valid (field with default value is required)
Trying to test ModelForm by passing request.POST in it. The Model has created field with default value defined: created = DateTimeField(default=timezone.now) which works correctly when submitting the form manually in the admin interface. In unit tests, when I test it, it says that created is required: request = HttpRequest() request.POST = { "somefield": "value", } form = ModelForm(request.POST) self.assertTrue(form.is_valid()) Apparently, form.errors contains created: <ul class="errorlist"><li>This field is required.</li></ul> Why and how to fix it? -
How to run external python file in html
I want to use my html file to take user input and then I want to use my python program to process my input and then I want my html shows the answer HTML Part ` {% extends 'base.html' %} {% block title %}Home{% endblock title %}Home {% block body %} <style> #body { padding-left:100px; padding-top:10px; } </style> <div id="body"> <br> <marquee width="750px"> <h4>My name is ChatXBot. I'm your Childs Friend. Talk to me. If you want to exit, type Bye!</h4> </marquee> <br> <form action="/external" method="post"> {% csrf_token %} <textarea id="askchat" name="askchat" rows="10" cols="100" placeholder="Start Typing Here" required></textarea> {{data_external}}<br><br> {{data1}} <br> <input class="btn btn-secondary btn-lg" type="submit" value="Ask"> </form> </div> {% endblock body %} ` Python part ` #importing the neccesary libraries import nltk import numpy as np import random import string # to process standard python strings nltk.download('omw-1.4') #wow.txt is text collected from https://en.wikipedia.org/wiki/Pediatricsn f=open('F:\Ayan\WORK STATION (III)\Python\Python Project\chatbot.txt','r',errors = 'ignore') raw = f.read() raw=raw.lower()# converts to lowercase nltk.download('punkt') # first-time use only nltk.download('wordnet') # first-time use only sent_tokens = nltk.sent_tokenize(raw)# converts to list of sentences word_tokens = nltk.word_tokenize(raw)# converts to list of word sent_tokens[:2] word_tokens[:2] lemmer = nltk.stem.WordNetLemmatizer() #WordNet is a semantically-oriented dictionary of English included in NLTK. def LemTokens(tokens): … -
How to Test ValidationError in a function using assertRaises()
I found this assertRaises() for testing validators in pytest but I am not able to use it in my test function because all examples use classes. Every example I found use self.assertRaises() but I cannot use self. Examples I've tried to understand: Testing for a ValidationError in Django How to correctly use assertRaises in Django model.py - model I am testing for validators ` class AdTextTemplate(models.Model): adtext_template_headline_1 = models.CharField(max_length=270, validators=[headline_with_keyword_validation]) adtext_template_headline_2 = models.CharField(max_length=270, validators=[headline_with_keyword_validation]) adtext_template_description_1 = models.CharField(max_length=810, validators=[description_with_keyword_validation]) adtext_template_description_2 = models.CharField(max_length=810, validators=[description_with_keyword_validation]) campaign = models.ManyToManyField(Campaign, blank=True) conftest.py @pytest.fixture def campaigns(users): lst = [] for user in users: lst.append(Campaign.objects.create(campaign_name='test_campaign', user=user)) return lst @pytest.fixture def adtext_templates_headline_exceed_char_limit(campaigns): lst = [] for campaign in campaigns: x = AdTextTemplate.objects.create( adtext_template_headline_1='test template headline1 that have 41char', adtext_template_headline_2='test template headline2 that have 41char', adtext_template_description_1='test template description 1', adtext_template_description_2='test template description 2', ) x.campaign.add(campaign) lst.append(x) return lst tests.py @pytest.mark.django_db def test_validation_error(adtext_templates_headline_exceed_char_limit): adtext_template = adtext_templates_headline_exceed_char_limit[0] with adtext_template.assertRaises(ValidationError): assert adtext_template.full_clean() I know that the part adtext_template.assertRaises() is not good because there suppose to be self.assertRaises(ValidationError) but my test is not a class. I would like it to stay that way because my mentor said that data for testing should be in fixtures in conftest.py and tests should be in test … -
django.urls.exceptions.NoReverseMatch URLS path seem to be correct
Normally this would be a simple problem to solve and perhaps I'm missing something very basic. But I have been pounding my head against this problem all morning. I receive the error message: django.urls.exceptions.NoReverseMatch: Reverse for 'journalrep' with arguments '('',)' not found. 2 pattern(s) tried: ['reports/journalrep/(?P<column>[^/]+)/(?P<direction>[^/]+)\\Z', 'reports/journalrep/\\Z'] I the debug log of my application. My urls.py contains: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='reports'), path('sumlist/', views.summary_list,name='sumlist'), path('overallsummary',views.overallsummary,name='overallsummary'), path('checkreg', views.checkreg, name='checkreg'), path('checkdet/<chkno>/', views.checkdet, name='checkdet'), path('journalrep/', views.journalrep, name='journalrep'), path('journalrep/<column>/<direction>', views.journalrep, name='journalrep'), path('journaldet/<tranid>', views.journaldet, name='journaldet'), path('accountrep', views.accountrep, name='accountrep') ] The view that renders the template is a function view: @login_required def journalrep(request,column = 'date', direction = 'D'): ''' Produce journal register Will display information for a chart of accounts account if provided. If the value is 0 all journal entries will be shown ''' # # Get list of accounts (Chart of acconts) to be used for account selection box coa = ChartOfAccounts.objects.all().filter(COA_account__gt=0) coa_account = request.session.get('coa_account', None) if len(request.GET) != 0: coa_account = request.GET.get('coa_account') else: if coa_account == None: coa_account = '0' if direction == 'D': direction = '-' else: direction = "" if coa_account == '0': journal = Journal.objects.all().order_by(direction + column) else: journal = Journal.objects.filter(account__COA_account … -
django python ajax java script html
Hello every one , my problem is in django and ajax i want to use two block one for django and the other for ajax but the ajax code is not reading , why ? {% extends 'store/main.html' %} {% load static %} {% block content %} // code html {% endblock content_ajax %}` block content_ajax your text%} //code ajax {% endblock content_ajax %}` # -
How to do a costum SQL Query in Django
I have an external database wich is registered in the settings.py. No I want query some information. But it doesn't work. In the Terminal I can see that the query doesn`t start. I hope you can help me. view.py from django.db import connections def userquery(request): currentuser = request.user userinfoquery = "SELECT * FROM 'userinformation' WHERE 'username' = %s", [currentuser] with connections['mysql-server'].cursor() as cursor: cursor.execute(userinfoquery) userdata = cursor.fetchall() return render(request,'account_settings.html', {'userdata' : userdata}) call in html-file <label>{{userdata.name}}</label> -
some import in the project get error separated by newlines or semicolons
so i have many import in django project. suddenly, the import got red mark (like error sign) but i don't change anything. can someone fix it so it's not detect as error? i want to fix the error, so the color code can be appear again -
bad request 400 on POST request (Django React and axios)
I have a problem with Bad Reqauest 400 when trying to register new user in my app. I am using Django 4 and React 18. I've set up CORS headers and I added localhost:3000. I also checked login and it works fine. I have a problem with registration. I am new to React and I am not sure what is wrong with the code. When I check comsole I get the following error: my django files are below: serializers.py class UserRegistrationSerializer(serializers.ModelSerializer): # Confirm password field in our Registration Request password2 = serializers.CharField(style={'input_type':'password'}) class Meta: model = User fields=['email', 'password', 'password2'] extra_kwargs={ 'password':{'write_only':True} } # Validating Password and Confirm Password while Registration def validate(self, attrs): password = attrs.get('password') password2 = attrs.get('password2') if password != password2: raise serializers.ValidationError("Password and Confirm Password doesn't match") return attrs def create(self, validate_data): return User.objects.create_user(**validate_data) views.py def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } class UserRegistrationView(APIView): renderer_classes = [UserRenderer] def post(self, request): serializer = UserRegistrationSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() token = get_tokens_for_user(user) return Response({'token':token, 'msg':'Registration Successful'}, status=status.HTTP_201_CREATED) my react files are below: client.js import config from './config'; import jwtDecode from 'jwt-decode'; import * as moment from 'moment'; const axios = require('axios'); class DjangoAPIClient … -
How to combine two forms with one submit?
I have two forms and one submit button. But the content is only showing in one textbox. And if I try to upload a file with the second form. There is no output. SO I have the template like this: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="{% static 'main/css/custom-style.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'main/css/bootstrap.css' %}" /> </head> <body> <div class="container center"> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" action="/controlepunt140" method="POST" enctype="multipart/form-data"> <div class="d-grid gap-3"> <div class="form-group"> {% csrf_token %} {{ pdf_form }} </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="content" cols="70" rows="25"> {{content}}</textarea> </div> </div> </div> <div class="d-grid gap-3"> <div class="form-group"> {% csrf_token %} {{ excel_form }} </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="content.excel" cols="70" rows="25"> {{content.excel}} </textarea> </div> </div> </div> <button type="submit" name="form_pdf" class="btn btn-warning">Upload!</button> </form> </div> </span> </div> </body> </html> and the views.py: lass ReadingFile(View): def get(self, *args, **kwargs): pdf_form = UploadFileForm() excel_form = ExcelForm() return render(self.request, "main/controle_punt140.html", { 'pdf_form': pdf_form, "excel_form": excel_form }) def post(self, *args, **kwargs): pdf_form = UploadFileForm( self.request.POST, self.request.FILES) excel_form = ExcelForm( self.request.POST, self.request.FILES) content = '' content_excel = '' if pdf_form.is_valid() and … -
How to merge two queryset on specific column
Hello I am using a postgres database on my django app. I have this model: class MyFile(models.Model): uuid = models.UUIDField( default=python_uuid.uuid4, editable=False, unique=True) file = models.FileField(upload_to=upload_to, null=True, blank=True) path = models.CharField(max_length=200) status = models.ManyToManyField(Device, through='FileStatus') user = models.ForeignKey('users.User', on_delete=models.SET_NULL, null=True, blank=True) when = models.DateTimeField(auto_now_add=True) canceled = models.BooleanField(default=False) group = models.UUIDField( default=python_uuid.uuid4, editable=False) What I want is to group my MyFile by group, get all the data + a list of file associated to it. I managed to get a group associated to a list of file with MyFile.objects.all().values('group').annotate(file=ArrayAgg('file', ordering='-when')) which is giving me a result like: [{'group': 'toto', 'file':['file1', file2']}, ...] I can also get all my MyFile data with: MyFile.objects.all().distinct('group') What I want is to get a result like: [{'group': 'toto', 'file':['file1', file2'], 'when': 'ok', 'path': 'ok', 'user': 'ok', 'status': [], canceled: False}, ...] So I fought I could merge my two queryset on the group column but this does not work. Any ideas ? -
FieldError: Invalid field name(s) given in select_related: 'posts'. Choices are: (none)
I am getting this error when using the method select_related. FieldError: Invalid field name(s) given in select_related: 'posts'. Choices are: (none) models.py class Group(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) class Meta: default_related_name = 'groups' class Post(models.Model): text = models.TextField() pub_date = models.DateTimeField(auto_now_add=True) group = models.ForeignKey( Group, blank=True, null=True, on_delete=models.SET_NULL, ) class Meta: default_related_name = 'posts' views.py class GroupPostView(DetailView): model = Group queryset = Group.objects.select_related('posts') # queryset = Group.objects.all() slug_field = 'slug' But if you use all(), then the request is successful and there is no error. -
Django model import from app to onether model
Good Day. Could you please give me a directie. I has extended basic User model and I need to import it to another app Django. Could you please explain me a bit how and there is my mistake.? models.py user extended model from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT) hb_photo = models.ImageField('User photo', default='incognito.png', upload_to='users/%Y/%m/%d/') hb_phone = models.CharField('Phone number', max_length=50, null=True) hb_department = models.CharField('Department name', max_length=50, null=True) def __str__(self): return f'User profiles {self.user.first_name} {self.user.last_name}' models.py there i truing to import User extendet model from higabase.members.models import Profile class NewPlacement(models.Model): np_nationality = CountryField('Nationality', null=True) np_coming_date = models.DateField('Coming date', null=True) ex_test_user = models.ForeignKey(User, on_delete=models.PROTECT) location = models.ForeignKey('FeelFlexLocation', on_delete=models.PROTECT) ff_hb_photo = models.ManyToManyField('User photo', default=Profile.hb_photo) ff_hb_phone = models.ManyToManyField('Phone number', default=Profile.hb_phone) ff_hb_department = models.ManyToManyField('Department name', default=Profile.hb_department) Then i truing to makemigrations. from higabase.members.models import Profile ModuleNotFoundError: No module named 'higabase.members' (venv) PS C:\Users\Feelflex\Desktop\TESTING2\higabase> I do not understend how i can fix it :( -
How to output fields to html template correctly from User model in Django ORM?
Task: Create a Django SQL query, pulling out only the required fields. Submit them to the template. I have a Post model with a foreign key to a standard User model: from django.db import models from django.contrib.auth.models import User class Post(models.Model): text = models.TextField() pub_date = models.DateTimeField("date published", auto_now_add=True) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="posts" ) Here is the required fragment in the HTML template, where you need to insert the author's name: {% for post in posts %} <h3> Author: {{ post.author.first_name }}, Date: {{ post.pub_date|date:'d M Y' }} </h3> view function: from django.shortcuts import render from .models import Post def index(request): latest = ( Post .objects .order_by('-pub_date')[:10] .select_related('author') .values('pub_date', 'author__first_name') ) return render(request, 'index.html', {'posts': latest}) Here's what the page fragment looks like on the local server: template And here is the final sql query shown by django debug toolbar: Query In the user table, I have one user and all posts are related to him. If I do not use .values in the view, then all the attributes of the author that I request in the template are displayed perfectly (for example, last_name, username, get_full_name()), but then sql requests all the fields of the user table (as … -
How to make html drag and drop only accept videos
I'm using this HTML code to upload video files to my website. <div class="container mt-5"> <div class="row d-flex justify-content-center"> <div class="col-md-6"> <form method="post" action="#" id="#"> {% csrf_token %} <div class="form-group files"> <label class="d-flex justify-content-center">Upload Your File </label> <input type="file" class="form-control" multiple="" accept="video/mp4,video/x-m4v,video/*"> </div> <div class="row row-cols-auto"> <div class="col mx-auto my-2"> <button class="btn btn-primary" type="submit">Upload</button> </div> </div> </form> </div> </div> </div> and this CSS .files input { outline: 2px dashed #92b0b3; outline-offset: -10px; -webkit-transition: outline-offset .15s ease-in-out, background-color .15s linear; transition: outline-offset .15s ease-in-out, background-color .15s linear; padding: 120px 0px 85px 35%; text-align: center !important; margin: 0; width: 100% !important; } .files input:focus{ outline: 2px dashed #92b0b3; outline-offset: -10px; -webkit-transition: outline-offset .15s ease-in-out, background-color .15s linear; transition: outline-offset .15s ease-in-out, background-color .15s linear; border:1px solid #92b0b3; } .files{ position:relative} .files:after { pointer-events: none; position: absolute; top: 60px; left: 0; width: 50px; right: 0; height: 56px; content: ""; background-image: url(https://image.flaticon.com/icons/png/128/109/109612.png); display: block; margin: 0 auto; background-size: 100%; background-repeat: no-repeat; } .color input{ background-color:#f1f1f1;} .files:before { position: absolute; bottom: 10px; left: 0; pointer-events: none; width: 100%; right: 0; height: 57px; content: " or drag it here. "; display: block; margin: 0 auto; color: #2ea591; font-weight: 600; text-transform: capitalize; text-align: center; } when I … -
django.template.exceptions.TemplateSyntaxError: 'bootstrap_field' received some positional argument(s) after some keyword argument(s)
i was trying to modify my django sign_in template with bootstrap field along with some arguments but i was not able too ` i was trying to modify my django sign_in template with bootstrap field along with some arguments but i was not able tooC:\Users\hp\Desktop\fastparcel\core\templates\sign_in.html, error at line 25 'bootstrap_field' received some positional argument(s) after some keyword argument(s) {% bootstrap_field form.username show_lable=False placeholder ="Email" %}` {% extends 'base.html' %} {% load bootstrap4 %} {% block content%} <div class="container-fluid mt-5"> <div class="justify-content-center"> <div class="col-lg-4"> <div class="card"> <div class="card-body"> <h4 class="text-center text-uppercase mb-3"> <b> {% if request.GET.next != '/courier/'%} Customer {% else %} Courier {% endif %} </b> </h4> <form action="POST"> {% csrf_token %} {% bootstrap_form_errors form %} {% bootstrap_label "Email" %} {% bootstrap_field form.username show_lable=False placeholder ="Email" %} {% bootstrap_field field form.password %} <button class="btn btn-warning btn-block "> Sign in</button> </form> </div> </div> </div> </div> </div> {% endblock %}