Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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)) … -
Django: Using Faker to fill multiple tables
I am trying to populate my Django project with some test data. I have 3 tables, Person, Address, Employment. Both Address and Employment have a Person FK. My script is creating my person but when it gets to Address it fails at Address.person models class Person(models.Model): first_name = models.CharField(max_length=200) middle_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) class Address(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) address = models.CharField(max_length=200, blank=True, null=True) class Employment(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) employer = models.CharField(max_length=200) My script def populate(n=5): for entry in range(n): person = Person.objects.get_or_create( first_name = fakegen.first_name(), middle_name = fakegen.first_name(), last_name = fakegen.last_name(), FakeAddress(person) FakeEmployment(person) def FakeAddress(person): address = Address.objects.get_or_create( person = person, address = fakegen.street_address(), TypeError: Field 'id' expected a number but got <Person: Michael Baker>. I've tried to pass the Person to the address function and I get TypeError: Field 'id' expected a number but got <Person: Michael Baker>. Next I tried passing the Person's ID instead of the person and I get ValueError: Cannot assign "93": "Address.person" must be a "Person" instance. -
How to notify users of new blog post via django?
I am building a mobile app using Django Rest Framework, Flutter, and MongoDB. In that app users can view posts posted by other users. In my Django app, I don't have any notification model (and honestly don't really know how to use that either!). In Django, I have created endpoints to create posts @api_view(['POST']) def createPost(request): code/logic... , and to retrieve posts class blogsViewSet(ModelViewSet): queryset = Posts.objects.all() serializer_class = PostSerializer pagination_class = pagination.CustomPagination def list(self, request, *args, **kwargs): uid = request.META.get('HTTP_DATA') context = {"user": uid} queryset = Posts.objects.all().order_by('postID') paginatedResult = self.paginate_queryset(queryset) serializer = self.get_serializer(paginatedResult, many=True, context= context) return Response(serializer.data) Now in my app, lets say I have two users: User A, and User B. now if both of them are using the app at the same time and user A creates a new post, I want user B to be notified and showed that new post immediately, without the user B having to reload the page himself/herself. Now my question is, can I achieve this by using Django channel only, or do I have to use Redis (or any similar service). If yes, then how? Thanks! -
Boolean field update due to another field change in Django Admin
I have model Department like: class Department(models.Model): dep_title = models.CharField(max_length=30, verbose_name='Title') dep_description = models.CharField(max_length=100, blank=True, verbose_name='Description') dep_status = models.BooleanField(default=False, verbose_name='Is Active?') dep_start = models.DateField(verbose_name='Date of Establishment') dep_end = models.DateField(blank=True, verbose_name='Closing Date', null=True) and DepartmentAdmin: class DepartmentAdmin(admin.ModelAdmin): list_display= ('dep_title','dep_description','dep_status', 'dep_start', 'dep_end') I want to check dep_end date and if date is expired, set automatically dep_status = False How can I implement this? -
how to fix django.db.utils.IntegrityError
I have two nested models (task and Proposal) with a foreign key relationship, i've followed every necessary step but i'm getting an inegrity error below is d err and codes Serializer 1st serializer class JobSerializer(serializers.ModelSerializer): user = serializers.CharField(source='user.username', read_only=True ) user_id = serializers.CharField(source='user.id', read_only=True) proposals = ProposalSerializer(many=True, read_only=True) class Meta: model = JobPost fields = [ 'user', 'user_id', 'id', 'proposals', 'etc' ] 2nd Serializer class ProposalSerializer(serializers.ModelSerializer): user = serializers.CharField(source='user.username',read_only=True) class Meta: model = Proposal fields = [ 'id', 'proposal_description', 'duration', 'bid', ] APIVIEW class ProposalAPIView(generics.CreateAPIView): serializer_class = ProposalSerializer look_up = 'id', queryset = Proposal.objects.all() permissions_classes = [permissions.IsAuthenticated] 2nd APIView class CreateJobPost(generics.CreateAPIView): serializer_class = JobSerializer permissions_classes = [permissions.IsAuthenticated] def create(self, request, *args, **kwargs): serializer = self.get_serializer( data=request.data ) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) res = { 'message': 'Job Post Successfully Created', 'status': status.HTTP_201_CREATED, 'serializer': serializer.data } return Response(res) err msg django.db.utils.IntegrityError: null value in column "task_id" violates not-null constraint DETAIL: Failing row contains (3cc5ac3f-f1ef-4833-b775-a18ffa1b471b, 4 days, ahhdgdg, 10000, 2022-01-31 15:01:25.753828+00, null, null). can anyone pls help -
How do I import Django models into python file?
I have a Django model which stores inputs from a form, now that I have the data stored in Django I need to import those models to a python file. -
Django Formset Posting but formset is never valid
I have created a Formset based on modelformset_factory and an existing Form in my view and pass it a queryset of objects to edit. These render correctly on the view but whenever I try and confirm, it does not save. Printing the statement (print(formset.is_valid()) I see that this is what is stopping the formset saving. How does one correctly pass existing queryset to a formset to edit? Forms.py class RSVPForm(forms.ModelForm): class Meta: model = Invite fields = ['guest_name', 'plus_one', 'dietry_requirements', 'rsvp_attendance'] Views.py def view_rsvp_create(request, event_id, guest_id): event = get_object_or_404(Event, id=event_id) guest = get_object_or_404(Guest, id=guest_id) invites = Invite.objects.filter(event=event, guest=guest) RSVPFormset = modelformset_factory(Invite, form=RSVPForm, extra=0) formset = RSVPFormset(queryset=invites) if request.method == 'POST': if formset.is_valid(): print('okey') formset.save() return redirect('view_rsvp_overview', name = guest.wedding.subdomain, code = guest.code) data = {'formset': formset, 'guest': guest, 'wedding': event.wedding, 'invites':invites} template='experience/rsvp-create.html' return render(request, template, data) update.html ... <form method="post"> {% csrf_token %} {{ formset | crispy }} <button type="submit" class="btn">{% trans "Confirm RSVP" %}</button> </form> ... -
Celery inspecting workers in Django Management Command results in inconsistent behavior
I have a simple piece of code that I use to determine the number of active Celery tasks, using the Inspect API, inspired from this part of the documentation: from myapp.celery import app app.control.inspect().active() Running this from the Django shell gives me the right output every time, so no problem there. However, I am trying to write a very simple Django Management Command that runs the same code. The file structure looks like this: myapp └── celery.py └── settings.py | __init__.py secondapp └── management │ └── commands │ └── __init__.py │ └── celery_workers.py │ __init__.py | __init__.py manage.py Keeping it as simple as possible, the command would look like this: from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): from myapp.celery import app print(app.control.inspect().active()) Running this command as python manage.py celery_workers occasionally gives the expected output (same as running from the shell), but more often than not it says that there are no running tasks (knowing there are running tasks): {'app@project': []} I am wondering what could be the cause of this discrepancy. -
pdf link for search result
i want display a simple link for my pdf folder (static/media) in my search result , i try some things but not work. thank for watching :) view.py class SearchResultsList(ListView): model = Actes model= Pdflink context_object_name = "actes_context" template_name = "search_result.html" def get_queryset(self): query = self.request.GET.get("q") vector_column = SearchVector("contenue", weight="B") + SearchVector( "contenue", weight="A")+ SearchVector ("title", weight="C") file_path = os.path.join(settings.MEDIA_ROOT) if os.path.exists(file_path): with open(file_path, 'rb') as fh: link = Actes.title == Pdflink.title if link is True: link= Pdflink.title + '.pdf' return link response = HttpResponse(fh.read(), content_type="application/pdf") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response, link search_query = SearchQuery(query) search_headline = SearchHeadline("contenue", search_query) return ( Actes.objects.annotate(rank=SearchRank(vector_column, search_query)).annotate(headline=search_headline) .filter(rank__gte=0.8) .order_by("-rank") ) and i don't know how to write the "<a href =..." for display the result for the pdf link in my template -
Problem displaying admin in Django project
I ran the Django project on the C panel, but it looks like this in the admin section.