Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Chained dropdown in Django is not storing data to database(Postgresql)
I am trying to create a chained drop-down in Django that is on selecting country only those states who belongs to the country should come in the drop-down to select.I have used J-Query for drop-down and is working fine. But after sending data from form the form data is coming to console as i have print the form values into the console for better understanding, but is not saving the data to the database and form.is_valid is giving False even if data is correct. Why it is not storing to the database even if the form data s correct models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser,AbstractUser class Country_Model(models.Model): country = models.CharField(max_length=50) def __str__(self): return self.country class State(models.Model): country = models.ForeignKey(Country_Model,on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return self.name class StudentsRegistrationModel(AbstractUser): GENDER = (('F', 'Female',),('M', 'Male',),('O', 'Other',)) email = models.EmailField(unique=True) fathers_name = models.CharField(max_length=25) gender = models.CharField(max_length=1,choices=GENDER,default=None) address = models.CharField(max_length=50) country = models.ForeignKey(Country_Model,on_delete=models.CASCADE) state = models.ForeignKey(State,on_delete=models.CASCADE) phone_number = models.CharField(verbose_name="Phone Number",max_length=10) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS=[] form.py from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from app1.models import StudentsRegistrationModel,State class … -
How to get the Verification code from Django GraphQL Auth
how can I get verification token from this message that prints on the CLI after registering on Django GraphQL Auth? <h3>localhost:8000</h3> <p>Hello a!</p> <p>Please activate your account on the link:</p> <p>http://localhost:8000/activate/{ verification token }</p> -
Django forms with stored procedure in MySQL
I am trying to invoke a stored procedure within a django form. This will fill a select in the template. Apparently it can be called with cursor.execute (), but I can't get it to work. I leave part of the code: class FormX(forms.ModelForm): fieldX = forms.ModelChoiceField(queryset=cursor.execute('SELECT * FROM table'), required=True) -
Can anyone explain How to encrypt a url in Django?
I am going to develop a application in Django. I need to encrypt the url which needs to be decrypted again in business logic. Which module should I need to use.Can any one help me out please.... -
Adding multiple many_to_many from query
I'm going crazy with this problem. So I have a model Template which basically is a template of permissions (when you create a user it will automatically give the good permissions). My model looks like this: class PermissionTemplate(models.Model): name = models.CharField(max_length=100) company = models.ForeignKey(Company, on_delete=models.CASCADE) permissions = models.ManyToManyField(Permission, blank=True, related_name='templates') class Meta: default_permissions = () permissions = ( ("can_delete_template", "Can delete a permission template"), ("can_create_template", "Can create a permission template"), ("can_edit_template", "Can create a permission template"), ) constraints = [ UniqueConstraint(fields=['company', 'name'], name='Unique_template_name_per_company') ] def __str__(self): return self.name I'm now writing the tests so in my setupTestData I do this: @classmethod def setUpTestData(cls): templateperms = PermissionTemplate.objects.create(name="Administrators", company=company) perms = Permission.objects.filter( content_type__app_label__in=['authentication', 'company']) templateperms.permissions.add(*perms) print(perms) print(templateperms.permissions) But the result is not as expected the first print will return my queryset well: <QuerySet [<Permission: authentication | permission template | Can create a permission template>, <Permission: authentication | permission template | Can delete a permission template> .... ] But my second print: auth.Permission.None And I don't have the permissions saved in my template If someone have an idea it would be much appreciated -
<embed?> element not able to show pdf preview on safari
My embed element is able to show pdf preview in chrome but not in safari. Can anyone advise on how I can render the embed PDF Preview element on safari? I have tried some of the methods but none worked. Recommended way to embed PDF in HTML? Thank you! <embed src="" type="application/pdf"> -
unable to get groups and permissions working for auth0 user in django admin
I am using Auth0 authentication and allowing the users to login to admin site. How ever, I am not able to get the django groups and permissions to work with these users. The users are getting saved to auth_user table. I am using social_django with auth0. here is a brief of the authentication backends, login, logout urls . # declaring authentication backends for auth0 users AUTHENTICATION_BACKENDS = { 'django.contrib.auth.backends.ModelBackend', 'core.authentication.auth0.Auth0' } ##### Login and Logout Urls and Redirections LOGIN_URL = '/login/auth0' LOGIN_REDIRECT_URL = '/admin' LOGOUT_REDIRECT_URL = '/login/auth0' # social auth pipeline SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'core.authentication.authorization.process_roles', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) if I disable superuser status, staff users are not able to access anything in the admin site, even after assigning to a group. I would like to add users to a group and allow access based on that. Also I haven't created any custom user model on django side to read the users. Should I use a custom user model for auth0 authentication? Any guidance on this front would be really helpful. -
Filter many to many objects from parent queryset
I have 2 models like this class A(models.Model): x = models.CharField(blank=True, null=True, max_length=256) y = models.CharField(blank=True, null=True, max_length=256) class B(models.Model): m = models.ManyToManyField(to=A, blank=True) #other fields class C(models.Model): p = models.ManyToManyField(to=A, blank=True) #other fileds now when i query the objects of model 'B' using query_b = models.B.objects.all() i want to exclude those objects from many to many field 'm' if they exist in models.C.objects.all() and return query_b -
Django - Add block inside an included html
In Django, can we add block content in a included html page? Is it feasible? base.html {% block title %} <p>This is title base.html</p> {% endblock title %} {% include "head.html" %} head.html {% block subtitle %} <p>This is subtitle head.html</p> {% endblock subtitle %} index.html {% extends 'base.html' %} {% block title %} <p>This is title index.html</p> {% endblock title %} {% block subtitle %} <p>This is subtitle index.html</p> {% endblock subtitle %} Final result <p>This is title dashboard.html</p> <p>This is subtitle head.html</p> Meaning, that when we are rendering index.html, it will not find the subtitle block on head.html Thanks! -
How to extract the data from the uploaded file using filesystemstorage in django?
Hi I am learning python I tried uploading a file using FileSystemStorage defualt class that is defualt class in django and the file is uploading but I want to extract the data from the uploaded file that is being stored media folder like name: "soso" age: "so" the code which I tried so far is as below views.py: from django.shortcuts import render from django.conf import settings from django.core.files.storage import FileSystemStorage def index(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'index.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'index.html') index.html: {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> {% if uploaded_file_url %} <p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p> {% endif %} <p><a href="{% url 'home' %}">Return to home</a></p> {% endblock %} -
Django - How access the value of an instance in views.py
I have this model class Post(models.Model): title = models.CharField(max_length=100) title2 = models.CharField( max_length=100) content = models.TextField(default=timezone.now) content2 = models.TextField(default=timezone.now) post_image = models.ImageField(upload_to='post_pics') post_image2 = models.ImageField(upload_to='post2_pics') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) Then I have this simple view function that allows me to access each of its field in my HTML: def home(request): postings = { 'listings' : Post.objects.all(), } return render(request, 'front/front.html', postings) {% for listings in listings%} <h1>{{listings.content}}</h1> {% endfor %} With this, I'm able to access the content field for every instance of that model and display it My question is how can I access the content field in my view function and change it. The content field holds a zipcode and I want to use an API to display the city of that zipcode(which I already know how to do) and pass it back to the h1 tag. Each instance holds a unique zipcode so I need it to apply for each instance. How would I approach this? -
How to use object.id to make another object, creator of the current object?
I have two models in my django application 'Client' and 'Installment'. Below is my models.py: models.py rom django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class Client(models.Model): name = models.CharField(max_length = 100) dob = models.SlugField(max_length = 100) CNIC = models.SlugField(max_length = 100) property_type = models.CharField(max_length = 100) down_payment = models.IntegerField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.name def get_absolute_url(self): return reverse('client_details',kwargs={ 'pk' : self.pk}) class Installment(models.Model): client = models.ForeignKey(Client, null=True, on_delete=models.CASCADE) installment_month = models.CharField(max_length = 100) installment_amount = models.IntegerField() installment_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.installment_month def get_absolute_url(self): return reverse('installment_confirmation') and my views.py view.py # To create new client class ClientCreateView(CreateView): model = Client fields = ['name', 'dob', 'CNIC', 'property_type', 'down_payment'] # To add new installment class AddInstallmentView(CreateView): model = Installment #template_name = "property_details/addinstallment_form.html" fields = ['installment_month', 'installment_amount'] And the URL that I have to add a new installment is below: urlpatterns = [ path('', ClientListView.as_view(), name='client_list'), path('new/', ClientCreateView.as_view(), name='add_client'), path('<int:pk>/', ClientDetailView.as_view(), name='client_details'), path('<int:pk>/Add-Installment', AddInstallmentView.as_view(), name='add_installment'), path('confirmation/', views.installment_added, name='installment_confirmation'), ] You can see that the URL for adding new installment is unique. For example, /<local_server_addr>/<client.id>/Add-Installment (because of <int:pk> above) I can create a new client and also I can add installment. But … -
How to obtain geo co-ordinates of a remote user in group video chat?
I am building a group video chat application in Django with the help of Agora where I want to show the user their geo distance from every other user. To a given user, the UI would look something like this (along with the video of course) User A - (User A's remote video) - 5 miles away from you User B - (User B's remote video) - 100 miles away from you User C - (User C's remote video) - 10 miles away from you User D (local user - you) Now in the video chat, a user can log off & a new user can join the call any time. To compute the geo distance of a remote user with the local user, I need geo-coordinates of both the parties. I can obtain the geo-location of the local user by integrating with some location library. I am confused on how to obtain the geo-coordinates of the remote user? My django code flow looks something like renders links to views.py ----> video.html -------> agora.js Video.html renders the video chat room. I am using Agora to power the group video chat whose code is defined in agora.js. Any time a new … -
Is there a way to show Django messages in Django admin site?
I need to display a Django message on the Django admin index site. I am looking for a way to add certain conditions for the message to be displayed and pass it to Django index site. Is there a way to achieve that? -
how do i seed some data in to my table , that i have fetched from a specific extrernal api in Django?
so my requirment is i need to fetch some data from a github api and seed it into the table in my django api application. so while the app is running it should always be seeded with that data.. And then i need to make a REST api using that Table data which is already seeded with github api data. im a beginner and i have searched a lot but couldnt find what to do ? i have already created mmy fuction to fetch data and also i have created a model based on my requirment. all i need to know where should i put that code so that it seeds my table when the application runs so that i can create a rest api using that table data .. this is the data fetching code(which i currently have put in view as a function to see if its working) def apiOverview(request): mainarr=[] url = 'https://api.github.com/repos/afhammk/components/contents' try: r = requests.get(url, auth=("afhammk","token")) fish = r.json() for ele in fish: try: desc=requests.get("https://api.github.com/repos/afhammk/components/contents/"+ele["name"]+"/description.txt?ref=main" ,auth=("afhammk","token")).json() content=str(base64.b64decode(desc["content"])) name=content.split("'")[1::2][0] description=content.split("'")[1::2][1] y=Task(component=ele["name"],url=ele["html_url"],owner=name,description=description) y.save() except: mainarr=["cant fetch second url"] except: mainarr=["cant fetch first url"] below is the model i created class Task(models.Model): component=models.CharField(max_length=200) owner=models.CharField(max_length=200) description=models.CharField(max_length=200) url=models.CharField(max_length=200) def __str__(self): … -
how can i get category name instead of the ID
I'm working on a small project using Django Rest Framework, I have two models ( contacts and category) So a contact can be in a category, I have a foreign key between the models, I would like to know how can I get data category name instead of getting the id number. This is my code : class Category(models.Model): cat_name = models.CharField(blank=False, max_length=255) comment = models.CharField(blank=False, max_length=255) private = models.BooleanField(default=False) allowed = models.BooleanField(default=False) def __str__(self): return self.name class Contact(models.Model): category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) first_name = models.CharField(max_length=60) last_name = models.CharField(max_length=60) My serializer class ContactSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = "__all__" Result I get : "first_name": "John", "last_name": "Doe", "category": 1 ( i want to get the name of the category instead of the id ) -
Refused to execute script from 'chunk.js' because its MIME type ('text/html') is not executable,and strict MIME type checking is enabled
i have a django rest framework + reactjs app in frontend , It has deployed successfully in aws, and it's working fine in debug mode, When i change to production: i get these errors: Refused to execute script from '***ff1c1f05.chunk.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. Refused to apply style from 'https://www.dentistconsultationhub.ai/static/css/main.85597d13.chunk.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. can anyone explain to me what mayb be the problem ? cordially -
Django Model Form not saving to database
I have the following ModelForm which when I use as below it is not saving to the database. I have tried other posts and answers on here but cannot get this to save. If I use the same Class Base View (CreateView) and use the input of {{form}} in the HTML I can get this working and it saves to the database, but I need to have the form fields added separately in the HTML page as below that has been created for me with separate inputs. The output of the post prints in the terminal ok, but then as mentioned not to the database. Hope this all makes sense and thanks in advance for any help I can get on this. models.py class ASPBookings(models.Model): program_types = ( ('Athlete Speaker & Expert Program', 'Athlete Speaker & Expert Program'), ('Be Fit. Be Well', 'Be Fit. Be Well') ) presentation_form_options = ( ('Face to Face', 'Face to Face'), ('Virtual', 'Virtual'), ) organisation_types = ( ('Goverment School', 'Goverment School'), ('Community Organisation', 'Community Organisation'), ('Non-Goverment School', 'Non-Goverment School'), ('Other', 'Other') ) contact_name = models.CharField(max_length=80) program_type = models.CharField(max_length=120,choices=program_types) booking_date = models.DateField() booking_time = models.DateTimeField(default=datetime.now()) duration = models.CharField(max_length=10, default="1") email = models.EmailField() phone_number = models.CharField(max_length=120) speaker_brief … -
django 3.1 passing raw column aliases to QuerySet.order_by() is deprecated
I'm working on a project which just moved to django 3.1. And I need to remove the usage of this "passing raw column aliases to QuerySet.order_by()" thing. However, I am not sure if my project is using it. So I need to understand how "passing raw column aliases to QuerySet.order_by()" actually works, if someone could provide me an example of the code that does the passing of raw column aliases to QuerySet.order_by(), it would be really helpful and appreciated. -
Django - Accessing Model Field in class based view
I have this model class Post(models.Model): title = models.CharField(max_length=100) title2 = models.CharField( max_length=100) content = models.TextField(default=timezone.now) content2 = models.TextField(default=timezone.now) post_image = models.ImageField(upload_to='post_pics') post_image2 = models.ImageField(upload_to='post2_pics') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) and this function based view that uses the model: class PostListView(ListView): model = Post template_name = 'front/front.html' context_object_name = 'listings' ordering = ['-date_posted'] def get_context_data(self, **kwargs): check_for_zipcode = #where I want to access the author for the current instance context = super().get_context_data(**kwargs) context['zipcodes'] = check_for_zipcode return context All I want to know is how can I access the author field in the class-based view. I can access the author in my HTML like so" {% for listings in listings %} <h3>listings.author</h3> {% endfor %} With this, I'll get back the author field for every instance of that model. How would I get the author for the instance in the variable check_for_zipcode? I tried self.author, self.listings.author, etc; but nothing works -
Django Forms: non-model field won't render value with "view" permission
I'm having trouble displaying values of non-model fields in custom form for admin site. When user has only view permission, on object editing, model fields are filled and rendered as read-only, while non-model fields are not rendering any values. Django version: 2.1.15 forms.py class AccountModelForm(forms.ModelForm): custom_field1 = forms.IntegerField() custom_field2 = forms.IntegerField() class Meta: model = Account fields = '__all__' def __init__(self, *args, **kwargs): super(AccountModelForm, self).__init__(*args, **kwargs) # initializing non-model fields with values self.initial['custom_field1'] = 3 self.initial['custom_field2'] = 5 admin.py @admin.register(Account) class AccountAdmin(admin.ModelAdmin): form = AccountModelForm def get_fieldsets(self, request, obj=None): model_fields = ('Info', {'fields': [f.name for f in self.model._meta.fields]}) return ( model_fields, ('Advanced options', { 'classes': ('collapse',), 'fields': ('custom_field1', 'custom_field2') }) ) Result... I don't know what I'm doing wrong, I would appreciate any help. Thanks in advance. -
With Django ORM, get the item (the whole object!) from a related dataset with the greater or lower value for one property
I have this: # models.py from django.db import models as m class Station(m.Model): name = m.CharField(max_length=255) # etc... class Moment(m.Model): date = m.DateField() time = m.TimeField() class HumidityMeasurement(m.Model): station = m.ForeignKey(Station, on_delete=m.CASCADE, related_name='humidity_set') moment = m.ForeignKey(Moment, on_delete=m.CASCADE) relative = m.FloatField(null=True, default=None) #etc... And I have to get the maximum and minimum relative humidity record from each station. This is my view: # views.py class MinMaxView(GenericViewSet): queryset = Station.objects @action(detail=False, methods=['GET']) def station(self, request, *args, **kwargs): queryset = self.get_queryset().prefetch_related('humidity_set') result = [] for station in queryset: # here I get a list and `trim` useless data h_list = [st for st in station.humidity_set.all() if not st.relative is None and not st.relative == -9999] # get max and min from the list of objects h_max = max(h_list, key=lambda obj: obj.relative) h_min = min(h_list, key=lambda obj: obj.relative) # no serializers here, go old school humidity = { 'max': { 'value': h_max.relative, 'date': f'{h_max.moment.date} - {h_max.moment.time}' }, 'min': { 'value': h_min.relative, 'date': f'{h_min.moment.date} - {h_min.moment.time}' } } station_data = { station.name: { 'humidity': humidity, # 'temperature': temperature, # 'pressure': pressure, # 'wind': wind, # 'rain': rain, # 'radiation': radiation, }, } result.append(station_data) return Response(result, status=status.HTTP_200_OK) Ok. It is working, but I have a database … -
Django sorting by a category and pagination combining both in one function view
I'm trying to sort my projects by categories: all, css, HTML, Django, and so on. and also trying to add pagination when showing all projects have a limit of 6 projects per page. I'm stuck and have trouble combining either the pagination work or the filter/ sorting the items work, here's my code. Please Help :) models.py class Category (models.Model): category_name = models.CharField(max_length=150) slug = models.SlugField(unique=True) class Meta: ordering = ('-category_name',) def __str__(self): return self.category_name def get_absolute_url(self): return reverse('mainpages:project_by_category', args=[self.slug]) class Project(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, default='', null=True) title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) proj_url = models.URLField(max_length=200, blank=True) blog_link = models.URLField(max_length=200, blank=True) image = models.ImageField(default='post-img.jpg', upload_to='proj-img') class Meta: ordering = ('-title',) def __str__(self): return self.title view.py def portfolioView(request, category_slug=None): # added category = None categories = Category.objects.all() # filtering by project projs = Project.objects.all() # paginator added projects = Project.objects.all() paginator = Paginator(projects, 3) page = request.GET.get('page') try: projects = paginator.page(page) except PageNotAnInteger: projects = paginator.page(1) except EmptyPage: projects = paginator.page(paginator.num_pages) # added if category_slug: category = get_object_or_404(Category, slug=category_slug) projs = projs.filter(category=category) # return render(request, 'mainpages/portfolio.html', { 'category': category, 'categories': categories, 'projects': projects, 'page': page, 'projs': projs, }) def projectDetail(request, pk): project = Project.objects.get(pk=pk) context = { … -
Passing variables in django browser string
I am doing a search on the page with the ability to filter. It is necessary to pass the selected fields to form the correct queryset. What is the best way to do this? I am creating str variable in urls. But what if you need to pass 10 or more filter conditions? how to organize dynamically passed variables? urls from django.urls import path from .views import * urlpatterns = [ path('', OrdersHomeView.as_view(), name='orders_home'), path('filter/<str:tag>', OrdersFilterView.as_view(), name='orders_filter'), ] I understand what to do through ?var=&var2=, as in php, but I can't figure out how? it is possible to just process the string str, but maybe there is some django magic? -
Context value for the variable {{ media }} in django views
There is a {{ media }} variable used in some of the django admin templates. delete_confirmation.html, change_form.html , and delete_selected_confirmation.html . This variable adds several javascript files including jQuery library to the templates. I want to know what is the value passed to the context variable in the views that call those templates. My purpose is to use the same javascript files in the templates that I create for the custom views in the django admin. Thank you.