Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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': … -
Order models by a property or custom field in Django Rest Framework
Am having this kind of a Model, and I wanted to order by blog_views property, how best can this be done. This is the model : class Post(TimeStampedModel, models.Model): """Post model.""" title = models.CharField(_('Title'), max_length=100, blank=False, null=False) # TODO: Add image upload. image = models.ImageField(_('Image'), upload_to='blog_images', null=True, max_length=900) body = models.TextField(_('Body'), blank=False) description = models.CharField(_('Description'), max_length=400, blank=True, null=True) slug = models.SlugField(default=uuid.uuid4(), unique=True, max_length=100) owner = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) bookmarks = models.ManyToManyField(User, related_name='bookmarks', default=None, blank=True) address_views = models.ManyToManyField(CustomIPAddress, related_name='address_views', default=None, blank=True) likes = models.ManyToManyField(User, related_name='likes', default=None, blank=True, ) class Meta: ordering = ['-created'] def __str__(self): """ Returns a string representation of the blog post. """ return f'{self.title} {self.owner}' @property def blog_views(self): """Get blog post views.""" return self.address_views.all().count() I read about annotate but couldn't get a clear picture, how can I formulate this in my view. class PostList(generics.ListCreateAPIView): """Blog post lists""" queryset = Post.objects.all() serializer_class = serializers.PostSerializer authentication_classes = (JWTAuthentication,) permission_classes = (PostsProtectOrReadOnly, IsMentorOnly) filter_backends = [filters.SearchFilter, filters.OrderingFilter] search_fields = ['title', 'body', 'tags__name', 'owner__email', 'owner__username' ] I want to filter by a property in the URL -
Django Hosted on Apache: Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state:
I am trying to host a Django app on Apache 2.4. The service won't start and produces the folowing error [Thu Oct 28 13:12:37.898096 2021] [mpm_winnt:notice] [pid 5144:tid 628] AH00418: Parent: Created child process 7828 Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\apache24\\bin\\httpd.exe' sys.base_prefix = 'C:\\Users\\myuser\\AppData\\Local\\Programs\\Python\\Python310' sys.base_exec_prefix = 'C:\\Users\\myuser\\AppData\\Local\\Programs\\Python\\Python310' sys.platlibdir = 'lib' sys.executable = 'C:\\apache24\\bin\\httpd.exe' sys.prefix = 'C:\\Users\\myuser\\AppData\\Local\\Programs\\Python\\Python310' sys.exec_prefix = 'C:\\Users\\myuser\\AppData\\Local\\Programs\\Python\\Python310' sys.path = [ 'C:\\Users\\myuser\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', '.\\DLLs', '.\\lib', 'C:\\apache24\\bin', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00000fa0 (most recent call first): <no Python frame> [Thu Oct 28 13:12:38.413708 2021] [mpm_winnt:crit] [pid 5144:tid 628] AH00419: master_main: create child process failed. Exiting. The server ran before I did all the configurations and went to the "it worked" screen. I think it has to do with either my httpd-host conf <Directory /some/path/project> Require all granted </Directory> <VirtualHost *:80> ServerName localhost WSGIPassAuthorization On ErrorLog "C:/Users/myuser/Desktop/app.error.log" CustomLog "C:/Users/myuser/Desktop/app.access.log" combined WSGIScriptAlias / "C:/Users/myuser/Desktop/app/wsgi_windows.py" <Directory "C:/Users/myuser/Desktop/app/EmployeeKiosk"> <Files wsgi_windows.py> Require all granted </Files> </Directory> Alias … -
django many to one relationships
In the django document https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_one/, there are two tables, Report and Article, class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): return self.headline class Meta: ordering = ['headline'] My question, if you have a list of Reports, how would you get their articles? I've tried articles = [] for report in reports: article = Article.objects.filter(report = report) articles.append(article ) but this does not give me all my data. -
I'm building a website where users can download digit assets and I wanna know if anyone can throw some light to speed up the load time in Django
Hello guys please I would really appreciate it if someone could help me out with this website problem I am building a website where users can download digital assets from using Django, for example download website templates, graphics templates and all that. But now the issue is that when it's already hosted it takes a whole lot of time loading up because I think the files are slowing down the website and I don't really know the perfect way to fix this because I'm still kind of a beginner in Django and any help will be really appreciated. -
Django Form so many fields
I have a Django page using bootstrap and crispy forms that present a form. but the form is growing so much now that I probably have around 50 fields :( which are all within 1 massive HTML page. I'm pretty sure this is the wrong way to do it. Is it possible to split the forms into say 5 pages, but still have a submit button to post all of the fields to the database? For now, what I have done is to create tabs for each section of the giant form so it's easy than scrolling. I'm thinking it's probably better to create different views for each section and then link the data somehow back using an IndexKey or something? But i have no idea how i would configure the button to capture all the fields. I know this is a rubbish question, but I don't really know what to search for? Cheers