Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Covert a string into list & sublist with characters sepration in python
Covert a string "Welcome to Baramati" into list & sublist (ex: 1st list has 3 letters ['W','E','L']. The 2nd list has 4 letters ['C','O','M','E'] and the 3rd list has 5 letters & the 6th list has 6 letters. -
Filtering tagged blog posts using intermediate table in Django
I am trying to render a page by filtering the posts by tags. I want the related articles to be displayed when a user clicks the tag in All-articles.html Im not sure how to go about it or how I would write the code. Should I create a path in urls.py like path('tag/<str:tagslug>', views.tag, name='tag'), so that I can access the url within the views.py? How would I write the ORM to filter articles by tags in views.py? Any help will be appreciated :) Thanks models.py class ArticleTags(models.Model): article = models.ForeignKey('Articles', models.DO_NOTHING) tag = models.ForeignKey('Tags', models.DO_NOTHING) class Tags(models.Model): tag = models.CharField(unique=True, max_length=75) tagslug = models.SlugField(max_length=200, unique=True, default=None) class Articles(models.Model): title = models.CharField(max_length=155) metatitle = models.CharField(max_length=155) slug = models.SlugField(unique=True, max_length=155) summary = models.TextField(blank=True, null=True) field_created = models.DateTimeField(db_column='_created', blank=True, null=True) cover = models.ImageField(upload_to="cover", blank=True, default='logo-00-06.png') views.py def allarticles(request): articles_list = Articles.objects.all() paginator = Paginator(articles_list, 12) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = {'page_obj': page_obj} return render(request, "All-articles.html", context) All-articles.html {% for article in page_obj %} <article> <div> <img src="media/{{ article.cover }}" alt="menu item" class="article-photo" /> </div> <header> <h4>{{ article.title }}</h4> </header> </article> {% endfor %} -
ModuleNotFoundError: No module named 'arrow' python3 django2.2.6
line 44, in import arrow ModuleNotFoundError: No module named 'arrow' -
How to implement Swagger api in django project? [closed]
Can anyone suggest me how to swagger api should connect instead of rest framework api in django. -
Writing Django Session Middleware based on view kwargs
I am in need of the ability to not set a session in my Django App when I hit specific URLS because the URLs dictate which DB to go to and the session django uses is stored in those DBs So, please how can I write the SessionMiddleware to use process_view instead of process_response()? import time from importlib import import_module from django.conf import settings from django.contrib.sessions.backends.base import UpdateError from django.contrib.sessions.exceptions import SessionInterrupted from django.utils.cache import patch_vary_headers from django.utils.deprecation import MiddlewareMixin from django.utils.functional import SimpleLazyObject from django.utils.http import http_date class SessionMiddleware(MiddlewareMixin): pass # RemovedInDjango40Warning: when the deprecation ends, replace with: # def __init__(self, get_response): def __init__(self, get_response=None): super().__init__(get_response) engine = import_module(settings.SESSION_ENGINE) self.SessionStore = engine.SessionStore def process_request(self, request): session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME) print(request.__dict__) if hasattr(request, 'client_url'): print('client url') request.session = self.SessionStore(session_key) print(self.SessionStore(session_key), self.SessionStore(session_key).__dict__) else: from django.contrib.sessions.backends.db import SessionStore s = SessionStore(session_key) print('session eluded...') request.session = s print('session eluded after...') request.session = {} def process_view(self, request, callback, callback_args, callback_kwargs): # I NEED TO CALL THIS TO ENSURE SESSIONS ARE IN A SPECIFIC DB pass def process_response(self, request, response): """ If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie or delete … -
In Django swagger_auto_schema' is not defined
i am using Django 2.2.6 and python3 find this error line 122, in CaseListView @swagger_auto_schema( NameError: name 'swagger_auto_schema' is not defined -
React Authentication error: Cannot read properties of undefined (reading 'forEach')
i downloaded a React Admin Template to learn, i am using Django with django rest framework as the backend technology, i am using djangorestframework-simplejwt for authentication. In the Login component i ask for Email and Password: import { yupResolver } from '@hookform/resolvers/yup'; import TextField from '@mui/material/TextField'; import Button from '@mui/material/Button'; import Icon from '@mui/material/Icon'; import IconButton from '@mui/material/IconButton'; import InputAdornment from '@mui/material/InputAdornment'; import { useEffect, useState } from 'react'; import { Controller, useForm } from 'react-hook-form'; import { useDispatch, useSelector } from 'react-redux'; import { submitLogin } from 'app/auth/store/loginSlice'; import * as yup from 'yup'; import _ from '@lodash'; /** * Form Validation Schema */ const schema = yup.object().shape({ email: yup.string().email('You must enter a valid email').required('You must enter a email'), password: yup .string() .required('Please enter your password.') .min(4, 'Password is too short - should be 4 chars minimum.'), }); const defaultValues = { email: '', password: '', }; function JWTLoginTab(props) { const dispatch = useDispatch(); const login = useSelector(({ auth }) => auth.login); const { control, setValue, formState, handleSubmit, reset, trigger, setError } = useForm({ mode: 'onChange', defaultValues, resolver: yupResolver(schema), }); const { isValid, dirtyFields, errors } = formState; const [showPassword, setShowPassword] = useState(false); useEffect(() => { setValue('email', '', { … -
How to have two either or owner for a data in table django?
Lets say I have a table, Class Application: owner = models.OneToOneField(Student, on_delete=models.CASCADE) name = models.CharField(max_length=64) dob = models.CharField(max_length=64) Basically, a student can make a application ! That's how the above on linked, now lets say I have user type called "Agents". I also want them to make application, how to achieve that ? Should i create a new field named employee = models.OneToOneField(Employee, on_delete=models.CASCADE, null=True) Can i have two onetoone field ? Or it should be foriegnField ? How to manage to store when students applies and also when employee applies ? -
Django REST API accept list instead of dictionary in post request
I am trying to consume data from a callback API that sends the POST request in this format: [ { "key1": "asd", "key2": "123" } ] However my API currently only works when it is sent like this: { "key1": "asd", "key2": "123" } serializers.py: class RawIncomingDataSerializer(serializers.ModelSerializer): class Meta: model = RawIncomingData fields = '__all__' views.py: class RawIncomingDataViewSet(viewsets.ModelViewSet): queryset = RawIncomingData.objects.all() serializer_class = RawIncomingDataSerializer There will only ever be one object in the post data, so I am looking for a simple work around without having to rewrite my serializer to interpret multiple objects in one post request. -
How can I retrieve my raster data from PostGIS database in Django project and calculate my value of the raster at Given location
I have the raster data stored in my database. I want to get that raster data back in my Django and try to find the value at that certain pixel. My code class dataviewView(views.View): def post(self, request): data = json.loads(request.body) name = data['name'] lat = data['lat'] long = data['long'] point = ogr.Geometry(ogr.wkbPoint) point.AddPoint(lat,long) if ndvimodel.objects.filter(name = name).exists(): p1 = ndvimodel.objects.all() for raster_data in p1: rasterdata = raster_data.rast print(type(rasterdata)) But I am unable to get that raster content. How can I solve these issues -
Python3 ModuleNotFoundError: No module named 'drf_yasg'
I found and error when i execute python3 manage.py runserver line 37, in from drf_yasg.utils import swagger_auto_schema ModuleNotFoundError: No module named 'drf_yasg' -
React App gets stuck in Loading component
I downloaded a React Admin Template to learn, i am using Django with django rest framework as a backend technology. I am having trouble showing the backend information in the front-end. I already managed to get the information to be stored in redux but when i ask for the component that renders that information it gets stuck in the "Loading" component. I have a button that redirects to an item detail url: function handleClick(item) { props.history.push(`/apps/sales/enterprises/${item.id}`); Then the "Enterprise" component gets rendered: routes: [ { path: '/apps/sales/enterprises/:enterpriseId', component: lazy(() => import('./enterprise/Enterprise')), }, Function "getEnterprise" is triggered in Enterprise component: useDeepCompareEffect(() => { function updateEnterpriseState() { const { enterpriseId } = routeParams; if (enterpriseId === 'new') { /** * Create New Enterprise data */ dispatch(newEnterprise()); } else { /** * Get Enterprise data */ dispatch(getEnterprise(routeParams)).then((action) => { /** * If the requested enterprise is not exist show message */ if (!action.payload) { setNoEnterprise(true); } }); } } updateEnterpriseState(); }, [dispatch, routeParams]); getEnterprise Axios get request: export const getEnterprise = createAsyncThunk('sales/enterprise', async (params) => { const response = await axios.get( `http://gustavohenry.localhost:8000/api/tenant/sale/enterprise/`, { params } ); const data = await response.data; return data === undefined ? null : data; }); Information is stored … -
Django Session Middleware causing Exceptions
I cannot figure out what is going on here. I have a session that is stored when a user accesses a url like: website.com/client, where the client is the client using the system. This is stored in the session using django.contrib.sessions Here is my middleware declaration: MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', # must be before session middleware 'utils.middleware.routers.ClientDatabaseRouterMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', # custom middleware # 'utils.middleware.CookieMiddleware.CookieMiddleware', # 'utils.middleware.ExtendSession.ExtendSessionMiddleware', 'utils.middleware.UniversalDataMiddleware.UniversalDataMiddleware', 'apps.fort.middleware.LoginRequiredMiddleware', 'utils.middleware.TimezonesMiddleware.TimezonesMiddleware', 'utils.middleware.SessionMiddleware.SessionMiddleware', # maybe rewrite this? 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # 'simple_history.middleware.HistoryRequestMiddleware', # auto adds user who makes change # 'utils.middleware.Profilers.ProfileMiddleware', # anything under this is excluded when decorator @property_not_important is called 'utils.middleware.CheckPropertyMiddleware.ExcludePropertyMiddleware', # allow exclusion 'utils.middleware.CheckPropertyMiddleware.CheckPropertyMiddleware', # 'utils.middleware.ExcludeMiddleware.ExcludeMiddleware', ] It is also in INSTALLED_APPS. My problem is when I git the client url django stores the session, but when I go back to the main site the session lookup causes a 500 error because the sessions are stored in each client DB... how can I fix this? If I manually remove the sessionid session generated by django in my browser, my site loads without 500, so I am not sure how to remove it. -
Django app conflicts with an existing Python module
I have a function that generates a bash script file '.sh' to create a django project and a few apps. This is the bash file I generate: #! /bin/bash cd projectx source projectxenv/Scripts/activate python manage.py startapp app1 python manage.py startapp app2 deactivate When I execute the bash I generated, it gives me the following errors: django.core.management.base.CommandError: 'app1' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name. django.core.management.base.CommandError: 'app2' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name. I don't think app1 and app2 are existing modules, and also, I tried running these commands manually and they work, but when I try ./bash.sh, it doesn't work. -
Django path and routing
My folder structure inside the app: pwa->static->pwa->serviceworker.js and pwa->templates->indexPWA.html How can I refer to the indexPWA.html inside the serviceworker.js? var filesToCache = ["indexPWA.html"] doesn't work, cause it's not the right path, but what is the right one? -
"ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable?" On homebrew
This is a typical problem but I couldn't find any solution in other threads. Here's my setup: MacOS Big Sur -> homebrew -> python3.9 I am running in a virtual environment, I've also manually de~ and activated it several times. I've checked wsgi.py. All requirements are installed properly. Here's what brew says about pythonpath: % brew link --overwrite python@3.9 Warning: Already linked: /usr/local/Cellar/python@3.9/3.9.7_1 To relink, run: brew unlink python@3.9 && brew link python@3.9 Same error again % brew unlink python@3.9 && brew link python@3.9 Unlinking /usr/local/Cellar/python@3.9/3.9.7_1... 24 symlinks removed. Linking /usr/local/Cellar/python@3.9/3.9.7_1... 24 symlinks created. I've tried doing what it suggests and un~ and linking python. Still no luck. That were all I could find on SO. Maybe I'm missing something? Or is there a way to analyze the problem I'm not aware of? -
How to retrieve raster data from postgis database in my Django project and do my calculation
I have the raster data stored in my database. I want to get that raster data back in my Django and try to find the value at that certain pixel. My code enter code hereclass dataviewView(views.View): def post(self, request): data = json.loads(request.body) name = data['name'] lat = data['lat'] long = data['long'] point = ogr.Geometry(ogr.wkbPoint) point.AddPoint(lat,long) if ndvimodel.objects.filter(name = name).exists(): p1 = ndvimodel.objects.all() for raster_data in p1: rasterdata = raster_data.rast print(type(rasterdata))enter code here But I am unable to get that raster content. How can I solve these issues -
django server sometimes doesn't response anything with serving webpacked vue
I have backend(django) and frontend(vue). Vue app is run by node with npm run serve command And this is running with webpack for hot-reload. So I was already done all settings and those settings are working well. But I have one trouble with running app odering. Like I usually run django and node server almost at the sametime, but sometimes django server doesn't get response from vue. ( I could realize that I can access /admin page.) At that time, I usually re-run django server and then everyhing is working well. I want to know what is the problem. -
How to delete a model object only for a one of two users, when both of them are belonged to this model as ManyToOneField?
I just make a web application "Simple Mail". This is just for a practice, it will be like a VEEERY simplified mail service, where you can send letters and receive them too. I'd like to introduce an example with two users of my service(Their names are "Pop" and "Mob"): 1. Pop sends a mail to Mob. 2. After some time, Pop decides to delete this letter, but, of course, it must be deleted only from Pop's list of mails, but not Mob. Or Mob wants to delete this letter from Pop, and just like in above example it must me be deleted only from Mob's mails. How to realize it in my case ? There are necessary files: models.py class Mail(models.Model): from_user = models.ForeignKey( User, related_name="FromUser", on_delete=models.CASCADE, verbose_name="User who sent" ) to_user = models.ForeignKey( User, related_name="ToUser", on_delete=models.SET_NULL, null=True, verbose_name="User who received" ) title = models.CharField(max_length=128, verbose_name="Title") body = models.CharField(max_length=9999, verbose_name="Body") datetime_created = models.DateTimeField(auto_now_add=True) Functions in views.py that have to delete mail from only one(that one who deletes) of two users. @login_required def sent_mail(request, pk): try: mail = Mail.objects.get(id=pk) except ObjectDoesNotExist: return redirect("all-sent-mails") if request.method == "POST": if request.POST.get("Delete"): mail.delete() return redirect("all-sent-mails") form = SendMailForm(instance=mail) context = {"form": form} return render(request, … -
Save to Database when someone updates notes field in html table (django)
I have found many answers to this on SO but my understanding of all of this is still too new to be able to understand how to implement so just posting my exact question: I have a table which is a filtered view of my database that shows up on one page of my app. It has a notes column where each cell uses content-id-editable. I want to add a save button and when someone wishes to save that particular notes section cell I want them to be able to press "save" and have the updated cell post to the database. Here is my views.py: def notes(request): try: if request.method == 'POST': note = request.POST['tm.Notes'] updated_note = TM.Object.save(Notes__=note) return render(request,'homepage/detail.html', {'Notes': updated_note}) else: return render(request,'homepage/detail.html', {}) except TM.DoesNotExist: raise Http404("Info Does Not Exist") Here is my html: <table class= "content-table"> <thead> <tr> <th>Name</th> <th>Distributor</th> <th>State</th> <th>Brand</th> <th>Cell</th> <th>Email</th> <th>Notes</th> </tr> </thead> <tbody> <tr> {% for tm in territory_manager %} <td style="white-space:nowrap;">{{ tm.Name }}</td> <td style="white-space:nowrap;">{{ tm.Distributor }}</td> <td style="white-space:nowrap;">{{ tm.State }}</td> <td style="white-space:nowrap;">{{ tm.Brand }}</td> <td style="white-space:nowrap;">{{ tm.Cell }}</td> <td style="white-space:nowrap;">{{ tm.Email }}</td> <td style="white-space:wrap;" input type="submit" class="primary" value="Submit" ><div contenteditable>{{ tm.Notes }}</div></td> </tr> {% endfor %} </tr> {% else … -
Python2 to Python3 migration causes problem in django-earthdistance package I rely on
File "/opt/folder/api/views.py", line 63, in from django_earthdistance.models import EarthDistance, LlToEarth File "/opt/folder/venv/lib/python3.8/site-packages/django_earthdistance/models.py", line 4, in from django.utils import six ImportError: cannot import name 'six' from 'django.utils' (/ I am finally moving to Python3 from Python2 and I just have about everything wrapped up, but I am getting this error from the dango-earthdistance package which hasn't been updated for a couple of years and apparently doesn't support the latest version of Python3 that I'm using (3.8.9). This lets me calculate distances with lat and lng in Postgres. What's my best option? -
Cannot install Django on Windows because there is an invalid character in a filename
I have been trying to pip install django, but I can’t do it because Windows doesn’t like the invalid filename. Do I have any options other than running a Linux virtual machine? -
Django Validate a Foreign Key Email
I have this profile resource: class ProfileResource(resources.ModelResource): email = fields.Field(attribute='email', widget=CharWidget(), column_name='email') class Meta: model = Profile clean_model_instances = True import_id_fields = ('email',) which validates the email when the profile is created. It works fine but when I use it as a foreign key like: class InvestmentResource(resources.ModelResource): email = fields.Field(attribute='email', widget=ForeignKeyWidget(Profile, field='email'), column_name='email') class Meta: model = Investment clean_model_instances = True import_id_fields = ('id',) It doesn't validate the email anymore. I tried adding two widgets, ForeignKeyWidget and CharWidget for the email on InvestmentResource, but it didn't work. How do I then validate the email inside the InvestmentResource? -
jquery event button showing right response but view is not rendering it correctly in django
I want to show wrong login errors on jquery click.My code is working fine,jquery event(click) button showing response correct too but django views are not rendering the response correctly.In response in inspect element they are showing error as i sending the context but the change do not display on screen. login view def logn(req): if req.user.is_authenticated: return redirect('home') else: context={ 'error_msg':'blah' } if req.method == 'POST': usrname = req.POST['lusername'] psswd = req.POST['lpass'] if len(usrname) == 0 and len(psswd) == 0: print('error') context={ 'error_msg':'password?' } return render(req,'base.html',context) usr = authenticate(req,username=usrname,password=psswd) if usr is not None: login(req,usr) redirect('home') Jquery $('#lbtn').click(function(){ let lusername = $('input[name=lusername]').val(); let lpass = $('input[name=lpassword]').val(); $.ajax({ type: 'POST', url: '/login/', headers :{ 'X-CSRFToken': getcsrfToken(), }, data: { lusername : lusername, lpass : lpass, }, success: (data) => { if(data){ $('input[name=lusername]').val(''); $('input[name=lpassword]').val(''); } }, }) }) HTML <div class='bg'> <span><i class='material-icons tiny left cross'>clear</i></span> <i class='material-icons tiny right spin'>cached</i> {% if error_msg %}<p class='red-text'>{{error_msg}}</p>{%endif%} </div> <div class='white-text log_title'> LOGIN </div> <div class='white-text log_title1'> Please enter your username and password </div> {% if error_msg %} <p class='red-text'>{{ error_msg }}</p>{% endif %} {% csrf_token%} <div class="row"> <div class="input-field col s9"> <p for="lusername" class='white-text log_user'>Username</p> <input name='lusername' type="text" class="validate white-text" id='in1'> </div> </div> … -
New users can't login sessions in Django
I am practicing with a small project in Django that I got through a tutorial, but I have a problem and can't find the solution. I have created a form to register new users, but when I do, the page returns me to the registration form instead of redirecting me to the login page When you tried to enter the data of the new user who is supposed to be 'already registered' to start the session. Receipt in template "Incorrect username or password" However when I try to login with the superuser I created via command line after installing django. This one opens without problems views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import * from django.forms import inlineformset_factory from .forms import OrderForm, CustomerForm, CreateUserForm from .filters import OrderFilter from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required def registerPage(request): if request.user.is_authenticated: return redirect('home') else: if request.method == 'POST': form_value = CreateUserForm(request.POST) if form_value.is_valid(): form_value.save() user = form_value.cleaned_data.get('username') messages.success(request, 'Account was create for {}'.format(user)) return redirect('login') form_value = CreateUserForm context = {'form_key':form_value} return render(request, 'accounts/register.html', context) def loginPage(request): if request.user.is_authenticated: return redirect('home') else: if request.method == 'POST': …