Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reducing size of Django JSON object through mapping
I have User and Post models, that broadly look like the following: class User(models.Model): # a bunch of fields class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # a bunch of fields When I query for some posts and then serialize them to JSON, if there are multiple posts from the same user, which usually happens, all the user's data ends up being repeated, as seen in the following very simplified example. [ { "user":{ ... }, ... }, { "user":{ ... }, ... }, { "user":{ ... }, ... }, { "user":{ ... }, ... } ] Is there any way to automatically create a dictionary, that will store separately all users, and have the posts reference that dictionary? It could, basically, look like this: { "users": [ { ... }, { ... } ], "posts":[ { "user": 0, ... }, { "user": 1, ... }, { "user": 1, ... }, { "user": 0, ... } ] } Where user would be the index of the user in the other -
Permission for object that share the same attribute
I am trying to create a permission that extend the "get_queryset" method to several Class based views. Let's say I have a two models, one call guestcard and one call notebook, they both share the same attribute which is properties so I would like to create a permission that apply to both of them. For example : class IsPropertyMember(object): def get_queryset(self): return Notebook.objects.filter(properties=self.request.user) Where notebook would be replace by a general object so I can use it in model which share the same attribute. I have some idea, maybe using getattr ? But I fail to see the logic in order to implement it. -
AttributeError: 'dict' object has no attribute 'headers'
Please help how to solve this problem. :( Views def chatbot_process(request): #INITIALIZATION CHATBOT lemmatizer = WordNetLemmatizer() intents = json.loads(open('chatbot/intents.json').read()) words = pickle.load(open('words.pkl', 'rb')) classes = pickle.load(open('classes.pkl', 'rb')) model = load_model('chatbotmodel.h5') # FUNCTION DEFINITION def clean_up_sentence(sentence): sentence_words = nltk.word_tokenize(sentence) sentence_words = [lemmatizer.lemmatize(word) for word in sentence_words] return sentence_words def bag_of_words(sentence): sentence_words = clean_up_sentence(sentence) bag = [0] * len(words) for w in sentence_words: for i, word in enumerate(words): if word == w: bag[i] = 1 return np.array(bag) def predict_class(sentence): bow = bag_of_words(sentence) res = model.predict(np.array([bow]))[0] ERROR_THRESHOLD = 0.25 results = [[i,r]for i, r in enumerate(res) if r > ERROR_THRESHOLD] results.sort(key = lambda x: x[1], reverse = True) return_list = [] for r in results: return_list.append({'intent': classes[r[0]], 'probability': str(r[1])}) return return_list def get_response(intents_list, intents_json): tag = intents_list[0]['intent'] list_of_intents = intents_json['intents'] for i in list_of_intents: if i ['tag'] == tag: result = random.choice(i['responses']) break return result # TAKING OF INPUT MESSAGES message = request.POST.get("input_text") ints = predict_class(str(message)) response = get_response(ints, intents) response2 = str(response) print("MESSAGE: ", ints) print("REPONSE: ", response2) context = { 'message': message, 'response': response } return context # return render(request, "chatbot/chatbot.html", context) # return HttpResponse(response) def chatbot(request): return render(request, "chatbot/chatbot.html") HTML {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta … -
using filter with django tables 2
So I am trying to add filter to django tables 2 using django filter and I can see the filters but it does not apply to table. What do I do from this point? Is it something with url or do I have to do something with function on TestView? views.py from django.shortcuts import render from django.views.generic import TemplateView from django_tables2 import SingleTableView import django_tables2 as tables from .models import Test from .tables import TestTable from .filters import TestFilter class TestView(LoginRequiredMixin, tables.SingleTableView): model = Test template_name = "/test_info.html" filterset_class = TestFilter def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = TestFilter(self.request.GET, queryset=self.get_queryset()) return context filters.py import django_filters from django_filters import DateFilter, CharFilter from .models import * class TestFilter(django_filters.FilterSet): class Meta: model = Test fields = { 'name': ['icontains'], } test_info.html {% extends "base.html" %} {% load render_table from django_tables2 %} {% load bootstrap4 %} {% block head_title %} Vendor Info {% endblock %} {% block header %}{% endblock %} {% block content %} <div class="container-fluid w-75 p-3"> <div class="card card-body"> <form method="get" class="form-inline"> {% bootstrap_form filter.form layout='inline' %} {% bootstrap_button 'filter' button_type='submit'%} <!-- <button class="btn btn-primary" type="submit">Search</button> --> </form> </div> <div class="row justify-content-sm-center table-responsive mt-4"> {% render_table table %} </div> </div> … -
Summernote editor not show any content on django admin page
I'm using summernote package in my django project. However, the editor is not showing any content. The body = TextField() is completely blank (the whole space is white) in the admin page as shown in the attached file. admin.py class postAdmin(SummernoteModelAdmin): summernote_fields = '__all__' admin.site.register(post, postAdmin) settings.py X_FRAME_OPTIONS = "SAMEORIGIN" models.py class post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) slug = models.SlugField() title = models.CharField(max_length=50) body = models.TextField() ... serializers.py class post_serializer(serializers.ModelSerializer): class Meta: model = post fields = '__all__' lookup_field = 'slug' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('summernote/',include('django_summernote.urls')), ... ] I saw similar question online but none of the approaches I saw worked for me. How do I make the textfield in the screenshot editatble? I'm not using bootstrap or css because I'm creating an api that will be consumed by a frontend react app. -
how to connect DJANGO app to AWS RDS connected to a bastion via SSH
Is there a way to connect Django to a private RDS connected to a bastion via SSH? My current AWS infrastructure has a EC2 Bastion in a public subnet and two private subnets where postgres RDS DB reside. DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "aaaa", "USER": "bbbb", "PASSWORD": "cccc", "HOST": "xxx.zzz.us-east-z.rds.amazonaws.com", "PORT": 5432, } } using the terminal i can ssh into the bastion and check the connection with RDS, OK. Now i want to connect Django settings above to RDS so: i connected my RDS to https://dbeaver.com/ software (result say: connected!) On Django side now when I edited the settings.py above with the AWS RDS credentials started django python manage.py runserver i receive the following error. django.db.utils.OperationalError: could not translate host name "xxx.zzz.us-east-z.rds.amazonaws.com" to address: nodename nor servname provided, or not known. Is there something that i am missing on the approach? -
To insert elements into the javascript input box
I am a student studying JavaScript. I want to put the checkValue value in the strong tag into the input box, but I don't know how to write JavaScript to get it into the input box. Do I need to find cart_table of div? Or should I find a strong tag? <script> $().ready(function() { $("#optionSelect").change(function() { var checkValue = $("#optionSelect").val(); var checkText = $("#optionSelect option:selected").text(); var product = $("#productname").text(); var price = parseInt($("#price").text()); var test = parseInt($(this).find(':selected').data('price')); var hapgae = price + test if (checkValue != "no") { var whtml = " <div class=\"cart_table\">\n" + " <hr style='width: 300px; margin-bottom: 30px;'>" + " <p style='font-size: 17px;'>" + product + "</p>" + " <p style='font-size: 13px; margin-top: -10px; class=\"check\" margin-bottom: 20px;'>" + checkText + "</p>" + " <strong class=\"value_code2\">" + checkValue + "</strong>\n" + " <input name=\"value_code\" id=\"value_code\" class=\"value_code\">" + Strong tags and input tags refer to this part. " <strong class=\"value_code2\">" + checkValue + "</strong>\n" + " <input name=\"value_code\" id=\"value_code\" class=\"value_code\">" + -
django += 1 increments by 2 instead of 1
models.py class ModFile(models.Model): mod = models.ForeignKey(Mod, on_delete=models.CASCADE) title = models.CharField(max_length=128) downloads = models.IntegerField(default=0) file = models.FileField(upload_to='mods/') views.py class downloadMod(APIView): def get(self, request, id): file = models.ModFile.objects.get(id=id) file.downloads += 1 file.save() return FileResponse(file.file) In views.py, the get() function retrieves the model by its id and should increment file.downloads by 1 but for some reason it increments by 2, what am I doing wrong? -
Adding new instances of model to database Django
I'm very new to Python and programming at all. I'v encountered quite weird problem. While creating and adding certain amount of new instances to database it generates some amount of additional instances. For example I'm passing parameter of 10 new instances to view function but it creates 10 plus 70 additional. Two examples of view function please find below. def generate_students(request): class CountForm(forms.Form): count = forms.IntegerField(min_value=1, max_value=100) form = CountForm(request.GET) if form.is_valid(): count = form.cleaned_data['count'] studentList = [] for _ in range(count): studentList.append(Student(first_name=f.first_name(), last_name=f.last_name(), age=random.randint(18, 100))) Student.objects.bulk_create(studentList) output = [ f"{student.id} {student.first_name} {student.last_name} {student.age};<br/>" for student in studentList] else: return HttpResponse(str(form.errors)) return HttpResponse(output) def generate_students(request): class CountForm(forms.Form): count = forms.IntegerField(min_value=1, max_value=100) form = CountForm(request.GET) if form.is_valid(): count = form.cleaned_data['count'] studentList = [ Student.objects.create(first_name=f.first_name(), last_name=f.last_name(), age=random.randint(18, 100)) for _ in range(count)] output = [ f"{student.id} {student.first_name} {student.last_name} {student.age};<br/>" for student in studentList] else: return HttpResponse(str(form.errors)) return HttpResponse(output) def generate_students(request): class CountForm(forms.Form): count = forms.IntegerField(min_value=1, max_value=100) form = CountForm(request.GET) if form.is_valid(): count = form.cleaned_data['count'] studentList = [] for _ in range(count): studentList.append(Student(first_name=f.first_name(), last_name=f.last_name(), age=random.randint(18, 100))) Student.objects.bulk_create(studentList) output = [ f"{student.id} {student.first_name} {student.last_name} {student.age};<br/>" for student in studentList] else: return HttpResponse(str(form.errors)) return HttpResponse(output) def generate_students(request): class CountForm(forms.Form): count = forms.IntegerField(min_value=1, max_value=100) form = … -
How to redirect HTTP to HTTPS in default.conf file with Nginx dockerized
I have a Django project already using AWS SSL certificate from Route53 service. My application is accessible via HTTPS, however, it isn't redirecting automatically when accessing via HTTP. My Nginx default.conf file before redirect (works like a charm!): upstream django { server my_app:8000; } server { location / { proxy_pass http://django; } } After setting up the redirect: upstream django { server my_app:8000; } server { listen 80; if ($http_x_forwarded_proto = 'http'){ return 301 https://$host$request_uri; } location / { proxy_pass http://django; proxy_set_header X-Forwarded-Proto $scheme; } } And here is my Django settings.py for this: . . . SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') CORS_ORIGIN_ALLOW_ALL = True CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True SECURE_HSTS_SECONDS = 340505040 SECURE_SSL_REDIRECT = True . . . Then I'm getting http 400 (this is the Load Balancer Health Checker): I look around and didn't find any example that helps me. If someone could help with any information, it'll be great. Thanks in advance. -
how to receive django-html dynamic 'div-id' tag from template to views.py
<p class="main_heading" type= "text" action='profile_search' name="{{ v.user }}" id="{{ v.user }}"> above, there is dynamic name and 'id', i want to receive that id into my view function, i am giving my code , but its not working. `def profile_search_view(request): people = request.GET['id'] query_result = Professional.objects.get(user__username__icontains=people) context = { 'query_result':query_result, } return render(request, 'profile_search.html',context)` but, after commenting request.get line, if i put some username in place of 'people' in paranthesis it works . Please help -
How to switch between models in one model?
In the admin interface, I want to make the shared tab "Tasks" and in it the choice of one of the 3 types of tasks. Type types are input and output. In the tabs tab, I just want to switch between task types, and switching to any type of information from the database on it. I have a Tasks model and I want it to unite the model Type1, Type2, Type3. I only know the way with GenericForeignKey (Many To One), but I don't like it very much, I would just like to switch between models for direct work with them. How can this result be achieved? -
How do I load an image into the img tag from a python field?
I am currently loading an object in HTML using jinja as follows <span> {{ object.name }} </span> <img src = "{{ object.image }}" > The image field is an ImageField in the database. The image URL looks like this http://127.0.0.1:8000/uploads/testimage.png How do I render the image correctly in the <img> tag? -
AddEventListener event fires only once
I am using django templating engine and javascript.My html looks like this <div class = "content-card-inner"> <p class = "content-card__review">Отзывы ({{ z.post_relate.all.count }})</p> <p class = "content-card__phone">{{ z.international_phone_number }}</p> <div class = "div-shaddow"></div> <p class = "content-card__text">Показать</p> </div> Cards with text to be generated on the backend using a template engine.My javascript code only works on the first card and I need it to work on all cards. With javascript I add a class to the div elements. Here is my javascript let divShadow = document.querySelector('.div-shaddow'); call.addEventListener('click', clickCall) function clickCall() { call.classList.add('visually-hidden'); divShadow.classList.add('visually-hidden'); } Help me, please.I'm a newbie -
Django FormView method 'form_valid()' not working when I specify html form action
I'm trying to send this form data by POST. When I click on submit it redirects me to the <form action="{% url 'create-checkout-session' %}" specified but I never get the email. If I delete the <action="" it sends the data by email but of course I'm not getting redirected to the url I want. The thing is that this url is not something I can hardcode since It's generated by Stripe payments and for each request it's a new one, so the success_url of the FormView is not something I can use. The thing I want to achieve is to get redirected to the form action but at the same time get the form data by email. This is the form. <form action="{% url 'create-checkout-session' %}" method="POST"> {{form.name}} {{form.surname}} <button type="submit" class="btn btn-success"> Card Payment </button> And I'm handling it this way in the view. class checkoutView(UserPassesTestMixin, FormView): template_name = 'store/checkout.html' form_class = userInfoForm success_url = reverse_lazy('create-checkout-session') def form_valid(self, form): subject = 'New message from: ' + form.cleaned_data['email'] message = form.cleaned_data['name'] recipient_list = settings.EMAIL_HOST_USER connection = settings.EMAIL_HOST_USER, send_mail(subject, message, recipient_list, connection) return super().form_valid(form) -
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 …