Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a slug from non-English values?
I have the model Author with fields firstname, lastname. I wanna add another field 'slug' that will contain a slug of a concatenation of the fields. However, these fields contain non-English chars and I need an English slug to create the link template "localhost/authors/str::slug" How can I implement it? -
How to use force_update in Django?
a = Article(title="New Article", slug="new-article") a.save() print a OUTPUT New Article How I update only title using force_update. -
Django is not rendering the Images in Development
I started learning Django recently and I am also new to Web development. I am facing an issue with Django not loading images but loading CSS and JS files. I have done the setup as shown in Django documentation and also referred to many youtube videos. My setup is almost the same. But still images are not loading. Below is the Pip freeze of my virtual environment (venv) PS E:\django\myproject> pip freeze asgiref==3.4.1 Django==3.2.8 pytz==2021.3 sqlparse==0.4.2 Below is my Settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'products/static'), ] HTML {%for product in products %} <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{% static 'products/images/flour.png' %}" alt="No Image"> <div class="card-body"> <h5 class="card-title">{{product.product_name}}</h5> <p class="card-text">{{product.product_description | default:"Nothing"}}</p> <a href="/products/{{product.id}}" class="btn btn-primary">Update</a> </div> </div> {%endfor%} Folder Structure myproject - settings.py - urls.py products - static - Products - images - flour.jpg - templates - models.py - urls.py - views.py Please let me know if anything more required Thanks in advance -
Django get_model() model has no attribute 'objects'
im writing a migration to update the data, i used get_model() like the docs describe to get the model class like so: from django.db import migrations def update_student(apps, schema_editor): # We can't import the model directly as it may be a newer # version than this migration expects. We use the historical version. CourseClass = apps.get_model('backend', 'CourseClass') from pprint import pprint pprint(vars(CourseClass)) for course_class in CourseClass.objects.all(): if course_class.course: if course_class.course.student: course_class.students.add(course_class.course.student) Course = apps.get_model('backend', 'Course') for course in Course.objects.all(): if course.student: course.students.add(course.student) class Migration(migrations.Migration): dependencies = [ ('backend', '0199_auto_20211027_1026'), ] operations = [ migrations.RunPython(update_student, migrations.RunPython.noop) ] And here is my model with some custom manager: class CourseClass(models.Model): class Meta: db_table = 'classes' verbose_name = _('Class') verbose_name_plural = _('Classes') student_manager = StudentManager() teacher_manager = TeacherManager() objects = models.Manager() # other fields When running my migration i got the following error: File "/Users/admin/Library/Caches/pypoetry/virtualenvs/base.django-AnqsdXoZ-py3.8/lib/python3.8/site-packages/django/db/migrations/operations/special.py", line 190, in database_forwards self.code(from_state.apps, schema_editor) File "/Users/admin/Documents/git/icts/vietphil.hoola/backend/migrations/0200_update_student.py", line 13, in update_student for course_class in CourseClass.objects.all(): AttributeError: type object 'CourseClass' has no attribute 'objects Printing out attributes of CourseClass using pprint return the following: mappingproxy({'DoesNotExist': <class '__fake__.CourseClass.DoesNotExist'>, 'MultipleObjectsReturned': <class '__fake__.CourseClass.MultipleObjectsReturned'>, '__doc__': 'CourseClass(id, name, date, time, duration, course, ' 'substitute_teacher, delay_from, status, over, ' 'class_type, canceled_by, note, teacher, ' 'datetimestart, … -
Django - inlineformset create view NOT NULL constraint failed
I have a CreateView with an inline formset that has a forecast_month & forecast_cost for each month of the year, I want it to save all 12 forecasts for each month but I keep getting this error. Ideally it should save 12 Forecast's one for each month with the selected project as the foreign key for each. Error: NOT NULL constraint failed: forecasting_forecast.forecast_cost (I have deleted & rerun migration multiple times) Models.py class Forecast(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) forecast_month = models.CharField(verbose_name="Month", max_length=200) forecast_cost = models.DecimalField(verbose_name="Forecast", decimal_places=0, max_digits=11) Views.py class ForecastCreateView(LoginRequiredMixin, CreateView): model = Forecast fields = ["project"] login_url = "/login/" success_url = '' def get_context_data(self, **kwargs): financialYears = ["July", "August", "September", "October", "November", "December", "January", "February", "March", "April", "May", "June"] initial = [{'forecast_month': forecast} for forecast in financialYears] ForecastChildFormset = inlineformset_factory( Project, Forecast, fields=('project', 'forecast_month', 'forecast_cost'), can_delete=False, extra=len(financialYears), widgets={'forecast_month': forms.Select(attrs={'disabled': True})}, ) data = super().get_context_data(**kwargs) if self.request.POST: data['forecast'] = ForecastChildFormset(self.request.POST, initial=initial) else: data['forecast'] = ForecastChildFormset(initial=initial) return data def form_valid(self, form): context = self.get_context_data() forecast = context["forecast"] form.instance.creator = self.request.user if forecast.is_valid(): self.object = form.save() forecast.instance = self.object forecast.save() else: return self.form_invalid(form) return super(ForecastCreateView, self).form_valid(form) -
How to get the names from a tuple list
I currently have a list of Names in a tuple list and when they are displayed on my form, they are displayed like so: ('Name1','Name1'), ('Name2','Name2'), ('Name3','Name3'), Which is exactly how they are shown in the code. How would I get them to display like so: Name1 Name2 Name3 My code currently looks like so Views.py def customerDetails(request): model = complex_list content = {'model': model} return render(request, 'main/customerDetails.html', content) template.html <form> <<select name="Complex"> {% for x in model %} <<option value="{{ x }}">{{ x }}</option> {% endfor %} </select>> Complex </form> -
Accessing self reference object in property/method Django
I have a user model class Account(AbstractBaseUser): first_name = models.CharField(max_length = 255, unique = False) last_name = models.CharField(max_length = 255, unique = False) email = models.EmailField(verbose_name = "email", max_length = 60, unique = True) is_sponsor = models.BooleanField(blank=True, default=True, help_text='Check if the user is a sponsor', verbose_name='Is this user a sponsor?') sponsored_by = models.ForeignKey('self',blank=True,null=True, on_delete=models.SET_NULL, default=None,limit_choices_to={'is_sponsor': True}), is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [ 'first_name', 'last_name', ] I have made a property for which I need to make use of 'sponsored_by' @property def sponsored_by_test(self): if self.sponsored_by is not None: if self.sponsored_by.first_name=="test": return True return False When I test it, x = Account.objects.get(first_name="test") print(x.sponsored_by) >> (<django.db.models.fields.related.ForeignKey>,) Hence I cannot access the 'sponsored_by' variable in the property (or anywhere). Am I missing something here? -
Why does an exception occur when I pop validated_data in DRF?
I am performing the creation using DRF's ModelSerializer. In the current model, there is a foreign key called description_type. So, when I receive a request, I receive it as a string in the field called description_type_code, pop the description_type_code in the validated_data of the create() method of the serializer, and use this description_type_code to get the corresponding description_type model. However, performing this task causes the following errors. Got AttributeError when attempting to get a value for field `description_type_code` on serializer `PostSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Post` instance. Original exception text was: 'Post' object has no attribute 'description_type_code'. What's wrong with my code? Here's my code. models.py class Post(models.Model): ... description_type = models.ForeignKey(DescriptionType, models.DO_NOTHING, db_column='description_type') ... serializers.py class PostSerializer(serializers.ModelSerializer): description_type_code = serializers.CharField() class Meta: model = Post fields = ('title', 'description', 'description_type_code') def create(self, validated_data): description_type_code = validated_data.pop('description_type_code') description_type = DescriptionType.objects.get(name=description_type_code) post = Post.objects.create(**validated_data, description_type=description_type) return post -
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