Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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): … -
Django check box from models WITHOUT using the form.py?
How to render a checkbox with multiple selection allowed in Django by just using the model.py file and without using the form.py file? This is my code (which works however only for dropdown single selection and not checkbox multiple selection): from django.db import models class PropertyAmenities(models.Model): # here below is the list of multiple choices that I would like the user to be able to select PROPERTY_AMENITIES_CHOICES = ( ('maid_room', 'MAID_ROOM'), ('study','STUDY'), ('balcony_or_terrace', 'BALCONY_OR_TERRACE')) # the below only work as "dropdown single choice". How can I have it as a "multiple choice check box"? property_amenities = models.CharField(max_length=20, choices=PROPERTY_AMENITIES_CHOICES) Question: How to modify the model class without having to touch or use the form.py file? -
Dynamically get field name which relates two Django models
Let's say I have the following Django model: class Parent(models.Model): name = models.CharField(max_length=50) children = models.ManyToManyField("Child") class Child(models.Model): name = models.CharField(max_length=50) I have the Parent and Child models stored in variables in a script. Given these two models, how can I dynamically get the field name children as a string: def get_field_name(model, related_model): # what do I need here get_field_name(Parent, Child) # "children" -
How can only certain users see the page?
I created a system with Django. I have several users and these users can have different ranks. I have a page but I want to just one rank (lead) can see these page. How can I do that? models.py class UserProfile(AbstractUser): ranks = ( ('analyst', 'Analyst'), ('seniorAnalyst', 'Senior Analyst'), ('lead', 'Lead'), ('manager', 'Manager'), ('seniorManager', 'Senior Manager'), ('director', 'Director'), ('regionalDirector', 'Regional Director'), ('cfo', 'Chief Financial Officer'), ) 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 @login_required def lead_page(request): return render(request, 'lead.html') -
Subtract Time from Datetime Field in Django/Python
This question seems obvious and easy but I am getting my head stretched out here. Problem is I have datetime field in model and I want to subtract time from another attribute. here is my code I have tried so far. @property def boarding_time(self): print('---------------------------') time = self.schedule.travel_date_time.time() print() time_added = self.schedule.bus_company_route.routeboardingpoint_set.get( point=self.boarding_point ).time_added time1 = timedelta(hours=time.hour, minutes=time.minute, seconds=time.second) time2 = timedelta(hours=time_added.hour, minutes=time_added.minute, seconds=time_added.second) return (time1-time2) Scenario is I have suppose time=date and time of 2021/1/13 8:15 am and time_added is 8:45am now I want to return 30 minutes added to your location like that but I am getting error as 'datetime.timedelta' object has no attribute 'isoformat' -
What is the pypi link for django_saml package?
As discussed in this link, can any one guide me to the pypi link for the answer provided by Nessi? -
Django static files are saved recursively creating bloat via collectstatic
When running collectstatic on my production system, it seems like a bunch of files is stored recursively e.g. (real example): 'production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/production/css/lib/nestable/nestable.css' This causes bloat every time I update my static files (which is necessary when I update any javascript for the front-end). My settings.py file has the following: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/production/') STATICFILES_DIRS = ([ os.path.join(BASE_DIR, "static"), ]) I also have + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in my main urls.py In my Nginx available-sites config file I have the following lines: location /static/ { alias /home/ubuntu/myapp/static/production/; expires modified +1w; } To circumvent this issue, I now have to run collectstatic -c and delete all my static files with every update which isn't ideal. Where am I going wrong? -
Django-channels file/image handling
I'm trying to upload files/images to server via django-channels I have no idea how to send it to my consumers.py while I'm sending the file as var file = attachment.prop("files")[0]; var fileName = file.name; var fileSize = file.size; var fileType = file.type; finalData = { "attachment": file, "attachment-name": fileName, "attachment-size": fileSize, "attachment-type": fileType, } socket.send(JSON.stringify(finalData)); in server side just i can asscess the file name,size,type but not the actual file to save it, instate i get an empty dictionary. in server i'm using data = json.load(mydata) to get the the data and data.get("attachment") is always {} while I can assess type name.. i think it sends the file object to my server as string right? how to send the file as it is( actual savable file), so that i can use FileSystemStorage(url).save(filename,file) to my server. -
Django - Aggregating scores based on nested objects
my model is structured as follows: Model A -> Bundle Model B -> Products Model C -> Products Feedback Example: Bundle X Product A Feedback #A.1: score = 4 Feedback #A.2: score = 5 Product B Feedback #B.1: score = 2 Feedback #B.2: score = 4 ... In the "Bundle" detail view, I'd like to show this: Bundle X Product A (avg score = 4.5) Product B (avg score = 3.0) While in the "Product" details view I'm able to display the average scores, in the "Bundle" details view I'm able to display the list of products related to it, but I can't figure out how to show the scores. Any idea? Here some relevant code: class BundleDetail(generic.DetailView): model = Bundle template_name = 'bundle_detail.html' def get_context_data(self, **kwargs): context = super(BundleDetail, self).get_context_data(**kwargs) bundle = self.object context["hyp"] = Product.objects.filter(bundle=bundle).order_by('bundle') return context class ProductDetail(generic.DetailView): model = Product template_name = 'product_detail.html' def get_context_data(self, **kwargs): context = super(ProductDetail, self).get_context_data(**kwargs) test_conducted = self.object context["test_conducted"] = ProductFeedback.objects.filter(product_tested=test_conducted).order_by('test_conducted') a_s = ProductFeedback.objects.filter(product_tested=test_conducted).all().aggregate(Avg('score')) h_t = ProductFeedback.objects.filter(product_tested=test_conducted).all().aggregate(Count('score')) context["avg_score"] = round(a_s['score__avg'],1) context["nr_tests"] = h_t['score__count'] return context bundle_details: ... <div class="container"> <div class="row"> <div class="col mb-4 mt-3 left top"> {% for a in hyp %} <div class="card mb-2 mt-2 left top"> <div class="card-body"> … -
Write if else logic before creating api in serializer DRF
I need to write if else logic to show text alongside my values.before using get method. models.py class AnalysisResult(models.Model): user_id=models.IntegerField(primary_key=True) E=models.IntegerField() A=models.IntegerField() C=models.IntegerField() N=models.IntegerField() O=models.IntegerField() total=models.IntegerField() class Meta: db_table='analysis_result' def __str__(self): return self.response using DRF and serializer I have created api for this model.my created api looks like this when i hit url . [ { "user_id": 1, "E": 25, "A": 14, "C": 14, "N": 38, "O": 8, "total": 99 } ] but now i want to show some text based on the value of individual E,A,C,N,O. my api should look something like this [ { "user_id": 1, "E": 25 :"some text", "A": 14 :"some text", "C": 14 :"some text", "N": 38 :"some text", "O": 8 :"some text", "total": 99 } ] this texts vary with different values of E,A,C,N,O how can i achieve this task i am not understanding.Please give me a lead. serailizer.py class AnalysisResultSerializer(serializers.ModelSerializer): class Meta: model=AnalysisResult fields='__all__' views.py @api_view(['GET']) def AnalysisResultInfo(request,user_id): if request.method == 'GET': Results=AnalysisResult.objects.filter(pk=user_id) serializer=AnalysisResultSerializer(Results, many=True) return Response(serializer.data) urls.py path('Results/<int:user_id>/',views.AnalysisResultInfo) -
Django inserting data into loop but insert as object [duplicate]
I am adding data into table using foreign key of another table in for loop. It is inserting only id and another is in as Object. Here is my code for , model.py class companySaleStages(models.Model): userId = models.ForeignKey(userInfo , on_delete=models.CASCADE) saleStage_id = models.ForeignKey(saleStages , on_delete=models.CASCADE) saleStatus = models.CharField(max_length=250) salePercentage = models.CharField(max_length=250) created_date = models.DateTimeField(default=timezone.now) class Meta: db_table="companySaleStages" views.py def sectorData(request): saleStage = saleStages.objects.all() if request.method == 'POST': if request.POST.get('sectorId'): for sale in saleStage: companySale = companySaleStages() companySale.userId = userInfo.objects.latest('id') companySale.saleStage_id = saleStages.objects.get(id=sale.id) companySale.saleStatus = saleStages.objects.get(saleStatus=str(sale.saleStatus)) companySale.salePercentage = saleStages.objects.get(saleStatus=str(sale.saleStatus)) companySale.save() return redirect('capabilities') else: return redirect('sector') else: return render (request , 'sector.html' , {'saleStage' : saleStage}) Into database, value for 'saleStatus' and 'salePercentage' insert as "saleStages object (1)" instad of string value from data.