Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why swagger documentation doesn't work on PythonAnywhere domain?
I have used swagger to document my APIs on the Django rest framework, and deploy it on Pythonanywhere. but the documentation URL doesn't have any response. it is my urls.py code for swagger: from drf_yasg.views import get_schema_view from drf_yasg import openapi schema_view = get_schema_view( openapi.Info( title="BoardGame API", default_version='v1', description="Test description", terms_of_service="http://****.pythonanywhere.com/", contact=openapi.Contact(email="contact@boardgame.local"), license=openapi.License(name="TEST License"), ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ ... path('', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), ] and my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'drf_yasg', 'rest_framework_swagger', 'rest_framework_simplejwt', 'django_extensions', ... ] -
How to get Django Admin reset password functionality?
When I enter the login view, I see the username & pasword fields and the only button available is "Login". How come there is no "forgot your password?" here? I've looked everywhere and can't find anything to satisfy this. Is it that there is no such functionality in Django? (which would surprise me a lot) I've already read about Authentication Views, but I'm pretty sure this is not it. Also, when I access /accounts/login it prompts the error TemplateDoesNotExist at /accounts/login. Do I really have to implement this? Are there no defaults? -
django-bootstrap-modal-form workaround for FileField required
I am using the django-bootstrap-modal-form package and there currently is an open bug for FileField where it cannot be set to required on the Model or Form level, else the form does not process. I have not seen any updates as to when this will be fixed, however it is a pretty important feature to have a file upload required as a field in a form. Can anyone help to provide me with a workaround for this in the view on form_valid or post? passing error back to modal to notify user of required field? views.py # Create class FileUploadCreateView(BSModalCreateView): template_name = 'fileupload/create-file.html' form_class = FileUploadModelForm success_message = 'Success: File was uploaded.' success_url = reverse_lazy('files_list') # Validate FileUpload field is not null # Until FileField bug fixed with django-modal-forms blank=False # Add required fields prior to posting form def form_valid(self, form): file_upload = form.cleaned_data['file_upload'] if file_upload == None: form.add_error(None, "File is required.") return super().form_valid(form) else: self.instance = form.save(commit=False) self.instance.file_upload = form.cleaned_data['file_upload'] self.instance.my_user = self.request.user self.instance.file_status = 'ready' return super().form_valid(form) template <form method="post" action="" enctype="multipart/form-data"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" style="color:#7a7a7a;"> <i class="fas fa-plus-square fa-med pr-2 align-middle"></i> <span class="align-middle">ADD File</span> </h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> … -
Django _set.all in template with one to many relationship
I am trying to output a web page with many blog posts, each of them potentially containing many images. Models.py: class FreeImage(models.Model): f_img = models.ImageField(null=True, blank=True, upload_to="img/f") f_img_alt = models.CharField(max_length=100, blank=True, null=True) post = models.ForeignKey('Post', on_delete=models.SET_NULL, null=True) class Post(models.Model): title = models.CharField(max_length=100, unique=True) Views.py: def home_view(request): posts = Post.objects.order_by('-id') freeimgs = FreeImage.objects.filter(post__in=posts) context = { 'posts':posts, 'freeimgs' :freeimgs,} return render(request, 'home.html', context) Template: {% extends 'base.html' %} {% block main %} {% for post in posts%} <h3>{{post.title}}</h3> {% for i in freeimgs.post_set.all %} <h5>Test</h5> <img src="{{ freeimage.f_img.url }}" alt="{{freeimage.f_img_alt}}"> {% endfor %} {% endfor %} {% endblock %} freeimgs.post_set.all does not return anything here. I have no idea how else I could show the images corresponding to the right post inside template. -
How return ObjectId instead of ID from Django REST Serializer?
Django REST Serializer return int id not ObjectId _id: api_views.py urls.py models.py serializers.py Return int 27, not a ObjectId: My requirements.txt Django==2.2.17 sqlparse==0.2.4 djongo==1.3.1 djangorestframework==3.12.2 rest-meets-djongo==0.0.13 -
Is this use of select_related() beneficial?
In Django's documentation, there is the following example. >>> b = Blog.objects.get(pk=1) # Update all the headlines belonging to this Blog. >>> Entry.objects.select_related().filter(blog=b).update(headline='Everything is the same') And the example is based on the following definitions of models. from django.db import models class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=200) email = models.EmailField() def __str__(self): return self.name class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() mod_date = models.DateField() authors = models.ManyToManyField(Author) number_of_comments = models.IntegerField() number_of_pingbacks = models.IntegerField() rating = models.IntegerField() def __str__(self): return self.headline What is the benefit of having select_related() in the line of Entry.objects.select_related().filter(blog=b).update(headline='Everything is the same') ? I don't see any benefit of having select_related() in the update statement. In fact, I think Entry.objects.filter(blog=b).update(headline='Everything is the same') has a better performance for it doesn't perform an unneeded inner join and doesn't populate the unneeded Blog objects. What do you think? -
Django Rest Framework - Search by query within a particular category of books
in my Django Rest Framework project, I have the following simple model: class Book(models.Model): book_title = models.CharField(max_length=100, blank=False) book_category = models.CharField(max_length=50, blank=False) Now, the user should be able to search for a title within a certain category. Therefore, I use the built-in SearchFilter provided by Django Rest Framework: class SearchBooks(generics.ListAPIView): serializer_class = BookSerializer filter_backends = [filters.SearchFilter] search_fields = ['book_title'] def get_queryset(self): return Book.objects.filter(book_category=self.request.data.get('category')) So, what I want is that the user should type the book title as search query but Django should only search within a certain category. What I do in PostMan: I pass the book title as search query and put the category into the Body section as form-data. For example, let's say I have two Book instances: Book(book_title="My Happy Days", book_category="Horror") Book(book_title="My Happy Days", book_category="Lifestyle") When I type http://127.0.0.1:8000/books/searchBooks?search=My Happy Days with category=Horror in the Body section of the PostMan application as form-data, then I should get only the 1st Book instance. But with the view you have seen above, I get both instances no matter what the category is. With my current solution, it seems that Django only focuses on the search query and that what I implemented in the get_queryset() method is not computed. How … -
How to filter queryset to current user in Django
I have a site that grabs all the records that is listed under the current user. Right now it grabs and filters it to all the available records and then filters it to the current user. Is there a way to make it so it doesn't have to do the initial filtering? class PromiseView(SingleTableView): queryset = Promise.objects.filter(deleted__isnull=True) table_class = PromiseTable template_name = 'promise.html' def get_queryset(self): current_user = str(self.request.user)[10:len(str(self.request.user))] return self.queryset.filter( windows_user=current_user, # There has to be a better way for this one. ) I would want to make it so the initial query set is equal to queryset = Promise.objects.filter(windows_user=current_user,deleted__isnull=True) and get rid of the get_queryset function. It makes no sense to query the entire database first and then query it again to filter it to how I want it. -
django favicon icon does not display
I have the following django project file structure: lecture3/ lecture3/ urls.py tasks/ static/ img/ favicon.ico urls.py my tasks/urls.py file is: from django.urls import path from . import views from django.contrib.staticfiles.storage import staticfiles_storage from django.views.generic.base import RedirectView app_name = 'tasks' urlpatterns = [ path("",views.index, name="index" ), path("add",views.add, name="add" ), path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('img/favicon.ico'))), ] but when I run I get a 404 error. How do I fix this? -
Running my LoginView doesn't log me in and writes the csrf-token and the User credentials in the URL
Whenever I try to login using my custom class-based LoginView, my URL updates (writes the csrf token, the password, and the username in it), and nothing else happens. My views.py class LoginView(View): def post(self, request): username = request.Post['username'] password = request.Post['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('/') else: message.info(request, 'inavalid credentials!') return redirect('login') else: return render(request, 'registration/login.html') def get(self, request): return render(request, 'registration/login.html') My urls.py urlpatterns = [ path('login/', LoginView.as_view(), name='user-login'), ] My login.html <body> <form class="box" action="{% url 'user-login'%}" methode="post"> {% csrf_token %} <h1>Login</h1> <hr class="line"> <input type="text" name="username" placeholder="&#xf007; Username"> <input type="password" name="password" placeholder="&#xf084; Password"> <p>Don't have an Account? <a href="{% url 'register' %}">Sign in!</a></p> <hr class="line"> <input type="submit" name="" value="Login"> <input type="submit" value="Login"> <p>{{ form.errors }}</p> <input class="btn login_btn" type="submit" value="Login"> </form> {% for message in messages %} <p id="messages">{{message}}</p> {% endfor %} The URL that appears after I submitted through the Button on my login.html Does anyone have any ideas? I have spent about 8 hours to make it work and tried a lot of different approches but nothing seems to work. -
Django Query string stay in url during session
I pass the Query string through a form like this: <form action="stockChart" autocomplete="off" method="GET"> <input type="text" required="required" name="Ticker" maxlength="5"> </form> and then it redirects me to the page with all the data corresponding to the input and puts my input in the url /stockChart?Ticker=AAPL views.py def stockChart(request): TICKER = request.GET['Ticker'].upper() But if I go to another tab where I also want to use the same ticker it doesn't work, since the URL doesn't have the query string in it. Right now I'm using TICKER = request.session['Ticker'] but by doing that the URL doesn't contain the query string. Is there a way to keep the string (?Ticker?AAPL) in the url, when navigating to other pages? -
Django get objects that are foreign key of two models
I have the following three models where Budget and Sale both contain a foreign key to Customer: class Customer(models.Model): name = models.CharField(max_length=45) # ... class Budget(models.Model): customer = models.ForeignKey(Customer, on_delete=models.PROTECT) # ... class Sale(models.Model): customer = models.ForeignKey(Customer, on_delete=models.PROTECT) # ... I want to get a queryset of all Customer objects for which both a Budget and Sale exists. I initially tried getting the intersection of the customer field of all Budget and Sale objects: customers = { budget.customer for budget in Budget.objects.all() } & { sale.customer for sale in Sale.objects.all() } This returns the correct objects, but becomes horribly inefficient as the size of my database grows. How can I retrieve these objects in a more efficient way? Thanks for any help! -
Django Foreign Key not getting updated
Hi Guys I'm new to Django and I'm struggling with a problem that should be easy to be solved. This is my UserSerializer: class UserSerializer(serializers.ModelSerializer): role = RoleSerializer(many=False) class Meta: model = User fields = ['id', 'first_name', 'last_name', 'email', 'password', 'role', 'role_id'] extra_kwargs = {'password': {'write_only': True},} This is my GenericAPIView: class UserGenericAPIView(generics.GenericAPIView, mixins.UpdateModelMixin): serializer_class = UserSerializer queryset = User.objects.all() def put(self, request, pk=None): return self.partial_update(request, pk) The request that the frontend sends is this: PUT http://localhost:8000/api/users/1/ Content-Type: application/json { "first_name": "First Name", "last_name": "Last Name", "email": "email@example.com", "role_id": 2 } All the fields change except for the role_id... Any idea what is the best way to update the role_id? -
Why is django not sending mail?
hola estoy tratando de enviar correo atraves de django con smtp.lib library pero a la hora de ejecutar me dice que la libreria no me reconoce los datos de autenticacion este es el codigo que tengo dentro de mi archivostrong text -
How can I create a Django model with days of the week already embeeded?
How can I create a model, just like in this image: That it has the Days of the week already embeeded, PLEASE I don't need neither the date nor a calendar, just a model with every day of the week, so that each new class already has these days and from where i can add additional information (options). What kind of relation or model form should be added to a class so that it looks like this when created? -
Opening database in Pycharm for Django project
I am working on a django project using pycharm. How do I view the data in my sqlite db. From sources I found online, I have to open View-Tools Windows-Database, but I don't have that option. Can anyone help? I barely starting using pycharm today, thanksenter image description here -
How to show a field as list of instead of choicelist on django
Here is an invoice. In this case, it shows lines of products and user can select products on each line from dropdown list. My need is to show all products, each line with one product which i can fill with details as price and quantity as example bellow. Models: class Invoice(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) number = models.CharField(max_length=64, unique=True, default=invoice_number) date = models.DateField(default=timezone.now) client = models.ForeignKey('Client',on_delete=models.CASCADE) class InvoiceItem(models.Model): invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(max_digits=20, decimal_places=2) quantity = models.DecimalField(default=0, max_digits=20, decimal_places=2) forms: class InvoiceForm(ModelForm): class Meta: model = Invoice fields = "__all__" class InvoiceItemForm(ModelForm): class Meta: model = InvoiceItem fields = "__all__" InvoiceItemFormSet = inlineformset_factory(Invoice, InvoiceItem, form=InvoiceItemForm, extra=3, can_delete=False) View : class InvoiceCreate(CreateView): form_class = InvoiceForm model = Invoice template_name = "sales/invoice_form.html" def get_success_url(self): return reverse_lazy('invoice_details', kwargs={'pk' : self.object.pk}) def get(self, request, *args, **kwargs): company_instance = request.user.company self.object = None form = InvoiceForm(company_instance) formset = InvoiceItemFormSet(form_kwargs={"company":company_instance}) products = list(Product.objects.values()) return self.render_to_response( self.get_context_data(form=form,formset=formset, products=products)) def post(self, request, *args, **kwargs): self.object = None company_instance = request.user.company form = InvoiceForm(company_instance, self.request.POST) formset = InvoiceItemFormSet(self.request.POST, form_kwargs={"company": company_instance}) if (form.is_valid() or formset.is_valid()): return self.form_valid(form, formset) else: return self.form_invalid(form, formset) def form_valid(self, form, formset): self.object = form.save() formset.instance = self.object formset.save() try: … -
Using ForEach in Javascript with a django json response
I have a json response from django and I'm trying to display each item in the json response as its own div using javascript. The json response is as follows: [{"model": "network.posts", "pk": 1, "fields": {"user": 1, "post": "hi", "timestamp": "2020-11-10T21:24:51.118Z"}}, {"model": "network.posts", "pk": 2, "fields": {"user": 1, "post": "My first post!", "timestamp": "2020-11-10T21:25:07.893Z"}}, {"model": "network.posts", "pk": 3, "fields": {"user": 2, "post": "This is my 3rd post :)", "timestamp": "2020-11-10T22:43:23.383Z"}}, {"model": "network.posts", "pk": 4, "fields": {"user": 2, "post": "This is my 3rd post :)", "timestamp": "2020-11-10T22:44:34.421Z"}}, {"model": "network.posts", "pk": 5, "fields": {"user": 2, "post": "This is my 3rd post :)", "timestamp": "2020-11-10T22:47:17.896Z"}}] That comes from a django view which is: def get_posts (request): # Get list of posts posts = Posts.objects.all() if request.method == "GET": return JsonResponse(serializers.serialize('json', posts), safe=False) For now I'm just trying to console log each 'post' using javascript. Here's what I have so far: // Load all posts fetch(`/posts`) .then(response => response.json()) .then(data => { console.log(data); }); That works, but it logs the whole json response. What I want to do is chop it up so each post is logged separately, but I can't work it out! I tried using ForEach like this: // Load all posts … -
What should be the method called with a number field in django
I have created a forms.py file in my Django application to add additional fields to my Registration form. email attribute is added. Now i want to enter an attribute of Student no that every user will have. so instead of forms.EmailField() what field should my Student_No attribute should have from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegistrationForm(UserCreationForm): email = forms.EmailField() -
Django, how to have an array in model without M2M?
I want my model to have an array of other model's instances. Let me explain. I have a Company model which has a localizations field which is supposed to be a set/array of addresses. Since one address can only be for one Company, M2M relationship seems wrong here. When Company gets deleted, all of its localizations should also be deleted. How do I accomplish that? (I don't use Postgres) -
Django reverse multiple args
i want to use multiple args in Django sitemaps reverse ,but not working , i mean example.com/title/daily and /title/love def get_absolute_url(self): return reverse("singCategory", args=[self.Title, "Daily" "Love"]) i try but not working args=[self.Title, "Daily" and "Love"]) args=[self.Title, "Daily" or "Love"]) -
Django ORM SELECT with JOIN (and some condisions)
So sorry, I don't have up skills from Django ORM, as so have this question. I have that model: class Calendar(models.Model): start = models.DateField(null=False) end = models.DateField(null=False) user = models.ForeignKey(User, models.CASCADE, related_name='calendars') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) And I want aggregate all intersections. This not big deal. Then I execute sql query: select a.id, b.id from calendar a join (select * from calendar where user_id = %s) b on ( a.id <> b.id and a.start < b.end and a.end > b.start ) where b.id is not null order by a.id, a.id; But I have no idea how this query translate in ORM presentation. -
How to achieve shared customers across accounts in stripe ? (Clone customers across accounts)
I am working on stripe payments, where i require having a shared customer across different connected accounts, that are connected with the platform, I am using "Express Accounts" in stripe connect for connecting the connected accounts, and all of them are linked with the platform account. On the frontend (client-side) (Angular), using the "Stripe Prebuilt checkout page", for accepting payment and I am verifying the payment in webhooks(checkout.session.completed) at backend using Django Rest Framework. I am using Destination Charges, for handling the payments and separate charges and transfers. (That i am able to achieve using stripe prebuilt checkout page by specifying payment_intent_data.application_fee_amount and payment_intent_data.transfer_data.destination) A destination charge means the charge is processed on the platform and then the funds are immediately and automatically transferred to the connected account’s pending balance. Now I have a requirement where I need to have shared customers and share customers across the connected accounts, Is it even possible to achieve shared customers using a stripe prebuilt checkout page? If yes, how can I achieve it? Or Do I need to go with "Custom payment flow" for accepting a payment? I tried to follow this article Clone customers across accounts but I have not had any … -
How do I can change the default django rest_auth redirection?
hi I'm using django rest_auth package for managing my project's authentication system. when I do register or log in with a user it gives me just a key and doesn't redirect user to any page and for logout as well. how do I can redirect users to my home page after login, logout and register??? -
Django NoReverseMatch at /register
I'm attempting to enable users to register on my Django based website; however I am running into the following error: NoReverseMatch at /register Reverse for 'register' not found. 'register' is not a valid view function or pattern name. I am struggling to see what needs to be changed below, I feel that I have tried tweaking everything to get it working, but nothing seems to. I am using a namespace "Flightfinder" for my application, not sure if this has something to do with it? Full Error: NoReverseMatch at /register Reverse for 'register' not found. 'register' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8001/register Django Version: 3.1.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'register' not found. 'register' is not a valid view function or pattern name. Exception Location: /mnt/c/Users/tjmce/Desktop/Git/CS50w/Final Project/finalproject/.venv/lib/python3.8/site-packages/django/urls/resolvers.py, line 685, in _reverse_with_prefix Python Executable: /mnt/c/Users/tjmce/Desktop/Git/CS50w/Final Project/finalproject/.venv/bin/python3 Python Version: 3.8.5 Python Path: ['/mnt/c/Users/tjmce/Desktop/Git/CS50w/Final Project/finalproject', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/mnt/c/Users/tjmce/Desktop/Git/CS50w/Final ' 'Project/finalproject/.venv/lib/python3.8/site-packages'] Server time: Wed, 11 Nov 2020 20:32:27 +0000 Layout Template: {% load static %} <!doctype html> <html lang="en"> <head> <!-- jQuery & jQuery UI --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <!-- Bootstrap (includes Popper) --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script> <!-- …