Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to call the same model class inside it s self?
I have a function make_fields_permissions that I need to use it inside the model calss in order to parse the fields and to make permissions for each field like [('can_view_first_name_field','can view first name'),...] goal I need to call and override Person class and inside it self I tried def __init__(self,*args, **kwargs): self.Meta.permissions = make_fields_permissions(self.model) super().__init__(*args, **kwargs) from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def __init__(self, *args, **kwargs): # kwargs['user']['permissions'] = make_fields_permissions(Profile) # x = self['age'] super().__init__(*args, **kwargs) class Meta: permissions = make_fields_permissions(Person) #< I can't use the same model inside meta -
How can I use prefetch_related to get the name field of objects with ForeignKey relationships?
I have two models: class ModelA(models.Model): name = models.CharField() class ModelB(models.Model): A = models.ForeignKey(ModelA, related_name="links") name = models.CharField() In my template I would like to print out the 'name' of each object associated to each ModelA object via ForeignKey, I am doing so like this {% for a in modela_list %} <p>{{ a.name }} </p> {% for link in modela_list.links.all % } <p>Link name: {{ link.name }} </p> {% endfor %} {% endfor %} While this does work, from what I understand it is incredibly inefficient, and very slow. How can I use prefetch_related to make this better? -
TypeError: contact() got an unexpected keyword argument 'name' -why I get such error in django?
Hello I am learning django framework for web development. After makemigrations and migrate command I did runserver command hence I got the following error. File "D:\learn django\ashokWeb\portfolio\home\views.py", line 21, in contact ins=contact(name=name,email=email,phone=phone,desc=desc) TypeError: contact() got an unexpected keyword argument 'name' [06/Jun/2021 15:08:25] "POST /contact HTTP/1.1" 500 64573 from django.shortcuts import render from home.models import contact # Create your views here. def home(request): return render(request, 'home.html') def about(request): return render(request, 'about.html') def projects(request): return render(request, 'projects.html') def contact(request): if request.method=="POST": name=request.POST['name'] email=request.POST['email'] phone=request.POST['phone'] desc=request.POST['desc'] #print(name,email,phone,desc) ins=contact(name=name,email=email,phone=phone,desc=desc) ins.save() print('the deta has been written to the db') return render(request, 'contact.html') '''models.py file''' from django.db import models # Create your models here. class contact(models.Model): name = models.CharField(max_length=30) email = models.EmailField(max_length=50, null='True') phone = models.CharField(max_length=10) desc = models.TextField() -
Django looping through 10 items of an array each time a button is pressed
I would like a page to start by showing 10 items, once a button is clicked, the next 10 items are shown and so on. Pressing the back button will show the previous 10 items. How would I got about doing this? The items are in an array. Each item is a queryset. Current code: {% for item in items %} #format item to be shown {% endfor %} -
Writing DRF reusable APIs
I am trying to create a PIP package for a set of reusable APIs. I have already implemented those API in a project and are working perfectly fine. I started looking for the way to package these API so that it can be integrated with any other project and that is how I learned about setuptools. To gain a little hands on experience with setuptools I simply created a PIP package for a helloworld() program. Now, I have started creating the package for the API I have in my DRF app. I created an empty directory and moved all the modules of this DRF app into that directory. The setup.py file is well configured to install the dependencies which are required by these modules. However, now I want to start this application and see if it is working or not. So when I run python manage.py runserver it didn't work because of an obvious reason - No such file or directory. Moreover, there are certain configuration which are required for this package to work and in my previous project it is defined in settings.py file. setup.py import os from setuptools import setup, find_packages # allow setup.py to be run from … -
how to return to a precise position in a django template
I have an html table where I can modify the cell fields, since the table is a bit long; when i commit the change i want to go back to the last modified line. i am using django. is there a solution for that. ps: I am using this code for page loading: return render(request, "./ui-panneaux-gerer-prix-form.html", context) and this is the table row : <td> <div class="row mb-5 mb-lg-5"> <div class="col-lg-3 col-sm-6 mt-4 mt-md-0"> <form action="gerer-prix-operation" method="POST"> {% csrf_token %} <fieldset> <legend class="h6">Matiere de fonds</legend> {% for objet_list in produit_list_fond %} <div class="form-check"> <input class="form-check-input" type="radio" name="matiereFond" id="exampleRadios2" value="{{objet_list.id}}" > <label class="form-check-label" for="exampleRadios2"> {{objet_list.nom}} </label> </div> {% endfor %} </div> <div class="col-lg-3 col-sm-6 mt-4 mt-md-0"> <legend class="h6">Champs</legend> {% for objet_list in produit_list_contour %} <div class="form-check"> <input class="form-check-input" type="radio" name="matiereContour" id="exampleRadios2" value="{{objet_list.id}}" > <label class="form-check-label" for="exampleRadios2"> {{objet_list.nom}} </label> </div> {% endfor %} </div> <div class="col-lg-3 col-sm-6 mt-4 mt-md-0"> <legend class="h6">Autre</legend> {% for objet_list in produit_list_autre %} <div class="form-check"> <input class="form-check-input" type="radio" name="autreMatiere" id="exampleRadios2" value="{{objet_list.id}}" > <label class="form-check-label" for="exampleRadios2"> {{objet_list.nom}} </label> </div> {% endfor %} <div class="form-check"> <input type="hidden" name="id" value="{{panneaux.id}}"> </div> <div class="form-check"> <input type="hidden" name="idObjetPanneaux" value="{{objet_panneaux.id}}"> </div> <div id="test"> </div> <button id="gerer_surface" class="btn btn-sm btn-danger" type="submit">Valider</button> <!-- End of Radio … -
Filtering Django admin site by user group
i want to filter the objects displayed on the admin site by using user groups. Each user is assigned to one or more groups which represent different categories of articles. Each article falls into one or more categories (the names of the groups and categories are identical). On the admin site for the Article object, users shall only see articles from categories of which they are a member. I found a basic approach by overriding get_queryset within ModelAdmin and retrieving a list with the user's group names. But how can i reference the ArticleCategory model within ArticleAdmin to do the comparison with the group names? models.py class Article(models.Model): title = models.CharField(max_length=200, default=None) class Category(models.Model): name = models.CharField(max_length=50, default=None) class ArticleCategory(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, default=None) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=None) admin.py class ArticleAdmin(admin.ModelAdmin): model = Article def get_queryset(self, request): if request.user.is_superuser: queryset = Article.objects.all() else: try: l = request.user.groups.values_list('name',flat = True) l_as_list = list(l) queryset = Article.objects.filter(??? in l_as_list) except: queryset = Article.objects.none() return queryset admin.site.register(Article, ArticleAdmin) -
Is there a way to make clickable images and select an that particular one?
I am working on a Graphical password authentication system using Django. During the registration process, I want to display few images , out of which the user can select any one. i want the selected image to be highlighted and also on the click of submit button, i want that image to be stored in the database. I had tried adding images in a button, but it did not work out. This is what i did <button name="b3" style="border:0px"><img src="/static/r9.jpg" class="d-block w-100" alt="..."></button> Then I tried a different approach and used use-maps in HTML. But apparently that also seems to not work. <img src="/static/r1.jpg" class="d-block w-100" name="img" alt="..." usemap="#imagemap"> the use map is defined as follows: <map name="imagemap"> <area shape="rect" coords="34,44,270,350" href=""> </map> Can you please guide me what is the way to go forward with it. Thanks in advance. -
I'm trying to link the post created by the specific user account in Django
models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Customer(models.Model): user = models.OneToOneField(User,null=True,blank=True,on_delete=models.CASCADE) name = models.CharField(max_length=200,null=True) ## phone = models.IntegerField(null=True) email = models.EmailField(max_length=250) profile_pic = models.ImageField(default='default_pic.png',null=True,blank=True) date_created = models.DateTimeField(auto_now_add=True,null=True) def __str__(self): return self.name class Task(models.Model): customer = models.ForeignKey(Customer,on_delete=models.CASCADE,null=True) title = models.CharField(max_length=200) description = models.TextField(null=True,blank=True) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ['complete'] views.py @login_required(login_url='login') def taskCreate(request): if request.method == 'POST': form = TaskForm(request.POST or None) if form.is_valid(): form.instance.customer = request.user form.save() return redirect('tasks') else: form = TaskForm() context = {'form':form} return render(request,'todo_list/task_create.html',context) Error: ValueError at /create_task/ Cannot assign "<SimpleLazyObject: <User: Dominic>>": "Task.customer" must be a "Customer" instance. I am trying to link the username in the user account to be shown on the model Task.customer that represents the post is created by that user. May I ask any methods could be done in order to specify the customer in the model Task? Also I do not understand the error message in detail because my admin panel already has the current username in the Customer model. However if I used request.user.customer the username does not show up instead returning None so how to solve this issue? -
How to add password toggle functionality on a form extended from Django's built-in Authentication Form?
I am extending a form UserLoginForm from Django's built-in AuthenticationForm. I am passing this form to my login page. I want to add password toggle functionality to this. This is my UserLoginForm and this is my login page. But I want to add password functionality like this. I have tried 'data-toggle' attribute in my form but that didn't work. As I am extending from built-in form, I could not toggle functionality through "id" of the element. I am using Bootstrap5. Please let me know how do I add password toggle functionality in this case. -
What is similar to postgresql uuid DEFAULT uuid_generate_v4() in a Django Model?
What would be similar to the postgresql schema below in a Django model? The current model, when doing an insert into the database, gives the error null value in column "account_uuid" violates not-null constraint. When generating the table directly in postgresql the insert works fine. postgresql schema example: CREATE TABLE accounts ( account_uuid uuid DEFAULT uuid_generate_v4() ); django model attempt: import uuid from django.db import models class Account(models.Model): account_uuid = models.UUIDField( default=uuid.uuid4, editable=False) -
Intergrating Firebase Phone authentication and Django Backend
I have created a Django backend for my flutter app. I have used the Django rest framework to connect two. Now for user authentication, I am using firebase on my flutter application. It's working fine. Now since the user management is done by firebase, how can I add a user to my Django backend when the user signup through my app to firebase. I want firebase to handle the signup/sign-in process but also want to create a user profile on my Django server which contains information about the user's address, profile pic, orders, payment history etc. Also, I want Django to know if the user is authenticated with firebase while calling API requests. How can I make Django handle such requests? -
Can't change the name form which the email is being sent
Here is the code that I am using subject = 'Opinion - OTP for login' message = 'Your OTP to login is {}'.format(callbacktoken) email_from = 'Opinion@noreply.com' # email_from = settings.EMAIL_HOST_USER recipient_list = [email] send_mail(subject, message, email_from, recipient_list) I expect the email to show Opinion@noreply.com as the name but they still show my email id that is in settings.EMAIL_HOST_USER. How to solve this problem? -
Executing scripts on remote server as user
I have a django service that is running under sudo account. All the operations like job submission, database operations etc. are performed by sudo account. However there are certain scripts that should be executed as user for traceability purpose later on. What is the best way to transfer the user password so that it can be taken as input to a script that does su myid and subsequent commands in the script are run under userid. For example my server is running as sys_admin. The password mypassword should be given by the user from the webpage and passed onto the script as argument. Below is my sample script: su - myid <<! >/dev/null 2>&1 mypassword whoami > /dev/tty ! The above script will print myid and not sys_admin. What is the best and the most secure way to perform this operation so that password is not exposed to backend as well. Can some form of encryption and decryption be performed on client or server side with some passphrase? -
Wagtail : How do I query related names (inline models) of a child page?
I have two pages: ArticlePage and TimelinePage. TimelinePage has an inline panel which is related to the model TimelinePageEntry. TimelinePage displays all of it's child TimelinePageEntry(s) just fine. However when I try to get all the TimelinePageEntry(s) from ArticlePage, it fails with an exception. ArticlePage fails with an exception when I try to do: context['timeline_entries'] = timeline_page.timeline_entries.all() Here's the source code for the three classes in models.py: import datetime from django.db import models from modelcluster.fields import ParentalKey from wagtail.admin.edit_handlers import FieldPanel, InlinePanel from wagtail.core.fields import RichTextField from wagtail.core.models import Orderable from wagtail.core.models import Page class ArticlePage(Page): date = models.DateField("Creation date", default=datetime.date.today) hero_biography = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('date'), FieldPanel('hero_biography'), ] subpage_types = [ 'articles.TimelinePage' ] def get_context(self, request, *args, **kwargs): context = super().get_context(request) timeline_pages = self.get_children().type(TimelinePage) timeline_page = timeline_pages[0] # prints "Page" print(type(timeline_page).__name__) # prints the title of the timeline page, so I know I'm getting a query result print(timeline_page.title) context['timeline_page'] = timeline_page # Throws an exception context['timeline_entries'] = timeline_page.timeline_entries.all() return context class TimelinePage(Page): max_count_per_parent = 1 subpage_types = [] content_panels = Page.content_panels + [ InlinePanel('timeline_entries', label="Timeline Entries") ] parent_page_type = [ 'articles.ArticlePage' ] def get_context(self, request, *args, **kwargs): # Prints "TimelinePage" print(type(self).__name__) # Prints a list of … -
Make django ModelForm required False?
I am using Django to develop my site, and let's say that I have a tabbed template that has two specific ModelForm that I want to make it required False if user does't fill the data in the form but if user fill some fields the form must be checked if it is valid or not. Note: the user can fill one form and leave the other but when use start to fill the other form it must be checked if its valid or not. My Template <section class="{{ document.form_flexbox|default:" col-lg-12 " }} connectedSortable hidden"> <!-- form input card--> <form {% if form.is_multipart or formset.is_multipart %} enctype="multipart/form-data" {% endif %} action="{{ name_space }}" method="post" id="baseFormInput"> <div class="card card-primary card-outline"> <div class="card-header"> <h3 class="card-title"> <i class="fas fa-keyboard mr-1"></i> {{ document.title_form }} </h3> <div class="card-tools"> <!-- <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#modal-permission" title="Date range"> {% trans 'Object Permissions' %} <i class="fas fa-lock"></i> </button> --> <button type="button" class="btn btn-tool" data-card-widget="collapse"> <i class="fas fa-minus"></i> </button> </div> </div> <!-- /.card-header --> <div class="card-body"> <ul class="nav nav-tabs" id="custom-tabs-three-tab" role="tablist"> <li class="nav-item" role="presentation"> <a class="nav-link active" id="home-tab" data-toggle="tab" href="#custom-tabs-three-home" role="tab" aria-controls="home" aria-selected="true">Move Order</a> </li> <li class="nav-item" role="presentation"> <a class="nav-link" id="profile-tab" data-toggle="tab" href="#custom-tabs-three-store" role="tab" aria-controls="profile" aria-selected="false">Exchange Store</a> … -
ModuleNotFoundError: No module named 'crispy_formsdjango'
Very green here. I am getting this error when I try to migrate: ModuleNotFoundError: No module named 'crispy_formsdjango' Part of me thinks there is some typo because of the formatting 'crispy_formsdjango', but I have no idea where that would be. settings.py: INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms' 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Installation: (venv) C:\Users\zacha\PycharmProjects\django1\django1>pip install django-crispy-forms Requirement already satisfied: django-crispy-forms in c:\users\zacha\pycharmprojects\django1\venv\lib\site-packages (1.11.2) No idea if this is helpful.. when attempting to runserver I receive this error: OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' I'm feeling like this migrate is higher upstream then this error, but its what I tracked back to here from. Thanks! -
gunicorn service is not starting even with all configuration files are correct
gunicorn service is not starting even though i configured everything correctly its not working please take a look on my directory structure directory structure This is my service file [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=developer Group=www-data WorkingDirectory=/home/developer/myprojectdir ExecStart=/home/developer/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ bharathwajan.wsgi:application [Install] WantedBy=multi-user.target This is my socket file [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target when i try to check the logs of gunicorn using 'sudo journelctl -u gunicorn' its showing me no module named myproject.wsgi (here myproject is bharathwajan) ModuleNotFoundError: No module named 'bharathwajan.wsgi' Jun 02 11:06:36 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[195812]: [2021-06-02 11:06:35 +0000] [195812] [INFO] Booting worker with pid: 195812 Jun 02 11:06:36 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[195811]: [2021-06-02 11:06:36 +0000] [195811] [INFO] Worker exiting (pid: 195811) Jun 02 11:06:36 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[195813]: [2021-06-02 11:06:36 +0000] [195813] [INFO] Booting worker with pid: 195813 Jun 02 11:06:36 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[195812]: [2021-06-02 11:06:36 +0000] [195812] [ERROR] Exception in worker process Jun 02 11:06:36 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[195812]: Traceback (most recent call last): Jun 02 11:06:36 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[195812]: File "/home/bharathwajan/bharathwajan/django/lib/python3.8/site-packages/gunicorn/arbiter.py",> Jun 02 11:06:36 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[195812]: worker.init_process() Jun 02 11:06:36 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[195812]: File "/home/bharathwajan/bharathwajan/django/lib/python3.8/site-packages/gunicorn/workers/base> Jun 02 11:06:36 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[195812]: self.load_wsgi() Jun 02 11:06:36 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[195812]: File "/home/bharathwajan/bharathwajan/django/lib/python3.8/site-packages/gunicorn/workers/base> Jun 02 11:06:36 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[195812]: … -
Accessing all children from different apps of abstract base class in django
I'm trying to access all Child classes including their data from all the apps in this project which are inherited from an abstract class and show it in Django Admin panel.From this admin panel one can view and edit the data and changes will be reflected globally in this project. How it can be done ? Thanks in advance -
Django from is not loading
I have created a Django form and I am trying to load it in a HTML page . But unfortunately its not working. It's just showing the submit button which i have added manually.I have tried everything bt nothing seems working. Here are my files. views.py from home.models import Details, Image_Data from django.shortcuts import render, redirect from django.shortcuts import render, redirect from datetime import datetime from django.contrib import messages from .forms import DetailsForm def register_new(request): form = DetailsForm return render(request, 'register1.html', {'form': form}) register_new.html {% extends 'base.html'%} {% block title %}Register1{% endblock title %} {% block body %} <div class="container my-3" > <h1 class="display-3" align="center">Register Here</h1> <br> <h1 class="display-6" >STEP 1: </h1> <form action="" method="post"> {% csrf_token %} {{ from.as_p }} <input type="Submit" value="Save" class = "btn btn-secondary" style="background: #0a9396"> </form> </div> {% endblock body %} forms.py from django import forms from django.forms import ModelForm from .models import Details, Image_Data class DetailsForm(ModelForm): class meta: model = Details fields = ('name', 'username', 'password', 'email') # tupple name = forms.CharField(label='Your name', max_length=100) username = forms.CharField(max_length=100) models.py class Details(models.Model): name = models.CharField(max_length=122) username = models.CharField(max_length=122) email = models.EmailField(max_length=122) password = models.CharField(max_length=20) date = models.DateField() def __str__(self): return self.name urls.py urlpatterns = [ path("register_new", … -
Error when getting the value of a field with type OneToOneField
I encountered a problem that I can't get the value of a field with type OneToOneField. I am linking 2 models using Tabularinline. And I want to get the value from the linked model when I create the object. I am trying to use signals, namely post_save. When I save I get this error: "Servers has no info". How can I get info object when creating Servers object or after creating it? class Servers(models.Model): name = models.CharField(max_length=120) class ServerInfo(models.Model): info = models.TextField() server = models.OneToOneField(Servers, on_delete=models.CASCADE, related_name="info") @receiver(post_save, sender = Servers) def create_server2(instance, sender, **kwargs): print(instance.info) -
How to build a HttpResponse containing a file in Django to a jquery request?
I am making a request to a django server with the $.post method- $.post('/merger/merge/', JSON.stringify(mergeList), function(data, status, jqXHR) { console.log('inside'); var a = document.createElement('a'); a.href = window.URL.createObjectURL(data); a.download = "merged-pdf.pdf"; a.style.display = "none"; document.body.appendChild(a); a.click(); document.body.removeChild(a); }, 'application/octet-stream' ); mergeList is an array with filenames. This is the code that returns the file- viewresponse = HttpResponse(open("merged.pdf", "rb").read(), content_type = "application/octet-stream", status=200) viewresponse['Content-Disposition'] = "attachment; filename=\"merged.pdf\"" return viewresponse However the methods fails with the folowing error- parsererror No conversion from text to application/octet-stream How do I fix this error? -
store UUID in session using middleware
I want to tag all requests with a UUID (if the request doesn't have it in the first place). I want to store the UUID in the session, so I wrote this middleware. class MachineIDMiddleware: """ tags requests with machine UUIDs. The machine-ID is set in the session. """ MID_KEY = "machine_id" def __init__(self, get_response): self.get_response = get_response def __call__(self, request): print(request.session.get(self.MID_KEY)) if self.MID_KEY not in request.session: # set the machine-ID for the request # if it has not been set already (making # sure that it is serializable). next_id = str(uuid.uuid4()) request.session[self.MID_KEY] = next_id return self.get_response(request) However, from my client, I noticed that the UUID keeps changing for every request. From my client, I noticed that the sessionid cookie also changed for every request made. As a result, a new UUID was generated for every request. This is not what I want, though. I want to maintain only one UUID per person (who might be anonymous). How can I achieve this? Thanks a lot! -
How do I login into the admin page if I disable password?
I am making a passwordless app (using token auth from DRF so login using email otp, social auth etc) so my user model has password = none. class User(AbstractUser): email = models.EmailField(verbose_name='email', unique=True, blank=False, max_length=60) username = models.CharField( verbose_name='username', blank=False, unique=True, max_length=20) first_name = models.CharField( verbose_name='first name', blank=False, unique=False, max_length=20) last_name = models.CharField( verbose_name='last name', blank=False, unique=False, max_length=20) password = None Now how do login in the admin page because it requires a password -
I want to implement file management in django
In django, I want to create a folder for each user, and allow users to create folders with arbitrary names, and upload and download csv and pdf to the created folders. I know how to do the upload and download, but I don't know how to create a folder for each user, and how to create a folder with a user's arbitrary name.