Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting value from looped form
I'm building an ecommerce with django that sells shirts and prints. My idea is showing a form for the shirts so customers can select the desired size. Like this: {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row justify-content-center"> {% for product in products %} <div class="col-xs-12"> <img class="thumbnail" src="{{ product.imageURL }}"> <div class="box-element product"> <div class="container"> <div class="row"> <div class="col"> <h4><strong>{{ product.name }}</strong></h4> </div> {% if product.print %} <div class="col" id="size-info"> <h4 style="display: inline-block; float: right"> <strong>size: {{ product.print.size }}</strong></h4> </div> {% endif %} </div> </div> <hr> <div class="container"> <div class="row"> <div class="col-xs-2"> <div class="row"> {% if product.shirt %} <div class="col select-outline"> <select id="size-selector" class="browser-default custom-select"> <option value="" disabled>Size</option> {% for value, text in product.shirt.available_sizes %} <option value="{{ text }}">{{ text }}</option> {% endfor %} </select> </div> {% endif %} </div> </div> <div class="col-8"> <button data-product="{{ product.id }}" data-action="add" data-size="{{ text }}" class="btn btn-outline-secondary add-btn update-cart">Add to Cart </button> <a class="btn btn-outline-success" href="#">View</a> </div> <div class="col"> <h4 style="display: inline-block; float: right"><strong>${{ product.price }}</strong> </h4> </div> </div> </div> </div> </div> {% endfor %} {% endblock content %} </div> All the products are looped, and if the product is a shirt, it will contain this "size-selector" … -
Django: when using a customer user model (AbstractBaseUser), what is the best way to organise the forms across the admin.py and forms.py files?
I'm new to programming and Django, and I'm building a website implementing a custom user model using AbstractBaseUser. I want the forms in the admin site to mirror almost all of the forms being used by clients on the website. For example, creating a user on the live website will require the same data inputs as when creating a user on the admin site, and the same applies to other forms like creating posts. How should I arrange the forms across the admin.py and forms.py files? Should I build them in admin.py and then import them into forms.py? Or the opposite? Or should I keep them completely separate (both inheriting from the same classes and referencing the same models)? Or have I just misunderstood the relationship between admin.py and forms.py? -
Traslate this queryset?
My query is made in MYSQL I would like to know how to translate it to the ORM django tnhanks you SELECT *,(SELECT count(*) FROM tesisnueva.donador_desactivar ds where ds.motivo=1 and ds.donador_id= dd.id and date_add(ds.fecha_desactivar, INTERVAL 90 DAY)<now()) as cantidad FROM tesisnueva.donador_donador dd where dd.genero='F'; -
How to use Rest Framework's default token authentication view?
I am trying to use DRF's builtin TokenAuthentication view, but I can't get it to work. Here is the test: import requests import json data = json.dumps({ 'username': 'test-sandbox-root', 'password': 'password' }) headers = {'Content-Type': 'application/json'} r = requests.post('http://localhost:8000/api/auth', data=data, headers=headers) >>> r.status_code 400 >>> r.text '{"non_field_errors":["Unable to log in with provided credentials."]}' But the user clearly exists: >>> User.objects.get(username='test-sandbox-root', password='password') <User: test-sandbox-root> I've added the DEFAULT_AUTHENTICATION_CLASSES to my settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ] } And migrated the rest_framework.authtoken app: INSTALLED_APPS = [ ... 'rest_framework', 'rest_framework.authtoken', ... ] And added optain_auth_token to my urls.py: from rest_framework.authtoken import views urlpatterns = [ path('/api/auth', views.obtain_auth_token), ] What am I missing? -
Django - Creating Field that is Product of Other Fields and Access on Querysets and Serializers
I have a model that has two fields hours and hour_cost. I want a field that is named total_cost where total_cost = hours * hours_cost. I thought of creating a new field in the model, but after some browsing on stackoverflow I came to the conclusion that I shouldn't be saving total_cost to database and I need to use the @property. SO 1 or annotate every queryset with total_cost. Models.py class Example(models.Model): hours = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) hour_cost = models.FloatField(blank=True, null=True) @property def total(self): return self.hours * self.rate But I would like for total to be in every queryset when I do Example.objects.all() automatically and for it to also be added to automatically to the serializers(what I mean by that is that I want 'total' included on the API response, maybe I don't need it on serializer, just queryset?). I've been looking on stackoverflow and many of the answers seem outdated 2011, 2012. Some look too complex for what I'm trying to do and some look like they are not following best programming practices. Is there a clean way to add automatically add the @property fields to querysets, admin, and APIs? -
Django Allauth signup form not saving custom fields
I'm trying to do something that should be very simple: adding a field to signup and saving it to my user object. I am using allauth, so the way this is supposed to be done as far as I can tell is by modifying the allauth form for signup. I've followed the instructions here: How to customize user profile when using django-allauth: This is what my forms.py looks like: from allauth.account.forms import SignupForm from django import forms UNASSIGNED = 'NA' CLIENT = 'CL' USER_TYPE_CHOICES = ( (UNASSIGNED, 'Unassigned'), (CLIENT, 'Client'), ) class CustomSignupForm(SignupForm): user_type = forms.CharField( widget=forms.Select(choices=USER_TYPE_CHOICES)) def signup(self, request, user): user.user_type = self.cleaned_data['user_type'] user.save return user and then my custom user: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=254, null=True, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) UNASSIGNED = 'NA' CLIENT = 'CL' USER_TYPE_CHOICES = ( (UNASSIGNED, 'Unassigned'), (CLIENT, 'Client'), ) user_type = models.CharField(max_length=2, choices=USER_TYPE_CHOICES, default=UNASSIGNED) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) I know that the field that I added to the user works as I can see it in the admin and access it … -
How to Catch a Stolen Token Key in Django Rest Framework
Whenever I grab a token from Token, I check for client's device serial number along with key to reduce the risk of serving hijackers. See the details below. I have a custom Token model that stores device serial number of the client's mobile phone. My models.py is located under my app name called accounts class Token(rest_framework.authtoken.models.Token): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='accounts_token_user_set') logged_in_device_serial = models.CharField(max_length=36, null=False, blank=False) class Meta: constraints = [ models.UniqueConstraint(fields=['user', 'logged_in_device_serial'], name='uq_token_userloggedindeviceserial') ] My settings.py considers TokenAuthentication and IsAuthenticated REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'accounts.authentication.TokenAuthentication', ] } authentication.py is located here accounts -> authentication.py import rest_framework.authentication from .models import Token class TokenAuthentication(rest_framework.authentication.TokenAuthentication): model = Token That's how I grab my token. I always pass the key AND the device number of the caller to avoid serving stolen keys. Token.objects.get(key=..., logged_in_device_serial=...) If I return a token using the key alone Token.objects.get(key=...), I might be at the risk of serving hijackers who may have stolen keys from my customers. Instead I'm checking key's device's number that was registered with the key the first time I created the token. I think checking key and logged_in_device_serial offers an extra protection against hijackers unless hijackers manage to get the … -
Django get_absolute_url without Id
I want to use get_absolute_url, however, I don't want to use the model id as then people will know the order of that instance's creation (because Django increments ids by 1). I know that Instagram uses letters here. What are some common alternatives? Thanks! -
Failing to make a POST request from ReactJS to Django
Hello so I am working on a Django and React project I am fairly new to the domain I can't understand why this is not working, so I would love to make a POST request to my API and save the contents to the database and the after then the function that is currently working to retrieve contents in my DB will do its work to update the website. So after I made the POST request this is the response I get when I console logged: Response { type: "cors", url: "http://127.0.0.1:8000/api/upload-lecture/", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, body: ReadableStream, bodyUsed: false } I personally thought after getting a status code of 200 everything is fine but when I go check the database the is nothing new that was added. I even checked the with Django logs that were coming and this is what I got too: "POST /api/upload-lecture/ HTTP/1.1" 200 108 So I do not understand why the contents are not in the database. Code to my Api: Upload method: @api_view(['POST']) def videoUpload(request): serializer = LectureVideosSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) Code to React:This is where I was trying to make the POST request import … -
How to upload multiple image with django rest api
I want to know how i can upload multiple image (list) in my views and get a Response like this : { "id":1, "title":"text", "roms":2, "image":[ "http:localhost:8000/media/images/houses/image1.png", "http:localhost:8000/media/images/houses/image2.png", "http:localhost:8000/media/images/houses/image3.png", ] } I have tried this way : models.py from django.db import models class House(models.Model): title = models.CharField(max_length=255) rooms = models.IntegerField() images = models.FileField(upload_to="images/houses/") def __str__(self): return self.title serializers.py* from rest_framework import serializers from .models import House class HouseSerializer(serializers.ModelSerializer): image = serializers.ListField(max_length=None,child=serializers.FileField) class Meta: model = House fields = '__all__' views.py from rest_framework import viewsets from .models import House from .serializers import HouseSerializer class HomeViewSet(viewsets.ModelViewSet): queryset = House.objects.all() serialiezer_class = HouseSerializer But it didn't work, i don't know how to write serializer and views to do this, any body help please. Thanks in advance -
Mimic Slack Groups Django
You know how in Slack, you can belong to many different groups? I have a similar structure in my Django app. In my User model: organizations = models.ManyToManyField(Organization, related_name='organizations') I am struggling to figure out how to store which organization the User is currently operating in. Similar to Slack, depending on what Organization they are in, different data will be displayed. Do I store it as a session variable? Do I make a model field for the current Group that they are in? What is best to do here? -
CSRF cookie not set [Django/AngularJS]
First of all, this is not a duplicate question. I have tried all the related posts on stackoverflow but could not find a solution. I have a Django app for the backend and and AngularJS app for the frontend. I am using djangorestframework-jwt for API authentication. I have an API endpoint that does not require any authentication and I am getting this error only for this endpoint. In my django settings I have: ALLOWED_HOSTS = ['*'] and it does not include any CSRF_COOKIE_SECURE, CSRF_COOKIE_HTTPONLY, or SESSION_COOKIE_SECURE settings. The djangorestframework-jwt settings is: JWT_AUTH = { 'JWT_SECRET_KEY': SECRET_KEY, 'JWT_ALGORITHM': 'HS256', 'JWT_VERIFY': True, 'JWT_VERIFY_EXPIRATION': True, 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=3000), 'JWT_ALLOW_REFRESH': True, 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=1), 'JWT_AUTH_COOKIE': 'refresh-token' } I noticed that in the browser cookies if there is any refresh-token key then the endpoint works just fine. The problem arises when that key is not present in the browser cookies. I set 'JWT_AUTH_COOKIE': None or removed the following lines: 'JWT_ALLOW_REFRESH': True, 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=1), 'JWT_AUTH_COOKIE': 'refresh-token' from the JWT_AUTH settings but no luck. I also tried @csrf_excempt for that endpoint but that did not work either. Interestingly, when I send the request from postman it works. Here is the request I am sending from the frontend: $http({ url: … -
Model field validation in Django
I want to validated a custom form field . I have made a model for contact us form . fields are name, subject, email and message . Now user from "DIU" company can contact us only . email must have '35-' and '@diu.edu.bd' in the email address . How can i validate this email field like this ? Please help -
Adding comment feature inside DetailView Using GenaricForeignKey
I invested lots of time to fix it but i was unsuccessful so i am hopping here i will get help from you. What i am trying to do is i want to add comments on detail page through comment form i know my post method is incomplete what should i add in this method so i get posted comments. I am using ContentTypes framework to make it reuseable. comments/models.py class GlobalComment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() published = models.DateTimeField(auto_now_add=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') # by default it will take these two parameters if u dont provide objects = GlobalCommentManager() def __str__(self): return self.body[:10] comments/forms.py class GlobalCommentForm(forms.Form): content_type = forms.CharField(widget=forms.HiddenInput) object_id = forms.IntegerField(widget=forms.HiddenInput) body = forms.CharField(widget=forms.Textarea) myapp/views.py class ProductDetailView(DetailView, FormMixin): model = Product form_class = GlobalCommentForm def post(self, request, *args, **kwargs): instance = self.get_object() # to get the particular product instance initial_data = { 'content_type': instance.get_content_type, # get_content_type defined in models.py as a property to get the content type of the model 'object_id': instance.id } if request.method == 'POST': global_comment_form = GlobalCommentForm(request.POST, initial=initial_data) if global_comment_form.is_valid(): print(global_comment_form.cleaned_data) global_comment_form.save() return ....missing..... return ....missing... def get_context_data(self, **kwargs): particular_product = self.get_object() # return the particular … -
Elastic Beanstalk instance profile for Secrets Manager
I am new to AWS and want to use Secrets Manager in my Django app on Elastic Beanstalk. How can I create an elastic beanstalk instance profile and use it for secrets manager? Thanks! -
'function' object has no attribute 'categories'
I want to solve this problem I am a newbie so I don't understand this problem so please help me try to solve this. I want to show related products in the product detail page I follow some tutorial but I don't understand this. models.py from django.db import models from django.urls import reverse from django.utils.text import slugify from django.db.models.signals import post_save,pre_save # Create your models here. class ProductQuerySet(models.query.QuerySet): def active(self): return self.filter(active=True) class ProductManager(models.Manager): def get_queryset(self): return ProductQuerySet(self.model, using=self._db) def get_related(self, instance): products_one = self.get_queryset().filter(categories__in=instance.categories.all()) product_two = self.get_queryset().filter(default=instance.default) qs = (products_one | product_two).distinct() return qs class Product(models.Model): title = models.CharField(max_length=120) description = models.TextField(null=True,blank=True) price = models.DecimalField(decimal_places=2, max_digits=20) active = models.BooleanField(default=True) categories = models.ManyToManyField('Category', related_name='product_category',blank=True) default = models.ForeignKey('Category', on_delete=models.CASCADE, related_name='default_category', null=True,blank=True) objects = ProductManager() def __str__(self): return self.title def get_absolute_url(self): return reverse('products:product_detail',kwargs={'pk':self.pk}) class Category(models.Model): title = models.CharField(max_length=120, unique=True) slug = models.SlugField(unique=True) description = models.TextField(blank=True,null=True) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('product_categories:categories_detail',kwargs={'slug':self.slug}) -
Python createsuperuser - Django
Everything is going good in the username and email fields, they're writable, but when it comes to the password field, I'm not allowed to write anything, even if i pressed enter twice to give me the bypass password, it doesn't allow me.. What should I do to let the password field writable and enable me to create the admin user? -
oder by nulls first in descending order in django
I want to order my data in Django admin in descending order, but I want the null field which represent task that has not ended to come to the top first following the descending order of dates. for Example End date is listed like this -- -- Dec 5 ,2018 March 2,2017 and not like this Dec 5 ,2018 March 2,2017 -- -- in my view.py I have tried in this way class TaskViewset(Viewsets.ModelViewset) queryset = Task.objects.filter(end_date__isnull=True).order_by("-end_date") This limit what was return back to only data where end_date is null. How can i do this to return data including those Task that have ended while returning the not ended task first? Thanks for your help. -
Passing an html element from anchor tag to django view
I would like to know how i can pass the html link element as a string into a django view and have the information rendered on that specific view. to be clear: I have this In html {% if list_1 %} <h3 class="display-5"><u>{{ choice }}</u></h3> <div class="row justify-content-md-center row-eq-height"> {% for item in list_1 %} <div class="col-md-4"> <a id = "search_item" name = 'search_item' href="{% url 'search_stock' %}" value={{ item }} target="_blank">{{item}}</a> A django view rendered the items from a list and each item would ideally be clickable and the specific item would be passed into this view: def search_stock(request): search_item = request.POST.get('search_item') ticker_request = search_item ..... my urls.py reads as : path('search_stock', views.search_stock, name='search_stock'), The problem I think may be that the click action is not actually passing the value into the function based view and I am not sure how to work around this easily. Essentially once the information loads (each item is a link for a specific ticker), I would like the user to be able to click on that link with the ticker being passed into the search_stock function as a string in order to actually render the specific search_stock view. Much thanks now and in … -
null value in column "patient_id" violates not-null constraint DETAIL Django
I am getting this error in Django: null value in column "patient_id" violates not-null constraint DETAIL Even though my model field is: patient = models.ForeignKey(Patient, null=True, blank=True, on_delete=models.SET_NULL) What is it referring to with DETAIL? Why am I getting this error? Thanks! -
How to use url variables in class based views
I'm having problems with the url variables and the class based views, but mostly in the html or template because I don't know how to represent it, I'll show you the code so you can understand. urls.py app_name = 'app1' urlpatterns = [ path('add_post/<str:sym>',AddPostView.as_view(), name='addpost'), ] views.py class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'app1/createpost.html' def get_queryset(self): ala = Post.objects.filter(stock__symbol=self.kwargs['sym']) return ala models.py class StockNames(models.Model): name = models.CharField(max_length=255) symbol = models.CharField(max_length=255) def __str__(self): return self.symbol class Post(models.Model): title = models.CharField(max_length= 255) header_image = models.ImageField(null = True, blank = True, upload_to = 'images/') author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank = True, null = True) #body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default='coding') snippet = models.CharField(max_length=255) likes = models.ManyToManyField(User, related_name = 'blog_posts') stock = models.ForeignKey(StockNames, null=True, on_delete = models.CASCADE) def total_likes(self): return self.likes.count() def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('app1:article-detail', args=(self.id,)) Template (I'm having problems with Add Post(current) ) {% extends "app1/base.html" %} {% block body_block %} {% if stock_sym %} <h1> {{sym}} </h1> <a href ="{% url 'app1:addpost' StockNames.symbol %}">Add Post<span class="sr-only">(current)</span></a> {% if stocks %} <ul> {% for post in stocks %} <li><a href="{% url 'app1:article-detail' post.pk … -
Django Template engine, checking for time difference in Jinja2
I'm trying to check for some things before displaying my content. So right here I got some Invitation links for users to join our forum. When the ticket is sent to the user it's valid for 24 or 48 hours. So my goal is to check if the ticket is valid for now or it's expired. I have tried adding the timesince filter to my variable, but it's still not working. <td class="pt-3-half"> {% if query_time|timesince == invite.token_expires|timesince %}Not-valid {%else%}Valid{%endif%} </td> However, the current time is more recent, than the ticket expiration date, but the engine says that the ticket is still valid. I'm checking for these times: query_time = 2020-08-15 18:04.15 token_expires = 2020-08-13 22:33.16 -
How to integrate Web MIDI API with React frontend and Django backend
I'm fairly new to Django and React but have a good grasp of Python and JavaScript. What I'm trying to do is use the Web MIDI API to monitor some MIDI data, extrapolate some information from it and store that in a database. It's basically for a DAW, Software synth monitoring system, information can be transmitted as MIDI to the browser (via IAC) and then various pieces of information stored in the database. This needs to be done per user, with user data separation. I'm guessing I would need to implement a CRUD API. I currently have a Python project that does this and holds the data in memory formatted as JSON - the plan is to take this and turn it in to a Web App. I've watched and followed a bunch of tutorials on integrating Django & React and also found this boilerplate for a basic login system. https://github.com/justdjango/django-react-boilerplate If possible I'd like to use this and just add in the functionality I need, can anyone point me in the right direction of where to start and where I would add the additional code for the MIDI stuff to this boilerplate. There is another stage to this project … -
Django validation returns two errors instead of one
as the questions states i receive two errors in my template. Here is the code def create(request): full_content = forms.InputForm() if request.method == "POST": full_content = forms.InputForm(request.POST) if full_content.is_valid(): title = full_content.cleaned_data["title"] content = full_content.cleaned_data["content"] if full_content.clean_title():#Works full_content.create(title, content) context= { 'title' : util.get_page_name(title), 'entry' : util.get_entry(title), } return render(request, "encyclopedia/entry.html",context) #From here on its not valid: context = { 'form':full_content } return render(request, "encyclopedia/create.html", context) return render(request, "encyclopedia/create.html", { 'form':full_content }) And the forms.clean_title(): def clean_title(self): title_name = self.cleaned_data.get("title") filename = f'entries/{title_name}.md' if default_storage.exists(filename): raise ValidationError("This title is already taken") return title_name Ofcourse the create.html aswell: <h3>Create new entry</h3> <form action="{% url 'create'%}" method="POST"> {{ form.title.errors }} {% csrf_token %} <table> {{form.as_p}} </table> <button type="submit" value="save">Save</button> </form> Any ideas why i get two bullets?: This title is already taken This title is already taken -
Field 'id' expected a number but got 'abdullah123'
I hope all are safe and good! I am working on this below code, i am trying to get balance from the UserBalance table filter by username. I have tried using UserBalance.objects.filter(username=username) where i am actually getting error. Please help me out how can i proceed with this #views.py def login_validation(request): if request.method=='POST': username=request.POST.get("username") password=request.POST.get("password") user=auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) user_balance=UserBalance.objects.filter(username=username) #error_i_am_getting_here return render(request, "homepage.html", {'name':username, 'balance':user_balance}) else: return redirect("http://google.com/") else: return redirect("http://yahoo.com/") #models.py from django.db import models from django.contrib.auth.models import User class IncomeExpense(models.Model): entry_type=models.CharField(max_length=100) amount=models.IntegerField() details=models.TextField() capture_date=models.DateField() username=models.ForeignKey(User, on_delete=models.CASCADE) class UserBalance(models.Model): balance=models.IntegerField() username=models.ForeignKey(User, on_delete=models.CASCADE) I have pasted views.py and models.py code, Please help me to solve this problem. I tried using filter with username and its giving that error and i tried using get method also...but again getting same error. Also please explain me how get and filter works