Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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() -
Views and HTTPresponse with user's data - Django
Given a GET the url is /home/data Where data is a value that will depend on the user, that is, the complete domain will be domain/home/data What I want is to return an HTTP response depending on the data value url.py urlpatterns = [ path('admin/', admin.site.urls), path('home/', home, name='home'), ] views.py def home (request): response =item.objects.filter(radius<data) return HttpResponse(response ) As you can see, radius is an attribute of the item model. And I want to filter all radius that are less than data. How can I include data in that home function? -
Im am doing a project in the book "Python crash course 2nd eddition"
I am doing the web applications project and I have successfully deployed my project to heroku.com but my topics and entries are not synced with the server only the person who created the topic/ entry can see it. When I am on the admin sight i can see who all the different entries but for some reason, even as an admin no one can see each others topics or entries. -
Django overriding form_valid with other processing functions not related to form
This is more of a best practices Django question that I am struggling with. I am uploading an excel file via a form, in which the form_valid function is overridden adding some data prior to calling form.save(), however I also need to save the headers (columns) for the file at the same time, to ensure the file and the headers are saved together. Is this acceptable below or am I handling too much logic inside of form_valid that really does not belong there? It would look something like this in views: class FileUploadCreateView(generic.CreateView): template_name = 'fileupload/file-create.html' form_class = FileUploadModelForm success_message = 'Success: File was uploaded.' def get_success_url(self): return reverse('files_list') def form_valid(self, form): self.instance = form.save(commit=False) self.instance.file_upload = form.cleaned_data['file_upload'] self.instance.my_user = self.request.user self.instance.file_status = 'ready' form.save() # Get file object just saved fileObj = FileUpload.objects.filter(id=self.instance.id) file_upload_path = fileObj.file_upload.path # validation logic handled in forms to determine file type # Process excel file headers df = pd.read_excel(file_upload_path, header=0) col_names = list(df.columns.values) fhModel = FileHeaders() fhModel.my_user = userObj fhModel.file_upload = fileObj fhModel.file_headers = json.dumps(col_names) fhModel.save() return super().form_valid(form) -
How to make field editable not for all instances in django admin list view?
How to make field editable not for all instances in django admin list view. For example if sum exists make this instance editable. I tried override ModelForm and add widget but it doesn't work. Also I tried override has_permission function but it doesn't work too. -
Database for a fair reservation system
I'm developing a fair reservation system for people who sign up for using a stand of the fair but I'm quite complicated on defining the database since I later on need to use a search feature and see which stand is occupied for specific date, so here is what I've come up with: from django.db import models from .choices import CATEGORY class Fair(models.Model): name = models.CharField(max_length=30) number_of_stands = models.IntegerField() class Stand(models.Model): entrepreneur = models.ForeignKey(Entrepreneur, on_delete=models.CASCADE) check_in = models.DateTimeField(null=True, blank=True) checkout_in = models.DateTimeField() entrepreneur_category = models.IntegerField(choices=CATEGORY, default=3) class Entrepreneur(models.Model): name = models.CharField(max_length=30) email = models.EmailField() I'm looking for some guidance to have this working later on when using the search and date range filter. I'm not quite sure if this could work because the check_in/checkout might not the the most proper way to do it. Is this the best way to do it? -
Celery task hanging on Django app with Rabbitmq
I'm following the First Steps With Django for my app running on a docker container. I have rabbitmq setup on a separate docker container. Opening a python shell to run the task add just results in hanging/freezing without any reports/errors from celery interface. Below are the details. Django version - 3.0.5 Celery - 5.0.2 amqp - 5.0.2 kombu - 5.0.2 Rabbitmq - 3.8.9 myapp/myapp/settings.py CELERY_BROKER_URL = 'pyamqp://guest:guest@myhost.com//' CELERY_RESULT_BACKEND = 'db+postgresql+psycopg2://postgres:111111@myhost.com/celery' myapp/myapp/celery.py import os from celery import Celery import logging logger = logging.getLogger(__name__) # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') app = Celery('myapp') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') logger.error('in celery') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') myapp/myapp/init.py from .celery import app as celery_app import logging logger = logging.getLogger(__name__) logger.error('in init') __all__ = ('celery_app',) myapp/otherapp/tasks.py from celery import shared_task import logging logger = logging.getLogger(__name__) @shared_task def add(x, y): logger.error('add') return x + y Once I run celery -A demolists worker --loglevel=INFO in terminal, I get the …