Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it necessary to use class based views in django with react-frontend application or we can work with functional view also for login authentication?
I have gone through a few tutorials on user authentication in a Django + React web app. All of them simply use class based views in Django for login backend with react frontend. Any suggestion to work with functional views? -
Issue when running manage.py runserver (Django)
I was about to run my colleague's Django project. She runs it in Apple Mac and I am about to run it in my Windows. In this scenario, I was running python manage.py runserver in my virtual environment as shown here. After that, it prompts a window indicating how to open the file like this instead of running the server. If the command is run correctly, it will show runs this. I am not sure what I am doing here. Is it because of the project was created in Mac? I did create a new virtual environment on my Windows, though everything is okay. Any help would be highly appreciated. Thank you. -
I want to understand what this code does, django we application [closed]
i want to know what exactly this code does during making webApp --models.py-- From django.db import models #1 From django.constrib.auth.models import User#2 Class Notes(models.Model): user = model.Foreignkey(User, on_delete=models.CASCADE) #3 -
models.UniqueConstraint doesn't raise an error when submitting the form
I am wondering why I am not getting an error when I submit a form where I've added a UniqueConstraint on two of the fields together; the data doesn't get submitted to the database (which is expected because of the constraint I've added to the model) and all that happens is that the same form is returned. I want some sort of indication under the Key Name field to say something like "Key Name already exists". Here is my code: In models.py class Meta: verbose_name = "Key Definition" constraints = [ models.UniqueConstraint(fields=['key_name', 'developer_email'], name='unique key names for each user') ] In forms.py class KeyDefinitionForm (BSModalModelForm) : ## code I have not included goes here ## def save(self): log.debug("ENTER: forms.KeyDefinitionForm.save") if self.request: instance = super(CreateUpdateAjaxMixin, self).save() log.debug("EXIT: forms.KeyDefinitionForm.save") return instance In views.py class KeyDefinitionView (BSModalCreateView) : """Class based view for key definition loading form.""" model = KeyDefinition form_class = KeyDefinitionForm template_name = 'generate_keys/keydef_add_modal.html' body_template_name = 'generate_keys/keydef_add_body.html' def get(self, request): log.debug("ENTER: views.KeyDefinitionView.get()") form = self.form_class( initial = { 'developer_email' : request.user.email, 'issue_date' : datetime.date.today(), 'HGE_TLS' : 'N', } ) data = { 'form' : form, } result = render(request, self.template_name, data) log.debug("EXIT: views.KeyDefinitionView.get()") return result def post(self, request, *args, **kwargs) : log.debug("ENTER: … -
Reverse lookup inside a queryset in django
I have three models in my Django app. # models.py class Membership(models.Model): field1 field2 class MembershipServiceDetails(models.Model): membership = models.ForeignKey(Membership, on_delete=models.CASCADE,related_name="msd_services") service = models.ForeignKey(Service,blank=True, null=True, on_delete=models.CASCADE) field3 class MembershipSubscriber(models.Model): membership = models.ForeignKey(Membership, blank=True, null=True, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, blank=True, null=True, on_delete=models.CASCADE) field4 Now I want to query the service data with customers details. But the models are related through Membership only. I'm trying something like this service_details = MembershipServiceDetails.objects.select_related('membership', 'service').annotate( service_data=F('membership').membershipsubscriber_set.first() ) Obviously it didn't work. How can this be achieved? Any help would be appreciated. -
getting error in user_profile form submition
I am getting error user_profile() got an unexpected keyword argument 'phoneNumber' Using the post method and trying to post data to the database but getting this error. model.py class user_profile(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE) phoneNumber=models.CharField( max_length=12, blank=True) name=models.CharField(max_length=100, blank=True) address=models.CharField(max_length=500,blank=True) user_profile.html {% extends 'firmApp/basic.html'%} {% block body%} <div class="row"> <div class="col-md-4"> <form action="/user_profile/" method="post" >{% csrf_token %} <div class="mb-3"> <label for="name" class="form-label">Full-Name</label> <input type="text" class="form-control" name="Name" > <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div> </div> <div class="mb-3"> <label for="address" class="form-label">Address</label> <input type="text" class="form-control" name="address"> </div> <div class="mb-3"> <label for="phoneNumber" class="form-label">Contact Number</label> <input type="text" class="form-control" name="phoneNumber"> </div> <div class="mb-3"> <label for="formFile" class="form-label">select image</label> <input class="form-control" type="file" name="formFile"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> {%endblock%} views.py def user_profile(request): if request.method=="POST": phoneNumber=request.POST.get('phoneNumber') name=request.POST.get('Name') address=request.POST.get('address') user=request.user print(user) profile=user_profile(phoneNumber=phoneNumber, name=name, address=address,user=user) profile.save() return render(request, "firmApp/blog/user_profile.html") I have checked the complete code but am unable to solve the issue. I am getting below error user_profile() got an unexpected keyword argument 'phoneNomber' -
I want to get data from JavaScript with Django
There is price filtering written in JavaScript in the template. I want to take the price range given in this filter with dajngo and write a filtering function. I couldn't because I don't know JavaScript. How will I do? So, i want to write a django function that takes the given start and end values and sorts the products accordingly. main.js // PRICE SLIDER var slider = document.getElementById('price-slider'); if (slider) { noUiSlider.create(slider, { start: [1, 100], connect: true, tooltips: [true, true], format: { to: function(value) { return value.toFixed(2) + '₼'; }, from: function(value) { return value } }, range: { 'min': 1, 'max': 100 } }); } -
How to access all the object in the params object in Django html template?
I have a function send a confirmation email template to user, the params on argument contains two object booking which is a Django object from DB and emails_text object which pulling from a json file and definitely I can access it when I print it import json with open('emails_text.json') as json_file: emails_text = json.load(json_file) my emails_text.json file { "booking_confirmation_email_template": { "title": "booking confirmation", xxxxx } } but the confirmation function can read the booking object but not the emails_text def preview_confirmation_email(self, request, object_id, **kwargs): params = { 'booking': Booking.objects.get(id=object_id), 'emails_text': emails_text['booking_confirmation_email_template'], } return HttpResponse(content=render_email_template('email/booking/confirmation.html', params)) my confirmation.html is as follow {% extends "email/sook_booking/temp_confirmation_base.html" %} {% load static %} {% load booking %} {% block title %}Booking Confirmation{% endblock %} xxxxxxxxx <h1 class="email-title">{{emails_text.title}}</h1> xxxxxxx -
Error with dj_rest_auth.jwt_auth.JWTCookieAuthentication
Everytime I run my server, I get this error on my terminal. I have tried researching about the cause but no luck with a response. This is the error below: CreateProfileView: could not resolve authenticator <class 'dj_rest_auth.jwt_auth.JWTCookieAuthentication'>. There was no OpenApiAuthenticationExtension registered for that class. Try creating one by subclassing it. Ignoring for now. This is my rest_framework settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'dj_rest_auth.jwt_auth.JWTCookieAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', } Thanks. -
how to calculate students total marks in django using total function and sort
model class from django.db import models class Student(models.Model): Name = models.CharField(max_length=50,) Roll_no = models.IntegerField(default = 0 , unique = True ) Emailid = models.EmailField(max_length=54 ) Submrk1 = models.PositiveIntegerField() Submrk2 = models.PositiveIntegerField() Submrk3 = models.PositiveIntegerField() Total = models.IntegerField(default = total) def __str__(self): return self.Name + self.Total def total(self): self.Total = self.Submrk1 + self.Submrk2 + self.Submrk3 return self.Total views from django.shortcuts import render , redirect from .models import Student from django.shortcuts import HttpResponseRedirect def liststu(request): student = Student.objects.all() return render(request, 'liststu.html',{'student': student}) def Createstu(request): if request.method == 'POST': name = request.POST.get('name') rollno = request.POST.get('rollno') email = request.POST.get('email') sub1 = request.POST.get('sub1') sub2 = request.POST.get('sub2') sub3 = request.POST.get('sub3') stu = Student.objects.create(Name = name,Roll_no = rollno, Emailid = email, Submrk1 = sub1, Submrk2 = sub2 , Submrk3 = sub3) return HttpResponseRedirect('list') else: return render(request, 'create.html') def sort(request): ctx = Student.objects.order_by('Total') return render(request, 'liststu.html' , {'student':ctx}) -
Django HTML image not found but path is correct
So i am creating a list with images but the image is not showing. This is my model: enter image description here This is my view: enter image description here And this is my directory: enter image description here I think it should work since the path is correct, but it is not working. -
AttributeError in django(Got AttributeError when attempting to get a value for field)
views: class ProductListView(APIView): def get (self,request): products = Product.objects.all() serializer = ProductSerializer(products,many=True, context={'request' : request}) return Response(serializer.data) serializer: class ProductSerializer(serializers.ModelSerializer): categories = CategorySerializer(many=True) file_set = ProductsFileSerializer(many=True) class Meta: model = Product fields = ('title','description','avatar','categories','file_set') model: class Product(models.Model): title = models.CharField(max_length=50) description = models.TextField(blank=True) avatar = models.ImageField(blank=True, upload_to="products/") is_enable = models.BooleanField(default=True) categories = models.ManyToManyField('Category' , verbose_name='categories' , blank=True ) class Meta: db_table = 'products' verbose_name = 'Product' verbose_name_plural = 'Products' def __str__(self): return self.title my error: Got AttributeError when attempting to get a value for field file_set on serializer ProductSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Product instance. Original exception text was: 'Product' object has no attribute 'file_set'. -
Rendering highest integer value from three models instances in django
I have three models which are related all to one model. class MyModelParent(models.Model): name = models.CharField(max_lenght=36, blank=True) def __str__(self): return self.name or "" class MyFirstModel(models.Model): mymodelparent = models.ForeignKey(MyModelParent, related_name="first_models", blank=True, Null=True, on_delete=models.CASCADE ranking = models.IntegerField(max_lenght=36, blank=True) def __str__(self): return self.name or "" class MySecondModel(models.Model): mymodelparent = models.ForeignKey(MyModelParent, related_name="second_models", blank=True, Null=True, on_delete=models.CASCADE ranking = models.IntegerField(max_lenght=36, blank=True) def __str__(self): return self.name or "" class MyThirdModel(models.Model): mymodelparent = models.ForeignKey(MyModelParent, related_name="third_models", blank=True, Null=True, on_delete=models.CASCADE ranking = models.IntegerField(max_lenght=36, blank=True) def __str__(self): return self.ranking or "" I am rendering MyParentModel in DetailView (CBV) and passing related models as a context to render individual models 'ranking' field on the same template. Now I need to render same 'ranking' on MyParentModel ListView, but I only want to display 'ranking' which has highest value. Question is, how I can compare my related models 'ranking integer value' and display highest on MyParentModel ListView page? I am on learning curve so appreciate your help... -
Trying to get a Google maps to display in Django
I wondered if anyone has managed to get Google maps working within a Django project and if so, could they tell me what I may be doing wrong. In base.html, I have the following scripts at the end of the body : <script src="{% static '/js/script.js' %}" ></script> <script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script> <script async defer src=https://maps.googleapis.com/maps/api/js?key=”API_KEY”&callback=initMap"></script> <script src="{% static '/js/maps.js' %}" ></script> Script.js is working fine and map.js is executing but after map.js runs the div element doesn’t display. In maps.js, I have: function initMap() { var map = new google.maps.Map(document.getElementById("map"), { //zoom: 3, zoom: 10, center: { lat: 46.619261, lng: -33.134766 } }); var labels = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var locations = [ { lat: 40.785091, lng: -73.968285}, { lat: 41.084045, lng: -73.874245}, { lat: 40.754932, lng: -73.984016} ]; var markers = locations.map(function(location, i){ return new google.maps.Marker({ position: location, label: labels[i % labels.length] }); }); var markerCluster = new MarkerClusterer(map,markers, {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});} I do not seem to have any Google API key issues. However I have a div in the index.html with the following element and the map is not being displayed: <div class="row"> <!-- Map --> <div id="map" class="col-12"></div> <div class="col-12 mt-2 request-page"> <h2>Map Will Go Above Here </h2> </div> </div> I … -
Exception Type: AttributeError at / Exception Value: 'dict' object has no attribute 'headers'
Exception Type: AttributeError at / Exception Value: 'dict' object has no attribute 'headers' -
Sending information through Django channels from a view function
I am currently trying to set up a user interface for my app with Django. Basically, I want to send the user updates about what is going on in the backend when he starts a task (do like a loading bar or display the number of steps remaining, for instance) and thought of using Django channels for that. I set up my rooting.py, consumers.py files as well as asgi.py file, and everything is working correctly. However, I want to be able to send the user information through a function in views.py and I am not sure how I can do that, since I don't know how to identify the socket the user is currently connected to from the views.py and how to send information through it. I might be completely wrong using Django channels, maybe there's another (simpler) way of doing so, so I would like to have your advice on that! Thank you! -
selenium tests in django webapp don't work
I'm doing some tests on my django webapp. I install firefox(geckodriver) webdriver in /home/nicola/selenium_drivers/geckodriver, set execution permission and so on. Here is my test from django.test import TestCase from django.test import LiveServerTestCase from selenium import webdriver from selenium.webdriver.common.keys import Keys from pygiustizia.models import Users from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.firefox.options import Options from datetime import datetime, date class ViewsTopicsTestCase(LiveServerTestCase): USERNAME = None PASSWORD = None BASE_URL = None def setUp(self): self.BASE_URL = self.live_server_url self.USERNAME = 'nicolapaganotti1@gmail.com' self.PASSWORD = '$2b$12$Xv0W8PCBnGTqNpo96gxS/e3olh685kMyxE2tFM028Ex7bz/7Y3nMS' d = datetime(2022, 7, 20, 10, 10, 10, 342380) options = Options() #options.binary_location = '/usr/bin/firefox' options.add_argument("binary_location=/usr/bin/firefox") self.driver = webdriver.Firefox(options=options,executable_path=r'/home/nicola/selenium_drivers/geckodriver') #self.driver = webdriver.Firefox() # create user self.user = Users.objects.create_user(username=self.USERNAME, admin=1, firstname="Nicola", lastname="Paganotti", created_at=d, password=self.PASSWORD) def tearDown(self): self.driver.quit() def test_login(self): self.driver.get(self.BASE_URL + '/pygiustizia/login') username = self.driver.find_element_by_name("username") username.send_keys(self.USERNAME) password = self.driver.find_element_by_name("password") password.send_keys(self.PASSWORD) btn_login = self.driver.find_element_by_name("submit_login") # Login btn_login.click() # Check home page WebDriverWait(self.driver, 5).until( EC.presence_of_element_located((By.CSS_SELECTOR, '.selAddField'))) When I launch python3.9 manage.py test I get this output in terminal: Traceback (most recent call last): File "/var/www/html/elastic_queries/python/djangosite/giustiziasite/pygiustizia/tests/test_views_topics.py", line 33, in setUp self.driver = webdriver.Firefox(options=options,executable_path=r'/home/nicola/selenium_drivers/geckodriver') File "/usr/local/lib/python3.9/dist-packages/selenium/webdriver/firefox/webdriver.py", line 177, in __init__ super().__init__( File "/usr/local/lib/python3.9/dist-packages/selenium/webdriver/remote/webdriver.py", line 277, in __init__ self.start_session(capabilities, browser_profile) File "/usr/local/lib/python3.9/dist-packages/selenium/webdriver/remote/webdriver.py", line 370, in start_session response … -
Django filter using DateTimeField that can be null
I want to filter a table objects using a DateTimeField => last_user_action_time, this field can be null so I need the cases where its null to be included in the result. Here is what I tried: notification_objects = SinglePushNotification.objects.filter( last_user_action_time__lte=day_start, last_user_action_time__isnull=True, ).select_related("customer") This return an empty querySet knowing there is objects where null=True -
Running pyramid and django side by side
We have a pyramid application that provides API endpoint. Now we want to implement frontend as well but to our surprise, i10n/l10n tooling in pyramid is not as good as in django. So I have been thinking what if we implement the frontend with django instead? So I manage to get the PoC running with this code:- # in pyramid main() entry point def main(global_config: t.Dict[str, str], **settings: str) -> Router: """Return a Pyramid WSGI application.""" # Expand environment variables in .ini files settings = expandvars_dict(settings) settings["ini_path"] = global_config["__file__"] # Configure Pyramid config = Configurator(settings=settings) configure(config) # Up, Up and Away! from myapp.wsgi import application as django_app pyramid_app = config.make_wsgi_app() def wsgi_app(environ, start_response): request_url = environ["PATH_INFO"] if request_url.startswith("/api"): return pyramid_app(environ, start_response) return django_app(environ, start_response) return wsgi_app Basically the idea is that, for any request path that starts with /api, we pass it to pyramid, while everything else will be handled by django. This seems to be working well for a simple pages I'm testing, with all the i10n/l10n stuff also working. I'm wondering if there's any gotchas that I should be aware of, if I'm going this route. -
How to serialize file without host?
I am working on my Django (DRF) app. I have a user avatar class CustomUser(AbstractBaseUser, PermissionsMixin): avatar = models.ImageField(upload_to='avatars/', blank=True) ... I want to serialize avatar field: class CustomUserSerializer(serializers.ModelSerializer): avatar = serializers.FileField(use_url=False, required=False) class Meta: model = CustomUser fields = [ 'avatar', ... ] Current result is "avatar": "avatars/ZZZ.png" How can I get "avatar": "media/avatars/ZZZ.png" ??? (what is the proper way) Saved file location is http://localhost:6060/media/avatars/<file_name>.png -
How to write changes to auditlog from action in admin panel?
I have the model Players and rewritten auditlog. And when I'm trying to change some field from admin panel for example status - changes writing to the auditlog. But when I'm do changes using action (action change the value on the selected objects on the field status) - nothing is happened, no changes writing to the auditlog. What is the reason? And how to resolve it? -
Django Static doesn't load but is accessible. NGINX and Docker
I have connected my Django (DRF) to Gunicorn and Nginx and put it all in docker. When I load mysite.com/admin/ it looks bad, just plain text. So it seems like it does not load any static file. However, in Browser Console there are zero errors. Moreover, I see that all the static files have been successfully loaded from server (all the /static/ requests are HTTP 200) and I can open them right in my browser by putting url: mysite.com/static/admin/css/base.css. And this file will successfully open. But admin site does not want to apply it. On localhost with Debug=True everything is working fine too. On main web site all the /media/ is working good too, so the problem is only within /static/. nginx.conf events {} http { server { listen 80; server_name mysite.com; server_tokens off; location / { return 301 https://$host$request_uri; } } server { listen 80; server_name api.mysite.com; server_tokens off; location / { return 301 https://$host$request_uri; } } server { listen 443 ssl; server_name mysite.com; server_tokens off; ssl_certificate /etc/nginx/certs/mysite.com-chain.pem; ssl_certificate_key /etc/nginx/certs/mysite.com-key.pem; location / { proxy_pass http://10.0.2.237:3004; # React Frontend } } server { listen 443 ssl; server_name api.mysite.com; server_tokens off; ssl_certificate /etc/nginx/certs/api.mysite.com-chain.pem; ssl_certificate_key /etc/nginx/certs/api.mysite.com-key.pem; location /media/ { autoindex on; alias … -
Django form is not showing up on template
I am trying to show two forms (UserRegisterForm and TeacherRegisterForm) in one template. But, only the UserRegisterForm is showing up in the rendered HTML. teacher-register.html <form enctype="multipart/form-data" action="" method="post"> {% csrf_token %} {% crispy user_form %} {% crispy teacher_form %} <div class="form-group mt-3"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> urls.py urlpatterns = [ path('login/', LoginView.as_view(template_name='accounts/login.html'), name='login'), path('register/', register, name='register'), path('TeacherRegister/', register_teacher, name='teacher-register'), path('logout/', sign_out, name='logout'), path('profile/', sign_out, name='logout'), ] views.py def register_teacher(request): if request.user.is_authenticated: return redirect('dashboard') if request.method == 'POST': user_form = UserRegisterForm(request.POST) teacher_form = TeacherRegisterForm(request.POST, request.FILES) if user_form.is_valid() and teacher_form.is_valid(): user = user_form.save(commit=False) user.is_student = False user.is_teacher = True user.save() profile = teacher_form.save(commit=False) profile.user = user profile.save() messages.success( request, f'Your account has been created!') return redirect('login') else: user_form = UserRegisterForm() teacher_form = TeacherRegisterForm() context = { 'user_form': user_form, 'teacher_form': teacher_form, } return render(request, 'accounts/teacher-register.html', context) forms.py class TeacherRegisterForm(forms.ModelForm): image = forms.ImageField( label='Profile Picture', help_text='Upload a recent clear image.', required=False, ) birth_date = forms.DateField( label='Birth Date', widget=forms.widgets.DateInput(attrs={'type': 'date'}), ) facebook = forms.URLField( label='Facebook Profile URL' ) class Meta: model = Teacher fields = [ 'image', 'birth_date', 'facebook', ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Div( Div('image', css_class="col-sm-6"), Div('birth_date', css_class="col-sm-6"), css_class='row', … -
How to show possible OrderingFilter fields in graphql documentation explorer in graphene-django
I have a model class ProductOnRetailerOfOrganization(models.Model): name = models.CharField(max_length=200, blank=True, null=True) product_id = models.CharField(max_length=100, blank=true, null=true) and a graphql node like class ProductNode(DjangoObjectType): class Meta: model = Product interfaces = (graphene.relay.Node,) connection_class = connections.ExtendedConnection filterset_class = ProductFilter And filterset class ProductFilter(FilterSet): class Meta: model = Product fields = { "name": ["exact", "contains"], "product_id": ["exact", "contains"], } order_by = OrderingFilter( fields=( ( "name", "product_id", ) ) ) and query, schema import graphene from django.contrib.auth.mixins import LoginRequiredMixin from django.http import JsonResponse from graphene_django.views import GraphQLView class Query(graphene.ObjectType): products = DjangoFilterConnectionField(nodes.ProductNode) schema = graphene.Schema(query=Query) class PrivateGraphQLView(LoginRequiredMixin, GraphQLView): raise_exception = True def introspection_schema_view(request): data = {"data": schema.introspect()} return JsonResponse(data) when I enter into localhost:8000/graphql Documentation Explorer, I can't identify which fields can be passed with orderBy argument. Its just shows orderBy: String! unlike other filter fields which is listed as exact lookup arguments. eg. (nameIcontains: String !, name: String!) Is there a way to show the OrderingFilter fields just like showing filter and other arguments in documentation explorer ? -
local variable 'name' referenced before assignment in Django
My views.py def index(request): if request.method=="POST": name=request.POST.get('name') email=request.POST.get('email') phone=request.POST.get('phone') message=request.POST.get('message') contact=Contact(name=name, email=email, phone=phone, message=message) contact.save() return render(request, 'home/index.html') Error C:\Django venv\CodingSchool\home\views.py, line 12, in index contact=Contact(name=name, email=email, phone=phone, message=message)