Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django JWT - Allow request with no credential if key in body is valid
I have an endpoint that needs an Access Token for authentication. Also in this endpoint, there's a serializer UUID field that is not required. What I would like to do is: In case the UUID field is passed in the body, check if this UUID is valid and registered in the Database. If it's not valid it'll raise a DRF ValidationError. If no UUID field is passed then the request needs to be authenticated with an Access Token. Is there a way to have this kind of seletive auth verification? -
Highlight Repeated Names
I have a webpage that shows a list of students being requested by teachers for tutoring. A student can only be listed requested once in reality but multiple teachers may accidentally request the same student unknowingly. Is there a way to highlight a student's name each time they are requested except for the first request? The highlighting will be used to signify to teachers that these requests are to be ignored. See attached picture for clarity. Screenshot of Webpage -
Long running request causes connection refused with daphne and nginx
I have a Django 3.2.4 application which I am running on Kubernetes, fronted by NGINX, served via ASGI / daphne. I have a long running API call (no longer than 30 seconds) that when running, seems to cause other requests to be refused. In the NGINX logs I see connect() failed (111: Connection refused) while connecting to upstream and in the pods I see the liveness probe fails (because connection refused), and get Killed 8 pending application instances. Can someone tell me what might be happening? -
How to get currently logged-in user in signals.py file?
I'm making a todo app and one of it's functionalities is to send an email to the user that his task was overdue. Part of the views.py file: from .models import Todo from django.utils import timezone from .signals import overdue def index(request): ... overdue_tasks = Todo.objects.filter(time__lte=timezone.now()) if overdue_tasks: overdue.send_robust(sender=Todo) ... return render(request, 'todo/index.html', {'overdue_tasks' : overdue_tasks }) Part of the signals.py file: from django.dispatch import receiver, Signal from .models import Todo from django.core.mail import send_mail overdue = Signal() user_email = request.user.email @receiver(overdue) def my_handler(sender, **kwargs): send_mail('My Task Manager', 'Your task was Overdue !', 'abdullahatif132@gmail.com', 'user_email', fail_silently=False)' It's raising exception: "NameError: name 'request isn't defined." -
Why does my React Dom render method not work?
I'm building a React-Django application, and on my App component, I'm getting an issue on the final line with my render(<App />, appDiv). Please can someone tell me what I'm doing wrong? I have the necessary modules imported, and this worked on my previous project. I am aware that Function-based components are better, but I'm more experienced with Class-based. Error: Code: import React, { Component } from "react"; import { render } from "react-dom"; import HomePage from "./HomePage"; export default class App extends Component { constructor(props) { super(props); } render() { return ( <div className="center"> <HomePage /> </div> ); } } const appDiv = document.getElementById("app"); render(<App />, appDiv); Thanks, DillonB07 -
How to pass parameters in django form
views.py def ATMlogin(request,id): global loginname loginname=='ATM_login' if request.method == 'POST': ATMnumber1=request.POST['ATMnumber'] mobnum1=request.POST['mobnum'] global mobnum global atmnum atmnum=ATMnumber1 mobnum=mobnum1 if Customer_details.objects.filter(ATMnumber=ATMnumber1).exists() and ATMLogin.objects.filter(mobnum=mobnum1).exists() : user_set=Customer_details.objects.all() for user in user_set.iterator(): if (user.ATMnumber==atmnum): id=user.id current_user={id:1} #current_user=Customer_details.objects.get(id=id) return render (request,'dashboard.html',{'current_user':current_user}) form=ATMLoginform() return render (request,'ATM_login.html',{'form':form}) urls.py from django.urls import path from . import views urlpatterns=[ path('',views.login,name='login_option'), path('savings_login',views.savingsloginform,name='Savings_Login'), path('ATM_login',views.ATMloginform,name='ATM_Login'), path('OB_login',views.OBloginform,name='OB_Login'), path('Register_OB',views.registerOB,name='Register_OB'), path('dashboard/<int:id>',views.ATMlogin,name='dashboard'), path('sentsms',views.sendsms,name='sms_sent'), path('VerifiedDashboard',views.verifiedDashboard,name='Dashboard'), path('Logout',views.Logout,name='Logout'), ] **Atmlogin.html** {% csrf_token %} <img src="{% static 'Images/portrait_black_24dp.svg' %}" alt="" class="icon">{{form.ATMnumber}}<br><br> <img src="{% static 'Images/portrait_black_24dp.svg' %}" alt="" class="icon">{{form.mobnum}}<br><br> //--> class="fas fa-sign-in-alt"> Log-in guys help me i haveto finish this project aa soon as possible............................................... -
Retrieve data from Salesforce using Django
I am trying to integrate salesforce Rest API with Django, so for hours I have been trying to figure out the endpoint which it exposes, I have learned to create records but how do I access those records as the URL mentioned in docs is https://yourInstance.salesforce.com/services/data/v52.0/query/?q=SELECT+name+from+Account, what is "yourinstance" here, any help will be appreciated, thanks in advance when i tried to access above URL in thunder client it gave me this error Couldn't resolve the hostname to an IP address, Verify Url: https://trial65.salesforce.com/services/data/v52.0/query/?q=SELECT+name+from+Account -
How to use lock with pymemcache on Django?
I am using pymemcache 3.5.0 with Django 3.2.7. I have a lot of script running on my Django instance and also using the cache to share data between them. I have thoses configration in my Django settings: def json_serializer(key, value): print("Message Type: " + str(type(value))) if type(value) == str: return value, 1 return json.dumps(value), 2 def json_deserializer(key, value, flags): if flags == 1: return value.decode('utf-8') if flags == 2: return json.loads(value.decode('utf-8')) raise Exception("Unknown serialization format") CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '127.0.0.1:11211', 'OPTIONS': { 'no_delay': True, 'ignore_exc': True, 'max_pool_size': 1000, 'use_pooling': True, 'serializer': json_serializer, 'deserializer': json_deserializer, } } } I see in the pymemcache documentation that i can add a lock_generator parameter it is written this as the description: • lock_generator – a callback/type that takes no arguments that will be called to create a lock or semaphore that can protect the pool from concurrent access (for example a eventlet lock or semaphore could be used instead) But no exemple anywhere i have shearched a lot but found nothing on how to implement this. Is there anyone here that know how to implement a lock so not 2 threads can write or read the same key twice ? … -
'method' object is not subscriptable problem in python
in my code I am trying to make a guessing game, i take input from what num do you want to start to what num do you want to stop and that the code which break(that code in a while loop): ''' while True: user = int(randrange[num1 , num2]) ''' -
How to remove the post-fix 's' from the database table name in Django Model, which is automatically added by Djanog
can anyone tell me, how can I get rid of the postfix 's' from the db_table name. Below is the sample model code. When is see this model through the admin portal I see the database table name is 'countrys'. How can I remove this 's' from my db_table name? class Country(models.Model): name = models.CharField(max_length=30) population = models.IntegerField() alpha2Code = models.CharField(max_length=2, primary_key=True) languages = models.CharField(max_length=256) class Meta: db_table = "country" Thanks in advance -
How to Serve Media Files in Django + React
I'm confused about serving media files on django and react. Here is my code: Here is my settings.py : STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api-user/', include('landingpage.urls')), path('', TemplateView.as_view(template_name='index.html')) ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Render it on react : <img src="/img/logo.jpeg" // is it true? /> I put my image on build/img folder. When i open with localhost 3000 it's rendered but when i open with localhost 8000, i get not found error with this image link http://127.0.0.1:8000/img/logo.jpeg My question is : Where to put images? Should i create media folder to store all my image or put it on build/image folder? How to specify the src link to image on in react? Thanks. -
Can't run makemigrations after moving modules
I've got a module named: validators.py located at ./project/app1/validators.py. I have imported it inside one of my Models: # app1/models.py from .validators import validate_something After a while, I decide to move this validators.py to a separated directory utils/ ("package", __init__.py), so I can use its functions in all my apps without referencing the app1: ./project/utils/validators.py. After moving the module, I changed my import at the beginning of the Model: # app1/models.py from utils.validators import validate_something Now that I want to create new migrations using manage.py makemigrations I'm getting this error: File "project/app1/migrations/0001_initial.py", line 5, in <module> import app1.validators ModuleNotFoundError: No module named 'app1.validators' I can remove all migrations and regenerate them but I guess there should be another way to resolve this dependency issue. -
Prevent TypeError: updates[0] is undefined in Vue.js/Django application
I'm developing a Django/Vue.js application. Right after the login form, the Django view redirects to the user/username page, in which the Vue.Js file loads the data from the server. Here is the code: async created(){ await this.getUpdates(); } The detail of the getUpdates() function is reported below; basically, it posts at Django the date that the server needs to do its calculations. async getUpdates(){ await fetch(baseurl + 'getupdates', { method: 'post', headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': await this.getCsrfToken() }, body: JSON.stringify(this.date) } ); var response = await this.loadUpdates(); this.updates = await response.json() }, async loadUpdates(){ await this.getUser(); var response = await fetch(baseurl + 'loadupdates', { method: 'post', headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': await this.getCsrfToken() }, body: JSON.stringify(this.date) } ); this.updates = await response.json() } The html snippet that uses these updates are reported below <!--Avvisi--> <h3>Avvisi:</h3> <div class="container" > <div class="row" v-if="updates[0].length"> <div v-for="notice, index in updates[0]" class="col-md-3 col-6 my-1"> <!--Qua metto le carte--> <div class="card"> <div class="card-body"> <h4 class="card-title">[[notice.titolo]]</h4> <p><a v-bind:href="'notices/'+ notice.id" tabindex=0>Vedi dettaglio</a></p> <button class="btn btn-primary" @click="hide(notice)" tabindex=0>Nascondi</button> </div> </div> </div> </div> <div class="row" v-else> Nessun nuovo avviso oggi </div> </div> <br> The problem is that when I firstly log in to the page … -
ValueError when uploading resized django images to google cloud
i have this model which works fine when uploading resized images to the media file on my django project class ItemImage(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True,upload_to='item_img/') created = models.DateTimeField(auto_now_add=True) def save(self): im = Image.open(self.image) im_name = uuid.uuid4() im = im.convert('RGB') output = BytesIO() # Resize/modify the image im = im.resize((700, 700)) # after modifications, save it to the output im.save(output, format='JPEG', quality=90) output.seek(0) # change the imagefield value to be the newley modifed image value self.image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.image.name, 'image/jpeg', sys.getsizeof(output), None) super(ItemImage, self).save() def __str__(self): return self.item.title when i changed the file storage to google cloud i faced this error when uploading the images ValueError at /ar/dashboard/my_items/edit_item/add_item_image/2/ Size 120495 was specified but the file-like object only had 120373 bytes remaining. note that the images are uploaded successfully when i remove the save method that is added so is there anything that i need to change in that save method when dealing with gcloud? -
for root in settings.STATICFILES_DIRS: TypeError: 'WindowsPath' object is not iterable WHILE MIGRATING in DJANGO(3.2.7)
(env) C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\social>python manage.py migrate Traceback (most recent call last): File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\social\manage.py", line 22, in main() File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\social\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\core\management_init_.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\core\management_init_.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle self.check(databases=[database]) File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\contrib\staticfiles\checks.py", line 7, in check_finders for finder in get_finders(): File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\contrib\staticfiles\finders.py", line 281, in get_finders yield get_finder(finder_path) File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\contrib\staticfiles\finders.py", line 294, in get_finder return Finder() File "C:\Users\Amitesh Sethi\OneDrive\Desktop\T\dj\env\lib\site-packages\django\contrib\staticfiles\finders.py", line 57, in init for root in settings.STATICFILES_DIRS: TypeError: 'WindowsPath' object is not iterable -
In Django project uploaded img not showing in website
I just want to display profile picture.Img upload successfully but not showing the img.But if i try in admin panel then show me img. Here is my index.html code {% extends 'Login_app/base.html' %} {% block body_block %} {% if user.is_authenticated %} <p>Hi {{ user_basic_info.username }},</p> <p>Your Email {{ user_basic_info.email }}</p> <p><a href="{{user_basic_info.facebook_id }}"> Facebook Profile </a></p> <img src="/media/{{ user_more_info.profile_pic }}" width="200px"> {% else %} <div class="alert alert-primary"></div>You are not logged in!!</div> {% endif %} {% endblock %} Here is my setting.py media setting import os MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # This is a tuple MEDIA_URL = '/media/' Here the ss of website -
Method Not Allowed (POST): /cbvdelete/5/ Method Not Allowed: /cbvdelete/5/
i am not able to run this code viwes.py from django.shortcuts import render, redirect from django.urls import reverse_lazy, reverse from . models import Task from . forms import Taskform from django.views.generic import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import UpdateView,DeleteView class Tasklistview(ListView): model = Task template_name = 'home.html' context_object_name = 'task' class Detailview(DetailView): model=Task template_name = "details.html" context_object_name = 'task' class Updateview(UpdateView): model = Task template_name = "update.html" context_object_name = "task" fields = ('name', 'priority', 'date') def get_success_url(self): return reverse_lazy('todoapp:cbvdetail',kwargs={'pk':self.object.id}) class Deleteview(DetailView): model = Task template_name = 'delete.html' success_url = reverse_lazy('todoapp:home') urls.py from django.urls import path from . import views app_name='todoapp' urlpatterns = [ path('',views.home,name='home'), path('delete/<int:id>/',views.delete,name='delete'), path('edit/<int:id>/',views.update,name='update'), path('cbvhome/',views.Tasklistview.as_view(),name='home'), path('cbvdetail/<int:pk>/',views.Detailview.as_view(),name='cbvdetail'), path('cbvupdate/<int:pk>/',views.Updateview.as_view(),name='edit'), ] when i run this code i am getting a error this page isn't working right now i am not able to run this code gngnitgbnugriujvnnvtvnviuvntnvtvitu -
Why does Django's AuthenticationForm return weird str in error message
I've recently implemented the Django AuthenticationForm into my project and recognized that the error returns some weird str __all__ Returned error message in the frontend when using a wrong password: My template <div class="error-wrapper"> <div class="errors">{{ form.errors }}</div> </div> So I took a look into the Django source code to check out the form which doesn't include __all__ in the error message str: class AuthenticationForm(forms.Form): """ Base class for authenticating users. Extend this to get a form that accepts username/password logins. """ username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True})) password = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput(attrs={'autocomplete': 'current-password'}), ) error_messages = { 'invalid_login': _( "Please enter a correct %(username)s and password. Note that both " "fields may be case-sensitive." ), 'inactive': _("This account is inactive."), } What do I miss? -
Is POST only way to send data in django?
So i am creating an application in which am showing university information to students. When the click on apply - i will be showing a modal and asking them to select "Month". So am using "id" from the main page to get the course students selected and now i want to know the month which they selected. If its just sending "id" means i can just do {% url 'application-save' data.id %} But i also need to Month from modal, so i tried that by making a form inside modal and collecting the selected ! And ya its working, i used the below request.POST['selected_month'] And its perfectly saved, now my concern is this the right way ? is this secure way to do ? How to send a data without post and passing to url ? -
how to create user login with roles, eg.is_staff,is_manager,is_teamlead (diffrent template)?
this is my models.py class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True) full_name =models.CharField(max_length=55) mobile = models.CharField(max_length=11) is_superuser = models.BooleanField(default=False) is_manager = models.BooleanField(default=False) is_teamlead = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) login.py file def login(request, *args, **kwargs): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request,username=username, password=password) this is my login page, i need to login diffrent html pages as per role -
Trying to parse all information from Tempbooking model to Booking model if the admin changes is_active to 'true' in the tempbooking django
This is the model: class Booking(models.Model): booker = models.CharField(max_length=50) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() discount_code = models.CharField(max_length=50, null=True, blank=True) guest_no = models.PositiveIntegerField() arrival_date = models.DateTimeField(auto_now=False, auto_created=False, auto_now_add=False, null=True,blank=True) departure_date = models.DateTimeField(null=True,blank=True) is_active = models.BooleanField(default=False) class Meta: db_table = 'booking' managed = True verbose_name = 'Booking' verbose_name_plural = 'Bookings' class Tempbooking(models.Model): booker = models.CharField(max_length=50) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() discount_code = models.CharField(max_length=50, null=True, blank=True) guest_no = models.PositiveIntegerField() arrival_date = models.DateTimeField(auto_now=False, auto_created=False, auto_now_add=False, null=True,blank=True) departure_date = models.DateTimeField(null=True,blank=True) is_active = models.BooleanField(default=False, null=True, blank=True) def __str__(self): return self.first_name class Meta: db_table = '' managed = True verbose_name = 'Tempbooking' verbose_name_plural = 'Tempbookings' This is the form: class BookingForm(forms.ModelForm): discount_code = forms.CharField(required=False) is_active = forms.HiddenInput() class Meta: model = Tempbooking fields = '__all__' widgets = { 'booker': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Your username'}), 'first_name': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter Your First Name'}), 'last_name': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter Your Last Name'}), 'email': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter Your Email'}), 'guest_no': forms.NumberInput(attrs={'class':'form-control'}), 'arrival_date': forms.DateTimeInput(attrs={'class':'form-control','type':'date'}), 'departure_date': forms.DateTimeInput(attrs={'class':'form-control','type':'date'}), 'discount_code': forms.TextInput(attrs={'class':'form-control','placeholder':'If our discounted product'}) } This is the view: def booking(request): form = BookingForm() form2 = TempbookingForm() if request.method=='POST': form = BookingForm(request.POST) if form.is_valid() or form2.is_valid: form2 = TempbookingForm(form) form2.save() return redirect('booking') context = { 'form': form, } return render(request, … -
django allauth github authentication get 400 bad request
I'm trying to apply github authentication to my blog. I followed the tutorials but I got Social Network Login Failure. the detailed error is: {'provider': 'github', 'code': 'unknown', 'exception': HTTPError('400 Client Error: Bad Request for url: https://api.github.com/user?access_token=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')} I have confirmed the consistency of the url I set in github applications and my blog admin. I don't know what the problems are. -
How to iterate over a queryset in django template?
I am aware that this is very likely a duplicate but solutions provided in alike questions did not help. This is at first glance very straightforward issue, it should work by all means but for some reason, it does not. In a Django template, I am filtering a queryset of records based on the current user. Then I loop through it and want to display each result separately. Nothing complicated. The code goes: {% if user.is_authenticated %} {% if user.quick_links.all %} {{ user.quick_links.all }} <h2>Moje rychlé přístupy:</h2> {% for link in user.quick_liks.all %} <div class="col-md-2"> <a href="{{ link.link }}"><button class="btn btn-info">{{ link.link_name }</button></a> </div> {% endfor %} {% endif %} {% endif %} the {{ user.quick_links.all }} displays <QuerySet [<UserQuickAccessLink: Link uživatele david@email.eu: Google>, <UserQuickAccessLink: Link uživatele david@email.eu: Coding Music>]> but then the program never enters the for loop even though the iterable is clearly there. {% for link in user.quick_liks.all %} <div class="col-md-2"> <a href="{{ link.link }}"><button class="btn btn-info">{{ link.link_name }} </button></a> </div> {% endfor %} The above is never executed. What is the trick here? -
how to get the value of html element on the same page using django/jinja
i am writing code for django project and my html code is like, Course <select name="Courses" value="Courses" id="Courses"> <option value="MCA" selected>MCA</option> </select> Year/Pattern <select name="pattern" value="Courses" id="pattern"> <option value="newPattern" selected>New-Pattern</option> <option value="oldPattern" selected>Old-Pattern</option> </select> and here i wanted to get the value as MCA from the option element and then compare with the database value, on the same page, so how can I write jinja code for this...? -
Best way to manage file upload in a django-angular API Rest
I have a Django API Rest as backend and a Angular frontend interface for an app and I'm currently implementing a tool to upload specific files and save them in my server directory or in drive via its own API. My question is what is the best/most formal/correct way to handle this. Maybe angular can take the file and save it? Or should I pass the uploaded file via post request so Django do the necessary logic? I'll thank some example code for the post request if it is the second case.