Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django admin groups and queryset
I'm searching for a way to customize the Django Administration to support permissions and data based on the user group. For example, I've just created the Developers1, Developers2 groups.. now I've also created the Transaction model, with AdminModel to specify how to list data. Transacton model: class Transaction(models.Model): income_period_choices = (('Weekly', 'Weekly'), ('Fortnightly', 'Fortnightly')) chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11, choices=income_period_choices, null=True, blank=True) property_market_rent = models.DecimalField(help_text='Weekly', max_digits=7, decimal_places=2, null=True, blank=True) *group = models.ForeignKey(Group, on_delete=models.CASCADE) im not sure about the *group field, should i delete it , or should i create Charfield, which is not a foreignkey to the django.contrib.auth.group model? and this is the admin transaction: @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.user = request.user super().save_model(request, obj, form, change) def get_queryset(self, request): qs = super().get_queryset(request) # for s in qs: if request.user.is_superuser: return qs return qs.filter(group_name__in=Group) search_fields = ['chp_reference','familymember__name'] inlines = [FamilyGroupInline,FamilyMemberInline] what im trying to do is i want each group to only access its own Transaction model, and each group can add, delete, update and view their own Transactions only(eg developers1 group cant access developers2 Transactions and vice versa) any thoughts should be appreciated thanks! -
I want to get result of two query data using ORM in django
I want to get result of two query data using ORM in django but only one data is being displayed. How may i resolve this? My codes: views.py def home(request): codes, descrp = Major.objects.raw('SELECT p.major_cd, m.description FROM percentages p, major m WHERE p.major_cd = m.major_cd;') context = { "codes": codes, "descrp": descrp } return render(request, "website/index.html" , context ) index.html <select class="form-control select2"> <option>Select Major Head</option> {% for cd, ds in codes, descrp %} <option> {{ cd, ds }} </option> {% endfor %} </select> -
how to dynamicly change db password in django settings
I have a case when my db requires new token generated dynamicly as a password every 15 minutes. But it is advice from django team not to modify settings at runtime. And I found out that this is really not so easy to accomplish. I already tried this approche: Django multiple and dynamic databases but it seems more complex then it could be ... -
Django Gqueries: Get Grandchildren as CHUNKS of Children
Given a mother how can I get her grandchildren as chunks of her children? Here are my models: class Mother(models.Model): name = models.CharField(max_length=7) class Child(models.Model): mother = models.ForeignKey(Mother, on_delete=models.CASCADE) name = models.CharField(max_length=5) class GrandChild(models.Model): mother = models.ForeignKey(Child, on_delete=models.CASCADE) name = models.CharField(max_length=6) # I am in desperate need of below: her_grandchildren_from_each_of_her_daughters_and_sons = { "Daughter A": [ {"Granddaughter A": "Name A"}, {"Grandson B": "Name B"} ], "Son C": [ {"Granddaughter C": "Name C"}, {"Grandson D": "Name D"} ] } -
I am not able to active django in vs code. i get the following error message:
& : File C:\Users\AFFAN QADRI\env\Scripts\Activate.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:3 & "c:/Users/AFFAN QADRI/env/Scripts/Activate.ps1" + CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess -
Show or hide field in form based on selection in admin panel in Django
I have a model in my django app as below: class Question(BaseMmodel): title = models.CharField(max_length=50) body = models.TextField() subject = models.Charfield(max_length=20) history_date = models.DateField("history_date") #other fields I have registered this model in admin.py. Now what I would like to do is to have a toggle option in the question page in admin panel. I want to name it like Show history date field in question page. Here if I select this option then in the question form in frontend the history_date should be displayed or else it should not be displayed. How can I implement the required functionality? -
How to render the vue template into the django views?
Firstly I am creating the question and answer type app which the user creates questions. If the user added the same question which is present in the django API then I need to through an error on the template. So this app I used vuejs and django, DRF and webpack. Now I want to compare the questions present in the DB and user ready to push question content. #1. If this is not correct process How can I compare in the vuejs script. #2. How can we render the vuejs template into the django views return render('request' , QuestionEditor.vue') Is it the correct way to render the template of vue into the django? from django.contrib import messages from .models import Question def content(request): if request.method == 'POST': content = request.POST.get('content') if Question.objects.filter(content=content).exists(): messages.warning(request, 'Question already exists') return redirect('ask') # ask is nothing but name in the vuejs router file else: question = Question(content=content) question.save() messages.success(request, 'Question has been added') return redirect('/') return render(request, '../views/QuestionEditor.vue') -
how to close the collapse automatically when i press on other collapse button - html
hello i want to hide collapse by auto when i press on other button and show button data I'm using this format , my problem is data keep show when i press on other button ... i want show just the data when i press on some button and hide other collapse my html code : <div class="d-flex justify-content-center"> <div class="btn-group" role="group" aria-label="Basic example"> <button type="button" class="btn btn-secondary" data-toggle="collapse" data-target="#phone_pics" aria-expanded="true" style="background-color:#7952b3;border-radius:7px"> phone pics </button>&nbsp; <button type="button" class="btn btn-secondary" data-toggle="collapse" data-target="#space" aria-expanded="true" style="background-color:#7952b3;border-radius:7px"> phone space </button>&nbsp; <button type="button" class="btn btn-secondary" data-toggle="collapse" data-target="#review" aria-expanded="true" style="background-color:#7952b3;border-radius:7px"> review </button>&nbsp; </div> </div> <!-- this for phone pics --> <div id="phone_pics" class="collapse" aria-expanded="true"> <br> <div class="d-flex justify-content-center"> <div class="img"> {% for img in mobile_posts.mobile_images_set.all %} <div class="d-flex justify-content-center"> <img src="{{img.get_image}}" class="img-responsive img-thumbnail" width="50%" height="80%"> </div> {% endfor %} </div> </div> </div> <!-- this for review --> <div id="review" class="collapse" aria-expanded="true"> <br> <iframe width="100%" height="400px" src="{{mobile_posts.mobile_review_video}}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen> </iframe> </div> <!-- this for space --> <div id="space" class="collapse show" aria-labelledby="headingOne" > <br> </div> -
Learning Django [closed]
I know it seems ambitious but I am interested in building a few internet startups. I am competent in a few languages, including python and am intending to use django for building these websites/apps. Was hoping someone could recommend a good guide that would start fairly simple and by the end have me at a level where it could work with and build some pretty complex web apps. I am a fan of free youtube content so this would be best. Appreciate all the help. -
Send response and get request after every execution of statement in the views.py function - Django
Is there any way to send response to html template when the statement executes in the function everytime ? def name(request): tts = _TTS() tts.speak("May I know your first name ?") #send response to index.html after this speak() execution. tts.speak("May I know your last name ?") #send again response to index.html after this speak() execution. return render(request, 'index.html') I want to notify the client side everytime when the speak() execute. what would be the best way to deal with it ? -
how to access foreign key in a model class into django templates
I want to access all foreign key fields of my Answer class in the template. models.py class Answer(models.Model): teacher = models.ForeignKey(Teacher, on_delete=models.SET_NULL, null=True) question = models.ForeignKey(Question, on_delete=models.SET_NULL, null=True) subject = models.ForeignKey(Subject, on_delete=models.SET_NULL, null=True) answer = models.SmallIntegerField(choices=RATING_CHOICES, default=1) views.py def questions(request): context = { "questions": Question.objects.all(), "answers": Answer.objects.all(), "departments": Department.objects.all(), "semesters": Semester.objects.all(), "teachers": Teacher.objects.all(), "subjects": Subject.objects.all(), "rating_choices": RATING_CHOICES, } return render(request, "evaluation/questions.html", context) in the template, I want to access teacher, question, and subject through Answer class to build a form for submission. like this: This is my template that I think is problematic. <div class="container" style="margin-top: 5%;"> <br> <form action="{% url 'evaluation:index' %}" method="post"> {% csrf_token %} <select name="semester" id="semester_id"> {% for semester in semesters %} <option value="{{ semester }}">{{ semester }}</option> {% endfor %} </select> <select name="teacher" id="teacher_names"> {% for teacher in answers %} <option value="">{{ teacher.get_teacher_name }}</option> {% endfor %} </select> <select name="department" id="department_name"> {% for department in departments %} <option value="{{ department }}">{{ department }}</option> {% endfor %} </select> <select name="subject" id="subject_name"> {% for subject in subjects %} <option value="{{ subject }}">{{ subject }}</option> {% endfor %} </select> <ol> <br> {% for question in questions %} <li> {{ question }} {% for choice in rating_choices %} <ul> … -
Database Unique Constraint With At Least 1 Element in a List
I am using django-multilingualfield which transforms a given Charfield into multiple similar named CharFields dynamically depending on the languages set in the settings. For example, if on the model field "description" is of MultiLingualCharField type, it does not create actually a field with name "description" but many like "description_en", "description_de", "description_es" etc. As the exact field to be used is dependent on the user's choice on the application, for some instances description_en, for others description_de, or desciption_es will be filled while the non-used ones will be None. My question is how can I implement a UniqueConstraint stating "whichever description_xxx is not None", the combination of that and some other field (say date) is unique. Of course, it is possible to define seperate UniqueConstraints for each possible lang choice, but it will be heavily repetitive and not elegant, especially for apps with 10+ language choices. -
How to validate dateField in django form
I am trying to validate my Date of birth field in my Django form. I want the d_o_b field to be less than the current year. def validate_dob(value): # fxn that check if date of birth is not the current year if value > datetime.date.year(): raise forms.ValidationError('Date must be greater than current year') I get the below error when the try to execute the above code: TypeError at /account/edit/ 'getset_descriptor' object is not callable Here is my form: class ProfileEditForm(forms.ModelForm): dob = forms.DateField(validators = [validate_dob]) class Meta: model = Profile fields = ('dob', 'photo') labels = { 'dob': ('Date of birth'), } widgets = { 'dob': DateInput(attrs={'type': 'date'}) } -
How to use external oracle database on docker container?
I have django web and external oracle database, it is running on docker. How can i store data from django web to external oracle database? this is setting.py DATABASES = { 'oracle_database': { 'ENGINE': 'dj_db_conn_pool.backends.oracle', 'NAME': 'xxxx', 'USER': 'xxxx', 'PASSWORD': 'xxxxx', 'HOST': 'xxx.xxx.xx.xx', 'PORT': 'xxxx' } } and this is docker-compose.yml version: '3' services: web: image: app:latest build: . command: python manage.py runserver 0.0.0.0:8000 ports: - "8105:8000" networks: - db_network depends_on: - db tty: true db: build: . environment: user: 'xxxxx' database: 'xxxx' password: 'xxx' hostname: 'xxx.xxx.xx.xx' ports: "xxxx" networks: - db_network networks: db_network: driver: bridge but got error like this: django.db.utils.DatabaseError: DPI-1047: 64-bit Oracle Client library cannot be loaded -
django / admin.py how to add multi models
How add to admin.py admin.register for 3 model: Page/PageAdmin/PageListing? Below screenshot from my code: screenshot from vscode. -
Apache Index Of / Whenever a domain tries to point to my Server IP address
I have a server that has hosts multiple domain. I'm running Django + Apache for my websites. I was having an issue when a fresh domain tries to point to my server ip address, it always shows "Index /" This poses a really big problem as it was able to view my server files I know i can setup redirect beforehand, but only if i know the domain and configured to do so. I have even tried to point my IP itself to redirect whenever it was pointed. <VirtualHost *:80> ServerAdmin webmaster@localhost ServerName XXX.XXX.XXX.XXX ServerAlias XXX.XXX.XXX.XXX DocumentRoot /var/www/TestServer/ ErrorLog ${APACHE_LOG_DIR}/defaulterror.log CustomLog ${APACHE_LOG_DIR}/access.log combined RewriteEngine on RewriteCond %{HTTP_HOST} ^XXX\.XXX\.XXX\.XX$ RewriteRule ^(.*)$ https://www.google.com$1 [R=permanent,L] </VirtualHost> -
TypeError: create_user() missing 1 required positional argument: 'group'
Everything worked fine, until I dropped the database and run the migrations again. Now, I'm not able to create superuser again. The error I got is: TypeError: create_user() missing 1 required positional argument: 'group' Anyone faced the same problem and is there any solutions to fix the error? models.py class CustomUserManager(BaseUserManager): def create_user(self, email: str, password: str, group: Group, **extra_fields): if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() if group is not None: group.user_set.add(user) return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email username = models.CharField(max_length=30, blank=True, default='') is_superuser = models.BooleanField(default=True) is_admin = models.BooleanField(default=True) is_employee = models.BooleanField(default=True) is_headofdepartment = models.BooleanField(default=True) is_reception = models.BooleanField(default=True) is_patient = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) forms.py class UserForm(ModelForm): group = forms.ModelChoiceField(queryset=Group.objects.all()) #temp['group']=request.POST.get('group') #role = forms.ChoiceField(choices=ROLE_CHOICES, label='', widget=forms.RadioSelect(attrs={})) class Meta: … -
Error message in Django when I try to runserver - does not appear to have any patterns in it. If you s ee valid patterns in the
Every time I write python manage.py runserver i get the error message The included URLconf '<module 'strana.views' from 'D:\novi projekat\strana\views.py'>' does not appear to have any patterns in it. If you s ee valid patterns in the file then the issue is probably caused by a circular import. mysite urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('strana/', include('strana.views')), ] myapp(named strana) from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] views.py from django.http import HttpResponse def index(request): return HttpResponse('Kita u Bila') -
I want to display data using ORM in django but only a query is being generated on my html webpage
I want to display data from the database using ORM in django but only a sqlquery is being generated on my html webpage instead of the data. can anyone please help me resolve this? My codes: views.py def home(request): Values = Major.objects.raw('SELECT p.major_cd, m.description FROM percentages as p, major as m WHERE p.major_cd = m.major_cd;') context = { "Values": Values } return render(request, "website/index.html" , context ) index.html {{ Values }} -
attribute error in django NoneType object has no attribute group
I kept writing the code in android but I get this error in the log, I tried coding in more than one way. The API works on Postman but the API keeps bringing this error when I use the HttpLoggingInterceptor.Where is the error in the code? The images are uploaded to Cloudinary in Django rest Framework. package com. iconic.enrollment_app; import androidx.appcompat.app.AppCompatActivity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.util.Base64; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.iconic.services.EnrollClient; import com.iconic.services.EnrollService; import com.iconic.services.models.Member; import org.jetbrains.annotations.NotNull; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Calendar; import java.util.Objects; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class NewMemberActivity extends AppCompatActivity implements View.OnClickListener { private static final int BUFFER_SIZE = 1024 * 2; @BindView(R.id.search_member) Button mSearchButton; @BindView(R.id.profile_photo) ImageView mProfilePhoto; @BindView(R.id.front_id) ImageView mFrontId; @BindView(R.id.back_id) ImageView mBackId; @BindView(R.id.title_member) EditText mTitleMember; @BindView(R.id.id_number) EditText mIdNumber; @BindView(R.id.first_name) EditText mFirstName; @BindView(R.id.middle_name) EditText mMiddleName; @BindView(R.id.surname) EditText mSurname; @BindView(R.id.birth_day) EditText mBirthDay; @BindView(R.id.phone_number) EditText mPhone; @BindView(R.id.email_address) EditText mEmail; @BindView(R.id.gender) EditText mGender; @BindView(R.id.postal_address) EditText mPostalAddress; … -
Search on NestedField with django-elasticsearch-dsl
I don't understand how to search with a NestedField. I first want to filter the results using a PK and then make a search on several fields from one or more words. I created a nestedfield because the relationship is "manytomany". My Model: class Club(models.Model): """ Sport club Model, related to :model:`auth.User` and :model:`clubs.CategoryClub` """ name = models.CharField(max_length=50, verbose_name="nom") category = models.ForeignKey('CategoryClub', on_delete=models.CASCADE) clubs_members = models.ManyToManyField(User, related_name="clubs_members", blank=True) token = models.CharField(max_length=8, unique=True, blank=True, null=True) class Meta: verbose_name = "Club" verbose_name_plural = "Clubs" def __str__(self): return self.name def get_absolute_url(self): return reverse("detailClub", kwargs={"pk": self.pk}) My document: @registry.register_document class UserDocument(Document): clubs_members = fields.NestedField(properties={ 'pk': fields.IntegerField(), 'name': fields.TextField(), }) class Index: # Name of the Elasticsearch index name = 'user' # See Elasticsearch Indices API reference for available settings settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = User # The model associated with this Document # The fields of the model you want to be indexed in Elasticsearch fields = [ 'id', 'first_name', 'last_name', 'email', ] My view: search = UserDocument.search() search = search.query( 'nested', path='clubs_members', query=Q('match', clubs_members__pk=request.user.profil.club_administrator.pk) # request.user.profil.club_administrator.pk == 1 in my example ) if form.cleaned_data['search'] != "": search = search.query( Qelastic('bool', should=[ Qelastic('multi_match', query=form.cleaned_data['search'], fields=['last_name^2', 'first_name^2', 'email^1'], fuzziness="auto" ), … -
How do I show the likes & my post in my template?
I have a created two models in my models.py file. I have also created a view and that view renders a template named index.html. I want to show the post and it's likes count in my index webpage/template. but the below code doesn't work. models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=42) author = models.ForiegnKey(User, on_delete=models.CASCADE, related_name='author_user') create_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.author.first_name} {self.author.last_name}' class Like(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='liked_post') user = models.Foreignkey(User, on_delete=models.CASCADE, related_name='post_liked_by') def __str__(self): return f'{self.user.username}@{self.post.title}' views.py from django.shortcuts import render from .models import * def index(request): posts = Post.objects.all() likes = Like.objects.all() context = { 'posts': posts, 'likes': likes, } return render(request, 'index.html', context) index.html <html> <head> <title> Home </title> </head> <body> {% for post in posts %} <h1> {{ post.title }} </h1> <p> Author: {{ post.author.first_name }} {{ post.author.last_name }} </p> <p> Date Created: {{ post.create_date }} </p> <p> <i class="fa fa-heart"></i> {{len(likes)}} </p> {% endfor %} </body> </html> thank you in advance. -
Does TemplateView supports pagination?
How can I implement pagination with Templateview? The below view is class-based view where I am using Templateview for listing out networks ( which I am calling from api from another application). Here I am not using models so I cant use Listview because I don't have queryset. class classView(TemplateView): template_name = 'view_network.html' # paginate_by = 5 context_object_name = 'networks' paginator = Paginator('networks', 5) def get_context_data(self, **kwargs): ... ... return context in html page i have added this: <span class="step-links" style="margin-left: 30%; margin-bottom: 0px; margin-top: 0px; width: 100%;"> <div style="text-align: justify"></div> <table style="width: 50%"> <tr> {% if page_obj.has_previous %} <td><a href="?page=1">&laquo; First</a></td> <td> <a href="?page={{ page_obj.previous_page_number }}">Previous</a></td> {% endif %} <td> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.</td> {% if page_obj.has_next %} <td><a href="?page={{ page_obj.next_page_number }}">Next</a></td> <td><a href="?page={{ page_obj.paginator.num_pages }}">Last &raquo;</a></td> {% endif %} </tr> </table> </div> </span> </div> -
Adding django_prometheus middlewares cause 500 (server error)
I wanted to monitor my django app with prometheus and I added the django-exporter and it worked well. Then I decided to change my dependency from django-exporter to django-prometheus and then all my requests, except /metrics causes 500, which surprisingly don't cause any errors on my server's logs. I tested different things, and by commenting the two django-prometheus middlewares, the 500 response code is gone. # 'django_prometheus.middleware.PrometheusBeforeMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # 'django_prometheus.middleware.PrometheusAfterMiddleware', Is there anything wrong about my middlewares? Another problem which I have is that without commenting these two middlwares, my local docker-compose (Only django and memchache with dbengine of sqlite) is working, but my deploy-test docker-compose, consisting of postgres, django, memcache, autoheal is not working. I can't understand how these middlewares are related to my deploy-test set-up. -
Django-Rest-framework private API
I am building a Django application which has a REST API. I want this API to be private, only allowing petitions from users who have an auth token. But I have my frontend, which is made with React and inserted into the Django template. I want that, when making requests from the frontend to the API, no token is necessary to get a valid response. The site is not going to have a user registration/login system, so it cannot be done with user params. Thank you!