Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: The view users.views.logout_user didn't return an HttpResponse object. It returned None instead
I am building a blog app in django. But, when I write a function for logging users out, I get this traceback error: Internal Server Error: /users/logout/ Traceback (most recent call last): File "C:\Users\Dell\Desktop\Django\blog\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Dell\Desktop\Django\blog\venv\lib\site-packages\django\core\handlers\base.py", line 186, in _get_response self.check_response(response, callback) File "C:\Users\Dell\Desktop\Django\blog\venv\lib\site-packages\django\core\handlers\base.py", line 309, in check_response "instead." % name ValueError: The view users.views.logout_user didn't return an HttpResponse object. It returned None instead. My logout_user view function is only two lines, so I can't seem to understand the error. Here is my view function: @login_required def logout_user(request): logout(request) Can anyone help me out? -
UNIQUE constraint failed: store_order.id
i have created a payment system so after successful payment the orders status will change to PAID Here is my models.py : class Order(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() date = models.DateField(datetime.datetime.today, null=True) status = models.CharField(max_length=100, null=True, default="Unpaid") payment_method = models.ForeignKey( PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) total = models.IntegerField(null=True) Here status field has been set to unpaid but when payment is successful it will show PAID For that i tried this : def post(self, request, *args, **kwargs): customer = Customer.objects.get(id=request.session['customer']['id']) print(customer) user_orders = Order.objects.get(pk=kwargs['id']) # index = Order.objects.get(customer=customer) # print(index.total) total = user_orders.total print(total) balance = request.session['customer']['coin'] print(balance) if balance >= total: balance = balance - total # Customer.objects.filter(id = request.session['customer']['id']).update(coin=balance) customer.coin = balance customer.save() user_orders.status = "PAID" user_orders.save() request.session['customer']['coin'] = str(balance) return HttpResponse("Remaining balance: " + str(balance)) return HttpResponse("Insufficient Balance") But getting this error : UNIQUE constraint failed: store_order.id -
How to create instance with pre-populated ChoiceField in form
This is my forms.py. I want to create instance with default 'V' choice into my model. So instance was created, but with choice 'A', which i provided in model for default. class VideoForm(forms.ModelForm): theory_type = forms.ChoiceField(choices=quests.StageTheories.THEORY_TYPE) class Meta: model = quests.StageTheories fields = ['title', 'youtube', 'stage'] class StageTheories(models.Model): THEORY_TYPE = ( ('Q', 'Quiz'), ('A', 'Article'), ('V', 'Video'), ) stage = models.ForeignKey(to=Stages, on_delete=models.CASCADE, db_column="stage_id",verbose_name="Этап", ) title = models.CharField(max_length=47, db_column="title", verbose_name="Заголовок теории",) text = models.TextField(db_column="text", verbose_name="Текст теории", null=True, blank=True,) youtube = models.URLField(db_column="youtube", verbose_name="Ссылка на youtube", null=True, blank=True,) sortOrder = models.PositiveIntegerField(null=True, blank=True, db_column="sort_order", verbose_name="Порядковый номер", ) theory_type = models.CharField(max_length=1, choices=THEORY_TYPE, default='A') class AddVideoView(CreateView): model = quests.StageTheories form_class = VideoForm success_url = '/' template_name = 'add_video.pug' def get_initial(self): initial = super().get_initial() initial['stage'] = quests.Stages.objects.get(id=self.kwargs['pk']) initial['theory_type'] = 'V' return initial Is initial value not going for form data? -
Django/Python zlib Compress Json - Uncompress JS Client Size
I'm compressing json in Python using the following code: chartDataListJsonCompressed = zlib.compress(str.encode(chartDataListJson)) Then I send the data to client-side using Httpresponse (convert it to string as well): return(HttpResponse(str(chartDataListJsonCompressed))) On Ajax client side I'm trying to convert this compressed string data back to string using the pako library: success: function (data) { //Convert string data to char data var charData = data.split('').map(function(x){return x.charCodeAt(0);}); //Convert char data to array var binData = new Uint8Array(charData); // Pako - inflate bin data var d = pako.inflate(binData); // Convert gunzipped byteArray back to ascii string: var strData = String.fromCharCode.apply(null, new Uint16Array(d)); } Unfortunately I get the error: Uncaught incorrect header check Thus, I'm obviously doing something wrong. I just cannot get my finger on it. Any ideas? -
How to use create function instead of perform_create in ListCreateApiView in django rest framework
I am trying to create a booking api for a website. For this, I used perform_create function in ListCreateApiView. But, it was someone else who helped me and told me to use perform_create function. But, I was thinking, it should be possible using create function and is a right approach rather than perform_create function. Also, I don't really know the difference between these two functions and don't really know when to use which. Here is my view: class BookingCreateAPIView(ListCreateAPIView): permission_classes= [IsAuthenticated] queryset = Booking.objects.all() serializer_class = BookingSerializer def perform_create(self, serializer): # user = self.request.user package = get_object_or_404(Package, pk= self.kwargs['pk']) serializer.save(user=self.request.user,package=package) Here is my serializer: class BookingSerializer(serializers.ModelSerializer): # blog = serializers.StringRelatedField() class Meta: model = Booking fields = ['name', 'email', 'phone', 'bookedfor'] Here is my model: class Booking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) package = models.ForeignKey(Package, on_delete=models.CASCADE, related_name='package') name = models.CharField(max_length=255) email = models.EmailField() phone = models.CharField(max_length=255) bookedfor = models.DateField() created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('created_at',) -
Django / MySQL / Python Programming Error ( 1064)
when I run python manage.py migrate I keep getting the following error. django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'None) NOT NULL, user_id_id integer NOT NULL)' at line 1") I'm running Python 3.8.6, and mysqlclient 2.0.1 and Django 3.1.3. Model from ..assets.provinces import PROVINCE_CHOICES from ..assets.industries import INDUSTRY_CHOICES from django.contrib.auth.models import User class GrantProfile(models.Model): user = models.ForeignKey(User, models.SET_NULL, blank=True, null=True) province = models.CharField( max_length=2, choices=PROVINCE_CHOICES, help_text="Province your organization is based out of" ) company_size = models.IntegerField(help_text="Company size") industry = models.CharField( max_length=150, choices=INDUSTRY_CHOICES, help_text="Industry your organization is part of." ) class Meta: db_table = "grantprofiles" View # Grant Profile View from rest_framework import viewsets from ..serializers.grantprofile import GrantProfileSerializer from ..models.grantprofile import GrantProfile class GrantProfileView(viewsets.ModelViewSet): serializer_class = GrantProfileSerializer queryset = GrantProfile.objects.all() Admin from django.contrib import admin from ..models.grantprofile import GrantProfile # Grant Profile Admin class GrantProfileAdmin(admin.ModelAdmin): list_display = ('user_id', 'province', 'company_size', 'industry') admin.site.register(GrantProfile, GrantProfileAdmin) Serializer from django.contrib import admin from ..models.grantprofile import GrantProfile from rest_framework import serializers from ..models.grantprofile import GrantProfile class GrantProfileSerializer(serializers.ModelSerializer): class Meta: model = GrantProfile fields = ('user_id', 'province', 'company_size', 'industry') I'm not sure if I'm missing something? -
Add item to dropdown without refresh
City is a (dropdown in a main form ) with a +(Add) button. This +(Add) button opens another form in separate window. On saving a new city in the second form, I want the new city name to be added in the City dropdown without refreshing the main form. Here is my code. <form method="POST" enctype="multipart/form-data" id="form"> {% csrf_token %} <td>City: {{ form.city }} <button class="btn btn-primary" onclick="addCity(event)">+</button> </td> <button type="submit" class="btn btn-primary">Save</button> </form> <script> function addCity(e){ e.preventDefault(); window.open("/city/", "", "width=500,height=500"); } </script> city.html <form method="POST" class="post-form" action="/city/" id="form"> {% csrf_token %} <div class="container"> <div class="form-group row"> <label class="col-sm-2 col-form-label">City:</label> <div class="col-sm-4"> {{ form.name }} </div> </div> <button type="submit" class="btn btn-primary">Save</button> </div> </form> urls.py urlpatterns = [ path('city/', views.add_city, name='city_master'), ] views.py def add_city(request): cities = City.objects.all() if request.method == "POST": form = CityForm(request.POST) if form.is_valid(): try: form.save() return redirect('/city/') except: pass else: form = CityForm() return render(request,'city.html',{'form':form}) -
empty tag {% empty %} in django template doesn't work when "if" condition is nested inside for loop
<ul> {% for entry in entries %} {% if title in entry %} <li><a href="/{{ entry }}">{{ entry }}</a></li> {% endif %} {% empty %} <li>Sorry! No result matches your search.</li> {% endfor %} </ul> This is my html template. Want to create a list where the list items have to meet certain condition, so I nested if condition inside for loop. The list works, but empty tag doesn't. When the list is empty, it doesn't show anything. When I tried to nest empty tag inside if condition, then the empty tag message shows for every list item where the item doesn't meet the if condition. How can I make it work? -
I am extending my header and footer but when i pass data in footer it is visible only at home page not on other pages
I am extending my header and footer but when i pass data in footer it is visible only at home page not on other pages. I know that i have to pass that data on every pages but i am looking for a easy solution example: from django.shortcuts import render,redirect from footer.models import Footer def home(request): contact_info = Footer.objects.all() return render(request,'frontend/index.html', {'contact_info':contact_info}) Index.html <div class="col-md-3 col-md-push-1"> <div class="gtco-widget"> <h3>Get In Touch</h3> <ul class="gtco-quick-contact"> {% if contact_info %} {% for i in contact_info %} <li><a href="tel:{{ i.phone }}"><i class="icon-phone"></i>{{ i.phone}}</a></li> <li><a href="mailto:{{ i.email }}"><i class="icon-mail2"></i>{{ i.email }}</a></li> <li><a href="http://maps.google.com/?q={{ i.location }}"><i class="ti-location-pin"></i>{{ i.location }}</a></li> {% endfor %} {% endif %} </ul> </div> </div> At Contact Page: At Index Page: -
Hello, can this function be converted into a class
I have a function that transfers data to the index page, def index(request): news = News.objects.all()[:3] sponsors = Sponsors.objects.all()[:6] programs = Programs.objects.order_by('date') speakers = Speakers.objects.reverse()[:3] context = { 'news': news, 'sponsors': sponsors, 'programs': programs, 'speakers': speakers, } return render(request, 'landing/index.html', context) can this function be converted into a class as in the example class Home(ListView): model = News template_name = 'landing/index.html' context_object_name = 'news' paginate_by = 3 def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'Новости' return context -
Grabbing models from database in asynchronous function (Channel Consumer) Django
Summary Hello, currently I am working on a application that sends data to the frontend in Realtime through using django-channels. I have been able to do this for all models that are created when they page is opened, however I have not yet been able to grab previous models for when the page has not been opened yet. Code Below was one of my first attempts at getting this system working, this would be called when the consumer connect method would be fired, and after the connection was accepted I would run this for loop for app in Application.objects.all(): app_json = ApplicationSerializer(app).data await self.send_json({'action': 'create', 'data': app_json}) When running this code I would get the error message of django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. This makes sense since the consumers connect method is asynchronous, so following the advice of the message I went ahead and used sync_to_async for app in sync_to_async(Application.objects.all)(): app_json = ApplicationSerializer(app).data await self.send_json({'action': 'create', 'data': app_json}) I decided to use sync_to_async around the Application objects since the error message highlighted the for loop line itself and also I know that the applicationSerializer would be working correctly since I … -
Modified User problem django but it's not registering to db
I have modified User in django but it's now registering user to the db. Here is views.py from django.shortcuts import render, redirect from .forms import RegisterForm # Create your views here. def login(request): return render (request, 'UsersAuth/login.html') def register(request): error = "" if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: error = 'Form is not valid' form = RegisterForm() context = { 'form': form, 'error': error } return render(request, 'UsersAuth/register.html', context) Here is the forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms import datetime class RegisterForm(UserCreationForm): email = forms.EmailField(widget = forms.EmailInput(attrs={'class':'form-control', 'placeholder':'Email *'})) first_name = forms.CharField(max_length=100, widget = forms.TextInput(attrs={'class':'form-control', 'placeholder':'First name *'})) last_name = forms.CharField(max_length=100, widget = forms.TextInput(attrs={'class':'form-control'})) class Meta: model = User fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2'] def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class']= 'form-control' self.fields['username'].widget.attrs['placeholder']= 'User name *' self.fields['password1'].widget.attrs['placeholder']= 'Create a password*' self.fields['password2'].widget.attrs['placeholder']= 'Confirm a password*' self.fields['password1'].widget.attrs['class']= 'form-control' self.fields['password2'].widget.attrs['class']= 'form-control' registration page register.html {%extends 'UsersAuth/base.html'%} {%block title%} Registration {%endblock%}s {%block content%} <form method ='POST' class="form-group text-white"> {%csrf_token%} <div>{{form.username}}</div><br> <div> {{form.first_name}}</div><br> <div>{{form.last_name}}</div><br> <div>{{form.password1}}</div><br> <div>{{form.password2}}</div><br> <button type="submit" class = "btn btn-success">Register</button> </form> {%endblock%} Form on method post and it's sending a post response but in DB … -
Using Django with NextJS
I am looking at integrating NextJS into an existing Django project. The project makes heavy use Django templates for most of its pages and I am looking at modernising the project by taking advantage of React and building out a design / component system. I have been able to use Django to proxy a request through to NextJS, and it works great! I have also been able to send data directly to the NextJS route so that I do not have to call back to Django to get data. Here is the working code. # django def _handle_request(self, data, make_request): data = {"hello": "world"} response = make_request("http://localhost:3000", data=data) return HttpResponse(response) //nextjs Home.getInitialProps = async (ctx) => { const { req, query } = ctx; const data = await parse(req); console.log("body", data); return {}; }; I have read online that using data on a GET request is not recommended for various reasons (eg How to send data in request body with a GET when using jQuery $.ajax()) and POST requests should be used instead. I have tried to get a NextJS route working with POST and it doesn't look like this is an option. So with this in mind, is there … -
Django Admin - Accessing New Model gives 500 error
I created a Django app with one Model initially, and hosted the site successfully with Heroku. I've since added another Model, have run makemigrations and migrate commands, and pushed code to Heroku. Everything appears to be working fine, I can even see the new Model listed on the Admin portal. However, when I click the model, or try to add a new instance of the model, I am thrown and internal service 500 error. I've turned DEBUG to True, and I am seeing this: relation "my_model" does not exist. The other model I have still works, even when I delete all instances. Please help -
AttributeError: 'NoneType' object has no attribute 'AddressLine'
I have: Models: class Profile(models.Model): # Họ Và Tên UserFirstName = models.CharField(max_length=128, validators=[name_regex]) UserMiddleName = models.CharField(max_length=128, validators=[name_regex]) UserLastName = models.CharField(max_length=128, validators=[name_regex]) UserFullName = models.CharField(max_length=256) AddressIDProfile = models.ForeignKey(Address, on_delete=models.SET_NULL, null=True) AddressProfile = models.CharField(max_length=128, null=True) class Meta: db_table = "Profile" def save(self, *args, **kwargs): try: self.AddressProfile = self.AddressIDProfile.AddressLine except ObjectDoesNotExist: pass super(Profile, self).save(*args, **kwargs) Problem: I want to assign data to the AddressProfile field by getting it from the foreign keyword AddressIDProfile. But when AddressLine is None, an error occurs. I tried to test it first but with no success. Please give me the solution.Thanks!!! -
Django Formsets - this field is required error
I am getting this error. I am using django formsets and whenever when I post data, the formsets shows this field is required error in everyfield in formset's form Each of them are errors displayed as by my views.py file Views.py def company_allocation_pot(request, company_name): company = Company.objects.get(company_name=company_name) qs=CompanyPotAllocation.objects.filter(company = company) or None if request.method == 'GET': # formset = CompanyPotAllocationFormset(queryset=None) formset = CompanyPotAllocationFormset(queryset=qs, form_kwargs = {"company_name": company_name}, auto_id = "id_%s") return render(request, 'company/create-company-pot.html', {'company_allocation_pot_formset': formset, 'company': company}) if request.method == 'POST': # formset = CompanyPotAllocationFormset(request.POST) formset = CompanyPotAllocationFormset(data=request.POST,queryset=qs,form_kwargs = {"company_name": company_name}, auto_id = "id_%s") if formset.is_valid(): for item_form in formset: item = item_form.save(commit=False) item.date_created = datetime.now() item.company = company item.save() return redirect('charity_app:company_allocation_pot', company_name=company) else: print("\n") print(request.POST) for error in formset.errors: print("\n") for k,v in error.items(): print(f"{k} {v}") return render(request, 'company/create-company-pot.html', {'company_allocation_pot_formset': formset, 'company': company}) Forms.py class CompanyPotForm(forms.ModelForm): fields = ['allocation_amount'] def __init__(self,company_name,**kwargs): super(CompanyPotForm,self).__init__(kwargs) self.company_name = company_name company = Company.objects.get(company_name=company_name) roles = company.company_jobroles or None if roles is None: return choices = tuple((role,role) for role in roles.split(",")) self.fields['grade'] = forms.ChoiceField( choices = choices, label="Specify Grade" ) def cleanRoles(self,value): company = Company.objects.get(company_name= self.company_name) if value in company.company_jobroles: return value else: raise forms.ValidationError("That role is not provided") class Meta: fields = ['allocation_amount',"grade"] model … -
Where do I setup django database credentials?
I've been trying to upload a pandas dataframe into a django database using to_sql, though I see content suggesting that I need to set up some credentials to make it work, such as: from django.conf import settings user = settings.DATABASES['default']['USER'] password = settings.DATABASES['default']['PASSWORD'] database_name = settings.DATABASES['default']['NAME'] # host = settings.DATABASES['default']['HOST'] # port = settings.DATABASES['default']['PORT'] database_url = 'postgresql://{user}:{password}@localhost:5432/{database_name}'.format( user=user, password=password, database_name=database_name, ) engine = create_engine(database_url, echo=False) My questions are, where do I set up those configurations user, password, and database_name? and is there a way to not expose sensitive data such as user and password? -
Restricting the url parameter values in Django URL
I have a Django web app that has 2 types of users, say customers, and business. I need to get the type of user trying to login. So I defined a url pattern as folows: path('login/<type>/', LoginView.as_view(), name='login'), But how can I restrict the url patten to match only the following patterns login/customers/ login/business/ -
Inheriting OneToOneField results in TypeError: __init__() got an unexpected keyword argument 'related_name'
I 'm using Django 2.2, Python 3.7 and my attempt was to setup some common kwargs (say, on_delete and related_name) to the OneToOneField, by a sub class like the following class MyOneToOneField(models.OneToOneField): def __init__(self, to): super().__init__(to, on_delete=models.CASCADE, related_name='extra_data') And the model class is like class UserExtraData(models.Model): entity = MyOneToOneField(USER_MODEL) However it results in TypeError: Couldn't reconstruct field entity on UserExtraData: __init__() got an unexpected keyword argument 'related_name' when running makemigrations. ( I tried removing all other fields so pretty sure this is the field that caused the issue ). Any ideas are appreciated! -
'login' is not defined error happens in React.js
I made frontend app in React.js. I wrote codes in App.js of frontend like import React, { Fragment, useState, useEffect, Component, View } from 'react'; import axios from 'axios'; import Routes from '../src/components/Routes'; import TopNavigation from './components/topNavigation'; import SideNavigation from './components/sideNavigation'; import Footer from './components/Footer'; import './index.css'; import Router from './Router'; const App = () => { const [user, setLogin] = useState(null) const [report, setReport] = useState(null) useEffect(()=>{ login().then(user => setLogin(user)) }, []) useEffect(()=>{ getReport().then(report => setReport(report)) }, []) return <div> {user != null? <p>name: {user.name}</p>:<button>Login</button>} </div> } export default App; I wrote in this code login().then(user => setLogin(user)) whether user already logined or not. Login system was made in Django,so I want to use it.I think React has login method but I really cannot understand what is wrong.How should I fix this? -
How to render signals.py error message to the django-rest API?
I am trying to render the error message from Django signals.py file to django-restframework views.py. I created the views.py file like this, class HazardIndexViewSet(viewsets.ModelViewSet): queryset = HazardIndex.objects.all() serializer_class = HazardIndexSerializer permission_classes = [permissions.IsAuthenticated] My signals.py file looks like, @receiver(post_save, sender=HazardIndex) def publish_to_geoserver(instance, created, *args, **kwrgs): try: geo.create_coveragestore(instance.name, instance.workspace_name, path=instance.file) exception as e: instance.delete() print("Something is wrong while creating coveragestore") I want this print statement(print("Something is wrong while creating coveragestore")) to display the error message in API. And another things is, I want to create the instance only if the publish_to_geosever function runs successfully. Otherwise it should through error. Any help? -
Cloudinary & Django - Django3 does not support django.utils.six fix?
I am using Heroku to deploy an application that I made with Django 3.1.2 (python 3.6.12), and I am using Cloudinary to store uploaded images. I am running into a ModuleNotFoundError (shown below) because cloudinary-storage imports django.utils.six, but Django 3.0 does not support django.utils.six. I have researched a bit, but have not found a working answer. One suggestion was to downgrade to Django2 - but when I did this I started receiving many other errors for other parts of my application so I don't want to go this route if possible. So now I am trying to figure out a way that I can use Django3 and Cloudinary together, and get around the problem that Django3 does not support django.utils.six. Any help/suggestions would be greatly appreciated Here is the traceback: Django Version: 3.1.2 Python Version: 3.6.12 Installed Applications: ['users.apps.UsersConfig', 'point_system.apps.PointSystemConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cloudinary_storage', 'cloudinary'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/generic/base.py", line 98, in dispatch … -
EC2 files - slow to display
Environment : Django I have a python function def get_downloading_videos(project_id, stream_name): objects = [] ssm = get_aws_service_client('ssm') response = ssm.list_commands(InstanceId='i-xxxxxxxxxxx', Filters=[{'key': 'ExecutionStage', 'value': 'Executing'}]) for download_req in response['Commands']: command = download_req['Parameters']['commands'][0] if project_id in command and stream_name in command: video_params = {'url': '', 'key': '', 'command_id': download_req['CommandId'], 'start_time': download_req['RequestedDateTime'].strftime('%Y-%m-%d %H:%M:%S'), 'status': 'executing'} objects.append(video_params) return objects When I want to display these files on a webpage, if I have some files which match with these filters, display is normal. But if I don't have any files, loading is very very slow. Also, is there any way to display EC2 files in instance in JavaScript with SDK? -
How to get data from another different ModelForm
Is it possible to auto populate data from a search to a two different ModelForm ? What I want to do is when I "search" using a GET Method, it shows the Asset details, after the query. the page shows the Asset details with a "Assign" button, when pressed it passes on the "asset_id" and goes to the next HTML create form(LoanerForm). My problem is that on the LoanerForm does not auto populate the "asset_number". I dont get why, the pk is correct and I pass it on as instance on the Form. The other fields updates except the "asset_number" remains the default select option. My View: def loaner_view_page(request): asset = request.GET.get('q') my_asset = Asset.objects.filter(asset_number=asset) print('Printing results', request.GET) context = { 'asset':my_asset, } return render(request, 'assets/asset_loaner_page.html', context) def loaner_assign(request, pk): asset = Asset.objects.get(id=pk) form = LoanerForm(instance=asset) if form.is_valid(): print('Printing results', request.POST) form.save() return redirect('/Dashboard/') context = { 'form': form, } return render(request, 'assets/asset_loaner_assign.html', context) My Model: class Asset(models.Model): model_item = models.ForeignKey(Model_Items, null=True, on_delete= models.SET_NULL) po_number = models.ForeignKey(Po, null=True, on_delete= models.SET_NULL) asset_number = models.CharField(max_length=10, default='') serial_number = models.CharField(max_length=10, default='') asset_location = models.ForeignKey(Location, null=True, on_delete= models.SET_NULL) asset_type = models.CharField(max_length=10, default='')#primary device owner/loaner def __str__(self): return self.asset_number class Loaner(models.Model): loaner = models.ForeignKey(Asset, null=True, … -
Patch ajax to a viewset returns 403 and works with APIview. DjangoRestFramework
I have a simple ajax request made with jQuery. It keeps returning 403, despite the same request works ok with APIview. let option_id = $('.option_checkbox_checked').attr('value') let token = $('#token').attr('value') var patch = { 'selected_options': option_id, 'csrfmiddlewaretoken': token } $.ajax({ url: 'http://127.0.0.1:8000/api/router/user_passed_test/5/', type: 'PATCH', dataType: 'json', data: patch, success: function (data) { console.log(data) } }) Viewset looks like following: class UserPassedTestViewSet(viewsets.ModelViewSet): permission_classes = [permissions.AllowAny] serializer_class = UserPassedTestSerializer queryset = UserPassedTest.objects.all()