Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to display details of a product in a new page when i click on a product in the product page
I am a newbie to django and i am doing a code along with a youtube tutorial on how to build an ecommerce site. My challenge right now is this: On my product page, there is a list of products. What i want is when a user clicks on a particular product, i want the user to be redirected to a page (a product details page) that has the custom details of that particular product. This is the structure of my code. In my views.py file, i have the 'products1' as the page view for all my products and the 'product_details' page is where i want the details of a particular product to be displayed def products1(request): products = Product.objects.all() context = {'products':products} return render(request, 'shopping_app/products1.html', context) def product_details(request, id): product = get_object_or_404(Product, id) context = {'product': product} return render(request, 'shopping_app/product_details.html', context) In my urls.py. I created the urls for the following pages like so. path('products4/', views.products4, name='products4'), path('product_details/<int:id>', views.product_details, name='product_details'), THe problem is whenever i click on the product for me to be redirected to the details page, a TypeError is thrown. -
JavaScript DOM function is skipped in Django project
I have a JavaScript function scroll(); which works with DOM elements. Now it is working on just html file, but not on Django server. I know that Django automatically is skiping js dom function like document.getElementById so is there any solution? Maybe something change in settings or something? -
specific variable in loop in Django
i have a questions list in views and i knew how to pass it to template and how to print it in loop {% for q in questions %} and i knew how to pass it to JavaScript and how to bring a specific questions from the list for example : document.getElementById("p").innerHTML = "{{questions.0}}"; BUT my question is How to bring specific question based on variable i for example ?? i tried this way: document.getElementById("p").innerHTML = "{{questions."+i+"}}"; but it didn't work? do you have any solution? -
Django serialize a field of a model to a dictionary
I have this model, class MyModel(models.Model): some_id = models.PositiveIntegerField(primary_key=True) diff_id = models.PositiveIntegerField(null=True) some_data = models.JSONField(null=True) I need to paginate this and serialize the some_data to a dictionary. query = MyModel.objects \ .order_by('some_field') paginator = Paginator(query, self.batch_size) for i in paginator: data = list(i.object_list.values(*fields, **suffixed_fields)) some_data field contains a json as follows. {"diff_id" :6916} diff_id is a field from the same model. Is there a way to do this in the model or in a serialize it self? if so please help -
django can't find template when trying to use forms
I am trying to follow the django documentation howto create a form using sjango form class. I am doing every step but when trying to access my form it says that is cannot find the template: django.template.exceptions.TemplateDoesNotExist: lform heres is my forms.py: class LoginForm(Form): uname=CharField(label='user name',max_length=20) passw=CharField(label='password', max_length=20) the template lform.html: <form action="ulogin" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> and my view. I think the problem is in the render function: def testform(request): if request.method=='POST': form=LoginForm(request.POST) if form_is_valid(): return render('index') else: HttpResponseRedirect('index') else: form=LoginForm() return render(request,'lform',{'form':form}) and url.py: path('lform',views.testform,name='lform') the last line in the view function, return render(request,'lform',{'form':form}) gives the error any suggestions? -
HTML table copy to outlook
Hi when i copy html table from website to outlook the headers takes more space. I use Datatble as a html table.After Pasting into Outlook Image Given Actual Image -
Django how to create button that visible only some type of users
I created a system with Django. I have several users and these users can have different ranks. I have a page and only 'lead' users can see the page. In user profile page I want to create a button that visible to only leads. models.py class UserProfile(AbstractUser): ranks = ( .. ('lead', 'Lead'), ('manager', 'Manager'), ... ) comp_name = models.CharField(max_length=200, default='', blank=True, null=True) user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True) username = models.CharField(max_length=500, unique=True) ... views.py def is_lead(user): return user.rank == 'lead' @user_passes_test(is_lead) @login_required def lead_page(request): return render(request, 'lead.html') profile.html <div class="col"> <a href="/leadpage" class="btn btn-outline-success"> Enter </a> </div> -
How to compare parameter passed through POST method with Django rest framework Model and generate custom response?
I am designing Basic Django rest framework based application, i need to compare external parameters passed through POST method in Postman with Coupon code in database and generate custom response like 'This code is redeemed/validate." or " This is invalid coupon/code." Here is my Model.py file : from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class Coupon(models.Model): code = models.CharField(max_length=50, unique=True) valid_from = models.DateTimeField() valid_to = models.DateTimeField() discount = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)]) active = models.BooleanField() def __str__(self): return self.code here is my views.py file: from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from .models import Coupon from .serializers import CouponSerializer from rest_framework import viewsets class CouponViewSet(viewsets.ModelViewSet): queryset = Coupon.objects.all() serializer_class = CouponSerializer @api_view(['POST']) def coupon_redeem(request): if request.method =='POST': serializer = CouponSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) here is my Serializer.py file from rest_framework import serializers from .models import Coupon class CouponSerializer(serializers.ModelSerializer): class Meta: model = Coupon fields = '__all__' Please help if possible, Thank you. -
Not Able To Deploy Django App Because of This Error How To Fix It
ERROR: mysqlclient-1.4.6-cp38-cp38-win32.whl is not a supported wheel on this platform. ! Push rejected, failed to compile Python app. ! Push failed -
Django Runserver fail without any error messag
I am trying to run Django application, when i run python manage.py runserver It fails without any error -
415 UNSUPPORTED MEDIA - API Post Javascript - Django
I am trying to create an API on my Django server but I am struggling to create a post method called by Javascript. This is my APIview class componentFrameAPI(APIView): def get(self, request): componentAPI = component.objects.all() serializer = componentSerializer(componentAPI, many=True) return Response(serializer.data) def post(self): serializer = componentSerializer(componentAPI, data=self.data) if serializer.is_valid(): # serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And this is my post request on Javascript. let data = {componentName:"PostTest",componentBody:"TEST"} datax = JSON.stringify(data) var xhttp = new XMLHttpRequest() xhttp.open("POST","http://127.0.0.1:8000/myurl/", true) xhttp.setRequestHeader('X-CSRFToken', csrftoken) xhttp.setRequestHeader('contentType', 'application/json') xhttp.send(datax) I continue to receive a 415 error and I really don't know what I am doing wrong. NOTE: The GET method works fine. Thanks for your help. Giacomo -
How to make a history for django operations
How to make a history view in Django that show user, time of modification/creation, the previous value and the updated/created value? and how to track user operation in all system to make insert to history table? I want the table like this. # time user operation field previous values new values 1 2020-1-16 Ali create title null New Record 10:10:10 when I click to link it forward me to page that field has been created ,Updated or deleted. -
In Django how to display username upon successful login
I am using the django User model to store user's information. Now after login I want to redirect the user to the dashboard where a message should be delayed: Welcome <his_first_name>. I tried the following code: @login_required(login_url='login') def dashboard(request): return render(request, 'accounts/dashboard.html', {"name": user.first_name}) but I am getting the following error: name 'user' is not defined. What am I missing? my register function looks something like this: from django.contrib.auth.models import User def register(request): if request.method == 'POST': firstname = request.POST['firstname'] lastname = request.POST['lastname'] username = request.POST['username'] password = request.POST['password'] user = User.objects.create_user(first_name=firstname, last_name=lastname, username=username, password=password) user.save() return redirect('login') Also as OOPs is a new concept for me, I don't actually understand what is the difference between User and user in the above code? -
User isn't getting registered
I'm working on a django project. I have created a register page but when I register my user isn't getting registered on the admin panel. Here is my code: views.py from .forms import OrderForm, CreateUserForm from django.contrib.auth.forms import UserCreationForm def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_date.get('username') messages.success(request, 'Account was created for' + user) return redirect('login') context = {'form':form} return render(request, 'accounts/register.html', context) forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] urls.py path('register/', views.registerPage, name='register'), Thank you for the help. Here is the link to the youtube channel:https://www.youtube.com/watch?v=tUqUdu0Sjyc&list=PL-51WBLyFTg2vW-_6XBoUpE7vpmoR3ztO&index=14&ab_channel=DennisIvy -
Django admin - grappelli, dropdownlist not available only for groups and users
I'm working on a Django project using particularly the administration interface, I installed Grappelli and TinyMce. Since I migrated the project from Python2 to Python3 and by upgrading the different libraries, I'm facing a problem that I can't find the origin of. I'm using Django 3.1.1 , django-grappelli 2.14.2 and Python 3.6. I tried to upgrade django-grappelli without success. The admin interface works correctly except for the drop-down lists in the "Authentication and Authorization" module. Impossible to have these drop-down lists for user and group permissions either in creation or modification. I can see the permissions field but the drop down arrow doesn't work (sorry no photo possible) I don't override these admin methods and have no code to show except settings.py INSTALLED_APPS = [ 'filebrowser', 'tinymce', 'grappelli', 'modeltranslation', 'taggit', 'django.contrib.admindocs', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', '...', 'bootstrap3', 'bootstrap_themes', ] ... GRAPPELLI_ADMIN_TITLE = 'Some title' GRAPPELLI_SWITCH_USER = True The permissions exist and I can add a permission to a group or user programmatically It looks like a problem with a JS file not found but no problem on the other drop down lists of the admin interface (from admin files made by me) It's possible to override the user/group admin interface but … -
AttributeError: 'Settings' object has no attribute 'AWS_S3_BUCKET' [closed]
can anyone help me with this 2021-01-13 08:20:42,100 || [ERROR] || django.request || Internal Server Error: /simplidrive/upload-file/ Traceback (most recent call last): File "/home/kuliza-397/KULIZA_PROJECTS/uti-backend/uti/lib/python3.5/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/home/kuliza-397/KULIZA_PROJECTS/uti-backend/uti/lib/python3.5/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/kuliza-397/KULIZA_PROJECTS/uti-backend/uti/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/kuliza-397/KULIZA_PROJECTS/uti-backend/uti/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/kuliza-397/KULIZA_PROJECTS/uti-backend/uti/lib/python3.5/site-packages/rest_framework/views.py", line 466, in dispatch response = self.handle_exception(exc) File "/home/kuliza-397/KULIZA_PROJECTS/uti-backend/uti/lib/python3.5/site-packages/rest_framework/views.py", line 463, in dispatch response = handler(request, *args, **kwargs) File "/home/kuliza-397/KULIZA_PROJECTS/uti-backend/webapp/apps/simplidrive/views.py", line 78, in post s3_response = self.upload_to_s3(file_path, object_name=simplidrive_upload_url) File "/home/kuliza-397/KULIZA_PROJECTS/uti-backend/webapp/apps/simplidrive/views.py", line 129, in upload_to_s3 bucket = settings.AWS_S3_BUCKET File "/home/kuliza-397/KULIZA_PROJECTS/uti-backend/uti/lib/python3.5/site-packages/django/conf/__init__.py", line 56, in __getattr__ return getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'AWS_S3_BUCKET' -
Django REST Framework problem with serializer.py
I'm trying to save some data like Image and it's info with POST method from Postman. But I got an error: init() got an unexpected keyword argument 'title'. Here is my code: 1.models.py from django.db import models class Images(models.Model): title = models.CharField(max_length=100) description = models.CharField(max_length=100) image = models.ImageField() serializers.py from rest_framework import serializers from .models import Images class ImgSerializer(serializers.ModelSerializer): class Meta: model = Images fields = ["title", "description", "image"] def create(self, validated_data): return ImgSerializer(**validated_data) def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.description = validated_data.get('description', instance.description) instance.save() return instance views.py class ImgApi(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request): serializer = ImgSerializer(data=request.data) if serializer.is_valid(): try: serializer.save() except Exception as e: logger.error(e) return Response(data={'msg':f'{e}'},status=status.HTTP_500_INTERNAL_SERVER_ERROR) return Response(data=json_data, status=status.HTTP_201_CREATED) And things in Postman: How should I fix this problem? -
Django Cache Per View - Different For Every User
I'd like to cache a view in my Django app. However, the result of the view varies for every user, so the cache should show a different result to each user. I've tried using vary_on_cookie, but I can't get it to work: @cache_page(60 * 15) @vary_on_cookie def my_view(request): ... Is there a better way to do this? P.S. I'm currently using a local, file-based cache for testing, but will eventually use Memcached. My middleware looks like this: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I'm using file-based caching for now (to test) and my middleware looks like this: -
Django Project on live server
How to I put my local project on a server so that it can be used by various user I haven't tried most of the things but I know I can get easy answers and explanation here I just want to know that how can I set up environment on server so that it can handle my Django projects and python libraries -
Generate a JWT token in django for authentication between different service
My use case is to create a JTW token ( probability from Django Admin ) and use that token from other services ( clients, postman, microservice, etc ). That token should not expire because if it expires than I have to create a new Token and configure all the services again with the new Token. I am aware that 'rest_framework.authtoken' exists but it has some drawbacks - It doesn't create JWT token I Can see it in Django Admin after creation, ( I want to surface token only at the time of creation ) I want to have a service similar to most of the sms/email providers have. They provide us an API key and we can use that for future API calls. Looking forward to a solution. Thanks. -
Django_plotly_dash with Apache and mod_wsgi is not working
Greetings of the new year. I am trying to use Plotly Dash with Django app for creating a Dhasboard page. I used the django_plotly_dash package and made all the configuration as per the documentation. The page is working fine when I am running locally with python manage.py runserver but when I am deploying to UAT its failing. The UAT Django app is running on Windows Server + Apache httpd server + mod_wsgi +python 3.9 +Django 3.0. 10 I dont get any error in the apache server log , the application just stop responding to any http request. All the request queue up in pending state with django_ploty_dash config enabled. If I remove the configuration for django_plotly_dash the application starts responding again. plotly file: import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input,Output import plotly.graph_objs as go import pandas as pd from django_plotly_dash import DjangoDash import dash_bootstrap_components as dbc df = pd.read_csv(‘C:/Data/gapminderDataFiveYear.csv’) app = DjangoDash(‘SimpleExample’,add_bootstrap_links=True,external_stylesheets=[dbc.themes.BOOTSTRAP]) year_options = for year in df[‘year’].unique(): year_options.append({'label':str(year),'value':year}) app.layout = html.Div([ dcc.Graph(id='my-graph'), dcc.Dropdown(id='year-picker',options=year_options,value=df['year'].min()) ]) @app.callback(Output(‘my-graph’,‘figure’), [Input('year-picker','value')]) def update_figure(selected_year): #Filtered Dataframe based on selected year filtered_df = df[df['year'] == selected_year] traces =[] for continent_name in filtered_df['continent'].unique(): df_by_continent = filtered_df[filtered_df['continent'] == continent_name] traces.append(go.Scatter( x= … -
How to make loacalhost django interact with posgtres worked in docker container?
I'm run my project through docker. It contains few django's apps (backend), vue.js (frontend), celery, redis and postgres. All services working as expected, but now I need edit my project source code. For it I want to stop container that responsible for backend and frontend and to run them on localhost. And other services like redis, postgress and etc I leave to work in containers. How can I do this better way? I was doing: stop mentioned containers, leave working in containers other services, gave python manage.py runserver. But now I get this error.: psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? I guess my project can't access to postgres db worked container. Why is it like this? I convinced in terminal that my db is running in docker container on port 5432 . -
Django: Filter records based on one to many relationship
I have following models, class User(models.Model): name = models.CharField(max_length=255) ... class InsuranceProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ... class ProductExpertiseMaster(models.Model): class Meta: db_table = 'product_expertise_master' name = models.CharField(max_length=255) main_category = models.CharField(max_length=255) class UserProductExpertise(models.Model): user = models.ForeignKey(User, on_delete=models.DO_NOTHING) product_expertise = models.ForeignKey(ProductExpertiseMaster, on_delete=models.DO_NOTHING) So what I am trying to do is I want to filter records based on various fields some of the belong to User model & some of them belong to the InsuranceProfile model.I am filter the records based on User & InsuranceProfile model which is working fine. Now i want to add one more filter which will be based on the UserProductExpertise model.I want to get all the User who have some product expertise entries in UserProductExpertise model. Any help would appreciated. -
How to send a list of objects to the next Django template?
I have a list of objects in my Django template.Each object can be selected and added to a list. I need to send the list to the next template. How can i send the list to the next template? Thankful. -
I'm not able to find what wrong in url pattern
I'm getting this message "The current path, groups/posts/in/sadads/{url 'group:join' slug= group.slug %}, didn't match any of these." pls see my code as below. # GROUPS from django.conf.urls import url from django.urls import path from . import views app_name = 'groups' urlpatterns = [ path('', views.ListGroup.as_view(), name='all'), path('new/', views.CreateGroup.as_view(), name='create'), # path('posts/in/<slug:slug>', views.SingleGroup.as_view(), name='single'), url(r"^posts/in/(?P<slug>[-\w]+)/$", views.SingleGroup.as_view(), name="single"), url(r"join/(?P<slug>[-\w]+)/$", views.JoinGroup.as_view(), name="join"), # path('join/<slug:slug>',views.JoinGroup.as_view(),name='join'), path('leave/<slug:slug>', views.LeaveGroup.as_view(), name='leave'), ] and also in views.ListGroup.as_view() i'm not able to see all groups which are created. html are as below from braces.views import SelectRelatedMixin from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.http import Http404 from django.urls import reverse_lazy from django.views import generic from . import models # Create your views here. User = get_user_model() class PostList(SelectRelatedMixin, generic.ListView): model = models.Post select_related = ('user', 'group') class UserPost(generic.ListView): model = models.Post template_name = 'posts/user_post_list.html' def get_queryset(self): try: self.post_user = User.objects.prefetch_related('posts').get(username__iexact=self.kwargs.get('username')) except User.DoesNotExist: raise Http404 else: return self.post_user.posts.all() def get_context_data(self, *, object_list=None, **kwargs): context = super(UserPost, self).get_context_data(**kwargs) context['post_user'] = self.post_user return context class PostDetail(SelectRelatedMixin, generic.DetailView): model = models.Post select_related = ('user', 'group') def get_queryset(self): query_set = super(PostDetail, self).get_queryset() return query_set.filter(user__username__iexact=self.kwargs.get('username')) class CreatePost(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView): fields = ('message', 'group') model = models.Post def form_valid(self, form): …