Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Drf view AttributeError
I'm trying to get data that is related to the request.user but i'm doing something wrong. serializers.py class SchoolSerializerList(serializers.ModelSerializer): class Meta: model = School fields = ('name', 'zone', 'city', 'subCity', 'abbr', 'woreda', 'Schooltype', 'schoolemail', 'schoolphone', 'created_date') views.py class MySchoolsView(generics.ListAPIView): permission_classes = [IsSchoolOwner, ] serializer_class = SchoolSerializerList def get_queryset(request): try: queryset = School.objects.filter(owner=request.user) except ObjectDoesNotExist: return Response({"error": "Nothing found."}) return queryset the owner field in the school model is a foreignkey to the user i wanted to check if the current user has any schools by trying to match request.user with School.owner but this returns an attribute error saying 'MySchoolsView' object has no attribute 'user' -
How to use limit and order_by together in Django rest-framework?
I want to use limit on following as [1:10] data = GroupPostsModel.objects.filter( group_id=group_id) & GroupPostsModel.objects.filter(post_type=post_type).order_by('-time_stamp') I try this data = GroupPostsModel.objects.filter( group_id=group_id & GroupPostsModel.objects.filter(post_type=post_type)[1:10].order_by('-time_stamp') But did not work..! -
Django Admin Login 'CSRF cookie not set' when deployed, but works on localhost
I added several variations of the domain to CORS_ALLOWED_ORIGINS and CSRF_TRUSTED_ORIGINS, and ALLOWED_HOSTS. I added django.template.context_processors.csrf to context_processors. I had neither CSRF_COOKIE_SECURE nor SESSION_COOKIE_SECURE set to true (which I'm hoping I can change). I can't think of anything else I could do to get it to work on Django admin, and it only stopped working after I set up session authentication, (which included configuring csrf and session cookies). When I didn't have any authentication for the frontend, Django login worked fine, and even after, like I said, it was working fine on localhost. I would really appreciate any suggestions on something else I could try to fix this issue. -
Testing POST request throwing a KeyError in Postman
I am currently testing my POST request for the Tagging model. For this, I have tried to override the create() method. I am not so sure I have done this correctly but I tried everything I could think of. I even removed it and tried testing the POST request without overriding it. I keep getting this error while testing with Postman: KeyError at /api/tagging 'user' How can I get rid of this error? What is my create() method missing? serializers.py class TaggingSerializer(serializers.ModelSerializer): tag = StringRelatedField() resource = serializers.PrimaryKeyRelatedField(read_only=True) gameround = serializers.PrimaryKeyRelatedField(read_only=True) user = CustomUserSerializer(required=False, read_only=True) class Meta: model = Tagging fields = ('id', 'user', 'gameround', 'resource', 'tag', 'created', 'score', 'origin') def create(self, validated_data): """Create and return a new tagging""" tagging = Tagging( user=validated_data["user"], gameround=validated_data["gameround"], resource=validated_data["resource"], tag=validated_data["tag"], created=validated_data["created"], score=validated_data["score"], origin=validated_data["origin"] ) tagging.save() return tagging def to_representation(self, data): data = super().to_representation(data) return data This is my post request: def post(self, request, *args, **kwargs): tagging_serializer = TaggingSerializer(data=request.data) if tagging_serializer.is_valid(raise_exception=True): tagging_serializer.save(tagging=request.data) return Response({"status": "success", "data": tagging_serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": tagging_serializer.errors}, status=status.HTTP_400_BAD_REQUEST) -
Django - vote system
I'm stuck with a simple problem. I want to create a voting system. I have a simple code that doesn't work properly. When I click UP it adds +1, when I click UP again, it removes -1. Same with the DOWN button. The problem is that when I click between the UP and DOWN buttons. The value increases or decreases (indefinitely) - it depends with the click of the button first. def vote_comment(request): comment = get_object_or_404(CommentsCode, id=request.POST.get('id')) is_voted = comment.is_voted.filter(id=request.user.id).exists() up = request.POST['name'] == "UP" down = request.POST['name'] == "DOWN" if up: if is_voted: comment.is_voted.remove(request.user) comment.vote -= 1 comment.save() else: comment.is_voted.add(request.user) comment.vote += 1 comment.save() elif down: if is_voted: comment.is_voted.remove(request.user) comment.vote += 1 comment.save() else: comment.is_voted.add(request.user) comment.vote -= 1 comment.save() -
How to validate that each wagtail page will have a unique slug?
I have several models that inherit from Page and I'd like to check that each page that is being added/edited has a unique slug. Also I'd like to avoid overriding the save method and do the validation there for each page. Is there another way to validate the slug uniqueness when creating/editing pages? -
formset not uploading pictures to the backend when user creates a new course?
When creating a new course all data in the formset get posted to the backend except the course cover image why is my formset not uploading the cover for a course, mean while i have added the field to OwnerCourseMixin and OwnerCourseEditMixin i see the cover field in my create formset, but it won't just save the cover image in my database. models.py class Course(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL,\ related_name='courses_created', on_delete=models.CASCADE) subject = models.ForeignKey(Subject,related_name='courses', on_delete=models.CASCADE) title = models.CharField(max_length=200) cover = models.ImageField(upload_to="course_pictures", blank=True,null=True) my view.py class OwnerMixin(object): def get_queryset(self): qs = super(OwnerMixin, self).get_queryset() return qs.filter(owner=self.request.user) class OwnerEditMixin(object): def form_valid(self, form): form.instance.owner = self.request.user return super(OwnerEditMixin, self).form_valid(form) class OwnerCourseMixin(OwnerMixin, LoginRequiredMixin): model = Course fields = ['subject', 'title', 'slug','overview','cover'] success_url = reverse_lazy('courses:manage_course_list') class OwnerCourseEditMixin(OwnerCourseMixin): fields = ['subject', 'title','slug', 'overview','cover'] success_url = reverse_lazy('courses:manage_course_list') template_name = 'manage/module/formset.html' class CourseCreateView(OwnerCourseEditMixin, OwnerEditMixin, CreateView, PermissionRequiredMixin): pass class CourseModuleUpdateView(TemplateResponseMixin, View): template_name = 'manage/module/formset.html' course = None def get_formset(self, data=None,): return ModuleFormSet(instance=self.course,data=data) def dispatch(self, request, pk): self.course = get_object_or_404(Course,id=pk,owner=request.user) return super(CourseModuleUpdateView, self).dispatch(request, pk) def get(self, request, *args, **kwargs): formset = self.get_formset() return self.render_to_response({'course':self.course, 'formset':formset,}) def post(self, request, *args, **kwargs): formset = self.get_formset(data=request.POST,) if formset.is_valid(): formset.save() return redirect('courses:manage_course_list') return self.render_to_response({'course': self.course, 'formset':formset}) -
How to use both Count() and Min/Max in sql
I have the following table: MyTable name | price |-------------------| | a | 10 | |-------------------| | b | 5 | |-------------------| | a | 7 | |-------------------| | a | 3 | |-------------------| | a | 12 | |-------------------| | b | 6 | |-------------------| | c | 2 | |-------------------| | c | 5 | |-------------------| I want to count the frequency of the name and need to get the max_price and min_price for each name. The expected output is: name | count | min_price | max_price |-------------------|----------------------| | a | 4 | 3 | 12 | |-------------------|----------------------| | b | 2 | 5 | 6 | |-------------------|----------------------| | c | 2 | 2 | 5 | |-------------------|----------------------| I would like to write Django ORM query. Please help me to achieve it. -
How to cast DurationField to second iin Django query
I have a model with a field defined like this: mask_label_ts = models.DurationField( default=timedelta ) In one of my query I'd like to multiply it by an integer, I aim at creating bill so I want to multiply the rate by hour by the nb of seconds. How can I cast my duration field into seconds ? I tried this: test=ExpressionWrapper(F('mask_label_ts') * F('mask__labeller__hour_rate'), output_field=FloatField()) But this is not working. Any ideas ? thanks -
Edit not updating and redirecting
form not updating records, cant really figure out the main issue. Below is by view.py @login_required def update_vehicle(request, pk): vehicle = get_object_or_404(Vehicle, pk=pk) if request.method == 'POST': mv_form = VehicleForm(data=request.POST, instance=vehicle, files=request.FILES) if mv_form.is_valid(): mv_user = mv_form.save(commit=False) mv_user.vehicle_owner = request.user mv_user.save() messages.success(request, 'Your vehicle information has been updated Successfully') return redirect('manage_vehicles', username=request.user) else: mv_form = VehicleForm(instance=vehicle) context = {'mv_form': mv_form, 'vehicle': vehicle} return render(request, 'dashboard/users/edit_vehicles.html', context) -
Django filter and Distinct together
I have to achieve the following. class rooms(models.Model): uniqueKey = models.IntegerField() #this can have same value multiple times sellingPrice = models.IntegerField() My query looks like something below rooms.objects.all().distinct('uniquekey').aggregate(Sum('sellingPrice')) I want to sum Selling price for all distinct uniquekeys.Above query Gives Following error. NotImplementedError("aggregate() + distinct(fields) not implemented.") Please Help Me. -
Target WSGI script cannot be loaded as a python module
I have been trying to get my django app deployed for a while now and no matter what I have followed and tried I keep running into errors. I am currently getting this error: Target WSGI script '/home/brickmane/djangoapp/myserver/backend/core/wsgi.py' cannot be loaded as Python module. and ModuleNotFoundError: No module named 'contextvars' which is not something I used myself in my project. I have tried some solutions like using: sudo chmod a+x wsgi.py and trying libapache2-mod-wsgi-py3 vs libapache2-mod-wsgi my apache2.conf file where I placed my virtual host and the settings for my app: WSGIPythonHome /home/brickmane/djangoapp/myserver/venv WSGIPythonPath /home/brickmane/djangoapp/myserver/backend <VirtualHost *:80> ServerAlias www.d8pricecheck.tk WSGIProcessGroup backend Alias /static/ /home/brickmane/djangoapp/myserver/backend/static/ <Directory /home/brickmane/djangoapp/myserver/backend/static> Require all granted </Directory> WSGIScriptAlias / /home/brickmane/djangoapp/myserver/backend/core/wsgi.py <Directory /home/brickmane/djangoapp/myserver/backend/core> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess backend python-path=/home/brickmane/djangoapp/myserver/backend/core python-home=/home/brickmane/djangoapp/myserver/venv WSGIProcessGroup backend </VirtualHost> my wsgi.py file: import os, sys # add the hellodjango project path into the sys.path sys.path.append('/home/brickmane/djangoapp/myserver/backend/') sys.path.append('/home/brickmane/djangoapp/myserver/backend/core/') # add the virtualenv site-packages path to the sys.path sys.path.append('/home/brickmane/djangoapp/myserver/venv/lib/python3.10/site-packages') # poiting to the project settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() This is my full apache error log from restarting the service and trying to access my website: [Mon Jan 31 12:28:54.228176 2022] [mpm_prefork:notice] [pid 19551] AH00173: SIGHUP received. Attempting … -
Django: how to implement form in a sidebar?
I am trying to implemen a form (PatientForm form and PatientCreate view) in a sidebar using CBV. But it doesn't works until now... I pass my form in context using context_processor. And PatientForm is displayed in sidebar but when I submit data are neither registered (if valid) nor errors messages are displayed (if not valid). I have tried like mentionned in this post Django sidebar form . Data are registered but I do not mange to display errors... base.py ... <nav class="navbar col-md-2 d-none d-md-block bg-light sidebar"> ... <form id="id-form" method="post"> {% csrf_token %} {{ patient_form | crispy }} <button class="btn btn-outline-secondary btn-sm" type="submit">Create</button> </form> ... </nav> views.py @method_decorator(login_required, name="dispatch") class PatientCreate(SuccessMessageMixin, CreateView): model = Patient form_class = PatientForm # fields = ["pat","pat_sit"] success_message = "Le patient a été créé." def get_success_url(self): return reverse("ecrf:index") def form_valid(self, form): # This method is called when valid form data has been POSTed. form.instance.pat_sai_log = self.request.user.username form.save() return super().form_valid(form) forms.py class PatientForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PatientForm,self).__init__(*args, **kwargs) self.fields["pat"] = forms.CharField(label= "Patient", required=True) self.fields["pat_sit"] = forms.ModelChoiceField(queryset = Site.objects.filter(sit_typ = "Site"),widget=forms.Select(), label = "Patient site") class Meta: model = Patient fields = ["pat","pat_sit"] -
Exe built from a Djabgo project not working. How to solve OSError: [WinError 123] syntax is incorrect: '<frozen importlib._bootstrap
I compiled my Django project with pyinstaller by running - pyinstaller manage.py --name=MyApp -w After running the MyApp.exe in cmd by the following command - start MyApp.exe runserver The following traceback is showing - Traceback (most recent call last): File "manage.py", line 22, in <module> File "manage.py", line 18, in main File "django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "D:\Loku\Python\Django\easy_library\dist\easy_library\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "D:\Loku\Python\Django\easy_library\dist\easy_library\django\core\management\commands\runserver.py", line 95, in handle self.run(**options) File "D:\Loku\Python\Django\easy_library\dist\easy_library\django\core\management\commands\runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "django\utils\autoreload.py", line 599, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "django\utils\autoreload.py", line 584, in start_django reloader.run(django_main_thread) File "django\utils\autoreload.py", line 299, in run self.run_loop() File "django\utils\autoreload.py", line 305, in run_loop next(ticker) File "django\utils\autoreload.py", line 345, in tick for filepath, mtime in self.snapshot_files(): File "django\utils\autoreload.py", line 361, in snapshot_files for file in self.watched_files(): File "django\utils\autoreload.py", line 260, in watched_files yield from iter_all_python_module_files() File "django\utils\autoreload.py", line 105, in iter_all_python_module_files return iter_modules_and_files(modules, frozenset(_error_files)) File "django\utils\autoreload.py", line 141, in iter_modules_and_files resolved_path = path.resolve(strict=True).absolute() File "pathlib.py", line 1215, in resolve File "pathlib.py", line 210, in resolve OSError: [WinError 123] … -
How to use Django's `full_clean` using a non-default database
Background: I'm modifying our code-base to make use of multiple databases for validation of user-submitted load files. This is for automated checks of that user data so that they can fix simple issues with their files, like checks on uniqueness and such. Originally, we erroneously used TestCase to wrap our load commands and run test database setup code to create and destroy a test database. Had our original code been constructed differently, I would have just used transaction.atomic, and while a refactor might occur in the future to fix that properly, to reduce effort and put out a validation bug fix on a newly release beta quickly, I'm inserting using in all the places necessary in order to make use of a second "validation database"). So I end up (to use a database other than the default) with things like: db = "validation" Compound.objects.using(db).get(...) and: db = "validation" for compound in self.validated_new_compounds_for_insertion: compound.save(using=db) But when I first tested the code, I ran into an error: django.core.exceptions.ValidationError: {'name': ['Compound with this Name already exists.'], 'hmdb_id': ['Compound with this HMDB ID already exists.']} coming from the last line of this validation code: new_compound = Compound( name=row[self.KEY_COMPOUND_NAME], formula=row[self.KEY_FORMULA], hmdb_id=row[self.KEY_HMDB], ) new_compound.full_clean() I looked … -
Add a "+" button that opens a popup inside my django model form
I want to add a "+" button that opens a popup inside my django model form.. Any idea about that? My code in models.py class library(models.Model): book_name = models.CharField(max_length=50, null=True,blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, limit_choices_to={'is_superuser': True},null=True,blank=True) description = models.TextField(null=True, blank=True) duration = models.DurationField(null=True, blank=True) date = models.DateField() book_image = models.ImageField(upload_to='lib/book_img',null=True, blank=True) parallel to author field i want to add a "+" button(To add new author) that opens a popup modal form. my forms.py is class library_details(forms.ModelForm): class Meta: model = library fields = "__all__" -
custom does_not_exist error_message for OneToOneField field in Django model not working
i am trying to use a custom error_message for the does_not_exist error in one specific field of my model: token = models.OneToOneField( to=TokenModel, on_delete=models.CASCADE, primary_key=True, error_messages={ 'unique': 'Ya existe un candidato con este token.', 'does_not_exist': 'El token proveído no existe.' } ) I just want to override the following message if the primary key do not exist on the related model, if i use extra_kwargs into the serializer it works, i think it should work in the model as well, but it does not: -
getting empty pdf by using data Table in ajax
I have made ajax function in the Django project and on-click I am appending table row inside table body by using the append method. for pdf, I am using jquery DataTable for downloading pdf but I got an empty pdf with only a heading. why I'm not getting data? function getData(el){ $.ajax({ url:"{% url 'indexajax' %}", type: 'GET', dataType: 'json', data: {saveVsl:el.value}, success: function(r){ for(let i=0; i<r.length; i++){ $('#table tbody').append(`<tr><td>${i}</td><td>${r[i].name}</td><td>${r[i].email}</td><td>${r[i].description}</td></tr>`) } }, }) } data table $('#table').DataTable( { buttons: [ { extend: 'pdf', text: 'Save current page', exportOptions: { modifier: { page: 'current' } } } ]} ); -
I need to post a data from react to django rest framework but when I use axios to post , it said network error
pic1 this is my ui and error at right pic2 handle submit is run when click submit button handle input is for set a value for input pic3 and this is my url that i want to post . it can work in postman pic4 and this is my post page in django . it can post in this page pic5 this is my code that i use to create a post page pic6 and this is my models.py I'm newbies at this and i don't know how to fix it didn't someone know ? -
Editing Fields on Formset before saving
What is the correct way to modify models in a formset before saving. In a normal context, I have become used to do as follows in the case of a normal form (with the field 'flagged'): formset = RSVPFormset(request.POST or None, queryset=invites) if form.is_valid(): new_registry = form.save(commit=False) new_registry.flagged = True new_registry.save() However, in the case of a formset, I see I am not able to do the same: if formset.is_valid(): new_registry = formset.save(commit=False) new_registry.flagged = True new_registry.save() How would I set this field before saving? -
Why does one of my static file is not found when deploying a Django app with Docker?
I am trying to do a django project and push it to Heroku. For now, I just try to make my container work locally. For my static files, I use Whitenoise. The problem I encounter is that my app work and all my statics work except one, script.js (the only file I have in the folder js). I have this error message on the docker console : Not Found: /static/js/script.js This is my Dockerfile : # pull official base image FROM python:3.8-alpine # set work directory WORKDIR /pur_beurre # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV DEBUG 0 # install psycopg2 RUN apk update \ && apk add --virtual build-essential gcc python3-dev musl-dev \ && apk add postgresql-dev \ && pip install psycopg2 # install dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt # copy project COPY . . # collect static files RUN python manage.py collectstatic --noinput # add and run as non-root user RUN adduser -D myuser USER myuser # run gunicorn CMD gunicorn pur_beurre.wsgi:application --bind 0.0.0.0:$PORT I have STATIC_URL = 'staticfiles' and STATIC_ROOT = BASE_DIR / 'staticfiles' and I added the line 'whitenoise.middleware.WhiteNoiseMiddleware', just after 'django.middleware.security.SecurityMiddleware',. My js folder is at the same … -
How to be autheticated in Django backend when autheticated in ReactJs frontend?
I'm making a web app with Django 3.2 (Python 9) as backend and ReactJs 17 as frontend with a Graphene(GraphQL) API in between. ReactJs uses Apollo Client Provider 3.4 to perform the API queries and mutations. I'm using the django-graphql-auth package to authenticate my users and I store the user's authentications token in the browser's localStorage that I then put in the headers of the Apollo Provider. Everything works well until there. Now, the problem is that the user should be able to download files by clicking on a link in the frontend. This link will redirect to a backend Django view where a file is put in a HttpResponse. The user will be prompt to accept downloading the file. However, the file is generated based on the user whom request it (on the user's Group to be more precise). So in my Django view, I use the request.user.groups variable to generate the file that will be downloadable. Here is the problem: on the backend side, the user is still anonymous while authenticated in the frontend. How can I authenticate the user in the backend when (s)he logs in in the frontend ? Can I simply pass the request.user value … -
Django query regardless of the diacritics with sqlite3
I need to make query Model.objects.filter(name__icontains=my_parameter) which will also ignore diacritics. I found a solution name__unaccent__icontains, but unaccent works with PostgreSQL and this solution does not work with sqlite3. Do you have any ideas on how to solve this? Thank you very much! -
how to add list filter for objects that created by user belongs to a group?
I want to add list filter option by a group for unrelated models in django. How to do that? For example if i have task logs like class TaskLogs(AuditModel): Status = models.BooleanFiled(default=0) i want to filter all tasklogs by a group which has group of users. Tasklog will created by a user. -
Django mptt: model with a mptt tree instance as a field
I am developing an app with Django where I have to model systems. A system is defined by a number of standard fields (name, owner, etc...) and then a tree of assets (implemented using mptt). A given asset can be part of several systems. A node in the tree of assets can point only to a given asset. So, I have a model to represent the assets (simplified): class Asset(models.Model): name = models.CharField(verbose_name = 'name', max_length = 64, unique = True, blank = False, null = False) I have a class to represent the system trees (simplified): class System_Tree(MPTTModel): parent = TreeForeignKey('self',verbose_name = 'parent', on_delete = models.CASCADE, blank = True, null = True, related_name = 'children') asset = models.ForeignKey(Asset, verbose_name = 'asset', on_delete = models.CASCADE, blank = False, null = False) I have a class to represent the system (simplified): class System(models.Model): name = models.CharField(verbose_name = 'name', max_length = 64, unique = True, blank = False, null = False) I would like to show in a template the system with its fields and its specific system tree, but I don't know how to relate a specific instance of a system tree (maybe identified by a root node (parent = null)) …