Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not able to figure out how to work with product size in django ecommerce website as select box for different products have same id
This is my html: {% if product.id in list_cart %} <div class="btn-group" style="display: none;"> <select class="selection-2 border" data-product={{product.id}} style="border: cadetblue;" name="size" required id="sizebox"> {% for t in product.size.all %} <option value="{{t}}" id="{{t}}">{{t}}</option> {% endfor %} </select> </div> {% else %} <div class="btn-group"> <select class="selection-2 border" data-product={{product.id}} style="border: cadetblue;" name="size" required id="sizebox"> {% for t in product.size.all %} <option value="{{t}}" id="{{t}}">{{t}}</option> {% endfor %} </select> </div> {% endif %} And this is my javascript: var updateBtns = document.getElementsByClassName('update-cart') for (i=0;i<updateBtns.length;i++){ updateBtns[i].addEventListener('click',function(){ var productId=this.dataset.product var action=this.dataset.action var sizebox = document.getElementById("sizebox"); var size = sizebox.options[sizebox.selectedIndex].value; console.log(size) updateUserOrder(productId, action, size) }) } I am working on a basic django ecom. website. I have come across a problem which I am not able to solve. The problem is that on the products page of my website every product has a select box for size of the item and every select box has the same id (As i am iterating over the products). So whenever I choose a size for any product other than the first product the size selected from the first select box under first product goes to my database instead of the size selected under that product. I want to figure out a … -
ContentType matching query does not exist on django 3.1
''' Am trying to create a comment system using GenericForeignKey and Content_type, it works just fine when a downgrade django to 2.1 or less, but am getting am error saying "ContentType matching query does not exist." if i try to use django 3.X. below are snippets of the code ''' class CommentManager(models.Manager): def filter_by_instance(self, instance): content_type = ContentType.objects.get_for_model(instance.class) obj_id = instance.id qs = super(CommentManager, self).filter(content_type=content_type, object_id=obj_id) return qs class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content_type=models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() content = models.TextField() time_stamp = models.DateTimeField(auto_now_add=True) objects = CommentManager() def __str__(self): return self.user.username #Forms.py class CommentForm(forms.Form): content_type = forms.CharField(widget=forms.HiddenInput) object_id = forms.IntegerField(widget=forms.HiddenInput) content = forms.CharField(widget=forms.Textarea) #views.py def detail(request, id): obj = get_object_or_404(Blog, id=id) obj_id = obj.id initial_data = { "content_type": obj.get_content_type, "object_id": obj.id } form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid(): c_type = form.cleaned_data.get("content_type") content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get("object_id") content_data = form.cleaned_data.get("content") new_comment, created = Comment.objects.get_or_create( user = request.user, content_type=content_type, object_id=obj_id, content= content_data ) if created: print("It worls \n") context = { 'form':form } return render(request, 'blod_detail.html', context ) -
How to make a filter in Django Listview queryset
I have a list of brands. Each brand has a list of categories I want to make each brand a link. And when the user click the brand he passes to the page with all the categories related to that brand Here is a template with brands: <ul> {% for brand in object_list %} <li><a href="{{ brand.get_absolute_url pk }}">{{ brand.name }}</a></li> {% endfor %} </ul> And here is the view: class CategoryListView(ListView): model = Category queryset = Category.objects.filter(brand=pk) template_name = 'category_list.html' But it gives an error. Can someone help me? Thank you -
Why is the difference between Serializer methods and View methods?
In Django DRF, I can add the following method to a serializer: def create(self, validated_data): user = User( email=validated_data['email'], username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user Previous to discovering this, I thought you typically did this within a view, by overriding a View/ViewSet methods. I had thought that all the Serializer did was to transform the data and send it out or receive it from external calls. Can someone explain to me the difference between doing this on the view vs doing it on a serializer? And more broadly, what is the benefit of calling methods on the serializer instead of somewhere else? -
Cant access username of objects from queryset in Django
I have been struggling with this for a while now. In my js code i fetch with a get request all the posts that users have made. In my django code,i query db for said posts. When i get the queryset of results, that is passed to the js code, where i try to access each object's author (user who posted it) in order to display it. But instead im given the pk, not the username. So basically, I dont know how to get the username as the author (user who made the post) of each object, instad of the pk. models.py: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) ## content = models.TextField(max_length=400, blank=False) date_posted = models.DateTimeField(auto_now_add=True) @property def username(self): return self.author.username def __int__(self): return self. serializers.py : class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' js code: function show_posts(sort) { fetch(`api/post-list/${sort}`) .then(response => response.json()) .then(posts => { //for each email console.log(posts); posts.forEach(post => update_posts(post, sort)); }); } function update_posts(post, sort) { const element = document.createElement('div'); element.setAttribute("class", "post-dv"); console.log(post); element.innerHTML += "Author: " + post.author + "<br>"; element.innerHTML += "Content: " + post.content + "<br>"; element.innerHTML += "Date: " + post.date_posted + "<br>"; element.innerHTML += "Likes: 0" + "<br>"; … -
passing ID parameter inside anchor href in Django template language
So let me clear about each thing step by step My model name is keybase model and database is stored in mongo DB and object id can be accessed by '_id' In views i have made object of that view What i want is basically just make delete button which goes in function of views along with object ID that is coming from mongodb Here is the code of anchor <a href="{% url 'Keybase_Management_System:Delete_Keybase' {{ i |mongoid:'_id'}} %}" role="button" aria-pressed="true" style="font-size:11px; display: inline;"> Basically i the parameter value and mongoid: '_id' is basically custom tag that converts object _id to string id now this is showing parsing error that could not parse the remainder: '{{' from '{{' What actually works If i use this {{ i |mongoid:'_id'}} separately it shows correct results for instance 9kas83n8d893n but i what want is to move this id as parameter which i am not able to do kindly help me out with this. {{ i |mongoid:'_id'}} works perfectly unless it is sent as as parameter inside anchor tag in href I know there is some sort of syntax error there might be way to send this but i am not able to figure it … -
How do I track field type in change log table of a database table
I have been working on Django and I wanted to track the changes of a table and I am thinking of a table to keep track of the changes on a field-based tracking system like audit_field (table_name, id, field_name, field_value, datetime) but I wanted to keep track of the field types too to use database validation against it. FYI I am working on Django and Mysql database -
'Client' object has no attribute '_deletetouch' in django admin logout section
I am unable to logout the user in admin panel of django. The logout task is not perform after using memcached code in django settings file. It shows an error like 'AttributeError at /admin/logout/' and 'Client' object has no attribute '_deletetouch'. The memcached code in settings.py as enter code here SESSION_ENGINE='django.contrib.sessions.backends.cache' CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } -
CKFinder ERR_SSL_PROTOCOL_ERROR on image upload
I am using CKEditor 5 and deployed CKFinder 3 on Apache + PHP. When I try to upload an image I get ERR_SSL_PROTOCOL_ERROR. Below is my finder config ckfinder: { uploadUrl: "https://localhost/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images&responseType=json", options: { resourceType: 'Images' }, } And when i use HTTP instead of HTTPS I get a CORS error. Access to XMLHttpRequest at 'http://localhost/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images&responseType=json' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: Response to preflight request doesn't pass I have given 777 permissions to userfiles directory -
How does flask run an app with environment variable FLASK_APP?
I realized there are at least 2 ways of running a flask app. The way I usually used to do it was the following: from flask import Flask app = Flask(__name__) @app.route('/') def home(): return "Hey there!" if __name__ == '__main__': app.run(debug=True) By doing python hello.py, name='main' so the app runs. By looking at the flask documentation basic example, I have seen there is another way. How does flask run works? Which way is better? Trying to understand what is happening with Python and flask under the hood. -
Why is there a difference between creating superuser and signing up to create user in django?
I am implementing membership using django custom user model and custom register serializer. But when I finished the implementation and tested it, there was a little problem, so I want to ask. It is the I from the console python manage.py, and when I was running a command createsuperuser sign up when to membership to access the results page with each other. Here are some pictures. If I sign up like this, password is not encrypted by pbkdf2_sha256 method, username has nothing, and profile has default_image However, the superuser created as a command in the console not only enters username and profile image normally, but password is normally encrypted in the pbkdf2_sha256 method. I hope that the user who joined the signUp page will be normal user name and profile like superuser and the encryption will be the same. How can I modify my code? Here's my code. models.py from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, email, profile, userName, password): user = self.create_user( email=self.normalize_email(email), password=password, userName=userName, profile=profile, ) user.set_password(password) user.save() return user def create_superuser(self, email, password, userName, profile): user = self.create_user( email=self.normalize_email(email), password=password, userName=userName, … -
can i send request to admin everytime a non admin wants to update the data in django
I want to create a web application where users have to update data(mostly numbers in editbox) regularly.But everytime they have to change the data they should have to ask admin via request to edit the data,the request would be visible to the admin and if the admin accepts the request than and only than the user should be able to edit the data.If the admin rejects the request the user should not be able to make any changes to the data. So in simple world I want admin controlled web application.Everything should be done under admins consent. -
on submitting the login button i got Page not found (404)
while trying to create login page i got the error- Page not found (404) Request Method:GET URL:http://127.0.0.1:8000/login.html?username=dfg&password=dfg Using the URLconf defined in app.urls, Django tried these URL patterns, in this order: [name='login'] about [name='about'] afterlogin [name='afterlogin'] admin/ The current path, login.html, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. i want to ask 2 things why is it taking about Request Method:GET when my views.py says def afterlogin(request): return render(request,'pages/afterlogin.html') def login(request): if request.method == 'POST': messages.error(request,'testing error') return redirect('login') else: return render(request,'pages/login.html') while my url.py in apps - urlpatterns = [ path('', views.login, name="login"), path('about',views.about,name="about"), path('afterlogin', views.afterlogin, name="afterlogin"), path('admin/', admin.site.urls), ] i got the login page righth but submit button is showing 404 , Anysolution to solve this problem kindly help -
CSS is not properly loading with Django, Nginx, Uwsgi on EC2, why?
I am working upon a web app and I have deployed it successfully. But sometimes there are some parts of CSS which do not get load properly but work fine on the local machine. I went through everything like checking the code on the EC2 and reloading the Nginx several times but nothing seems to be working right now. Can anyone help me? This is when I am working upon the local machine local machine This is when I deployed it in productions. productions can anyone tell me what could be wrong here since it's working perfectly on local machine ? -
DRF: How to return name instead of id for permission groups?
We have a Client model, and a ClientTeamMember model which allows one or more team members to be assigned to each client. TeamMember in our site is a profile extension of the User account. In the ClientTeamMember table, we also have a groups field, which is the same Group model defined in /django/contrib/auth. Its purpose is to be able to assign a group (role) to a TeamMember for a specific client, giving them extra permissions that they don't have for other clients. Like, for example, making a team member the "Project Manager" for only one client. Our models: class Client(models.Model): name = models.CharField(max_length=100) class ClientTeamMember(models.Model): client = models.ForeignKey( Client, related_name='client_team_members', ) team_member = models.ForeignKey( TeamMember, related_name='team_member_clients', ) groups = models.ManyToManyField( Group, blank=True, default='', related_name='client_groups', ) We want to return the group names (not just the ids) in the Client serializer. Like this: "results": [ { "id": 9, "name": "Acme Honey", "permission_groups": [ "Project Manager" ] } ] Just as on the User model, Group is a many-to-many field, allowing for multiple groups to be assigned at any level. Here are the serializers: class GroupNameSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ['name'] class ClientGroupsSerializer(serializers.ModelSerializer): groups = GroupNameSerializer(many=True, read_only=True) class Meta: … -
Should the amazon S3 bucket region be closer to the host server or the client server?
I have a website hosted on heroku which is US based, but my target audience is in India. I just have to display images from the storage to the users. For faster loading of the images, should the storage region be US or should it be India? -
Django Admin built in auth views do not go away
I am creating a Python Django app and working through authentication. I want to create my own styled html templates and forms to use with the built in flows. I have the following url configuration in my accounts/ app: from django.urls import path from django.contrib.auth import views as auth_views from .views import CustomRegisterView, ProfileView, CustomLoginView from .forms import CustomLoginForm, CustomPasswordResetForm urlpatterns = [ path('profile/', ProfileView.as_view(), name='profile'), path('register/', CustomRegisterView.as_view(), name='register'), path('login/', CustomLoginView.as_view(authentication_form=CustomLoginForm), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('password_reset/', auth_views.PasswordResetView.as_view(form_class=CustomPasswordResetForm), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete') ] I have sub-classed the login/, and logout/ built-in views and my custom views and forms are working at those urls. However, the password_reset/ url continues to display the basic Django admin site webpage for resetting the password, even though I have created the registration/password_reset_form.html file. I am at my wits end here as to what is going on - according to all documentation online all that is required to write a custom webpage for the password_reset/ url is to create the registration/password_reset_form.html file. -
python boto cannot get environ variable of docker container
I use the docker image jrei/systemd-ubuntu:18.04 installed golang and set up github.com/remind101/assume-role and run Django over uwsgi with nginx he Python version is 3.7 and boto version is 2.49.0 Also ,Django requirements is install in venv. After I set up the aws config file in the ~/.aws/config and credentials in ~/.aws/credentials The server works fine, but the boto package can't get the environ variable The Django Page show the error message: NoAuthHandlerFound at / No handler was ready to authenticate. 1 handlers were checked. ['HmacAuthV4Handler'] Check your credentials Request Method: GET Request URL: http://localhost/ Django Version: 3.0.5 Exception Type: NoAuthHandlerFound Exception Value: No handler was ready to authenticate. 1 handlers were checked. ['HmacAuthV4Handler'] Check your credentials Exception Location: /opt/web/camelot-portal-env/lib/python3.7/site-packages/boto/auth.py in get_auth_handler, line 1021 Python Executable: /opt/web/camelot-portal-env/bin/uwsgi Python Version: 3.7.8 Python Path: ['.', '', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/opt/web/camelot-portal-env/lib/python3.7/site-packages'] I checked the $AWS_ACCESS_KEY_ID and $AWS_SECRET_ACCESS_KEY both not empty, and I try config the $AWS_CREDENTIAL_FILE twice ,to ~/.aws/config and ~/.aws/credentials both time I restart the uwsgi service , boto still not getting any key or key ID. finally ,If I install the requirements and usepython manage.py runserver in my local environment, the boto package can get the environment variable normally, and all works … -
Usage of super in conjunction with a django ModelForm class to alter the __init__ method
While trying out some code ideas I stumbled over a problem I cant seem to wrap my head around. Please ignore the fact WHY I try to do this, the question is all about why its not working;) So I want to create a formclass in which I overwrite the __init__ method of the Baseclass but simply want to copy it. Basically what I want to do is the following: class A(): def __init(self, a, b, c)__: self.a = a self.b = b self.c = c class B(A): def __init__(self, a, b, c): super(B, self).__init__( a, b, c) # Do some stuff that was not implemented# I would expect the __init__ method of B to work exactly like there would be no change, exept for the added stuff at the end. However in my Example something definately changed since my form isnt working any more afterwards: class SignUpForm_test(forms.ModelForm): password_confirmed = forms.CharField(widget=forms.PasswordInput()) # --> This is the important stuff, the rest is just for completeness <--# ######################################################################### def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, label_suffix=None, empty_permitted=False, instance=None, use_required_attribute=None, renderer=None): super().__init__( data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, label_suffix=None, empty_permitted=False, instance=None, use_required_attribute=None, renderer=None) ######################################################################### class Meta: model = get_user_model() fields = ( … -
Initializing Django formset with different values using initial dictionary
I have following definition for ModelFormset: class MyModelDetailsForm(forms.ModelForm): status = forms.ChoiceField(choices=MyModel.STATUS) class Meta: model = MyModel fields = ['id'] MyModelDetailsFormset = modelformset_factory( MyModel, form=MyModelDetailsForm, extra=0) And this is how I'm creating instance in get_context_data formset = MyModelDetailsFormset(queryset=self.my_models) If I'll initialize status fields this way: for form in formset: form.fields['status'].initial = get_initial_value() everything works. If I'd like to do something like this (following answer https://stackoverflow.com/a/23497278): formset = MyModelDetailsFormset(queryset=self.my_models, initial=[{'status':1},{'status':2}]) initial values don't kick-in. Why is that happening? Am I missing something? -
Why does Django CSRF verification fail?
So I have a register form in Django. However when I fill in the form and hit submit, the page remains loading. (I'm not sure if this is the right expression. icon in the tab title turns to a rotating circle.) The page was loading for quite a long time, so I clicked the submit button again, and I got the Forbidden message, saying CSRF token is not verified. This keeps on happening. However the thing is, when I access the admin page, the user account IS created. And log in works fine. The only problem is when I hit submit button, it only keeps on loading, and when I hit the submit button again, I get error message saying CSRF token is not verified, but the account is created. What is wrong with it? I'll show you my code. <form method="post" class="form-group">{% csrf_token %} <div class="row login-block"> <div class="col"> <div class="row"> <div class="col col-4"> {{form.username|as_crispy_field}} </div> <div class="col col-8"> {{form.email|as_crispy_field}} </div> </div> <div class="row"> <div class="col col-5"> {{form.password1|as_crispy_field}} </div> <div class="col col-5"> {{form.password2|as_crispy_field}} </div> </div> <div class="row"> <div class="col text-left"> <button type="submit" class="btn menial-buttons">Submit</button> </div> </div> </div> </div> </form> views.py def register(response): if response.method == 'POST': form = RegisterForm(response.POST) … -
Create new report with Django and reportbro
I try to implement a pdf generator for my django app. I found reportbro. seems promising.. but the official website shows only demos and api documentation. I don't want to reverse engineering the demo code. is there a tutorial on how to create a new report or at least a basic full stack template (django+ js ) -
multiple form handling Django python 3.x
i wanted to make simple page with two input forms first one for posting data into file second for taking index and deleting data from file and both of them working independent but so far i can only use first form like the second one its not even reached not a single method from second form is completed here goes the code: ############### #Views.py class HomeView(TemplateView): template_name = 'index/num.html' def get(self, request): form = AddForm() form2 = DeleteForm() result = printResult() return render(request, self.template_name, {'form': form, 'form2': form2,'result': result}) def post(self, request): result = "result" ####____add option################### if request.method == 'POST': form = AddForm(request.POST) form2 = DeleteForm(request.POST) if form.is_valid(): text = form.cleaned_data['post'] if (re.match("[0-9]+", str(text))): text = text else: text= None result = addToFile(text) args = {'form': form, 'form2': form2, 'text': text, 'result': result } return render(request, self.template_name, args) ########## ###____Delete option####### if form2.is_valid(): index = form2.cleaned_data['dell'] result = DeleteIndexFromFile(index) args2 = {'form': form, 'form2': form2, 'text': index, 'result': result } return render(request, self.template_name, args2) ########## #forms.py from django import forms class AddForm(forms.Form): post = forms.CharField(required = False) class DeleteForm(forms.Form): delete = forms.IntegerField(required = False) #num.html <div class="container"> <p> <form method="post"> {% csrf_token %} {{ form }} <button type="submit">Submit</button> </form> … -
not able too add email in django admin
everything works fine but when I fillup the form, after submit when I go to my /admin then every field is added there but email field is still empty although I filled up the email field my views.py file from django.shortcuts import render from django.contrib import messages from django.http import HttpResponseRedirect from django.urls import reverse from .forms import userregisterform def register(request): if request.method=='POST': form=userregisterform(request.POST) if form.is_valid(): form.save() username=form.cleaned_data.get('username') messages.success(request,f'Account for {username} has been created successfully') return HttpResponseRedirect(reverse('blog-index')) else: form=userregisterform() return render(request,'users/register.html',{ 'form':form}) my forms.py file from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class userregisterform(UserCreationForm): email=forms.EmailField() class Meta: models=User fields=['username','email','password1','password2'] don't consider indentation here -
how can I use styles for Django auth_views.LogoutView and auth_views.LoginView?
Styles for forms I can use widgets variable, but how can I use CSS styles for auth_views.LogoutView and auth_views.LoginView?