Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Single user view in Django API (Rest Framework)
I created an API on Django using the rest framework, I populate that through the default Django Admin Page. My question: the API works fine and I'm able to get all the results, but I'm looking to create an endopoint like /api/<int:CID> that returns just one user. I would like to use the field 'CID' to filter. How can I do that? Thanks! I've some fields in my API, here my serializers.py class HCSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = HomeController fields = ('full_name','Staff','CID', 'OI', 'Rating', 'GND', 'TWR', 'APP', 'CTR', 'Notes') class VCSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = VisitingController fields = ('full_name','CID', 'OI', 'Rating', 'GND', 'TWR', 'APP', 'CTR', 'Notes') my views.py class HCViewSet(APIView): def get(self): HC = HomeController.objects.all().order_by('full_name') serializer = HCSerializer(HC, many=True) return Response(serializer.data) class VCViewSet(APIView): def get(self): VC = VisitingController.objects.all().order_by('full_name') serializer = VCSerializer(VC, many=True) return Response(serializer.data) my models.py class HomeController(models.Model): full_name = models.CharField(max_length=60) ATM = 'ATM' DATM = 'DATM' TA = 'TA' EC = 'EC' FE = 'FE' WM = 'WM' INS = 'INS' MTR = 'MTR' BLK = 'BLK' Staff = [ (ATM, 'Air Traffic Manager'), (DATM, 'Deputy Air Traffic Manager'), (TA, 'Training Administrator'), (EC, 'Events Coordinator'), (FE, 'Facility Engeneer'), (WM, 'Webmaster'), (INS, 'Instructor'), (MTR, 'Mentor'), (BLK, 'Blank'), ] Staff = … -
Django upload multiple images per post
Hi I want to let the user upload multiple images per post. Similary to an ecommerce platform with multiple images per product. But till now the images are not sent to the database. Thats my code so far: models.py class Project(models.Model): title = models.CharField(max_length=200) describtion = models.TextField(null=True, blank=True) class ProjectImage(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) image = models.FileField() forms.py class ProjectForm(ModelForm): image = forms.ImageField(widget=ClearableFileInput(attrs={'multiple':True})) class Meta: model = Project fields = ['title', 'describtion'] views.py def createProject(request): form = ProjectForm() if request.method == 'POST': form = ProjectForm(request.POST) images = request.FILES.getlist('image') if form.is_valid(): project = form.save() for i in images: ProjectImage(project=project, image=i).save() context = {'form':form} return render(request, 'projects/project_form.html', context) project_form.html <form class="form" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form__field"> <label for="formInput#text">{{field.label}}</label> {{field}} </div> {% endfor %} <input type="submit" name="" id=""> </form> -
Can't change style of Bootstrap datatables
I'M trying to use this bootstrap datatable in Django: <script src='https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js'></script> <script> $(document).ready(function () { $('#mydatatable').DataTable(); }); </script> But when I try to change default texts position it won't apply. These are the default divs with bootstrap. I find them from chromes inspect part.I want to change these : <div class="dataTables_info" id="mydatatable_info" role="status" aria-live="polite">Showing 1 to 10 of 22 entries</div> <div class="dataTables_paginate paging_simple_numbers" id="mydatatable_paginate"><a class="paginate_button previous disabled" aria-controls="mydatatable" data-dt-idx="0" tabindex="-1" id="mydatatable_previous">Previous</a><span><a class="paginate_button current" aria-controls="mydatatable" data-dt-idx="1" tabindex="0">1</a><a class="paginate_button " aria-controls="mydatatable" data-dt-idx="2" tabindex="0">2</a><a class="paginate_button " aria-controls="mydatatable" data-dt-idx="3" tabindex="0">3</a></span><a class="paginate_button next" aria-controls="mydatatable" data-dt-idx="4" tabindex="0" id="mydatatable_next">Next</a></div> My Actual html file: <div class="table-keep"> <div class="container"> <h1>My Table</h1> <table class="table" border=1 id="mydatatable"> <thead> <tr> <th>Name</th> <th>Age</th> <th>School</th> <th>Phone Number</th> <th>Email</th> </tr> </thead> <tbody> {% for x in x_list %} <tr> <td>{{x.name}}</td> <td>{{x.age}}</td> <td>{{x.school}}</td> <td>{{x.phone}}</td> <td>{{x.email}}</td> </tr> {% endfor %} </tbody> </table> </div> </div> <!-- Need to have JQuery and Javascript for DropDown Actions to work --> <script src="http://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script src='https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js'></script> <script> $(document).ready(function () { $('#mydatatablem').DataTable(); }); How can I grab and change style of the #mydatatable and the buttons above? -
How to pass iterable list of filtered users in Django template using form?
I have a custom user model that has additional filter than the default Django User, viz. is_candidate and is_voter. I want to pass the list of all those users who have is_candidate as True. I tried to make a form of such users and passed that form in template, but I ma getting following error: TypeError at /votes/ cannot unpack non-iterable User object Request Method: GET Request URL: http://localhost:8000/votes/ Django Version: 4.0.3 Exception Type: TypeError Exception Value: cannot unpack non-iterable User object Exception Location: C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\widgets.py, line 737, in _choice_has_empty_value Python Executable: C:\Users\Admin\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.4 Python Path: ['D:\\VU\\CS619\\BC170403979\\punjabbarcouncil', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python310', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages'] Server time: Sun, 12 Jun 2022 10:19:32 +0000 Complete details of error is: Traceback Switch to copy-and-paste view C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py, line 55, in inner response = get_response(request) … Local vars C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … Local vars D:\VU\CS619\BC170403979\punjabbarcouncil\register\views.py, line 142, in votes return render(request, 'register/votes.html', context) … Local vars C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\shortcuts.py, line 24, in render content = loader.render_to_string(template_name, context, request, using=using) … Local vars C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\loader.py, line 62, in render_to_string return template.render(context, request) … Local vars C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\backends\django.py, line 62, in render return self.template.render(context) … Local vars C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py, line 175, in render return self._render(context) … -
How to execute a task in django if condition matched?
I was trying to build a trading application which can handle multiple users, The users can add their bids on stocks. If the current prices of stock matches with the price entered by the user execute that order. Can this task be completed via Celery and celery-beat? if multiple users has placed order then all the order needs to be executed at a same time. I just need to know higher level knowledge on how we can solve this task? -
How Can i go to Customer.html page when i click on cancel link? I can go to dashboard but no to specific page customer because it have id?
CLick TO see picture Click to See the error -
How to upload payment picture by orders, 'QuerySet' object has no attribute '_meta'
I can't filter to upload pictures. I want to upload pictures by : orders= Order.objects.filter(id=orid, id_profil=id_profil) get error : 'QuerySet' object has no attribute '_meta' view.py def Detail(request, orid=None): data = cartData(request) cartItems = data['cartItems'] id_profil = request.user.profile orders = Order.objects.filter(id=orid, id_profil=id_profil) OrderItems = OrderItem.objects.filter(order=orid) pengirimans = Pengiriman.objects.filter(order=orid) if request.method == "POST": form = Uplaodpic(request.POST ,request.FILES ,instance=orders) if form.is_valid(): form.save() else: form=Uplaodpic(instance=orders) context = {'orders':orders, 'OrderItems':OrderItems, 'pengirimans':pengirimans, 'cartItems':cartItems, 'form':form} return render(request, 'store/detail.html' ,context) forms.py from django.forms import ModelForm from .models import Order, Profile class Uplaodpic(ModelForm): class Meta: model=Order fields=["id","bukti"] detial.html <td colspan="2"> <img src="{{ order.buktiURL }}" alt="image" class="img-thumbnail" style="max-height:100px"> </td> <td colspan="2"> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="Submit" id="submit" name="submit"> </form> </td> </tr> modes.py class Order(models.Model): id_profil = models.ForeignKey(Profile, on_delete=models.SET_NULL, blank=True, null=True) order_data = models.DateTimeField(auto_now_add=True) selesai = models.BooleanField(default=False, blank=True, null=True) status = models.BooleanField(default=False, blank=True, null=True) id_transaksi = models.CharField(max_length=200, null=True) bukti = models.ImageField(upload_to='bukti/',default="person-circle.svg",null=True, blank=True) ongkir = models.CharField(max_length=200, null=True) total = models.CharField(max_length=200, null=True) total_harga = models.CharField(max_length=200, null=True) pembayaran = models.CharField(max_length=200, null=True) -
Django URL Pattern Syntax - raw string
So this might sound like a newb question but I was just wondering what is the difference between path('index/', views... And... path(r'^index/$', views... I just wrote my first web app and I use the first example but I see everyone using the raw string syntax in examples I look up. Are there any differences between the way django handles the two examples? Thanks in advance. -
Add customer modal and edit in one view in django
I am kinda like stuck. I have a BankAccountCreation() and the the form is called in a modal in Django template. I am trying to get the same for be used for editing. but when I do that my edit button returns an empty form My view is as below def employee_info(request, id): if not request.user.is_authenticated: return redirect('/') context = {} banks = Bank.objects.all() employee = get_object_or_404(Employee, id = id) bank_instance = Bank.objects.filter(employee = employee).first() context = {} context['employee'] = employee context['bank'] = bank_instance context['banks'] = banks context['title'] = 'profile - {0}'.format(employee.get_full_name) if request.method == 'GET': form = BankAccountCreation() context['form'] = form return render(request, 'employee/employee_info.html', context) if request.method == 'POST': form = BankAccountCreation(data = request.POST) if form.is_valid(): instance = form.save(commit = False) employee_id = request.POST.get('employee') employee_object = employee instance.employee = employee_object instance.name = request.POST.get('name') instance.branch = request.POST.get('branch') instance.account = request.POST.get('account') instance.code = request.POST.get('code') instance.save() messages.success(request, 'Bank Details Successfully Created for {0}'.format(employee_object.get_full_name), extra_tags = 'alert alert-success alert-dismissible show') return redirect('employee_info', id=employee.id) else: context['form'] = form messages.error(request, 'Error Updating details for {0}'.format(employee_object.get_full_name), extra_tags = 'alert alert-warning alert-dismissible show') return redirect('employee_info', id=employee.id) form = BankAccountCreation() return render(request, 'employee/employee_info.html', context) The Bank model has a foreign key to the Employee model -
Django. How to return error 500 without sending mail to admins
I am using standard error handling in production - if there are server errors I am getting mails. However, on certain APIs I want to have a response with HTTP code 500 or 502 as part of the "valid flow". (It's done for educational purposes) So my view for that looks like this: from rest_framework.response import Response from rest_framework import status def give_me_error(request): return Response("This is expected error", status=status.HTTP_500_INTERNAL_SERVER_ERROR) And what I want is not to get email of this particular response (because I wanted it to be 500) I've also tried this way: from django.http import JsonResponse def give_me_error(request): return JsonResponse({'error': 'expected error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) But it also generates mail. Is there a way to have a view returning error 500 that will not trigger e-mail send? (without disabling the e-mail functionality system-wide) Per Django documentation: https://docs.djangoproject.com/en/4.0/howto/error-reporting/ When DEBUG is False, Django will email the users listed in the ADMINS setting whenever your code raises an unhandled exception and results in an internal server error (strictly speaking, for any response with an HTTP status code of 500 or greater) -
Django Pytest. Use database entries in parametrize
I want to have a test for data that will use real data from DB. The goal is to go through all the entries of a table Foo and apply some test logic on each entry. Ideally is to use parametrize for that but I am a bit struggling with DB access to parametrize. What I do so far: tests.py import pytest from app.models import Foo pytestmark = pytest.mark.django_db @pytest.fixture(scope='session') def django_db_setup(): settings.DATABASES['default'] = { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['DB_NAME'], 'USER': os.environ['DB_USER'], 'PASSWORD': os.environ['DB_PASSWORD'], 'HOST': 'localhost', } @pytest.mark.django_db class TestFoo: @pytest.mark.parametrize('foo', Foo.objects.all()) def test_foo_objects(self, foo): assert foo.is_ok Eventually I get E RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. However, if DB-access is not used in parametrize - it works. I.e inside test_foo_objects DB-access is allowed. So the question is how to allow parametrize use DB as well? -
How to run tests in Django app? Setting error
I try to write tests for my Django app but I'm getting an error and don't know how to fix it. Inside my sport_field_app folder I have files: conftest.py: import pytest from django.test import Client @pytest.fixture def client(): client = Client() return client tests.py: def test_list(client): response = client.get("sport-field-list/") assert response.status_code == 200 I've also added a file pytest.ini: [pytest] DJANGO_SETTINGS_MODULE = test.settings After running pytest test.py I got a message: Traceback (most recent call last): File "/home/maryla/marylaGIS_github/sport_field_reservation_v2/venv/lib/python3.8/site-packages/pytest_django/plugin.py", line 179, in _handle_import_error yield File "/home/maryla/marylaGIS_github/sport_field_reservation_v2/venv/lib/python3.8/site-packages/pytest_django/plugin.py", line 351, in pytest_load_initial_conftests dj_settings.DATABASES File "/home/maryla/marylaGIS_github/sport_field_reservation_v2/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/home/maryla/marylaGIS_github/sport_field_reservation_v2/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 74, in _setup self._wrapped = Settings(settings_module) File "/home/maryla/marylaGIS_github/sport_field_reservation_v2/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 183, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'test.settings' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/maryla/marylaGIS_github/sport_field_reservation_v2/venv/bin/pytest", line 8, in <module> sys.exit(console_main()) File "/home/maryla/marylaGIS_github/sport_field_reservation_v2/venv/lib/python3.8/site-packages/_pytest/config/__init__.py", line 187, in console_main code = main() File "/home/maryla/marylaGIS_github/sport_field_reservation_v2/venv/lib/python3.8/site-packages/_pytest/config/__init__.py", line 145, in main config = _prepareconfig(args, plugins) File "/home/maryla/marylaGIS_github/sport_field_reservation_v2/venv/lib/python3.8/site-packages/_pytest/config/__init__.py", line 324, in _prepareconfig config = pluginmanager.hook.pytest_cmdline_parse( … -
Import "article.models" could not be resolved (from article.models import ArticlePost)
This is a python code from my classmate, but I found a warning Import "article.models" could not be resolved at line from article.models import ArticlePost How to solve this? I use django 4.0.4 and did not find anything like ArticlePost in django-documentation from django.db import models from django.contrib.auth.models import User from article.models import ArticlePost from ckeditor.fields import RichTextField from mptt.models import TreeForeignKey # comments class Comment(models.Model): article = models.ForeignKey(ArticlePost, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='comments') body = RichTextField() parent = TreeForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True, related_name='children' ) reply_to = models.ForeignKey( User, null=True, blank=True, on_delete=models.CASCADE, related_name='replyers' ) created = models.DateTimeField(auto_now_add=True) class MPTTMeta: order_insertion_by = ['created'] def __str__(self): return self.body[:20] -
Display Data in Django table where data has similarities betwen row and column
Currently i'm dealing with timetable project, have a list of schedule saved in database and i want to print them in a table where a schedule should be placed on a right place based on row(days) and columns (timeslots). i have tried to arrange schedule and it appear as follows: appearance of current tried schedule arrangement picture The view used is as follows def lecturerTimeTable(request): lecname=Lecturer.objects.get(user=request.user.id) context={ 'schedule': TeachingTimetable.objects.filter(lecturer=lecname).order_by('meet_time'),#get lecturer 'program': Program.objects.all(), 'days': MeetingTime.objects.all().values('day').distinct(), #day 'slots': MeetingTime.objects.all().values('time').distinct(),#timeslot 'url_name':'class',#for active link 'lecturer':lecname, 'StarterPage':'Class-Timetable'# for head } return render(request,'users/class_timetable.html',context) The template table is as follows <table class="table table-striped table-bordered table-hover"> <thead> <tr> <th colspan="8"><center>{{lecturer}}</center</th> </tr> <tr> <th></th> {% for time in slots %} <th class="time">{{time.time}}</th>{% comment %} timeslot from 07:00-09:00 to 17:00-21:00 {% endcomment %} {% endfor %} </tr> </thead> <tbody> {% for day in days %} <tr> <th>{{day.day}} </th> {% for lesson in schedule %} {% if lesson.meet_day == day.day%} {% if lesson.meet_time == '13:00 - 15:00' %} <td>{{lesson.course}} <br> {{lesson.lecturer}}<br> {{lesson.venue}}<br> {{lesson.meet_day}} {{lesson.meet_time}}</td> {% comment %} {% endif %} {% endcomment %} {% endif %} {% endfor %} </tr> {% endfor %} So i appreciate i will get help soon! Thanks -
Django, generic view dynamic filtering
i'm starting out with Django and trying to render all Shows(screenings) that selected Movie had. Here's the code: url path('movie/<int:pk>/', MovieDetails.as_view(), name='movie'), Models class Movie(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=255, blank=True) def __str__(self): return f'{self.title}' class Show(models.Model): show_date = models.DateField() start_time = models.TimeField() movie = models.ForeignKey(Movie, on_delete=models.CASCADE, null=True, blank=True) city = models.ForeignKey(City, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200, blank=True) def __str__(self): return f'{self.show_date}' View class MovieDetails(DetailView): model = Movie context_object_name = 'movie' def get_queryset(self): self.movie = get_object_or_404(Movie, id=self.kwargs['pk']) #find movie by id from url shows_played = Show.objects.filter(movie=self.movie) print(shows_played) #prints out some shows return shows_played def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['shows_played'] = Show.objects.filter(movie=self.movie) return context The shows_played prints out some shows, so it seems like everything is fine but when the url: /movies/1 is called I get a 404, No show found matching the query rendered in browser and Not Found: /movie/1/ printed in console What am i doing wrong? Thank you -
nginx alias : where is the alias taking place (3 containers and a reverse proxy)
Im trying to get working a single page application with django/wagtail and react. But at the moment im serving django content via restframework and the request on media/ and djangostatic/ are not working. I have configured nginx to serve /media and /djangostatic to alias /app/media and /app/static but this is not working properly. Here is the nginx.conf file: server { listen 80; server_name localhost; location / { proxy_pass http://172.20.128.3:3000; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 20M; } location /wagtail { proxy_pass http://172.20.128.2:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Script-Name /wagtail; client_max_body_size 20M; } location /djangostatic/ { alias /app/static/; } location /media/ { alias /app/media/; } } When a page in need of /djangostatic is querried, i get the error : 2022/06/12 08:30:10 [error] 22#22: *2 open() "/app/static/wagtailadmin/js/vendor/jquery.datetimepicker.js" failed (2: No such file or directory), client: 172.20.0.1, server: localhost, request: "GET /djangostatic/wagtailadmin/js/vendor/jquery.datetimepicker.js?v=021047c1 HTTP/1.1", host: "localhost", referrer: "http://localhost/wagtail/cms-admin/login/?next=/wagtail/cms-admin/" So the alias seems to work (it is replaced by /app/media) but it doesnt open the file. I have checked the backend server container and the file exists. So my question is simple : on which server does the alias takes effect? I have actually three … -
SMTP email error after Google's removal of less secure app access
Error: SMTPAuthenticationError at /accounts/signup/ (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials n1-20020a05620a294100b006a6b6638a59sm3664075qkp.53 - gsmtp') Before the update, the email sender works. Now after the update the email sender has a STMP authentication error. How can I fix this error? Code: EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'tonoabot.noreply@gmail.com' EMAIL_HOST_PASSWORD = os.environ['mailbotPass'] EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' -
local variable 'med' referenced before assignment - Django
I have 2 models 1) patientprofile and 2) medInfo. In the first model patientprofile, I am trying to get patients informations like (name and other personal information) and 2nd model I want to add patients Medical information data.. when I am trying check is there a existing medical information for the patient then show and update it. otherwise need to create and update it. in medinfo model using forignkey of patientprofile (id). Its working good in admin panel perfectly. but when I am trying to do it UI getting error. below is code:view.py @login_required def medinfoupdate(request, patid): # to get patient name and id in medinfo page accessing patientprofile data patprofileedit = patientprofile.objects.get(id=patid) try: med = medInfo.objects.get(pat_ID=patid) if request.method == 'GET': form = medInfo_form(instance=med) return render(request, 'pmp/medinfo.html', {'med': med, 'form':form, 'patprofileedit' : patprofileedit} ) except: if request.method == 'GET': return render(request, 'pmp/medinfo.html', {'patprofileedit' : patprofileedit} ) if request.method == 'POST': try: form = medInfo_form(request.POST, instance=med) form.save() return redirect(patientlist) except ValueError: return render(request, 'pmp/medinfo.html', {'form': form, 'error': 'Data entered is wrong!'}) below is error : UnboundLocalError at /medinfo/pat-11 local variable 'med' referenced before assignment Request Method: POST Request URL: http://localhost:8000/medinfo/pat-11 Django Version: 4.0.4 Exception Type: UnboundLocalError Exception Value: local variable 'med' … -
How can I simplify retrieval of corresponding foreign key objects
I use Django on the backend and React on the frontend. I have quotes that are related to a character by foreign key, for example: class Quotes(models.Model): quote = models.CharField(max_length=1000, unique=True, null=True, blank=False) quote_ja = models.CharField(max_length=1000, unique=True, null=True, blank=True) quote_by = models.ForeignKey(Characters, on_delete=models.SET_NULL, null=True, blank=True) quote_from = models.ForeignKey(Media, on_delete=models.SET_NULL, null=True, blank=True) date_added = models.DateField(auto_now=True) I have some models with multiple foreign keys, for example in the above, quote_by returns the keys to the corresponding characters. image of the foreign keys in api This is the Characters Model connected to quote_by: class Characters(models.Model): first_name = models.CharField(max_length=100, null=True, blank=False) last_name = models.CharField(max_length=100, null=True, blank=True) ja_name = models.CharField(max_length=100, null=True, blank=True) image = models.ImageField(upload_to='characters/', null=True, blank=True) I would like to access the data from fields such as quote_by/quote_from with React. At the moment it seems overly complicated and I'm wondering if I should make a change to the backend. -
When I paginate my Django page my tables sizes and buttons positions are changing
In my Django site I want to show a table. Because of I can't show all table rows in one page I am using pagination. But every time I go to other page my tables size and buttons positions is changing. How can I fix their size and positions same on every page? This is the view I using: class TableView(ExportMixin, SingleTableView): model = MyModel table_class = MyTable template_name = 'table_list.html' context_object_name = 'table_list' paginate_by = 8 My html page: <div class="container"> <h1>Table</h1> <span class="current"> <h3>Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.</h3> </span> {% if page_obj.has_previous %} <a id="left-arrow" href="?page={{ page_obj.previous_page_number }}">PREVİOUS</a> {% else %} <div class="current"> <a id="left-arrow" href="#">PREVİOUS</a> </div> {% endif %} {% if page_obj.has_next %} <a id="right-arrow" href="?page={{ page_obj.next_page_number }}">NEXT</a> {% endif %} <table class="table" border=1 id="mytable"> <thead> <tr> <th>Name</th> <th>Age</th> <th>School</th> <th>Email</th> <th>Note</th> </tr> </thead> <tbody> {% for customer in customers %} <tr> <td>{{table_list.name}}</td> <td>{{table_list.age}}</td> <td>{{table_list.school}}</td> <td>{{table_list.email}}</td> <td>{{table_list.note}}</td> </tr> {% endfor %} </tbody> </table> </div> </div> -
Link to detailpage of object with todays date from navbar
In my application, I have objects that are connected to each day. The object's date must be unique. I want to include a link to the detailpage of the object of today from the navbar. However, I don't know how this should be implemented. Because essentially, I need to be able to get the pk of todays object from the navbar template. This is how I try to link to it right now in my navbar.html file: <a class="nav-link" href="{% url 'today' object.pk %}">Today</a> This is the url for the detail view: path('today/<int:pk>', TodaysView.as_view(), name='today') Is there anyway I could filter the dates inside of the template? -
Why does i am getting Django form: Key error
I am creating a creating a auction management system in which i was going to add the bid functionality and know i am facing this error i am highlighting the line in which i am getting error view.py class ItemDetailView(CreateView): template_name = "itemdetail.html" form_class = BidOnProduct success_url = reverse_lazy("auction:item_detail") def dispatch(self, request, *args, **kwargs): buyer_id = request.session.get("id") buyer_obj = Buyer.objects.filter(id=buyer_id) if buyer_obj: pass else: return redirect("auction:buyer_login") return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) item = Item.objects.get(slug=kwargs["slug"]) bids = Bid.objects.filter(item=item) context["item"] = item context["bids"] = bids return context def form_valid(self, form): buyer_id = self.request.session.get("id") if buyer_id: buyer_obj = Buyer.objects.get(id=buyer_id) form.instance.buyer = buyer_obj form.instance.item = Item.objects.get(slug=self.kwargs["slug"]) form.save() return redirect("auction:buyerhome") return super().form_valid(form) form.py class BidOnProduct(forms.ModelForm): class Meta: model = Bid fields = ["price"] Model.py class Bid(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) item = models.ForeignKey(Item, on_delete=models.CASCADE) price = models.IntegerField() biding_time = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.user.username htmlcode {% if request.user.buyer %} <form class="form-horizontal" action="" method="post""> {% csrf_token %} {{form.as_p}} <button class=" btn btn-info"> Add product</button> </form> {%endif%} this is the error These are the line -
Problem in Setting backend data into dropdown using Django
I have a backend data and successfully set the data into dropdown but the thing is whenever click on button then it will give me the desire result but the thing is after getting the result, the drop down is like having null values in it so what can i do. could someone suggest me whenever i click on dropdown then it will get refress or other methods are appreciable. Thanks! views.py def index(request): sparqlQueries = get_data() if(request.POST['Case_name'] and request.method =='POST'): name_cases = sparqlQueries.nameOfCases() data = { "cases_name":name_cases, 'flag2':True, 'suffix':'Cases', 'title':'Name of Cases' } return render(request,'index.html',context = data) if(request.method =='POST'): casename = request.POST['Case_name'] question = request.POST['Question'] #print(casename) #print(question) ... -
How to pass a value to a Bootstrap modal in Django
I'm trying to implement a feature where I get to change a product by passing its id to a modal and change it there, then reflect the changes in the same page, where the user can click on the product name, a modal page appears with the product name and a list of products, then he can change the product from the list of products, click save changes, the modal page closes, and the product is now updated. The problem is that I was facing difficulty in passing the product id to the modal div that exist in the same template, but couldn't figure it out, then I saw Martín De la Fuente's approach and tried it, but it didn't work with me as well. It shows me this error message: django.urls.exceptions.NoReverseMatch: Reverse for 'products_modal' not found. 'products_modal' is not a valid view function or pattern name. My code is as the following: In product template: Sending product id to the product_modal template: <td> <a href="#" class="open-modal" data-url="{% url 'products_modal' product.id %}"><span>{{product.name}}</span></a> </td> Creating an empty div to insert the product_modal in it: <div id="product-modal-div"></div> Javascript part: <script> var productModalDiv=$("#product-modal-div") $(".open-modal").on("click",function(){ $.ajax({ url:$(this).attr("data-url"), success:function(data){ productModalDiv.html(data); $("#ProductModal").modal(); } }) }) </script> … -
Reverse for 'Tools' with no arguments not found. 1 pattern(s) tried: ['home/(?P<category>[^/]+)\\Z']
Based on an answer to my previous question here This is my html code: <a href="{% url 'Tools' %}"><p>Tools</p></a> When I used category like this def home( request,category) in my views, I got a positional argument error so I used this : def home( request,**kwargs ): p=product.objects.filter(category__name= category) return render(request,'home.html',{'p':p}) This is URLs: urlpatterns = [ path('',views.home), path('home/<str:category>', views.home,name='Tools'), ] But after going to this URL http://127.0.0.1:8000/home/Tools I got this error : NoReverseMatch at /home/Tools Reverse for 'Tools' with no arguments not found. 1 pattern(s) tried: ['home/(?P<category>[^/]+)\\Z'] Why do I get this error? Or how can I solve this error home() missing 1 required positional argument: 'category' if I want to use this : def home( request,category)?