Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I get 8 random images URLS from my database in Django?
I am having a situation where I am using build in User model which have One-to-One relation with my UserProfile Model. I have an image field for user profile image in my UserProfile model. So I have to show random 8 images URLS of my Users. How can I achieve this? Thanks in advance for your addition to my knowledge. -
Loading extra fields for update in Django dependent dropdown list
I implemented a dependent dropdown on my Django webapp. I used this tutorial Implementing dependent drop down. However, challenge comes when I want to update the form. To put this in perspective, let me recreate the code here. Model.py class VehicleMake(models.Model): make = models.CharField(max_length=20) manufacturer = models.CharField(max_length=20) def __str__(self): return self.make class VehicleModel(models.Model): make = models.ForeignKey(VehicleMake, on_delete=models.CASCADE) model_name = models.CharField(max_length=20) def __str__(self): return self.model_name class Vehicle(models.Model): model = models.ForeignKey(VehicleModel, on_delete=models.CASCADE) description = models.TextField() Notice that unlike in the provided tutorial, I don't have both of the dependent fields on the vehicle model. That is to avoid repetition since if you know the vehicle model, you will definitely know the make from the VehicleModel table. Here is the form: forms.py class VehicleDetails(forms.ModelForm): make = forms.ModelChoiceField(queryset=VehicleMake.objects.all(), empty_label="Select Vehicle Make") class Meta: model = Vehicle fields = ['make', 'model', 'description' ] def __init__(self, *args, **kwargs): super(VehicleDetails, self).__init__(*args, **kwargs) self.fields['model'].queryset = VehicleModel.objects.none() if 'make' in self.data: try: make = int(self.data.get('make')) self.fields['model'].queryset = VehicleModel.objects.filter(make=make).order_by('model_name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty VehicleModel queryset elif self.instance.pk: vehicle_model = VehicleModel.objects.get(self.instance.model) self.fields['make'] = vehicle_model.make self.fields['model'].queryset = self.instance.model_set.filter(make=vehicle_model.make).order_by('model_name') So, my challenge is, when I want to update the form, I get … -
How to replace Php contact form with DJango
I have website template downloaded and now I want to replace its contact form backend whichin PHP with django codes. I have created all the stuffs of django and can't figure out whats wrong because on requesting localhost its says sendEmail.php is missing which I delete as didn't need that for now. <div class="row contact__main"> <div class="col-eight tab-full contact__form"> <form name="contactForm" id="contactForm" method="post" action="{% url 'home' %}"> {% csrf_token %} <fieldset> <div class="form-field"> <input name="contactName" type="text" id="contactName" placeholder="Name" value="" minlength="2" required="" aria-required="true" class="full-width"> </div> <div class="form-field"> <input name="contactEmail" type="email" id="contactEmail" placeholder="Email" value="" required="" aria-required="true" class="full-width"> </div> <div class="form-field"> <input name="contactSubject" type="text" id="contactSubject" placeholder="Subject" value="" class="full-width"> </div> <div class="form-field"> <textarea name="contactMessage" id="contactMessage" placeholder="message" rows="10" cols="50" required="" aria-required="true" class="full-width"></textarea> </div> <div class="form-field"> <button class="full-width btn--primary" onsubmit="">Submit</button> <div class="submit-loader"> <div class="text-loader">Sending...</div> <div class="s-loader"> <div class="bounce1"></div> <div class="bounce2"></div> <div class="bounce3"></div> </div> </div> </div> </fieldset> </form> {% if contact_Name %} <!-- contact-success --> <div class="message-success"> Thanks {{ contact_Name }}! <br> Your mail has been recieved! I'll reply you shortly. </div> {% else %} <!-- contact-warning --> <div class="message-warning"> Something went wrong. Please try again. </div> {% endif %} This is my form code var ssContactForm = function() { /* local validation */ $('#contactForm').validate({ /* submit … -
Django retrieve data from html form
this is my form in html <form action="#about" method="POST"> {%csrf_token%} <h2>Signup today</h2> <input type="text" name="name" class="form-control" placeholder="Full name" required=""> <input type="email" name="email" class="form-control" placeholder="Your email address" required=""> <input type="password" name="password" class="form-control" placeholder="Your password" required=""> <button class="submit-btn form-control" id="form-submit">Get started</button> </form> and this is views.py def Student(request): if request.method=="POST": print('this post') name =request.POST['name'] email =request.POST['email'] print(name, email) return render(request,'#about') this is my urls.py from django.urls import path from . import views urlpatterns = [ path('',views.index, name='index.html'), path('',views.Student, name="#about"), ] I'm new to Django and I spent the last 24h trying to get this right, it doesn't show any error but it doesn't print any of what there is in views.py and it doesn't retrieve form data as well, could anyone explain to me what I'm doing wrong and how to properly retrieve html data form to django? Thank you very much in advance! -
Django: What is the difference between ./manage.py [...] and python manage.py [...]
I am following a tutorial for Django and at some point, it says to run ./manage.py migrate and says that if I get an error, I should fix it. I get an error but when I search for it I can't find specifically ./manage.py but I keep finding mixes with that and python manage.py. But when I run the code python3 manage.py everything works fine and I don't get errors. So are ./manage.py and python(3) manage.py different or not? -
Django Textarea contains additional newline
Why does a Django Textarea Widget render the additional newline? Textarea().render('name', 'value') Result: '<textarea name="name" cols="40" rows="10">\nvalue</textarea>' Is there a way to avoid the unneeded \n? -
how to split django rest and react app for docker
I'm trying do dockerize Django Rest Framework server and React app, but I don't understand howto manage connection between them. At the moment, they are connected like so: django-app settings.py: (with front beign my React app) INSTALLED_APPS = [ 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'django_database.apps.DjangoDatabaseConfig', 'rest_api.apps.RestApiConfig', 'front', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] And in my front directory I have: urls.py views.py . Now, if I'll split them in separate containers this solution is not going to work. Then what should I do insted ? -
How to pass primary key at views.py without changing url?
In index if someone clicks the link, the result will be incremented by 1. But if I enter http://127.0.0.1:8000/1 then the total_downloads is incremented by 1. But I want no change in url. So, in my index page, when download link will be hit by anyone the total_downloads will be updated by 1. My views.py: from django.shortcuts import render from django.http import HttpResponse import os from .models import FilesAdmin def index(request): context = {'file': FilesAdmin.objects.all()} return render(request,'libooki/index.html',context) def totals(request,pk): n = FilesAdmin.objects.get(pk=pk) n.total_downloads += 1 n.save() return HttpResponse("Downloaded!") def download(request,path): file_path = os.path.join(settings.MEDIA_ROOT,path) if os.path.exists(file_path): with open(file_path,'rb') as fh: response = HttpResponse(fh.read(),content_type="application/adminupload") response['Content-Disposition']='inline;filename'+os.path.basename(file_path) return response My urls.py: from django.conf.urls.static import static from libooki import views from django.conf.urls import url from django.views.static import serve urlpatterns = [ path('', views.index,name='index'), path('<int:pk>',views.totals,name='totals'), path('admin/', admin.site.urls), url(r'^download/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>hello</title> </head> <body> {% for post in file%} <h2>{{post.name}}</h2> <a href="{{post.adminupload.url}}" download="{{post.adminupload.url}}">Download</a> {% endfor %} </body> </html> -
django on IIS encounter 404 for media file with chinese character in filename
I deploy django on IIS. Everything is ok. But I encounter 404 when I download a media file with chinese character in filename. Page not found (404) Request Method: GET Request URL: http://localhost:8089/media/attachment/2021/02/%25B2%25E2.txt Raised by: django.views.static.serve "D:\Python\MrDoc\media\attachment\2021\02\%B2%E2.txt" Not exist. I know that %B2%E2 is URLencode with gb2312 of chinese character '测'. When the media file name contains only ASCII, such as 1.txt, no 404 and the file can be downloaded via browser. When I run server with "py manage.py runserver 0.0.0.0:8088", no 404 for media file name with chinese character. So the 404 problem is probably caused by the urlencode of IIS. I do not know how to solve this problem. The web.config file content: <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="DjangoWebHandler" path="*" verb="*" modules="FastCgiModule" scriptProcessor="D:\Python\virtualenv\MrDoc\Scripts\python.exe|&quot;D:\Python\virtualenv\MrDoc\Lib\site-packages\wfastcgi.py&quot;" resourceType="Unspecified" /> </handlers> </system.webServer> </configuration> The settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') The urls.py: re_path('^static/(?P<path>.*)$',serve,{'document_root':settings.STATIC_ROOT}), re_path('^media/(?P<path>.*)$',serve,{'document_root':settings.MEDIA_ROOT}), or: ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
how to register this offline wallet in sign up?
here is my view.py from models import balance def profile(request): user = balance.objects.get(user=request.user return render(request,'profile.html',{"balance":user.balance}) and created model here class Balance(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) balance = models.IntegerField(default=0) def __str__(self): return self.user.username here is my registration and i think i have made mistake here: @unauthenticated_user def register(request): form = CreateUser() if request.method == 'POST': form = CreateUser(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') instance = Balance(user=request.user, balance=0) instance.save() messages.success(request, "Congrats !!" + username + "now you are member of the society") return redirect('login') context = {'form': form} return render(request, "register.html", context) I am able fetch the balance of the user in from the database at the time of showing the profile but not able save it into database while registration. As erorr returns: ValueError at /register/ Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7f98c64caa60>>": "Balance.user" must be a "User" instance -
the best way to insert three related models in django rest api in one request for user roles
I have three models for defining user roles. Each User can have multiple roles. What is the best way to inserts roles as a list in one request that also it will create a user account for them? my models: class Account(AbstractBaseUser): # django's own fields email = models.EmailField(blank=True, null=True, max_length=60, unique=True, verbose_name='آدرس ا .... class Role(models.Model): name = models.CharField(max_length=20, verbose_name='اسم رول') def __str__(self): return self.name class Meta: verbose_name = 'رول' verbose_name_plural = 'رول ها' class UserRole(models.Model): account = models.OneToOneField(Account, on_delete=models.CASCADE, verbose_name='اکانت', related_name='user_roles') roles = models.ManyToManyField(Role, verbose_name='رول') is_active = models.BooleanField(verbose_name='فعال') def __str__(self): return f"{self.account}" class Meta: verbose_name = 'رول کاربر' verbose_name_plural = 'رول های کاربر' my serializers: class RoleSerializer(serializers.ModelSerializer): class Meta: model = Role fields = ['id', 'name'] class UserRoleSerializer(serializers.ModelSerializer): roles = RoleSerializer(many=True, read_only=True) class Meta: model = UserRole fields = ['roles', 'is_active'] extra_kwargs = {'roles': {'required': False}} class NewAccountSerializer(serializers.ModelSerializer): user_roles = UserRoleSerializer(many=False, read_only=False) class Meta: model = get_user_model() fields = ['phone_number', 'user_roles',] -
What are the differences between APIView and Django generic views in terms of usage?
I am trying to build a Django backend API that will be accessible both by a mobile app and a website. I am setting up the user authentication functionality using the rest-framework module. Can anyone explain the difference in functionality and usage between the two types of views (APIView and Django display/editing generic views) and which ones would be more suitable for my goals? -
Python Django - multipule update form in a loop
So I'm trying to make a template which will show tests from different students and I would like to make it possible to grade (with a choice field) those tests on one view. I have a loop which shows all of ungraded tests and next to them an update possibility. So I tried this views.py class TestUpdate(UpdateView): model = Tests fields = ['grade'] template_name = "tests_update.html" success_url = reverse_lazy('home') class ClassDetails(WhichUserMixin, DetailView): model = Classes template_name = "class_test_details.html" def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) tests = Tests.objects.all().filter(grade = None, teacher = self.current_teacher) context['ungraded_tests'] = tests return context models.py class Tests(models.Model): teacher = models.ForeignKey(Teacher,on_delete=models.CASCADE, null = True) desc = models.CharField(max_length = 50, null = True) student = models.ForeignKey(Student, on_delete = models.CASCADE, null = True) subject = models.CharField(max_length=10, choices=SUBJECTS, null = True) classes = models.ForeignKey(Classes, on_delete = models.CASCADE, null = True) class Grades(models.IntegerChoices): F = 1 E = 2 D = 3 C = 4 B = 5 A = 6 grade = models.IntegerField(choices = Grades.choices, null = True) def __str__(self): return self.desc template: <h2> Class</h2> {% for test in ungraded_tests %} <p>{{test.student.user.first_name}} {{test.student.user.last_name}} - Class: {{test.classes}} - {{test.desc}}</p> <form method="post"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" class = 'btn … -
Django: Import legacy database data keeping primary keys having an autokey
I am using Django to develop new software to replace a legacy one, and all my new models have auto-increment primary keys. I want to import records from the legacy database keeping their original primary keys (users know them all), but I don't know how to do it with auto-increment primary keys. Is it possible to create my models with integer primary keys and change them to auto-increment ones without losing their data? -
How to compare DateTimeField with timezone.now()
I'm new to python/django and I have an Events app where users can see upcoming events of an organization but I don't know how to show only future events and disregard events from the past. models.py class Event(models.Model): title = models.CharField(max_length=500) description = RichTextField() start_date = models.DateTimeField() end_date = models.DateTimeField() created_date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(NewUser, on_delete=models.CASCADE) views.py class ShowEventsListPageView(ListView): model = Event template_name = 'registration/user_events.html' def get_queryset(self, *args, **kwargs): user = self.kwargs['pk'] return Event.objects.filter(author=user).annotate(Event.end_date > timezone.now()).order_by('-start_date') This code is returning '>' not supported between instances of 'DeferredAttribute' and 'datetime.datetime' -
Mapping access token to client IP
My Setup I am using React and Django as frontend & backend. For authorization purposes I chose Django-rest-knox, which works via tokens stored in a database. My Problem Now if an attacker gets a hold of the token (stored in local storage on the client side after a login), he can do anything that the user is able to. There is some expiration on the token and the ability to destroy all tokens of the user by the user himself. But I'd like to be on the safer side. My Solution My idea is to map all tokens to the IP address (of the user) that was used to login. That way the token would only be usable on the machine that was used to login. That token-to-IP-address relation would be checked on the backend. My Questions Is the idea feasible at all or is there anything in the nature of those IP addresses that breaks my intent? What is the best way to get the client IP-address? Do you think that is a secure approach? Thanks for the help! -
jquery save get response as csv file
I have this view that returns csv data def get_newsletters_email(request): if request.user.is_staff: df = pd.DataFrame(list(NewsletterSubscription.objects.all().values('name', 'email'))) file_path = settings.MEDIA_ROOT + '/newsletter_emails/emails.csv' df.to_csv(file_path) with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/csv") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response else: response = {} return HttpResponse( json.dumps(response), content_type="application/json" ) from a get request $('.download-newsletters').click(function(e){ e.preventDefault(); $.get("/newsletter_emails/", function( data ) { //Save file }); }); since it's a link click that prevents any redirect I need to tell the browser to use the response and opt to save the data. -
Can't login to Django Admin with custom User Model
I create a custom model for User, By this I can create superuser from command line, and its create successfully. But when I trying to login to Django admin with created Super user its show me This error @property def is_staff(self): return self.staff @property def is_superuser(self): return self.superuser @property def is_active(self): return self.active These property also set True models.py from django.db import models from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser) class UserManager(BaseUserManager): def create_user(self, email, password=None): """ creates a user with given email and password """ if not email: raise ValueError('user must have a email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(self._db) return user def create_staffuser(self, email, password): """ creates a user with staff permissions """ user = self.create_user( email=email, password=password ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, password): """ creates a superuser with email and password """ user = self.create_user( email=email, password=password ) user.staff = True user.superuser = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='Email address', max_length=255, unique=True ) active = models.BooleanField(default=False) staff = models.BooleanField(default=False) # <- admin user, not super user superuser = models.BooleanField(default=False) # <- super user USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] # <- email and password are required by default … -
Replace bearer token to Token
I am trying to implement google authorization in django rest. I am using django-rest-framework-social-oauth2. I get a response with a Bearer token. Is it possible to change Bearer to Token? And remove everything in the response, leaving only access and refresh token "access_token": "xX7KPdrMeINhO7yT0g5jhqHoR3oipI", "expires_in": 36000, "token_type": "Bearer", "scope": "read write", "refresh_token": "cwlZsSDL15NVbcE1VeUd5YEihQfR0E" -
How to delete a logger in the logger hierarchy using python3 logging?
I have created a logger hierarchy using the python3 logging module. Since I'm using multiprocessing (fork-based), I need re-create my loggers in the child processes, which are otherwise inherited. How can I delete loggers in the logging logger hierarchy (or reset the logging module in child processes)? I've looked at logging.Logger.removeHandler(), but I'd rather not have to loop through all loggers and call that method for each handler. Furthermore, I've experienced weird behaviour when attempting this. -
Total marks is not getting calculated properly here. Its always showing 0. How can i solve this?
1.This is my html code. <form class="form" autocomplete="off" onsubmit="return saveAns()" action="/calculate_marks_view" method="POST"> {% csrf_token %} <h1 style="text-align: center;">{{test.course_id.course_name}}</h1> {% for q in questions%} <h3 class="text-info">{{ forloop.counter }}. {{q.question}}</h3><h4 style="text-align: right;">[Marks {{q.marks}}]</h4> <input type="hidden" name="csrfmiddlewaretoken" value="{{csrf_token}}"> <div class="form-check mx-4"> <input class="form-check-input" type="radio" name="{{ forloop.counter }}" id="{{q.option1}}" value="Option1"> <label class="form-check-label" for="option1"> {{q.option1}} </label> </div> <div class="form-check mx-4"> <input class="form-check-input" type="radio" name="{{ forloop.counter }}" id="{{q.option2}}" value="Option2"> <label class="form-check-label" for="option2"> {{q.option2}} </label> </div> <div class="form-check mx-4"> <input class="form-check-input" type="radio" name="{{ forloop.counter }}" id="{{q.option3}}" value="Option3"> <label class="form-check-label" for="option3"> {{q.option3}} </label> </div> <div class="form-check mx-4"> <input class="form-check-input" type="radio" name="{{ forloop.counter }}" id="{{q.option4}}" value="Option4"> <label class="form-check-label" for="option4"> {{q.option4}} </label> </div> {% endfor %} <input class="btn btn-info btn-lg" type="submit" value="Submit"> </form> 2.This is my javascript code to save answer through cookies. But i guess that something is wrong here, but i couldn't put my eye on it. <script> function saveAns(){ var answer = document.getElementsByTagName('input'); for(i = 0; i < answer.length; i++) { if(answer[i].type="radio") { if(answer[i].checked){ setCookie(answer[i].name,answer[i].value,3) } } } } function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+ d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; } This is my calculate_marks_view. Here I … -
How can I pass string variable in JavaScript using Django URL?
This is my script: var id = $('#filename').val(); location.href = "{% url 'officelyapp:finalTemplate' privateId=id %}" This is my url: path('signature/template/merge/private/access/<str:privateId>/', views.finalTemplate, name='finalTemplate') I get the following error attached below whenever I tried to load my page. Error Shown In Image I find this link: https://stackoverflow.com/.../get-javascript-variables... that passes JavaScript value like this: window.location = "{% url 'your_view_name' 1234 %}".replace(/1234/, tmp.toString()); But this only works when one specifically writes a specific integer value in it like 1234 in the above line of code. -
Hotel Management System using Django and PostgreSQL
I'm a Front-End Developer and Graphics Designer. I need to build web-based application and i'm doing backend for first time using Django for my final yaer project. So, the idea of my project is that there will be waiter, stockstaff, chef, cashier and manager and each user will have their own pages after login on webite and it will go like this: Waiter book tables and take order when customer’s arrives to the restaurant using his page. StockStaff then get notify for the food item, they have to check in stock. Then at same time staff will notify both waiter, if there is stock or not and manger, if there is no stock. If waiter get notify that there is stock available then waiter will notify chef to cook meal otherwise he will go to customer and say no food available. At the same time manager will get notify too that there is no stock, he will notify staff that stock will be updated soon only. After meal is cooked, chef will notify waiter to take the meal at particular table number. Overall details are then transferred to cashier so that they can generate payment. Server process the request and … -
Why aren't my custom routes in django recognized?
I'm trying this Django tutorial https://www.javatpoint.com/django-crud-application Here is how my view is defined: def show(request): employees = Employee.objects.all() return render(request, "show.html", {'employees': employees}) Here is how my url file in the django_crud project (my project name) is defined: from django.contrib import admin from django.urls import path, include from employee import views urlpatterns = [ path('admin/', admin.site.urls), path('emp', views.emp), path('show', views.show), path('edit/<int:id>', views.edit), path('update/<int:id>', views.update), path('delete/<int:id>', views.destroy), ] My templates are in employee/templates My app is obviously registered: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'employee' ] I run the server with python manage.py runserver with no errors. Migrations are done with no error. The database is empty, but this should not matter. The problem is that only the admin route work. The show route (or any other) doesn't work. I hate when a tutorial doesn't work and I'm triying to figure out the problem, but I don't see any issue. Maybe the turorial is about an old version of Django and I have something missing? Any insight? -
Python Application for mobile
Hy everyone, I want to create python base earthquake mobile application for android. You anyone have idea about it guide me how can I create it and what are the prerequisites for application.