Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migration from 3.1 to 3.2 error while copying models instances
I'm trying to upgrade Django from 3.1 to 3.2, and one of the error that I encountered was endpoints that I have that duplicate resources and their related models. In this example: @action( detail=True, methods=['POST'], name='Duplicate one resource', url_name='duplicate', url_path='duplicate', ) @transaction.atomic def duplicate(self, request, pk=None): foo = self.get_object() # gets foo foo_bars = foo.foo_bars.all() # gets a queryset of FooBar new_name = self.append_copy_suffix(foo.name) new_foo = foo.copy_instance(name=new_name) # code below print(foo, new_foo) FooBar.objects.bulk_create( [FooBar(foo=new_foo, bar=foo_bar.bar, stuff=foo_bar.stuff) for foo_bar in foo_bars] ) return Response(self.get_serializer(new_foo).data, status=status.HTTP_201_CREATED) def copy_instance(self, **kwargs): """ Method to copy a model instance More info here: https://docs.djangoproject.com/en/3.1/topics/db/queries/#copying-model-instances :param kwargs: additional parameters to update :return: the duplicated resource """ new_resource = self new_resource.pk = None for k, v in kwargs.items(): setattr(new_resource, k, v) new_resource._state.adding = True new_resource.save() return new_resource This works pretty well in Django 3.1, but in Django 3.2, the related resources are not created for some reason. Things that I noticed in debug and printing the values: When I print the foo and new_foo, they are the same one (new_foo). foo_bars is empty. Maybe because the foo and new_foo are the same one before the bulk_create and the foo_bars is just a queryset that was yet to be … -
ModuleNotFoundError: No module named 'django_invoice'
I get this error every time I try to do migrations or even run my py manage.py runserver. I installed the 'django_invoice' module, inserted it in INSTALLED_APP but still I get the same error over and over again. I installed the requested module hoping that the problem would be fixed but unfortunately it wasn't. -
Can I define an Alias to a foreign field in Django?
I'm looking to define an alias to a foreign key related set so that it can then be used in a generic filtering function. To explain with a little more detail here is a simplified example of my use case demonstrating what I'm trying to achieve: models.py from django.db import models class Family(models.Model): family_name = models.CharField(max_length=100) pets: models.Manager['Pet'] = ... members: models.Manager['Person'] = ... def __str__(self): return f'{self.id} - {self.family_name}' class Pet(models.Model): class PetType(models.TextChoices): CAT = 'cat' DOG = 'dog' LIZARD = 'lizard' name = models.CharField(max_length=100) type = models.CharField(max_length=100, choices=PetType) family = models.ForeignKey(Family, on_delete=models.CASCADE, related_name='pets') def __str__(self): return f'{self.id} - {self.name} {self.family.family_name} [{self.type}]' class Person(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() family = models.ForeignKey(Family, on_delete=models.CASCADE, related_name='members') @property def pets(self) -> models.Manager[Pet]: return self.family.pets def __str__(self): return f'{self.id} - {self.name} {self.family.family_name}' If I have a Person entity, I can use it's pets property to get the pets from the family, what I'm looking for is a way to add an alias/annotation/whatever to a queryset of Person so that I can define: def has_a_cat(query_set): return query_set.filter(pets__type='cat') and then be able to use that for both Family and Person query sets. I know I can filter a Person queryset by the pet type … -
Django-filter with django-table
I've been stuck on this problem for a couple of weeks and can't seem to resolve it through self research. Scenario for testing: I have a 4 learners who are registered against different groups. Using tables2 I've created class GroupListView(SingleTableView), selecting the group takes me to class GroupDetailView(SingleTableView, FilterView). This should show a qs of LearnerInstances associated with that learner. However, when applying the f.qs to the learner queryset it shows all 4 learners on the detail page. views.py class GroupDetailView(SingleTableView, FilterView): table_class = LearnerGroupTable model = LearnerInstance template_name = "learner/group_detail.html" filterset_class = LearnerAimFilter # get all learners within the selected group def get_queryset(self): qs = super().get_queryset() qs = qs.filter( learner__group__slug=self.kwargs["slug"], ) return qs # a queryset of learners within the group from model learnerinstance def get_context_data(self, **kwargs): context = super(GroupDetailView, self).get_context_data(**kwargs) learners = self.get_queryset() context["learners_qs"] = learners f = LearnerAimFilter(self.request.GET, queryset=learners) learners = f.qs context["filter"] = f context["table"] = LearnerGroupTable(learners) context["learners"] = learners context["group"] = Group.objects.filter(slug=self.kwargs["slug"]).values() context["group_name"] = Group.objects.filter(slug=self.kwargs["slug"]).values( "short_name" ) return context If I # out the learners = f.qs the detail view shows the correct learner instances but does not filter. As soon as I undo the # it then shows all four learners but the filter … -
How to display users who are only included in the Group in django admin panel
I have an Author simple models in my Django project as below: class Author(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, default=None) def __str__(self): return self.user.username note: CustomUser is django's default User model which I added with a phone number In the Group models (in Django admin panel), I have created 'Author' group, to separate or differentiate ordinary users or authors. I want when I enter a new author name in the Author model, the only names that appear are those that belong to the 'Author' group. -
React Vite: npm run dev and npm run preview work but build shows TypeError on Render platform
I have a Django REST Framework (backend) + Postgresql + Vite React (frontend) Project which is working fine in local when I run the npm run dev command. Here is my package.json file: { "name": "frontend", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "vite build", "lint": "eslint .", "preview": "vite preview" }, "engines" : { "node" : ">=21.6.2 <22.0.0" }, "dependencies": { "@ant-design/icons": "^5.5.1", "@emotion/react": "^11.13.3", "@emotion/styled": "^11.13.0", "@mui/material": "^6.1.0", "@reduxjs/toolkit": "^2.2.7", "axios": "^1.7.7", "dotenv": "^16.4.7", "leaflet": "^1.9.4", "react": "^18.3.1", "react-dom": "^18.3.1", "react-leaflet": "^4.2.1", "react-paginate": "^8.2.0", "react-redux": "^9.1.2", "react-router-dom": "^6.26.1", "react-router-redux": "^4.0.8", "react-social-icons": "^6.18.0", "redux": "^5.0.1", "styled-components": "^6.1.13" }, "devDependencies": { "@eslint/js": "^9.9.0", "@types/leaflet": "^1.9.16", "@types/react": "^18.3.3", "@types/react-dom": "^18.3.0", "@vitejs/plugin-react": "^4.3.1", "eslint": "^9.9.0", "eslint-plugin-react": "^7.35.0", "eslint-plugin-react-hooks": "^5.1.0-rc.0", "eslint-plugin-react-refresh": "^0.4.9", "globals": "^15.9.0", "vite": "^5.4.14" } } My vite.config.js file below: import { defineConfig, loadEnv } from 'vite' import react from '@vitejs/plugin-react' import dotenv from 'dotenv' dotenv.config() // https://vitejs.dev/config/ export default defineConfig(({ mode }) => { const env = loadEnv(mode, process.cwd()); const isDevelopment = mode === 'development' const baseURL = isDevelopment ? env.VITE_API_BASE_URL_LOCAL : env.VITE_API_BASE_URL_DEPLOY console.log("baseURL") console.log(baseURL) return { plugins: [react()], server: { proxy: { '/api': { target: baseURL, changeOrigin: true, }, }, }, } }) I deployed … -
Why is this image upload test failing?
I am trying to test an ImageField file upload. The test returns AssertionError: 400 != 200, but when I upload the same image manually it works as expected. def test_profile_pic_upload_png(self): self.register_user() self.login_user() with open("./test_files/test.png") as f: response = self.client.post("/upload_profile_pic/", {'profile_pic': f}, **{'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}, content_type="multipart") self.assertEqual(response.status_code, 200) The view: @login_required def upload_profile_pic(request): if not request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' or not request.method == "POST": return HttpResponseNotAllowed(["POST"]) if not "profile_pic" in request.FILES: return JsonResponse({ "profile_pic": "No image selected." } , status=400) if not is_valid_image(request.FILES["profile_pic"]): ## Checks the MIME type with `magic` return JsonResponse({ "profile_pic": "Please select a valid image." } , status=400) if request.FILES["profile_pic"].size > 512000: return JsonResponse({ "profile_pic": "Filesize too large." } , status=400) form = UploadProfilePicForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): form.save() return JsonResponse({ "success": "Profile picture has been saved." }) else: return JsonResponse(dict(form.errors.items()), status=400) -
AttributeError: 'SimpleLazyObject' object has no attribute 'match'
I have a Django 3.2 application running with gunicorn 23 on Python 3.9. The app is in docker container with all other dependencies installed in virtualenv. I am getting this error: Traceback (most recent call last): File "/app/web/.venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/web/.venv/lib/python3.9/site-packages/sentry_sdk/integrations/django/middleware.py", line 175, in __call__ return f(*args, **kwargs) File "/app/web/.venv/lib/python3.9/site-packages/django/utils/deprecation.py", line 116, in __call__ response = self.process_request(request) File "/app/web/.venv/lib/python3.9/site-packages/django/middleware/locale.py", line 21, in process_request language = translation.get_language_from_request(request, check_path=i18n_patterns_used) File "/app/web/.venv/lib/python3.9/site-packages/django/utils/translation/__init__.py", line 291, in get_language_from_request return _trans.get_language_from_request(request, check_path) File "/app/web/.venv/lib/python3.9/site-packages/django/utils/translation/trans_real.py", line 531, in get_language_from_request lang_code = get_language_from_path(request.path_info) File "/app/web/.venv/lib/python3.9/site-packages/django/utils/translation/trans_real.py", line 510, in get_language_from_path regex_match = language_code_prefix_re.match(path) AttributeError: 'SimpleLazyObject' object has no attribute 'match' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/web/.venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/web/.venv/lib/python3.9/site-packages/sentry_sdk/integrations/django/middleware.py", line 175, in __call__ return f(*args, **kwargs) File "/app/web/.venv/lib/python3.9/site-packages/django/utils/deprecation.py", line 117, in __call__ response = response or self.get_response(request) File "/app/web/.venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 49, in inner response = response_for_exception(request, exc) File "/app/web/.venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/app/web/.venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 153, in handle_uncaught_exception return callback(request) File "/app/web/.venv/lib/python3.9/site-packages/django/utils/decorators.py", line 126, in _wrapped_view result = middleware.process_view(request, view_func, args, kwargs) File "/app/web/.venv/lib/python3.9/site-packages/django/middleware/csrf.py", line 269, in process_view good_referer = request.get_host() … -
How to paginate ckeditor content in django?
I have ckeditor content as book content. I want to show the content in a fixed width and height container. Instead of scroll. there will be option to navigate pages. Next button and previous button for navigate pages. from django.db import models from django_ckeditor_5.fields import CKEditor5Field class Book(models.Model): title = models.CharField(max_length=255) slug = AutoSlugField(populate_from='title') description = models.TextField() content = CKEditor5Field(config_name="extends") At first I have tried this feature with the default models.TextField(). By counting the words I have splited as pages in javaScript. It was ok but for more text formatting I have to use ckeditor and the ckeditor saves content as html so I can't figure out how I will split the page. Because If I want to split with the previous approch it's possible to miss starting or ending tag in a page. I am using django-ckeditor-5 -
cleaned_data returns old value if submitted field is empty
I'm trying to validate an image upload form. I want to check if the submitted field is empty or not, but when it is, cleaned_data returns the currently stored value. class UploadProfilePicForm(ModelForm): class Meta: model = User fields = ( "profile_pic", ) def clean_profile_pic(self): # if not self.cleaned_data.get("profile_pic"): # self._update_errors(ValidationError({ "profile_pic": "No image selected." })) # The following returns the submitted filename when a file is selected, # but the currently stored filepath/filename when no file is selected: self._update_errors(ValidationError({ "profile_pic": self.cleaned_data.get("profile_pic") })) -
The code works on my network, but not on the university's network
I have a Django server with DRF and custom JWT cookies through middleware. The frontend is built in Next.js and consumes the server routes as an API. Everything works on my machine and network, as well as on some friends' machines who are involved in the project, with the cookies being created and saved correctly. The problem is that this doesn't happen on the university's network, even though it's the same machine (my laptop) and the same browser. At the university, the cookies are not saved, and the error "Cookie 'access_token' has been rejected because it is foreign and does not have the 'Partitioned' attribute" appears. Both codes are on GitHub, and the only thing hosted in the cloud is the database. I am aware of the cookie creation and saving configurations, as well as the CORS policies. I can't figure out where I'm going wrong... Can anyone help me? I can provide the links if possible! Thanks in advance! -
Django testing: find link in email message
I'm trying to test email activation and password reset. How do I filter the email body down to a usable link? def test_activation(self): self.register_user() mail.outbox[0].body.find_the_link() # Find the link here response = self.client.get(link) self.assertEqual(response.status_code, 200) -
Sending data to a form using data from previous GET request
I have a dictionary app where users can view the words (Lemma) filtered by their first letter. I would like for users to be able to then filter those results according to combinations of part of speech (each Lemma has exactly one part of speech) or tags (each Lemma can have 0 to many tags); e.g., select only Lemma that are nouns or verbs or are tagged as agricultural vocabulary. I currently have two forms, one for selecting the first letter and one for selecting the part of speech/tag (the facets). class LemmaInitialLetterForm(forms.Form): LETTERS = [ ... ] initial = forms.ChoiceField( widget=forms.RadioSelect( attrs={"class": "lem_init"} ), choices=LETTERS ) class FacetSideBarForm(forms.Form): poss = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, label='Parts of speech', choices=list() ) tags = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, label='Tags', choices=list() ) def __init__(self, poss=None, tag_list=None, *args, **kwargs): super(FacetSideBarForm, self).__init__(*args, **kwargs) if poss: self.fields['poss'].choices = [ (pos, pos) for pos in poss ] if tag_list: self.fields['tags'].choices = [ (tag, tag) for tag in tag_list ] I've been able to display a list of Lemma filtered by first letter with the following view: class LemmaListView(generic.FormView): template_name = "emedict/lemma_home.html" lemmalist = None def get(self, request, *args, **kwargs): form = LemmaInitialLetterForm(self.request.GET or None) if form.is_valid(): initial = request.GET["initial"] … -
Django Simple JWT + Axios, always getting 401. How can I fix this?
I’m using Nuxt and a pinia store to store the token (the token is present in the store). I've created a plugin for Axios as follows: import axios from "axios"; export default defineNuxtPlugin((NuxtApp) => { axios.defaults.baseURL = "http://127.0.0.1:8000/api/"; axios.defaults.withCredentials = false; axios.defaults.proxyHeaders = false; if (process.client) { let token = window.localStorage.getItem("authTokens"); if (token) { token = JSON.parse(token); console.log(token.access); axios.defaults.headers.common["Authorization"] = `Bearer ${token.access}`; } } return { provide: { axios: axios, }, }; }); The endpoint in Django REST Framework is defined like this: class CreateEvent(CreateAPIView): permission_classes = [IsAuthenticated] serializer_class = CreateEventSerializer def post(self, request, *args, **kwargs): data = request.data.copy() z = request.META.get('HTTP_AUTHORIZATION') data['creator'] = request.user print(request.user, '--------------------') data['types'] = get_type_by_int(request.data.get('type', None)) serializer = self.get_serializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The method I use to call this endpoint is as follows: async sendEvent(): Promise<void> { try { const { $axios } = useNuxtApp(); const response = await $axios.post("event/create/", { latitiude: this.latitiude, longitude: this.longitude, description: this.description, type: this.type, }); console.log("Event sent:", response.data); } catch (error) { console.error("Error while sending event"); } } No matter what I do, I keep receiving a 401 error with the message: Authentication credentials were not provided. However, the z = request.META.get('HTTP_AUTHORIZATION') line contains … -
Importing model classes from other apps in Django with cicular import Problem
Hi i Need to import a model into another app models that will raise the cicular import Error so i use the django.app like this : from django.apps import apps Order = apps.get_model(app_label="orders", model_name='Order') its raise AppRegistryNotReady Error : File "C:\Users\Pourya\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\Pourya\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\core\management\commands\runserver.py", line 126, in inner_run autoreload.raise_last_exception() File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Pourya\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\Pourya\Desktop\fapo\shop\models.py", line 17, in <module> Order = apps.get_model(app_label="orders", model_name='Order') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\apps\registry.py", line 201, in get_model self.check_models_ready() File "C:\Users\Pourya\Desktop\fapo\.venv\Lib\site-packages\django\apps\registry.py", line 143, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models … -
Django: No tables found in the database after running migrations
I'm working on a Django project, but I'm facing an issue where no tables are being created in my database even after running migrations. Django version:5.1.3 Database:MySQL OS:ubuntu 24.04.1 LTS 1 I ran python manage.py makemigrations, and it successfully generated migration files 2 I ran python manage.py migrate, and it executed without any errors. 3 However, when I check the database in phpmyadmin, No tables found in database. I also tried these troubleshooting steps: 1 Verified that the database file exists. 2 Ensured that the INSTALLED_APPS list includes my app. 3 Checked that the models are defined properly in the models.py file. 4 Looked for migration history with python manage.py showmigrations, and all migrations are marked as applied. What could be causing this issue? Are there any additional steps I can take to debug or resolve this problem? I’d appreciate any guidance or suggestions. Let me know if more information is needed. -
How do i find "Average Word Count of Comments for Each Blog"?
This is my models: from django.db import models from django.conf import settings from django.utils import timezone class Blog(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return f"{self.title}" class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='comments') blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name='comments') comment = models.TextField() published_date = models.DateTimeField(default=timezone.now) def __str__(self): return f"{self.comment}" I tried annotate() using Blog.objects.annotate(avg_comment_length = Avg(Length(comments__comment))) but Length() gets the total characters in a comment, not word count. How can I modify this to calculate the average word count of comments for each blog? -
Error deploying django/python app to Heroku - 'Error with requirements to build wheel'
I am trying to deploy my Django app to Heroku. I get the following error output: Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'error' error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [24 lines of output] Traceback (most recent call last): File "/app/.heroku/python/lib/python3.13/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in <module> main() ~~~~^^ File "/app/.heroku/python/lib/python3.13/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) ~~~~^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.heroku/python/lib/python3.13/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheel return hook(config_settings) File "/tmp/pip-build-env-zgoqdfmt/overlay/lib/python3.13/site-packages/setuptools/build_meta.py", line 334, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=[]) ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/tmp/pip-build-env-zgoqdfmt/overlay/lib/python3.13/site-packages/setuptools/build_meta.py", line 304, in _get_build_requires self.run_setup() ~~~~~~~~~~~~~~^^ File "/tmp/pip-build-env-zgoqdfmt/overlay/lib/python3.13/site-packages/setuptools/build_meta.py", line 522, in run_setup super().run_setup(setup_script=setup_script) ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/tmp/pip-build-env-zgoqdfmt/overlay/lib/python3.13/site-packages/setuptools/build_meta.py", line 320, in run_setup exec(code, locals()) ~~~~^^^^^^^^^^^^^^^^ File "<string>", line 29, in <module> File "<string>", line 26, in get_version KeyError: '__version__' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. ! Error: Unable … -
AttributeError with User in django application
I am making an app for a clinic. I am in the finance section of my app. I want to make an income through an appointment. When I went to test this endpoint in postman, I get the following error: AttributeError: Got AttributeError when attempting to get a value for field user on serializer UserInfoSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'user'. I am sending you my files so that you can help me as I have had this error for a couple of days without being able to solve it. userinfo/models.py from django.db import models from django.contrib.auth.models import User class UserInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="userInfo") address = models.CharField(max_length=255, blank=True, null=True) phone = models.CharField(max_length=15, blank=True, null=True) fecha_nacimiento = models.DateField(blank=True, null=True) dni = models.CharField(max_length=10, blank=True, null=True) postal_code = models.CharField(max_length=6, blank=True, null=True) city = models.CharField(max_length=200, blank=True, null=True) country = models.CharField(max_length=100, blank=True, null=True) segundo_apellido = models.CharField(max_length=200, blank=True) def __str__(self): return f"Información de {self.user.username}"` My finanzas/models.py: from django.db import models from citas.models import Citas from userinfo.models import UserInfo class Transaccion(models.Model): INGRESO = 'INGRESO' GASTO = 'GASTO' INGRESO_COTIZADO = 'INGRESO_COTIZADO' TIPO_CHOICES = [ … -
getting started with grpc django throws import error
Sure! Here’s your question formatted according to Stack Overflow standards: Title: gRPC Python Import Error for Generated hello_pb2.py and hello_pb2_grpc.py Files Question: I have a hello.proto file on the server side. On the client side, I ran the following protoc command to generate the necessary Python files: python3 -m grpc_tools.protoc -I. -Iproto-lib/src/main/proto -Iproto-lib/src/main/proto/common --python_out=./publons/scholarly_person_master_service --grpc_python_out=./app proto-lib/src/main/proto/hello.proto This command created two files on the client side: hello_pb2.py hello_pb2_grpc.py I then created a Python script on the client side to use these files and set up a gRPC server. The code looks as follows: import grpc from concurrent import futures from scholarly_person_master_service.sp_master_ri_proto_lib.src.main.proto.hello_pb2 import HelloReply, HelloRequest from scholarly_person_master_service.sp_master_ri_proto_lib.src.main.proto.hello_pb2_grpc import SimpleServicer, add_SimpleServicer_to_server # Implementing the service class SimpleService(SimpleServicer): def SayHello(self, request, context): # This method handles the gRPC call and returns a response response = HelloReply(message=f"Hello, {request.name}!") return response # Running the gRPC server def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) add_SimpleServicer_to_server(SimpleService(), server) # Registering the service server.add_insecure_port('[::]:50051') server.start() print("Server started on port 50051") server.wait_for_termination() if __name__ == '__main__': serve() However, when I try to run the server, I encounter an error related to the imports (HelloRequest and HelloReply), even though other imports in the script are working fine. hello_pb2.py File The hello_pb2.py file looks like … -
Django 4 Everybody: 405 Error, Auto-grader assignment Ad List #1
I'm following the DJ4E coursera course and I am on the 5th module auto-grader assignment: Ad List #1 When I run the auto-grader everything passes except the last test and I get this error: Logging out... Loading URL: https://loupy316.pythonanywhere.com/logout/?next=/ads/ (Open URL) Could not find HTML The current node list is empty. Here is my html: {% extends 'base_bootstrap.html' %} {% load app_tags %} <!-- see home/templatetags/app_tags.py and dj4e-samples/settings.py --> {% block navbar %} <nav class="navbar navbar-expand-lg navbar-dark bg-dark" style="border-radius:10px !important"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'home:home' %}">LP's Site</a> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> {% url 'home:home' as home_url %} <a class="nav-link {% if request.get_full_path == home_url %}active{% endif %}" href="{% url 'home:home' %}">Home</a> {% url 'ads:all' as ads_url %} <li {% if request.get_full_path == ads_url %}class="active"{% endif %}> <a class="nav-link" href="{% url 'ads:all' %}" role="button">Ads</a> </li> </ul> <ul class="navbar-nav"> {% if user.is_authenticated %} <li> <a class="nav-link" href="{% url 'ads:ad_create' %}">Create Ad</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="rightnavDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> <img style="width: 35px; height: 35px; border-radius: 50%; object-fit: cover;" src="{{ user|gravatar:60 }}"/><b class="caret"></b> </a> <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="rightnavDropdown"> <li> <form method="post" action="/admin/logout/?next={% url 'ads:all' %}"> {% csrf_token %} <button type="submit" class="dropdown-item">Logout</button> </form> </li> </ul> </li> {% … -
Django 5.1 UserCreationForm won't allow empty passwords
I am upgrading a Django 3.0 app to 5.1 and have been moving slowly through each minor release. So far so good. However, once I upgraded from Django 5.0 to 5.1, I saw changed behavior on my "Create New User" page, which used to allow empty passwords, with a random password being generated if none is supplied. Now, I can no longer submit an empty password. I get a "required field" error on both the password fields, even though the fields are both explicitly set as required=False. I know there were some changes (5.1.0, 5.1.1) to the UserCreationForm class in Django 5.1. I tried using AdminUserCreationForm instead of UserCreationForm and setting the usable_password field to None, but it still won't allow empty passwords like before. Any ideas? Environment Python 3.12.8 Django 5.1.5 Simplified Code class SignupForm(AdminUserCreationForm): # previously using UserCreationForm usable_password = None # Newly added # Form fields sharedaccountflag = forms.ChoiceField( label='Cuenta compartida', required=True, choices=BOOLEAN_CHOICES ) # Constructor def __init__(self, *args, **kwargs): # Call base class constructor (i.e. SignupForm) super(SignupForm, self).__init__(*args, **kwargs) # Set password fields as optional self.fields['password1'].required=False self.fields['password2'].required=False # Set form helper properties self.helper = FormHelper() setFormHelper(self.helper) # set form method (POST / GET) and styling self.helper.form_tag … -
Using sessions in post requests django
I am currently trying to code my first website. I have a post request taking in answers from a form. I then try to save this information into the session and this doesn’t seem possible. Even when just editing the session data inside the request it doesn’t seem possible and I also can’t print to debug, this could be a stupid question as I am very inexperienced but I cannot find any solution or a reason why? -
Saving "last seen" time doesn't work beyond a few seconds
Based on this question I added the following middleware to track users' last seen date: from datetime import datetime, timedelta from dateutil.parser import parse from .models import User class LastSeenMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): last_seen = request.session.get("last-seen") now = datetime.now() too_old_time = now - timedelta(seconds=60) if not last_seen or parse(last_seen) < too_old_time: if request.user.is_authenticated: User.objects.filter(id=request.user.id).update(last_seen=now) request.session["last-seen"] = now.isoformat() return self.get_response(request) This works when I set the timedelta to only a few seconds, but anything more and it stops updating the field. Am I missing something obvious? -
Setting up Django in a subdirectory
I am trying to set up Django in a subdirectory (running under Apache2 through wsgi), but Django stops recognizing the static URLs. This is an example url, that gives me a 404: https:/<domain>/<subdirectory>/<appname>/en/static//img/favicon.png This should map to the filesystem here: /<projectpath>/<appname>/static/<appname>/img/favicon.png The development server (without a subdirectory) finds the file in the filesystem here: /<appname>/static/<appname>/img/favicon.png How do I setup django to recognize it's not running at / but at /<subdomain>/?