Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to store conditional statement variable in django model?
i am trying to store manage_quota and govt_quota to my model choice_filling but the error says that above named variables are not defined. how do i store those values in database? here is my views.py def seat_info(request): global manage_quota, govt_quota if request.method == "POST": institute_code = request.POST['institute_code'] seats = request.POST['seates'] # s75 = int(seats) * 75 / 100 s25 = int(seats) * (25 / 100) # s25 = int(float(seats) * (25.0 / 100.0)) print("25% is ", s25) mq = request.POST['manage_quota'] mq15 = int(float(s25) * (15.0 / 100.0)) print("15% is ", mq15) # mq = float(mq) / 15.0 if float(mq) <= mq15: manage_quota = int(s25 * float(mq)) gov = request.POST['govt_quota'] gov10 = int(float(s25) * (10.0 / 100.0)) # gov = float(gov) / 10.0 if float(gov) <= gov10: govt_quota = int(s25 * float(gov)) clg_id = request.POST['clg_id'] fees = request.POST['fees'] course = request.POST['course'] s = seat_metrix(clg_id_id=clg_id, code=institute_code, total_seats=seats, course_id=course, govt_quota=govt_quota, manage_quota=manage_quota, fees=fees) s.save() return redirect('college-dashboard') strm = streams.objects.all() title = "Seat Information" page = "Seat Registration" return render(request, 'seat_info.html', {'strm': strm, 'title': title, 'page': page}) And the error traceback Traceback (most recent call last): File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Dell\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) … -
I want to put html tag in password_reset_email.html but it doesn't render. How can I render it?
I want to put html tag in password_reset_email.html but it doesn't render. How can I render it? Django version is 1.4 There is no content in the document, is there any way? https://django-doc-test-kor.readthedocs.io/en/old_master/topics/auth.html -
How to Implement Cascading Dependent Drop Down List using Foreign Key Relationship in Django Admin GUI
Can anyone please provide me the resource or idea for the implementation of Cascading Dependent Drop Down List in Django Admin GUI. I don't want to create a new custom html page, I want to use the existing Admin GUI only. I've tried many things in the ModelForm and Model, but with not success. I have 4 tables: Person, Country, State and City. What I want to do is: In the New/Edit Admin Person GUI page, select the country, next select the state and at the end, select the city. Actually in the New/Edit Admin Person page I have only the city. My Actual database relationship: Country ----- State ---- City ----- Person -
I am receiving an error when try render template in django
I created a template.html from the pandas data frame em saved it to render in my HTML file. So, when I try to render it I receive an error: File "c:\users\eric2\appdata\local\programs\python\python37\lib\codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xed in position 347: invalid continuation byte The complete output is: Internal Server Error: /analise Traceback (most recent call last): File "D:\Projetos Dev\.venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\Projetos Dev\.venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\Projetos Dev\.venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Projetos Dev\analise\views.py", line 100, in analise return result(request) File "D:\Projetos Dev\analise\views.py", line 23, in result return render(request, 'result.html') File "D:\Projetos Dev\.venv\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "D:\Projetos Dev\.venv\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "D:\Projetos Dev\.venv\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "D:\Projetos Dev\.venv\lib\site-packages\django\template\base.py", line 171, in render return self._render(context) File "D:\Projetos Dev\.venv\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "D:\Projetos Dev\.venv\lib\site-packages\django\template\base.py", line 936, in render bit = node.render_annotated(context) File "D:\Projetos Dev\.venv\lib\site-packages\django\template\base.py", line 903, in render_annotated return self.render(context) File "D:\Projetos Dev\.venv\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "D:\Projetos Dev\.venv\lib\site-packages\django\template\base.py", … -
running migrations as a part of an MS Azure app service release pipeline for a Django web app
I am wondering if anybody has experience with integrating a python manage.py migrate command into a MS Azure release pipeline. The app is being deployed using CI/CD pipeline through DevOps. In the release pipeline portion, the app is being deployed to three different stages (dev, test and prod). I have not been successful in being able to integrate the migrate command into the deployment process. I have tried achieving this by using a post deployment inline script: /antenv/bin/python /home/site/wwwroot/manage.py collectstatic /antenv/bin/python /home/site/wwwroot/manage.py migrate If I run the above commands in the sandbox environment via SSH they are carried out successfully. However, including them in the release pipeline as a post deployment script raises the following error: 2020-03-22T19:00:32.8641689Z Standard error from script: 2020-03-22T19:00:32.8727872Z ##[error]/home/site/VSTS_PostDeployment_1321584903618191/kuduPostDeploymentScript.sh: 1: /home/site/VSTS_PostDeployment_1321584903618191/kuduPostDeploymentScript.sh: /antenv/bin/python: not found /home/site/VSTS_PostDeployment_1321584903618191/kuduPostDeploymentScript.sh: 2: /home/site/VSTS_PostDeployment_1321584903618191/kuduPostDeploymentScript.sh: /antenv/bin/python: not found 2020-03-22T19:01:34.3372528Z ##[error]Error: Unable to run the script on Kudu Service. Error: Error: Executed script returned '127' as return code. Error: /home/site/VSTS_PostDeployment_1321584903618191/kuduPostDeploymentScript.sh: 1: /home/site/VSTS_PostDeployment_1321584903618191/kuduPostDeploymentScript.sh: /antenv/bin/python: not found /home/site/VSTS_PostDeployment_1321584903618191/kuduPostDeploymentScript.sh: 2: /home/site/VSTS_PostDeployment_1321584903618191/kuduPostDeploymentScript.sh: /antenv/bin/python: not found Any ideas or suggestions would be very much appreciated! Thanks in advance. -
Filtering output of foreign key data
Since i am making a online futsal booking system, i am currently doing timeslot validation. If a timeslot is already booked, the user should not be able to book that timeslot again. models.py class futsals(models.Model): futsal_name = models.CharField(max_length=20) futsal_address = models.CharField(max_length=40) owner_email = models.EmailField(max_length=25) owner_name = models.CharField(max_length=25) def __str__(self): return f'{self.futsal_name}' class timeslot(models.Model): timesslot = models.CharField(max_length=15) name = models.CharField(max_length=15) def __str__(self): return f'{self.timesslot}' class Booking(models.Model): user_book = models.ForeignKey(User, on_delete=models.CASCADE) futsal = models.ForeignKey(futsals, on_delete=models.CASCADE) time_slot = models.ForeignKey(timeslot, on_delete=models.CASCADE) def validate_date(date): if date < timezone.now().date(): raise ValidationError("Date cannot be in the past") booking_date = models.DateField( default=None, validators=[validate_date]) def __str__(self): return f'{self.user_book}' forms.py def timeslot_validation(value): v = Booking.objects.all().values_list('time_slot') k = timeslot.objects.filter(pk__in=v) if value == k: raise forms.ValidationError("This timeslot is already booked!!") else: return value But i am not able to do the validation. Since the output of variable 'k' looks like: , , ]> the above shown timeslot are the timeslot booked by users. Now if another user enters this timeslot, it should show 'this timeslot is already booked.' now, i want this data to be shown as [(19:00 - 20:00), (18:00 - 19:00), (17:00 - 18:00)] any help would be appreciated. or if anyone could provide me a better solution for validation????? -
Method Not Allowed POST 405
I am trying to add a post to my website inDjango using Ajax. However, whenever, I click on the post button I get the error: 'Method Not Allowed: /home/ "POST /home/ HTTP/1.1" 405 0 I do not know what is causing the issue I have never seen it before. These are my views for creating a post and viewing them. @login_required def home(request): posts = Post.objects.all() context = {'posts':posts} return render(request, 'home/home.html', context) class PostListView(LoginRequiredMixin,ListView): model = Post #redirect_field_name = template_name = 'home/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] @login_required def post_create(request): data = dict() if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): form.save() data['form_is_valid'] = True posts = Post.objects.all() data['posts'] = render_to_string('home/home_post.html',{'posts':posts}) else: data['form_is_valid'] = False else: form = PostForm context = { 'form':form } data['html_form'] = render_to_string('home/post_create.html',context,request=request) return JsonResponse(data) These are my urls at home/urls.py: urlpatterns = [ path('',views.PostListView.as_view(), name='home'), path('post/<int:pk>/', views.post_detail, name='post-detail'), path('<int:pk>/like/', views.PostLikeToggle.as_view(), name='like-toggle'), path('api/<int:pk>/like/', views.PostLikeAPIToggle.as_view(), name='like-api-toggle'), path('post/<int:id>/update/', views.post_update, name='post-update'), path('post/<int:id>/delete/', views.post_delete, name='post-delete'), path('post/create/', views.post_create, name='post-create'), ] this is my post_create.html: {% load crispy_forms_tags %} <form method="POST" data-url="{% url 'home:post-create' %}" class="post-create-form"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" >Create a Post</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> … -
Django add custom search function with empty search_fields tuples
I have the following get_search_results within my ModelAdmin to search by user phone number and email: def get_search_results(self, request, queryset, search_term): queryset, use_distinct = super().get_search_results(request, queryset, search_term) try: search_string = str(search_term) users = User.objects.filter(Q(email__icontains=search_string) | Q(phone_number__icontains=search_string)) user_id_list = [int(user.pk) for user in users] queryset |= self.model.objects.filter(user__in=user_id_list) except Exception as e: pass So these search_term won't exist in my model column therefor i won't need model columns in the search_fields. But if i set my search_fields = () then it won't show the search box in the listing page. Are there anyway i can add search box to the list page without specify any columns from the model ? -
Looking in links: /usr/share/pip-wheels
I was using a virtualenv in Pythonanywhere and now after cloning my repo I tried to install all the packages by using this command pip install -r packageName/requrirements.txt What is get is this Looking in links: /usr/share/pip-wheels I don't know about pip a lot.So please tell me what this eror means and how can i fix it with examples!Thank you in advance. -
Django: Default ImageField Return
I have a Django ImageField with djangorestframework, and I want it to return a default image if it's none. How can I return an image from my staticfiles to replace this? class MyModel(models.Model): image = models.ImageField() ... def get_image(self): """ Returns an image, or the default image. """ if not self.image: # what goes here? <--- return self.image -
virtualenv: error: the following arguments are required: dest
enter image description here I can't install and configure virtual environment on python3 on my macbook pro. I was trying to install and try django for my next project but here problemts started arising. -
can we change the name of manage.py file in django?
In Django framework I need to rename manage.py file for the security reasons on production environment. I do not have any idea about this. could someone help me out for the same -
django.core.exceptions.FieldError: Unknown field(s) (datetime) specified for Class
So I have a class named InputArticle, and have a field named 'created' and 'modified.' Below is my code in models.py from django.db import models from django.contrib.auth.models import User from django.forms import ModelForm from django.utils import timezone class InputArticle(models.Model) ''' other fields ''' created = models.DateTimeField(editable=False) modified = models.DateTimeField() def save(self, *args, **kwargs): if not self.created: self.created = timezone.now() self.modified = timezone.now() return super(InputArticle, self).save(*args, **kwargs) However when I try to do python manage.py makemigrations I keep getting this error that says: django.core.exceptions.FieldError: Unknown field(s) (datetime) specified for InputArticle I have no idea on what the problem is. I very much appreciate your help :) -
Python Django request.GET.get method for urls with if statements
I'd want to filter the posts by its two different categories which are schools and category. models.py class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class School(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True) class Meta: ordering = ('name',) verbose_name = 'school' verbose_name_plural = 'schools' def __str__(self): return self.name class VideoPost(models.Model): category = models.ForeignKey('Category', on_delete=models.CASCADE) school = models.ForeignKey('School', on_delete=models.CASCADE) title = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique = True) author = models.ForeignKey(User, on_delete=models.CASCADE) video = models.CharField(max_length=100, blank=True) content = RichTextUploadingField() image = models.ImageField(upload_to='images', null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) def _get_unique_slug(self, *args, **kwargs): self.slug = slugify(self.title) super(VideoPost, self).save(*args, **kwargs) def __unicode__(self): return self.title School and Category are the foreignKeys for VideoPost, so in the db, it would only have its ids, not the slug or name. whcih are category_id & school_id views.py def post_list(request): school = request.GET.get('school', None) category = request.GET.get('category', None) posts = VideoPost.objects.all() if school: posts.filter(school=school).order_by('-date_posted') elif category: posts.filter(category=category).order_by('-date_posted') elif school & category: posts.filter(school=school).filter(category=category).order_by('-date_posted') else: posts.order_by('-date_posted') ## I wanted to filter them in multiple ways where the posts are filtered by either one of the category, or both. but It doesn't work. ## The … -
accessing javascript outside of django project
I have become the owner of an older webapp that uses django and esri/jsapi3.28. I am trying to reconstruct it in development environment. It works in production using apache2 with document root at the 'webapp' directory. I would like to create a development environment w/o apache2 and instead use django's runserver. But when trying to test in development using runserver, it cannot find the 'my_ext_js' directory. I believe this is because the document root is different? It appears I cannot change the document root. This is the webapp structure. webapp my_ext_js start.js django_app myapp django_app Again, in production, we run apache2 with mod_wsgi and document root is webapp. When running in development, I start runserver in django_app directory django_app> python manage.py runserver how can I run this using runserver in development and have it recognize/see the 'my_ext_js' folder? The production code does not have the 'my_ext_js' in a static folder. The html script just calls: <script src="/my_ext_js/start.js"></script> Any help would be great! Thanks! -
Starting a Django Docker project and getting error: ERROR: build path app/app either does not exist, is not accessible, or is not a valid URL
I'm using a Docker Django quick start tutorial. My dockerfile: FROM python:3.7.0-alpine WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip COPY ./requirements.txt /usr/src/app/requirements.txt RUN pip install -r requirements.txt COPY . /usr/src/app/ My docker-compose: version: '3.7' services: web: build: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8000:8000 env_file: - ./.env.dev The problem When trying to run the following command: docker-compose build I receive the following error: ERROR: build path /Users/defaultuser/Documents/dev/simple_product_inventory/app/app either does not exist, is not accessible, or is not a valid URL. Could somebody point me in the right direction as to whats going wrong? -
Mix data and schema migrations in one migrations file (Django)?
I've heard the opinion that mix data migration and structure migrations is bad practice in Django. Even if you are specify atomic=False in your Migration class. But i could not find any information on this topic. Even my more expirience collegues could not answer this question. So, is it bad to mix data and structure migrations? If so why? What exactly may happen if i do it? -
Setting verbose name of function field in Django
I have a simple Model like this: class Artist(models.Model): class Meta: verbose_name = "Artist" verbose_name_plural = "Artists" name = models.CharField(max_length=128, unique=True, blank=False) def test_function(self): return 'xyz' And Admin: class ArtistAdmin(admin.ModelAdmin): list_display = ['name', 'test_function'] search_fields = ['name'] readonly_fields = [] Now in the list view, the function field is verbosed as test_function: In a normal field I would use the Field.verbose_name parameter. How do I achieve that with the function field? -
Import CSV file with django
1.Summarize the problem I am importing a csv file with django. Only the fist line seems to be imported in my database. Here is the code inside myview. views.py def upload_csv(request): chantiers = Chantier.objects.all() data = {} if "GET" == request.method: return render(request, "chantiers/upload_csv.html", data) # if not GET, then proceed try: csv_file = request.FILES["csv_file"] if not csv_file.name.endswith('.csv'): messages.error(request,'File is not CSV type') return HttpResponseRedirect(reverse("chantiers:upload_csv")) #if file is too large, return if csv_file.multiple_chunks(): messages.error(request,"Uploaded file is too big (%.2f MB)." % (csv_file.size/(1000*1000),)) return HttpResponseRedirect(reverse("chantiers:upload_csv")) file_data = csv_file.read().decode("utf-8") print("1") lines = file_data.split("\n") #loop over the lines and save them in db. If error , store as string and then display for line in lines: line = line.strip() if not line or line.startswith("#"): continue print(line) # following line may not be used, as line is a String, just access as an array #b = line.split() print(line[0]) fields = line.split(",") data_dict = {} data_dict["name"] = fields[0] data_dict["addresse"] = fields[1] data_dict["postcode"] = fields[2] data_dict["city"] = fields[3] print("3") try: form = ChantierForm(data_dict) if form.is_valid(): form.save() print("form saved") return render(request, 'chantiers/index_table.html', {'chantiers': chantiers}) else: print(form.errors.as_json()) logging.getLogger("error_logger").error(form.errors.as_json()) except Exception as e: print(e) logging.getLogger("error_logger").error(repr(e)) pass except Exception as e: print(e) logging.getLogger("error_logger").error("Unable to upload file. "+repr(e)) messages.error(request,"Unable to upload … -
Django Include ManyToManyField on "other" model in ModelForm
I would like to have a form with the preselected checkboxes of a ManyToManyField. models.py class Store(models.Model): ... class Brand(models.Model): stores = models.ManyToManyField(Store, blank=True, related_name="brands") forms.py class StoreForm(ModelForm): class Meta: model = Store fields = ('brands',) I get this exception: django.core.exceptions.FieldError: Unknown field(s) (brands) specified for Store How is it possible to include the ManyToMany field from "the other side" of the model (from Store)? -
Django 3.0 Admin Change Page Not Displaying Selected Option Correctly
I am running Django 3.0 and using Chrome Version 80.0.3987.132 (Official Build) (64-bit) and Firefox version 74 (64-bit). I have a select box on an admin change page for a model, and the correct value from the database is shown this way on the html source page generated by django: <option value="228">Frank</option> <option value="8" selected>Sam</option> <option value="19">Henry</option> However, the page is displayed in both browsers, Chrome and Firefox, with the default value "Pick one of the people", as if nothing has been selected. If I select another value from the drop down list, it is correctly inserted into the database, but the html on the admin change page still does not have selected="selected" in the correct option, but just the word 'selected' as shown above. I was looking online at the correct way to select an option in an option list, and it seems the correct (X)HTML way is to use selected="selected" in the option tag. Why is Django generating the old HTML way with just the word 'selected' in the option tag? Is there a way to fix this, or is this a bug in django or my browsers? I am not using any javascript or css on this … -
Django: redirect to view where login was called
I have a very common problem - after login I want to redirect to the page where login was called. I can describe situation exactly like here: Django: Redirect to previous page after login There are 2 options where you can log in - from the home page (which is defined in base.html) and from bokeh.html (other views inherit from bokeh) my base.html and bokeh.html have the same block to redirect to login. Difference is, that login called from home page should return to home page and from other page should return to page where was called. <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Login</a> </li> my login.html <form method="POST"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control" placeholder="Enter Username" name="username" required> </div> <div class="form-group"> <input type="password" class="form-control" placeholder="Enter Password" name="password" required> </div> <div class="form-group"> <button type="submit" class="btn btn-dark">Login</button> </div> </form> and views.py def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user) return redirect('home') else: messages.info(request,'Invalid credentials') return redirect('login') else: return render(request,'login.html') I was trying to add next to my form in login.html but it didn't work. While accessing to login from page other than home page it … -
Swift 5 How to save UIImagePickerController edited image and upload to Django Rest Framework
Within my Swift app I am attempting to upload the selected image from UIImagePickerController to my Django Rest Framework backend. The problem: (Of many) Resource used: https://www.hackingwithswift.com/read/10/4/importing-photos-with-uiimagepickercontroller I have a "Change Image" button that brings up the image picker when the button is selected and the didFinishPickingMediaWithInfo handles generating the UUID for the photo's name, sets the image to the UIImageView on the storyboard and writes to the documents directory. However, I cannot upload the selected (now saved) image by its name or url. I've confirmed that I am able to upload images using Postman's form-data for Content-Type so I'm leaning more towards the Swift side being wrong. When printing to confirm paths: I receive the following imageName:::> testios1-a56078dc9bd749e98ebf095b94e9e3fc-606600911 jpegData:::> 1088255 bytes imagePath:::> file:///Users/testios1/Library/Developer/CoreSimulator/Devices/EE4E4C59-52FD-4ACB-9024-F2A3ACD3F794/data/Containers/Data/Application/E5BB861E-E3C9-47C7-8897-CD5535B259C6/Documents/testios1-a56078dc9bd749e98ebf095b94e9e3fc-606600911 imagePathExtension:::> imagePathAbsoluteURL:::> file:///Users/testios1/Library/Developer/CoreSimulator/Devices/EE4E4C59-52FD-4ACB-9024-F2A3ACD3F794/data/Containers/Data/Application/E5BB861E-E3C9-47C7-8897-CD5535B259C6/Documents/testios1-a56078dc9bd749e98ebf095b94e9e3fc-606600911 imagePathAbsoluteString:::> file:///Users/testios1/Library/Developer/CoreSimulator/Devices/EE4E4C59-52FD-4ACB-9024-F2A3ACD3F794/data/Containers/Data/Application/E5BB861E-E3C9-47C7-8897-CD5535B259C6/Documents/testios1-a56078dc9bd749e98ebf095b94e9e3fc-606600911 imagePathTestFileIsURL:::> true IBAction @IBAction func changeProfileImageButtonDidTouch(_ sender: Any) { let picker = UIImagePickerController() picker.allowsEditing = true picker.delegate = self picker.sourceType = .photoLibrary present(picker, animated: true, completion: nil) } didFinishPickingMediaWithInfo func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { // UserDefaults guard let username = UserDefaults.standard.string(forKey: "username") else { return } // Generate UUID var uuid = UUID().uuidString uuid = uuid.replacingOccurrences(of: "-", with: "") uuid = uuid.map { $0.lowercased() }.joined() // … -
DRF: How to get view to accept json with a list of dictionaries?
I'm using the APIClient to test my views. resp__1 = self.client.post(reverse('templates'), data=dict(data)) dict(data) shows the following: { "t_stops": [ { "address__pk": 1, "stop_num": 1 }, { "address__pk": 2, "stop_num": 2 } ], "customer__pk": 1 } What I don't want is for all my values in the JSON to be a list. Example would be my customer__pk value showing as [1]. When I do print(request.POST) in one of my views it shows the following: <QueryDict: {'t_stops': ["{'address__pk': 1, 'stop_num': 1}", "{'address__pk': 2, 'stop_num': 2}"], 'customer__pk': ['1']}> What's the proper way of getting these values to show correctly in Django rest? -
Django : How to build create view using forms and querysets?
I'm trying to create reservation create view that allows to break down the reservation process into 3 stages for handling all the database queries and displaying relevant choices accordingly to linkage between models (Personnel Profile has many to many key on Service) 1st stage - allows user to select service 2nd stage - displays available staff members (PersonnelProfile) who are handling this service 3rd stage - displays all the free dates / times based on staff member schedule / existing reservations, POST creates the reservation I got stuck at the 2nd stage as my form doesn't validate. I would appreciate any advise how to overcome this issue or how to handle the idea differently. Sorry for the long post :) Service class Service(models.Model): name = models.CharField(max_length=100) description = models.TextField() price = models.IntegerField() duration = models.IntegerField() def __str__(self): return self.name PersonnelProfile class PersonnelProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateField(default=None, null=True) address = models.CharField(max_length=200) services = models.ManyToManyField(Service) image = models.ImageField(default='profile_pics/default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.first_name} {self.user.last_name}' Schedule Model class Schedule(models.Model): user = models.OneToOneField(PersonnelProfile, on_delete=models.CASCADE) availability_days = models.ManyToManyField(WorkDay) start_hour = models.TimeField() end_hour = models.TimeField() def __str__(self): return f'Schedule of {self.user.user.first_name} {self.user.user.last_name}' WorkDay Model class WorkDay(models.Model): day_choices = [(str(i), calendar.day_name[i]) for i in …