Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Recaptcha v3 Validate 2 Forms On The Same Allauth HTML Page?
Allauth Code: https://github.com/pennersr/django-allauth/blob/master/allauth/templates/account/email.html https://github.com/pennersr/django-allauth/blob/ee630612f13f4930b7caf64bfc46d6712885621b/allauth/account/forms.py#L418 https://github.com/pennersr/django-allauth/blob/master/allauth/account/views.py#L373 There are 2 forms on the allauth email.html page. I was able to validate one of the forms on that page with recaptcha v3. But how do you validate both of the forms on the page with recaptcha v3? The form that remains to be validated has 3 buttons "make primary", "resend verification" and "remove". Current reCAPTCHA v3 code for only 1 form on that page: <form id="change_email" method="post" action="{% url 'account_email' %}" autocomplete="off" class="add_email"> {% csrf_token %} {{ form.email|as_crispy_field }} <script src="https://www.google.com/recaptcha/api.js?render=PUBLIC_KEY"></script> <script> grecaptcha.ready(function() { var grecaptcha_execute = function(){ grecaptcha.execute('PUBLIC_KEY', {action: "{% url 'account_email' %}"}).then(function(token) { document.querySelectorAll('input.django-recaptcha-hidden-field').forEach(function (value) { value.value = token; }); document.getElementById('change_email').insertAdjacentHTML('afterbegin', '<input type="hidden" name="recaptcha_token" value="' + token + '">'); return token; }) }; grecaptcha_execute() setInterval(grecaptcha_execute, 120000); }); </script> <button name="action_add" class="btn btn-primary form-control" type="submit">{% trans "Add E-mail" %}</button> </form> project_name/app/forms.py: class CaptchaAddEmailForm(AddEmailForm): recaptcha_token = forms.CharField(required=True) def clean(self): super().clean() url = 'https://www.google.com/recaptcha/api/siteverify' params = { 'secret': 'SECRET_KEY', 'response': self.cleaned_data['recaptcha_token'] } response = requests.post(url, params) if response.status_code == requests.codes.ok: print(response.json()['success']) print(response.json()['action']) if response.json()['success'] and response.json()['action'] == '/accounts/email/': print('Captcha valid for user={}'.format(self.cleaned_data.get('email'))) else: print('Captcha valid for user={}'.format(self.cleaned_data.get('email'))) raise forms.ValidationError('ReCAPTCHA is invalid.') … -
Form to show unique values from Model Django
Learning Django.. I have build a setup a below and need your expert advise to make it better.. I created a model, and form on top of it to show the data.. and I have two questions after the code where I need your advise :) Model: class profilestable(models.Model): choices = [ ('Active','Active'), ('Inactive','Inactive') ] Category = models.CharField(max_length=100) SubCategory = models.CharField(max_length=100) product_name = models.CharField(max_length=100) Status = models.ChoiceField(max_length=20,choices=choices) def __str__(self): return self.Category class Userlist(models.Model): User = models.CharField(max_length=100) Categorygroup = models.ForeignKey(profilestable,null=true,on_delete=models.SET_NULL) def __str__(self): return self.User Form: class userprofileform(forms.ModelForm): model = Userlist Fields = ('User','CategoryGroup') def __init__(self,*args,**kwargs): super(userprofileform,self).__init__(*args,**kwargs) Sample data in the profilestable Model: Queries: I want to add the category, subcategory and product name as drop downs to the form however I am not sure how to access each element to show on the form. I was able to pull only category since I am returning that value. The list currently has lots of duplicate values, is it possible to show only unique values in the drop down. Also, is it possible to make it a multi-select and dependent cascading drop downs Request you to please help advise/direct to implement this type of form. Thank you so much. -
Make a Radio Button required in Django Form
I have a form like this: class ReportForm(forms.Form): title = forms.CharField() severity = forms.ChoiceField(label='Severity:', widget=forms.RadioSelect(), choices=SEVERITY_CHOICES, required=True) I am using Crispy forms. If I am on my page that the form is rendering on, and I try to submit without filling anything in, it will tell me title is required. But it doesn't care if severity is filled in or not. I have tried adding required=True to the field but that did not help. -
Django, link to object in db
I've got a django test-project going with a postgresql db with a table called customers. Rendering all the customers in /customers/ is fine but I'm looking for a way to render a single customer like this: /customer/{{customer.id}}. Not really sure what I'm looking for, anyone that can guide me to the correct documentation or something? Much appreciated. -
Filter queryset for froeign key in Django autocomplete_fields
class InstitutionProfileAdmin(admin.ModelAdmin): def institute_pic_tag(self, obj): if obj.institute_pic: return format_html('<img src="{}" width="30x"/>'.format(obj.institute_pic.url)) institute_pic_tag.short_description = 'Instituion Image' list_display = ["institute_name", "institute_location", "institute_code", "institute_pic_tag", "owner_name", "owner_email", "active"] search_fields = ('user__username', 'institute_name', 'user__email',) list_filter = ['active'] list_editable = ['active'] autocomplete_fields = ['user'] list_per_page = 20 def owner_name(self, obj): return obj.user.username def owner_email(self, obj): return obj.user.email def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "user": kwargs["queryset"] = get_user_model().objects.filter( user_profile__user_type='1') return super().formfield_for_foreignkey(db_field, request, **kwargs) admin.site.register(InstitutionProfile, InstitutionProfileAdmin) Here If do not use autocomplete_fields then the foreign key filtering in working but if i use autocomplete_fields fields it gives all data Without autocomplete_fields With autocomplete_fields -
Install all the site packages of Django rest framework project at once
I have git-ignored venv/ of the Django rest framework project.(According to a git ignore file of a tutorial) Now the other users of the repository needs a way to install the site-packages that I use in my local pc. I want a command or way to install the same site-packages in other's pc's. And where are those site-packages are listed as a file? -
Group queryset by related field values
I have following models structure: class Chapter: name = ... class Atom: name = ... chapter = FK(Chapter) class Question: title = ... atom = FK(Atom) I want to get all Questions related to Chapter, grouped by Atoms in this chapter. How to do it with many queries I know: atoms = Question.objects.filter(atom__chapter__id=1).values_list("atom", flat=True).distinct() result = {} for atom in atoms: result["atom"] = Question.objects.filter(atom__id=atom) I suppose that it could be done with one query using annotate, Subquery and other Django's staff. Is this possible? -
auto_now_add creates a NotNullViolation in Django unit test
I am trying to set up a unit test for a view that creates 3 objects for use in methods: class TestIssuerSelected(TestCase): @classmethod def setUpTestData(cls): cls.i1 = Issuer(issuer_name='Issuer 1') cls.i2 = Issuer(issuer_name='Issuer 2') cls.i3 = Issuer(issuer_name='Issuer 3') cls.i1.save() cls.i2.save() cls.i3.save() This setUpTestData creates objects from the following model: class Issuer(models.Model): issuer_name = models.CharField() obj_created_datetime = models.DateTimeField( 'Date created', auto_now_add=True, editable=False ) However, it produces the following error: sycopg2.errors.NotNullViolation: null value in column "obj_created_datetime" violates not-null constraint DETAIL: Failing row contains (8, null, Issuer 2). What could be going on here? auto_now_add should not allow a null field, but it is clearly the error occurring. Of note, this error only seems to occur when I run it in sequence with another test before it that sets up the same error. In isolation, this does not occur. How can I debug this? -
Has anyone had their videos list as "aborted" in a django project?
I am trying to view videos in the browser on my django project. I have two videos that work and one that says "aborted". They are all .mp4 files and the one that is not working is not the biggest video. I can't find anything on this problem. Has anyone else had this issue? I have deployed with apache and mod_wsgi, I'm using Django 2.2.3, and python 3.7.3. I'm using a simple django view to connect to a view in mysql workbench. I'm using the Microsoft Edge browser. I have tried using Chrome (all videos show as aborted) and IE (same result as edge). aborted video picture -
My django project is not importing files from the same directory
from django.urls import path from .entries import views urlpatterns = [ path('', views.index), path('add/', views.add) ] This is my code..I am getting this error: from .entries import views ImportError: attempted relative import with no known parent package -
How to add social sharing buttons in Django template?
I googled and searched similar questions on Stackoverflow, but couldn't make it due to lack of details. I know how to get the current url {{ request.build_absolute_uri }} but I don't know how to use this to share the content in different social apps? -
CSS, JavaScript, HTML. Django
I am looking for good online sites or good youtube channel for learning HTML, CSS, JavaScript, Django. Give me some suggestion. -
Django REST Framework GET to retrieve rows that have NAME LIKE %NAME%
So I have a table which I want to query using GET request and it should return me the items that match the %NAME% but currently the request returns me the complete table with all entries, not what I want. request http://localhost:8000/inventory/?name=cookie/ response GET /inventory/?name=cookie/ HTTP 200 OK Allow: POST, OPTIONS, GET Content-Type: application/json Vary: Accept [ { "item_code": "61f6ccca-e822-4b36-9ddf-5ec79a55a184", "name": "Golden Nutella Filled Cookie", "price": 100, "description": "Delicious Nutella-filled homemade cookie which will satisfy your cravings.", "image": "https://images.unsplash.com/photo-1499636136210-6f4ee915583e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=80", "quantity": 12 }, { "item_code": "ef6f68c4-c9a3-4a4e-8d5a-14d8f75a01ba", "name": "Fudgy Dark Brownie", "price": 60, "description": "Fudgy and chewy dark chocolate passion.", "image": "https://bakerbynature.com/wp-content/uploads/2020/04/Cocoa-Fudge-Brownies-1-of-1.jpg", "quantity": 16 } ] expected response [ { "item_code": "61f6ccca-e822-4b36-9ddf-5ec79a55a184", "name": "Golden Nutella Filled Cookie", "price": 100, "description": "Delicious Nutella-filled homemade cookie which will satisfy your cravings.", "image": "https://images.unsplash.com/photo-1499636136210-6f4ee915583e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=80", "quantity": 12 }, ] MODEL: Inventory import uuid from django.db import models class Inventory(models.Model): item_code = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50, null=False) price = models.IntegerField(null=False) description = models.CharField(max_length=500) image = models.URLField() quantity = models.PositiveIntegerField(default=0, null=False) def __str__(self): return f'Item: {self.name} - Price:{self.price}' views.py @api_view(['GET', 'POST']) def inventory_list(request): if request.method == 'GET': inventory = Inventory.objects.all() serializer = InventorySerializer(inventory, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = InventorySerializer(data=request.data) if serializer.is_valid(): … -
How can I fix the error ModuleNotFoundError by class based-view? [django]
I try to update user image by class based-view and I set all attributes that update needs and when I send the request it returns me No reverse match finally I knew what is happen and I try to fix that by make function called get_success_url and I add the slug to parameter and it returns me the following error: No module named 'medoabdin' so how can I fix this error views.py # Update Avatar class UpdateAvatar(UpdateView): template_name = 'account/change-image.html' form_class = UpdateAvatarForm # success_url = reverse_lazy('account:view_profile') model = UserProfile slug_field = 'slug' slug_url_kwarg = 'user_slug' def get_success_url(self): return reverse_lazy('account:view_profile', self.request.user.userprofile.slug) forms.py class UpdateAvatarForm(forms.ModelForm): class Meta: model = UserProfile fields = ['logo'] urls.py urlpatterns = [ path('new-image/<slug:user_slug>/', views.UpdateAvatar.as_view(), name="add_avatar"), ] -
Installed uWSGI from cygwin but unable to find from installed package
I am new to Django framework. I need to develop a chat function in my app. I am required to install uWSGI as websocket. As I am using Windows so I will install it using cygwin. I followed the instruction from some of the website and had successfully installed it. However, I couldn't find it in my python project. I have tried to install it in the python project site-packages and also the django python site-packages. Yet, I still couldn't find it in my installed packages. May I know what have done wrong or misunderstood? enter image description here -
scrapping google featured snippets using python
https://www.google.com/search?q=LAPTOP+ACER+I3/4/1TB/8GEN+full+specs For example: I want to search this product and scrape the specifications of it directly from the featured snippets. How do I get everything inside of that box?? -
TypeError: object of type 'Task' has no len() Django
I am creating an api to get following details but getting the error.I want to fetch the date in right manner.I recently changed the code bit.not getting desired output #models class Task(models.Model): Id=models.IntegerField() Name=models.CharField(max_length=50,null=False,blank=True) Image1=models.FileField(blank=True, default="", upload_to="media/images",null=True) Image2=models.FileField(blank=True, default="", upload_to="media/images",null=True) Date=models.DateField(null=True,blank=True) def __str__(self): return str(self.Name) #viewset class TaskViewSet(viewsets.ViewSet): def list(self, request): try: response=HttpResponse(content_type='application/ms-excel') response['Content-Disposition']='attachment; filename="users.xls"' wb=xlwt.Workbook(encoding='utf-8') ws=wb.add_sheet('Tasks', cell_overwrite_ok=True) row_num=0 font_style=xlwt.XFStyle() font_style.font.bold=True columns=['Id','Name','Image1','Image2','Date'] for col_num in range(len(columns)): ws.write(row_num,col_num,columns[col_num],font_style) font_style=xlwt.XFStyle() data=Task.objects.all()#.values_list('Id','Name','Image1','Image2','Date') date_format=xlwt.XFStyle() date_format.num_format_str='dd/mm/yyyy' for row in data: row_num+=1 print('row_num', row_num) for col_num in range(len(row)): if isinstance(row[col_num],datetime.date): ws.write(row_num,col_num,row[col_num].replace(tzinfo=None),font_style) else: ws.write(row_num,col_num,row[col_num],font_style) wb.save(response) print(row.Date) return response except Exception as error: traceback.print_exc() return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK) -
The conditional Annotate looking up case match a list of multiple items returned duplicate Query set items
The Query set I Want >> # id| project_title |can_apply| #----------------------------------------- # 1 | Need a Singer | True | project_categories=[Singer], my_skills=['Sing,Cook] # ---------------------------------------- # 2 |Need a cook | True |# project_categories=[Cook], my_skills=['Sing,Cook] # ---------------------------------------- # 3 |Need Singer who can Dance | False |# project_categories=[Singer,Dance], my_skills=['Sing,Cook] But Instead, I am getting query set as below !! Where id no:3 is repeating twice!! Once with can apply True and False next time. I should have to get False for id no 3 # id| project_title |can_apply| # ----------------------------------------- # 1 | Need Singer | True | # project_categories=[Singer], my_skills=['Sing,Cook] # ---------------------------------------- # 2 |Need Singer who can cook | True |# project_categories=[Singer,Cook], my_skills=['Sing,Cook] # ---------------------------------------- # 3 |Need Singer who can Dance | True |# project_categories=[Singer,Dance], my_skills=['Sing,Cook] # ---------------------------------------- # 3 |Need Singer who can Dance | False | # project_categories=[Singer,Dance], my_skills= ['Sing,Cook] My models.py class Project(models.Model): project_title= models.CharField(max_length=100) categories = models.ManyToManyField('Category') class Applicant(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) full_name = models.CharField(max_length=50, null=True, blank=True) categories = models.ManyToManyField('Category') class Category(models.Model): category = models.CharField(max_length=50) I have Tried such queries on the shell: applicant=#current user my_skills = applicant.categories.values_list('pk', flat=True) skills_i_dont_have=Category.objects.exclude(pk__in=te_skills) projects_queryset = Projects.objects.annotate( can_apply=Case( When( project_categories__in=skills_i_dont_have, then=Value(False) ), default=True, output_field=BooleanField(), distinct=True, ), ) … -
Django Download a File after being redirected
Hello I was trying to figure out how to download a file and redirect and someone here suggested I use window.location.href to simulate a link click in the template where the user gets redirected to. At first I struggled with a good way to pass the urls from my views to the template which I got working but then ran into an issue when trying to pass two urls to the templates. I scrapped that idea and settled on just using template filters to return the urls I need which works and you can see below. filters.py @register.filter() def pdf_download_url(value, arg): """ Takes an attendance object and returns the url to download the PDF and Counseling PDF if available. :param value: Attendance object :return: A list with Url for PDF download and URL for Counseling PDF download if there is one """ attendance_download_url = arg + reverse('employee-attendance-download', args=[value.employee.employee_id, value.id]) try: counseling_id = value.counseling.id counseling_download_url = arg + reverse('employee-counseling-download', args=[value.employee.employee_id, counseling_id]) except Counseling.DoesNotExist: counseling_download_url = '' return [attendance_download_url, counseling_download_url] Then in my template I have the following code. account.html {% if download == 'True' and attendance.last.downloaded == False %} window.onload = function(e){ {% for url in attendance.last|pdf_download_url:request.get_host %} window.location.href = '{{ … -
How to make the search function work when the file is inside a model which is inside of another model
I use python and Django 2.2.9 with Django-filter 2.1.0, and I want to add some search function for the website. My database looks like this: Upper is the 'User' database, the downer is the 'Entry' database. Here are what I have in the filter.py: import django_filters from .models import * from django_filters import CharFilter from django.contrib.auth.models import User class UserFilter(django_filters.FilterSet): username = CharFilter(field_name='username', lookup_expr='icontains') class Meta: model = User fields = ('username',) class EntryFilter(django_filters.FilterSet): locations = CharFilter(field_name='locations', lookup_expr='icontains') class Meta: model = Entry fields = ('locations',) # name The search function for the 'username' works well, but the search for the location 'name' does not work. What I think is because the 'username' just in the 'User' model, but the 'name' of the locations is in the 'locations' model which is a model that inside another model called 'Entry'. So, I should try to make it search for something in the 'name' file which inside the 'locations' that inside the 'Entry', but I do not know how to make it. And here is the model.py, I am not sure if I should make any change on it: from __future__ import unicode_literals from djongo import models from django import forms # … -
Pass params to DRF API View
Is there a way to pass params to serializer_class in GenericAPIView? As in, when I try to do serizlizer_class = SomeSerializer(fields=('a', 'b', 'c')) I get the following error: TypeError: 'SomeSerializer' object is not callable I've also tried the following: def get_serializer_class(self): return serializers.SomeSerializer( fields=('a', 'b', 'c') ) but the same error is triggered. Any help would be greatly appreciated. -
SMTPSenderRefused at the deployed version
I've an issue at the reseting-password. Somehow, it is working normal locally but is sending me a (SMTPSenderRefused at /accounts/password-reset/) message error when I try to reset the email at the deployed version. I've already tried to find the answer on google but it seems an odd issue. File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/views.py", line 222, in dispatch return super().dispatch(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/edit.py", line 142, in post return self.form_valid(form) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/views.py", line 235, in form_valid form.save(**opts) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/forms.py", line 324, in save user_email, html_email_template_name=html_email_template_name, File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/forms.py", line 272, in send_mail email_message.send() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/mail/message.py", line 276, in send return self.get_connection(fail_silently).send_messages([self]) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 109, in send_messages sent = self._send(message) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 125, in _send self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n')) File "/app/.heroku/python/lib/python3.6/smtplib.py", line 867, in sendmail raise SMTPSenderRefused(code, resp, from_addr) Exception Type: SMTPSenderRefused at /accounts/password-reset/ Exception Value: … -
Swagger UI won't load on Django on Heroku, TemplateDoesNotExist
Trying to launch a DRF app on heroku with Swagger for UI. Django admin works fine but when I added Swagger, it fails to load, here's log: drf-yasg/swagger-ui.html Request Method: GET Request URL: https://uni-chat-3.herokuapp.com/api/v1/docs/ Django Version: 3.0.7 Exception Type: TemplateDoesNotExist Exception Value: drf-yasg/swagger-ui.html Exception Location: /app/.heroku/python/lib/python3.8/site-packages/django/template/loader.py in get_template, line 19 Python Executable: /app/.heroku/python/bin/python Python Version: 3.8.3 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python38.zip', '/app/.heroku/python/lib/python3.8', '/app/.heroku/python/lib/python3.8/lib-dynload', '/app/.heroku/python/lib/python3.8/site-packages'] And here's my urls.py file: # imports schema_view = get_schema_view( openapi.Info( title="API", default_version='v1', description="Description", terms_of_service="Terms of cervice", contact=openapi.Contact(email="contact@contact.com"), ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path('admin/', admin.site.urls), path('api/', schema_view.with_ui('swagger', cache_timeout=0), name='api-documentation'), ] -
Why isn't my form rendering on the homepage
Trying to render my form on this homepage div: <div class="col-5"> {% include "home/form.html" %} </div> This is my form.html: <h1>Contact Us</h1> <form method="post"> {% csrf_token %} {{ form.as_p}} <div class="form-actions"> <button type="submit">Send</button> </div> </form> views.py: def home(request): return render(request, "home/home.html") def contactView(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "home/form.html",{'form':form}) def successView(request): return HttpResponse('Success! Thank you for your message.') It works fine when I combine contactView and home into one and render it on home.html. thanks -
i create a website in two user are used. one is superuser and second is normal user how to authenticate a user is normal user or superuser
super user authenticat: {% if user.is_authenticated %} [ super user authenticate ] basically a super user is Edit,Delete Post And normal user first signup and then after he can post a commant {% if user.is_authenticated %} it's also authenticate a normal user