Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot resolve keyword 'vuelos' into field. Choices are: id, persona, persona_id, vuelo
So i've been trying to do de CS50 airport app. When i try to exclude by the related_name it seems that takes "vuelos" as a field. Im not sure what can i do. This is apparently in the non_pasajeros=Pasajero.objects.exclude(vuelos=vuelo).all() line on views.py, while i'm trying to exclude vuelos as the Pasajero related_name, the error says there is not vuelos keyword on the field. this is models.py from django.db import models from django.db.models.deletion import CASCADE from django.db.models.fields import BLANK_CHOICE_DASH # Create your models here. class Aeropuerto(models.Model): codigo = models.CharField(max_length=3) ciudad = models.CharField(max_length=64) def __str__(self): return f"{self.codigo} - {self.ciudad}" class Persona(models.Model): nombres = models.CharField(max_length=64) apellidos = models.CharField(max_length=64) def __str__(self): return f"{self.nombres} {self.apellidos}" class Vuelo(models.Model): origen = models.ForeignKey(Aeropuerto, on_delete=models.CASCADE, related_name="salidas") destino = models.ForeignKey(Aeropuerto, on_delete=models.CASCADE, related_name="llegadas") duracion = models.IntegerField() def __str__(self): return f"{self.id}: {self.origen} a {self.destino}" class Pasajero(models.Model): persona = models.ForeignKey(Persona, on_delete=CASCADE, related_name="vuelos") vuelo = models.ManyToManyField(Vuelo, blank=True, related_name="pasajeros") def __str__(self): return f"{self.persona}" this is views.py from django.http.response import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .models import Persona, Vuelo, Pasajero # Create your views here. def index(request): return render(request, "vuelos/index.html", { "vuelos": Vuelo.objects.all() }) def pasajeros(request): return render(request, "pasajeros/pasajeros.html", { "pasajeros":Pasajero.objects.all() }) def vuelos(request, vuelo_id): vuelo=Vuelo.objects.get(id=vuelo_id) pasajeros=vuelo.pasajeros.all() non_pasajeros=Pasajero.objects.exclude(vuelos=vuelo).all() return render(request, "vuelos/vuelos.html", … -
Can I only return data only if front-end webapp calls django app?
I have a Django app that "wraps" my Flickr API. The point of the wrapper is to hide the API key. views.py: ... def flickrApiGetPhotoSet(request): flickr_user_id = get_secret('flickr_user_id') flickr_photoset_id = get_secret('flickr_photoset_id') flickr_api_key = get_secret('flickr_api_key') response = requests.get('https://api.flickr.com/services/rest/?', params = { 'method': 'flickr.photosets.getPhotos', 'user_id': flickr_user_id, 'photoset_id': flickr_photoset_id, 'api_key': flickr_api_key, 'format': 'json', 'nojsoncallback': 1, 'extras': 'date_upload' } ) return HttpResponse(response, content_type='application/json') While is Api-key is not exposed, the response is freely viewable in a browser. e.g. mywebsite_domain.com/wrapper/flickrApiGetPhotoSet/ The 2 of the 3 pieces of data I was trying to hide (flickr_user_id, flickr_photoset_id) are exposed. I have these values in my settings.py: ALLOWED_HOSTS = ['localhost', '127.0.0.1','.mywebsite_domain.com','192.168.1.82'] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost', 'https://www.mywebsite_domain.com', ) On the front-end I'm using Axios to call the API: mywebsite_domain.com/wrapper/flickrApiGetPhotoSet/ Ideally, I'd like to only allow Axios to get the 'wrapped' response and get an error in the browser. I'm not sure if there's something I need to update in (1) the Django API or (2) my 'wrapper' app or (3) something else. Thanks in advance! Larry -
save() prohibited to prevent data loss due to unsaved related object 'order'. in django
i want to save a list of item in model with the help of form but when i click to save instead of saving it throws me the above mentoined error any idea what causing the problem here is my views.py class Checkout(View): def post (self, request,): user = request.user address = Address.objects.filter(default=True, user=request.user) cart = request.session.get('cart') items = Item.get_items_by_id(list(cart.keys())) prefer = request.POST.get('payment') total_price = request.POST.get('paying_price') total_price = json.loads(total_price) with transaction.atomic(): order = Order.objects.create( user=user, total_price=total_price, address=address.first(), method = prefer, ) for item in items: item_order = OrderItem.objects.create( order=order, item=item, size=cart.get(str(item.id)), price=item.price, ) request.session['cart'] = {} return redirect('orders:cart',) any suggestion and help will be appreciated -
django-tables2 modifying content of multiple columns
I know that the render_FOO function in django-tables2 allows us to modify the data of a single column called FOO, but is there any way we can apply the same modification to multiple columns? -
Flagging a django model instance during save for later processing
I'm running into a problem with using a flag to mark model instances for future processing. I have a class: class MyModel(models.Model): processed = models.BooleanField(default=False) changed = models.DateTimeField(auto_now=True) # More fields. def save(self): self.processed = False super().save(*args, **kwargs) Then I have a management command: class Command(BaseCommand): def handle(self, *args: Any, **kwargs: Any) -> None: models = MyModel.objects.filter(processed=False).order_by("changed")[:200] for model in models: # Do some processing model.processed = True model.save() Now, obviously when the model is saved, it's just going to re-mark the instance as unprocessed. I'm new to django, so my knowledge of the model lifecycle and the available methods is pretty limited. I've been reading through the documentation and haven't found any solution so far. Any ideas on how I could tackle this? -
How do i Get the first and second letter of a username in Django <div> {{Post.author.username.0} } </div>
I want to display images according to the user's first and second letter from the username instead of an image with rounded corners. But <div> {{Post.author.username.0} } </div> Returns only the first letter instead. Please help, how do I return 2 letters for example: Ahmed as Ah instead of A. -
Failed lookup for key - implementing pagination with elided_page
I am attempting to implement pagination with elided_page based on this blog post. My goal is to have pagination with only a few pages being showed and increase as a new page is viewed as I will eventually have over a hundred pages. view def home(request): page = request.GET.get('page', 1) paginator = Paginator(Post.objects.all(), 2) page_range = paginator.get_elided_page_range(number=page) context = { 'page_range':page_range, 'page':page, 'paginator':paginator} return render(request, 'blog/home.html', context) template <ul class="pagination justify-content-center flex-wrap mt-2 mb-4"> {% if page_obj.has_previous %} <li class="page-item"><a class="page-link" href="?page={{ page_obj.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled page-item"><span class="page-link">&laquo;</span></li> {% endif %} {% for i in page_range|default_if_none:page_obj.paginator.get_elided_page_range %} {% if page_obj.number == i %} <li class="active page-item"><span class="page-link">{{ i }} <span class="sr-only">(current)</span></span> </li> {% else %} {% if i == page_obj.paginator.ELLIPSIS %} <li class="page-item"><span class="page-link">{{ i }}</span></li> {% else %} <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endif %} {% endfor %} {% if page_obj.has_next %} <li class="page-item"><a class="page-link" href="?page={{ page_obj.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled page-item"><span class="page-link">&raquo;</span></li> {% endif %} However when i run this i get the error Failed lookup for key [page_obj] in [{'True': True, 'False': False, 'None': None}, {}, {}, {'page_range': <generator object Paginator.get_elided_page_range at 0x000001FB70D20E40>, 'page': '3', … -
Group objects not working in my detail view
I am trying to access the group object from detail view, but for one reason its not rendering the objects to my HTML template, in detail view, except the group name, but i want as well to be able to render the group cover image and group users. I would appreciate some help. Here is my detail view. def group_main(request, pk): context= {} group = get_object_or_404(Group,pk=pk) context['group'] = group return render(request,'group/grouptimeline.html',context) Here is the model class Group(models.Model): group = models.OneToOneField(Group, on_delete=models.CASCADE, related_name='groups') member = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="members" ) cover = models.ImageField(upload_to='group_cover') group_name = models.CharField(max_length=200, blank=True) description = models.TextField(max_length=500, blank=True) pic = models.ImageField(upload_to='path/post/img' ,blank=True) date_posted = models.DateTimeField(auto_now_add=True) This is part of my detail html template which only render the group name, but i can't access the group cover picture and users. <div class="main_content"> <div class="mcontainer"> <div class="profile is_group"> <div class="profiles_banner"> <img src="{{ group.name.cover.url }}" alt=""> </div> <div class="profiles_content"> <div class="profile_info"> <h1> {{ group.name }} </h1> <p> Public group · 12k members</p> </div> <div class="flex items-center space-x-4"> <div class="flex items-center -space-x-4"> <img src="assets/images/avatars/avatar-5.jpg" alt="" class="w-10 h-10 rounded-full border-2 border-white"> <img src="assets/images/avatars/avatar-6.jpg" alt="" class="w-10 h-10 rounded-full border-2 border-white"> <div class="w-10 h-10 rounded-full flex justify-center items-center bg-red-100 text-red-500 font-semibold"> 12+ </div> </div> <a href="#" … -
OperationalError - no such table: main.auth_user__old
So Im using pycharm and trying to learn django watching a few tutorials on youtube. Been following exactly how the instructors have been doing it but every time I try to create an instance of a model I created I get this error. I've seen the question with a few answers and I've tried 'python manage.py makemigrations' & 'python manage.py migrate' but im still getting no result. Error: OperationalError at /admin/products/product/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/products/product/add/ Django Version: 2.0.7 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: E:\Python\PythonWorkspace\Django_Unchained\venv\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 303 Python Executable: E:\Python\PythonWorkspace\Django_Unchained\venv\Scripts\python.exe Python Version: 3.9.6 Python Path: ['E:\\Python\\PythonWorkspace\\Django_Unchained', 'E:\\Python\\python39.zip', 'E:\\Python\\DLLs', 'E:\\Python\\lib', 'E:\\Python', 'E:\\Python\\PythonWorkspace\\Django_Unchained\\venv', 'E:\\Python\\PythonWorkspace\\Django_Unchained\\venv\\lib\\site-packages'] Server time: Fri, 13 Aug 2021 17:32:50 +0000 products.models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=50) desc = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() products.admin.py from django.contrib import admin from .models import Product admin.site.register(Product) django_unchained.settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'products' ] -
Django retrieve availability from Opening Hour and Booking Calendar
I am going through serious trouble in retrieving availability. I storing mentor calendar information in the following models. like when someone book his consultation, I store the date and time info like this. class Day(models.Model): user = models.ForeignKey( # tutor User, on_delete=models.CASCADE, related_name="day_slots" ) date = models.DateField() class Meta: unique_together = ('user', 'date',) class TimeSlot(models.Model): day = models.ForeignKey( Day, on_delete=models.CASCADE, related_name="time_slots" ) booking = models.OneToOneField( Booking, on_delete=models.CASCADE, related_name="time_slots", null=True, blank=True ) start = models.TimeField() end = models.TimeField() and also I have an opening hour for a mentor, like usually when he is available in the office for a consultation. it's similar to google my business. and the opening hour storing here: it means, in which week day in what time he is open to serve class Weeks(models.IntegerChoices): MONDAY = 1, _("Monday") TUESDAY = 2, _("Tuesday") WEDNESDAY = 3, _("Wednesday") THURSDAY = 4, _("Thursday") FRIDAY = 5, _("Friday") SATURDAY = 6, _("Saturday") SUNDAY = 7, _("Sunday") class WeekDay(models.Model): owner = models.ForeignKey( User, on_delete=models.CASCADE, related_name="weekday" ) weekday = models.IntegerField(choices=Weeks.choices) class OpeningHourTime(models.Model): weekday = models.ForeignKey( WeekDay, on_delete=models.CASCADE, related_name="opening_hour_time" ) from_hour = models.TimeField() to_hour = models.TimeField() Now the complexity here. When a candidate book a slot for consultation, it populates the Day and TimeSlot … -
AttributeError: Mixer (dashboard.ContactQueue): type object 'JSONField' has no attribute '_meta'
I am using mixer module to create test objects. Below is the model class. class ContactQueue(models.Model): arn = models.CharField(max_length=255) queue_id = models.CharField(max_length=50) queue_type = models.CharField(max_length=25) name = models.CharField(max_length=25, null=True) description = models.TextField(null=True) outbound_caller_config = models.JSONField() hours_of_operation_id = models.CharField(max_length=50) status = models.CharField( max_length=10, choices=( ('ENABLED', 'ENABLED'), ('DISABLED', 'DISABLED'), ) ) This is the test case that i have written. class TestContactQueue: def test_model(self): obj = mixer.blend("dashboard.ContactQueue") assert obj.pk == 1, "Should create a ContactQueue instance" While running the tests i got this error. __________________________________________________________________ TestContactQueue.test_model ___________________________________________________________________ self = <dashboard.tests.test_models.TestContactQueue object at 0x000002329C1C8548> def test_model(self): > obj = mixer.blend("dashboard.ContactQueue") dashboard\tests\test_models.py:21: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ..\venv\lib\site-packages\mixer\main.py:568: in blend return type_mixer.blend(**values) ..\venv\lib\site-packages\mixer\main.py:116: in blend for name, value in defaults.items() ..\venv\lib\site-packages\mixer\main.py:113: in <genexpr> value.gen_value(self, name, value) ..\venv\lib\site-packages\mixer\mix_types.py:229: in … -
how to pass data to backend in django from frontend when a checkbox item is checked but not submitted yet?
I need some guidance in implementing a functionality in django web-application, where I am performing elastic search on multiple pdfs. so in order to do that I have checkbox list of pdfs and user is supposed to select those pdf and then type "word" which he is looking for in those pdfs and then submit the form to perform elastic search. My question is, is it possible to run async methods in "views.py" which are executed when checkbox item is checked but the form is not submitted? These async methods convert those pdfs in to JSON. Once form is submitted it will use the "word" searched, the pdfs converted into a JSON, and then perform elastic search process and will return results. -
want to filter model objects by email, however filtering is not working in Django REST api
I have my API in Django REST Framework: Here is my models.py: class myModel(models.Model): user_email = models.CharField(max_length= 200, null= False) Here is my views.py: class GetItemsByEmail(generics.ListAPIView): def get_queryset(self): email_items = self.request.query_params.get("user_email") if(email_items is not None): itemsReturned = myModel.objects.all().filter(user_email = email_items) return Response(data= itemsReturned) Here is my urls.py: url_patterns = [ path('users/account=<str:id>/items', GetItemsByEmail.as_view()), ] My Question: I am getting an empty list, getting nothing from making an API call to the above endpoint. I want to get all the items in the database associated with a particular email, but the filter is not working ? What is the reason behind that ? -
Making input of a model field into a string [closed]
I want to make the input in a Charfield into a string so i can compare the string value to string values in a list. Does anyone know how to do this? -
Pycharm fails to create Django Application on Mac
Specs: macOS Big Sur 11.5.1 PcCharm 2021.2 (Pro Edition) Python 3.9 django 3.2.5 I've been using pycharm to write python code with no problems. Now I'm transitioning to learning Django. Initial Step: Create New Project Select Django from the left menu, New environment using: Virtualenv Location: /User/myname/Desktop/Project1 Base interpreter: /usr/bin/python3 Template languge: Django Template folder: templates Application name: myFirstProject Enable Django admin: Checked When I hit enter it starts creating Django, then I get the following error message. Create Django Application Error creating Django application: Error on Python Side. Exit code: 2, err:/usr/local/bin/bash: -c: line 1: unexpected EOF while looking for matching '"/usr/local/bin/bash: c: line 2: syntax error: unexpected end of file out: Then the okay button is displayed. I've tried deleting and reinstalling python, Django, Pycharm and even the bash app. None of this seems to have any affect on the result. I'm at my wits end. Any help would be greatly appreciated. When researching I only find Reference to "Exit code: 1". I find nothing about Exit code: 2 -
Django Using Variable in Filter within For Loop
I am trying to get the child object/field value using a parent object. The parent is a variable within a for loop and I can't seem to hand it into the custom tag. #custom_tags.py @register.simple_tag() def assigned_to(sample): #sample=sample.pk return Lab_Request.objects.filter(sample=sample).first().lab.lab_name @register.filter() def assigned_too(sample): #sample=sample.pk return Lab_Request.objects.filter(sample=sample).first().lab.lab_name #sample.html {% for sample in samples %} {% static sample.0|assigned_too %} {% if user.profile.employee.pk == sample.inspector.employee.pk or perms.ics.view_sample %} <tr> <td class="column1">{{ sample.sample_date }}</td> <td class="column2">{{ sample.status|sample_status_options }}</td> <td class="column3"><a href="#">{{ sample.sample_number }}</a></td> <td class="column4"><a href="#">{{ sample.order.customer.customer_name }}</a></td> <td class="column5"><a href="#">{{ sample.lab_request.placeholder_to_be_replaced }}{{ sample.lab_request.lab.lab_name }}{{ sample.inspection_request.inspector.employee.employee_first_name }}</a></td> <td class="column6">{{ sample.date_modified|date:'M. d, Y' }}</td> </tr> {% endif %} {% endfor %} {% static sample|assigned_too %} is the part I am struggling with. I have also tried to write a function and call it like {% assigned_to {{ sample }} %}. It does work if I use {% static 1|assigned_too %} but then it doesn't iterate with my loop like it needs to. I'm not sure if I am doing this this most complicated way possible. I just want information from a child of the parent such as {{ sample.lab_request.lab.lab_name }} where sample is a parent object and lab_request is a child model. EDIT: #views.py class … -
How to do a count based on the fields of a foreign key with Django queryset?
I have a Django model, called "Item" with a field "check" that FK's to a model "Check". The "Check" model has a field "is_checked". I want to get a count of the "Item"s where all the "Check"s have "is_checked" == True, and a count where it's False. How do I do this in one query? -
Django page not found when passing date
I'm building django app with django rest framework (DRF). I have model with DateField type and I want to query based on date in yyyy-mm-dd format for example http://127.0.0.1:8000/dataharian/2021-08-09/. I used the path converter as mentioned here with some adjustments so the URL able to accepts yyyy-mm-dd format. Here is the DataHarian model, DataHarian view, the converter, and the URL.py file DataHarian model: class DataHarian(models.Model): tanggal = models.DateField(blank=False, null=False) kumulatif = models.IntegerField(default=0) sembuh = models.IntegerField(default=0) dalam_perawatan = models.IntegerField(default=0) meninggal = models.IntegerField(default=0) def __str__(self): return str(self.tanggal) DataHarian view: class DataHarianDetail(generics.RetrieveAPIView): queryset = DataHarian.objects.all() serializer_class = DataHarianSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] Converter : from datetime import datetime class TanggalConverter: regex = '\d{4}-\d{2}-\d{2}' def to_python(self, value): return datetime.strptime(value, '%Y-%m-%d') def to_url(self, value): return value URL.py from django.urls import path, register_converter from datetime import datetime from . import views, converters register_converter(converters.TanggalConverter, 'yyyy-mm-dd') urlpatterns = [path('dataharian/<yyyy-mm-dd:tanggal>', views.DataHarianDetail.as_view()),] *Tanggal is date in Indonesian If my explanation isn't good enough, please give a feedback Thank you for your response -
Django admin Multiple dropdown for same FK based on certain rules
I'm trying to build a tagging system, where i have multiple tag types (Tags Category) and in each one 10-20 tags. Doing this by having Tags Categories table and Tags table, with relation to a certain category. In my main POSTS module, i have M2M FK to Tags table. In Admin, under Tags dropdown, i'm seeing ALL tags from All categories which is confusing to the user. Is there a way to show separate dropdown for each category, that will only show tags related to that category? -
How to configure LDAP authentication backend in Django?
I'm trying to configure LDAP authentication backend in Django, but it doesn't work for me. I followed the steps mentioned on the docs of django-auth-ldap library. My LDAP server is on Windows Server 2012 and I'm using two VMs. The first is my Windows Server 2012 and the second is a machine runing Ubuntu 20.04. I've installed all libraries on my Ubuntu machine, but Django can't loggin any user. I'm using Django 3.2.4 in this project. import ldap from django_auth_ldap.config import LDAPSearch, LDAPGroupQuery, GroupOfNamesType, PosixGroupType AUTH_LDAP_SERVER_URI = 'ldap://10.0.0.10' AUTH_LDAP_BIND_DN = 'cn=bind,dc=tech,dc=local' AUTH_LDAP_BIND_PASSWORD = '123@mudar' AUTH_LDAP_USER_SEARCH = LDAPSearch('dc=tech,dc=local', ldap.SCOPE_SUBTREE,'uid=%(user)s') AUTH_LDAP_GROUP_SEARCH = LDAPSearch('dc=tech,dc=local', ldap.SCOPE_SUBTREE,'(objectClass=top)') AUTH_LDAP_GROUP_TYPE = PosixGroupType(name_attr='cn') AUTH_LDAP_MIRROR_GROUPS = True AUTH_LDAP_REQUIRE_GROUP = "cn=enabled,ou=groups,dc=tech,dc=local" AUTH_LDAP_USER_ATTR_MAP = { 'first_name': 'givenName', 'last_name': 'sn', 'email': 'mail', 'username': 'uid', 'password': 'userPassword' } AUTH_LDAP_PROFILE_ATTR_MAP = { 'home_directory': 'homeDirectory' } AUTH_LDAP_USER_FLAGS_BY_GROUP = { 'is_active': 'cn=active,ou=groups,dc=tech,dc=local', 'is_staff': 'cn=staff,ou=groups,dc=tech,dc=local', 'is_superuser': 'cn=superuser,ou=groups,dc=tech,dc=local' } AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_TIMEOUT = 3600 AUTHENTICATION_BACKENDS = { 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.Modelbackend' } -
Django - paginate_by doesn't work correctly
can we help, why pagination doesn't work in this case? my search in controller: class PostSearchView(ListView): paginate_by = 5 model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] def get_context_data(self): inp_value = self.request.GET.get('search', '') context = super().get_context_data() objects = Post.objects.filter(title__icontains=inp_value).order_by('-date_posted') context['posts'] = objects context['inp_value'] = inp_value return context my form in view <form class="form-inline" method='GET' action="{% url 'blog-search' %}"> <input class="form-control mr-sm-2" type='text' name='search' value="{{ inp_value }}"> <button class="btn btn-outline-success my-2 my-sm-0" id="search_submit" type="Search" >Search</button> </form> i tried with get_queryset method, but when i push on second page button request results None and results all post which do not match the search query, now i use get_context_data, to return input search value again in form but pagination in this case doesn't work correctly def get_queryset(self): search_query = self.request.GET.get('search', '') return Post.objects.filter(title__icontains=search_query).order_by('-date_posted') -
This is the error i am getting while runnig this file
PS C:\Users\STECH\Documents\pro\env_myclub\project> python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\STECH\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\STECH\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\STECH\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autorel -
How to retrieve value from one class to another in Django
I have created a context in a TemplateView class, and I want to pass it into my FormView class to be rendered in my ModelForm, I have tried this way but it's showing an error, and since I'm new to Django I couldn't figure out how to do it. This is the FormView class that I want to pass the context value I got from TemplateView class: class CreatePatientPrescriptionFormView(FormView): template_name = 'MedCareApp/patientPrescription-form.html' def get_queryset(self): return Prescription.objects.get(id=self.kwargs.get('pk')) def get_context_data(self): return CategoryMedicinesTemplateView.get_context_data() form_class = PatientPrescriptionForm(medicine_choices=get_context_data()) def get_success_url(self): return '/' This is the TemplateView class that I want to pass its context value to the FormView class: class CategoryMedicinesTemplateView(TemplateView): template_name = 'MedCareApp/category_choices.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) random_user = User.objects.get(id=1) category_code = kwargs['category_code'] favMed = Medicine.objects.filter( favoritemedicine__favorite__user=random_user, category=category_code) favMedOptions = [] for med in favMed: option_name = "{} - {} - {} {} - {}".format( med.EN_name, med.EN_brand, med.dose, med.EN_doseUnit, med.EN_formula) favMedOptions.append((med.id, option_name)) allMed = Medicine.objects.filter(category=category_code) allMedOptions = [] for med in allMed: option_name = "{} - {} - {} {} - {}".format( med.EN_name, med.EN_brand, med.dose, med.EN_doseUnit, med.EN_formula) allMedOptions.append((med.id, option_name)) medicine_choices = ( ('Favorite Medicines', favMedOptions), ('Other Medicines', allMedOptions) ) context['medicines'] = medicine_choices return context -
how can os.listdir() fail in script but work in interactive interpreter when used on the same path?
During execution of django's manage.py migrate i get the error NotADirectoryError: [WinError 267] The directory name is invalid: followed by the correct path. When i Copy-Paste that path into an os.listdir call inside a python interactive session, it works perfectly fine. Background: I'm currently experimenting with django and basically following the tutorial (with minor changes like different names and such). I created a Project and App, checked/adjusted my settings, added the app to INSTALLED_APPS, created a model, ran "manage.py makemigrations" (and reviewed the result of "manage.py sqlmigrate ..." which worked) But then I tried to apply the changes by executing "manage.py migrate" which fails. The Path points to a mounted network share and is accessible normally via explorer, cmd/powershell or interactive python sessions. Console Output is: X:\django\Heizungsprotokoll>manage migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. Traceback (most recent call last): File "X:\django\Heizungsprotokoll\manage.py", line 22, in <module> main() File "X:\django\Heizungsprotokoll\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Programs\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Programs\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Programs\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Programs\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Programs\Python39\lib\site-packages\django\core\management\base.py", line 89, in … -
Json Django form and Storing key/value pairs?
I am having a bit of trouble with a custom Json form that I built, and how to iterate to store values from the form. I went with a json form, because down the road the form will be completely customizable (Legends/Labels and all) I have a simple model that stores the json form in a JSONField class House(models.Model): form = JSONField(default=dict) The form gets loaded from a json file "house_form.json" looking like... { "inside": [ { "field": "How many bedrooms?", "value": "" }, { "field": "How many floors?", "value": "" } ], "outside": [ { "field": "Pool?", "value": "" }, { "field": "Shed?", "value": "" } ] } form template looks like... <form method="post""> {% csrf_token %} {% for key, value in form_fields.items %} <div class="col-xs-12"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title"><i class="fa fa-fw fa-reorder"></i>{{key}}</h3> <div class="actions pull-right"> </div> </div> <div class="panel-body" class="panel-collapse collapse in"> {% csrf_token %} {% for val in value %} <div class="col-sm-6"><i class="fa fa-fw fa-reorder"></i><label name="{{ val.field }}">{{ val.field }} <input type="hidden" name="{{val.label}}" /></label></div> <div class="col-sm-6"> <div class="form-group"> <input type="text" name="value" class="form-control" value="{{ val.value }}"> </div> </div> {% endfor %} <div> </div> </div> </div> </div> {% endfor %} <button type="submit" class="btn btn-danger">Save</button> </form> My …