Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Retrieve specific user's profile information
In my web App I'm trying to add the function of clicking on the author of a certain post and being able to see their profile and also the posts said user has created. I've managed to get the post list working just fine but when I try to call specific user data, it gives me the data of the logged in user. Here's how I call the user profile in HTML: <section class="py-5"> <div class="container my-5"> <div class="row justify-content"> <div class="col-lg-6"> <div class="content-section"> <div class="media"> <img class="rounded-circle profile-img" src="{{ user.profile.image.url }}"/> <div class="media-body"> <h2 class="account-heading">{{ view.kwargs.username }}</h2> <!-- only This works --> <p class="text-secondary">{{ view.kwargs.username }} {{ user.last_name }}</p> <p class="text-secondary">{{ user.email }}</p> <div class="container"> <p class="lead"><Strong>Sobre mi:</strong></p> <p class="lead">{{ user.description }}</p> </div> <br> <p class="text-secondary">Se unió el {{ user.date_joined }}</p> <p class="text-secondary">Última vez visto: {{ user.last_login }}</p> <p class="mb-0">{{ user.profile.about }}</p> </div> </div> </div> </div> </div> Here is my views: class UserPostListView(ListView): model = Post template_name = 'forum/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') Here is how the problem looks: As you guys can see, that's Yonas1420's profile, but it's only returning the correct username, because the profile picture, the … -
Validation for unique in form
I have model and form like this class Article(models.Model): key = models.CharField(max_length=20,null=False,unique=True) class ArticleForm(forms.ModelForm): class Meta: model = Article key = forms.CharField(required=True) This key is unique in table, so I want to validate in form too. If I put the existing key, it comes to the 1062, "Duplicate entry 'inquiry' for key error in yellow screen However it also doesn't work, forms.CharField(required=True,unique=True) How can I make this validation? -
In Django : How can I multiply two columns and save to another column in update query?
class A(models.Model): revenue = models.FloatField() list_price = models.FloatField() unit_sold = models.FloatField() I have this model which has 1M records in list_price and unit_sold I want to fill revenue column using list_price * unit_sold -
How to check if record exists in django mysql before insert into database
Please pardon me, am still new to djando framework. This error i always get i run it. The view finance_lens_app.views.acct_type didn't return an HttpResponse object. It returned None instead. This is my model class Acct_type(models.Model): Aid=models.AutoField(primary_key=True) acct_type_name=models.CharField(max_length=200) class Meta: db_table="Acct_Type" This is my VIEW. def acct_type(request): if request.method=='POST': request.POST.get('acct_type_name') acct_type_record=Acct_type() acct_type_record.save() messages.success(request, 'Account Type Added Successfully...') return render(request, "admin_opera/acct_type.html") My Interface HTML <form method="POST"> {% csrf_token %} <div class="input-group mb-3"> <select name="acct_type_name" id="acct_type_name" class="form-control"> <option value="Assets">Assets</option> <option value="Liabilities">Liabilities</option> <option value="Equities">Equities</option> <option value="Incomes">Incomes</option> <option value="Expenses">Expenses</option> <option value="Expenses2">Expenses2</option> <option value="Expenses3">Expenses3</option> </select> </div> <input class="btn btn-primary btn-lg" type="submit" name="submit" value="Add Account"> </form> -
Is there an easier way to see changes made on front end?
I am building my first django + react project and my question is when I make a change to my front end, do I have to run build and then manage.py runserver every time after to see the changes? I mean this gets it to work for me but just felt I might be doing something wrong and there is an easier way. -
Frequently update an angularjs frontend with real time data from django server
There are some data which would be sent frequently from a django server to the angularjs, this is a data which would be modified frequently and the modification would be updated at the front end when the changes are made at the backend At the point where the data is made available I have inserted views.py send_event('test', 'message', {'text': dataModifiedFrequently}) asgi.py application = ProtocolTypeRouter({ 'http': URLRouter([ url(r'^event_url/', AuthMiddlewareStack( URLRouter(django_eventstream.routing.urlpatterns) ), { 'channels': ['test'] }), url(r'', get_asgi_application()), ]), }) angular.js $scope.EventSourceScope = function(){ if (typeof(EventSource) !== "undefined") { var source = new EventSource('event_url'); source.onmessage = function (event) { $scope.openListingsReport = event.data; $scope.$apply(); console.log($scope.openListingsReport); }; } else { // Sorry! No server-sent events support.. alert('SSE not supported by browser.'); } } I used the Django EventStream package and followed the example I do not seem to see any result in the angularjs. but in my browser it gave me the error EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection. Please how can I get django to send data to angularjs as it occurs -
Why is RDS MySQL Database with Django running very slowly with very simple queries?
I developed a simple application with Django, Django REST Framework and MySQL, and everything works fine in my local machine. I want to upload the application to AWS, so I started by creating an RDS MySQL instance and connected it to my Django app. After doing that and running the migrations, the application got very slow. I know that a local database is expected to be faster than an RDS instance, but the difference in the speed is way too big. As an example, this is one of the views I have: class DeckApi(viewsets.ViewSet): permission_classes = [IsAuthenticated] def list(self, request, *args, **kwargs): qs = Deck.objects.filter(user=request.user) serializer = DeckSerializer(qs, many=True) return Response(serializer.data, status=status.HTTP_200_OK) One call to this view takes about 5 or 10 seconds to respond and the database is almost empty. To find out whether the problem was in the RDS instance, I tested it from the terminal. I logged in and tried to make a query similar to what the above view would do: SELECT * FROM flashcards_deck WHERE user_id=2; This query runs in about 200 milliseconds. Although this is still a lot for such a simple query in an almost empty database, it is much less than 5 … -
How to fix login template dissappear problem?
I created 404 handler in my Django project and I am preparing it for deployment. So I change DEBUG = False and that remove my login page and I don't know how can I get the login page. When I change debug=true or remove 404 handler, my login page shows. But I cannot do them in deployment. How can I fix it? views.py @login_required def home(request): return render(request, 'index.html') def f_handler404(request, exception=None): return render(request, 'index.html') urls.py handler404 = "register.views.fray_handler404" settings.py LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/accounts/login' And my login template is in project/templates/registration/login.html -
Can i Create A Website Using HTML CSS JAVA (Not Javascript) Python Django Heroku?
Hi Everyone I Had A Question Regarding Creating Website Can i Make One Just Using HTML CSS JAVA (Not Javascript) Python Django Heroku? Reason i Don't Want To Touch Javascript Is Because i Hate it But im Pretty Open To Learning Vaadin and Springboot -
Use URL data to fill form in Django with Class Based Views
I have 2 Models: Projects and Members, each one with a form. I was able to add to the URL the number of the project (id) this: class PageCreate(CreateView): model = Page form_class = PageForm success_url = reverse_lazy('members:create') def get_success_url(self): return reverse_lazy('members:create', args=[self.object.id]) When I finish of filling the Project form, it redirects the page to the Member form. What I want to do is to extract the ID of the Project from the URL and use it in the Member form. I cannot think any other solution. Currently I have a Selection list to select the Project in the Member form but I want the Project loaded as soon as is created. I am using the CreateView in the models for both Projects and Members. This is the view for MemberCreate @method_decorator(login_required, name='dispatch') class MemberCreate(CreateView): model = Member form_class = MemberForm success_url = reverse_lazy('pages:pages') Only attempt I had to visualize the ID in the HTML was using {{ request.get }} To somehow get the value from the GET but I could not do it. -
django.db.utils.ProgrammingError: (1146, "Table 'ITnews$default.auth_user' doesn't exist")
when I do: python manage.py migrate I get: django.db.utils.ProgrammingError: (1146, "Table 'ITnews$default.auth_user' doesn't exist") I trying to deploy my website in pythonanywhere. And I cannot to connect site and mysql. Database settings in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'ITnews$default', 'USER': 'ITnews', 'PASSWORD': 'mypass', 'HOST': 'ITnews.mysql.pythonanywhere-services.com', } } :) -
Group By with Django's queryset
I have a model in Django and this is how it looks like with fewer fields - I want to group the rows w.r.t buy_price_per_unit and at the same time I also want to know the total units on sale for that buy_price_per_unit. So in our case only two distinct buy_price_per_unit are available (9, 10). Hence the query would return only two rows like this - The one last condition which I have to meet is the query result should be in descending order of buy_price_per_unit. This is what I have tried so far - orders = Orders.objects.values('id', 'buy_price_per_unit')\ .annotate(units=Sum("units"))\ .order_by("-buy_price_per_unit")\ The response for the query above was - [ { "id": 13, "buy_price_per_unit": 10, "units": 1 }, { "id": 12, "buy_price_per_unit": 9, "units": 10 }, { "id": 14, "buy_price_per_unit": 9, "units": 2 }, { "id": 15, "buy_price_per_unit": 9, "units": 1 } ] The problem with this response is that even for the same price multiple records are being returned. -
Django RestFramework Nested List view
I want to nest only the ListView of my objects like this: { "Organisations": [{ "OrganisationName": "Organisation1", "OrganisationID": "ABC12345" }, { "OrganisationName": "Organisation2", "OrganisationID": "XYZ12345" } ]} However I can only get results like this: [ { "OrganisationID": "Organisation1", "OrganisationName": "ABC12345" }, { "OrganisationID": "Organisation2", "OrganisationName": "XYZ12345" } ] models.py: from django.db import models class Organisation(models.Model): """Model class for the Atomo Organisations""" OrganisationName = models.CharField(max_length=60, blank=True, null=True, default="") OrganisationID = models.CharField(max_length=60, unique=True, blank=True, null=True, default="") class Meta: ordering = ['OrganisationName'] def __str__(self): """String for representing the MyModelName object (in Admin site etc.).""" return self.OrganisationName serializers.py: from rest_framework import serializers from ndx_org.models import Organisation class OrgSerializer(serializers.ModelSerializer): class Meta: model = Organisation fields = ["OrganisationID", "OrganisationName"] views.py: from ndx_org.models import Organisation from ndx_org.api.serializers import OrgSerializer from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status class OrgList(APIView): def get(self, request, format=None): orgs = Organisation.objects.all() serializer = OrgSerializer(orgs, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = OrgSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I have tried to nest the serializer but I nests every object. What I need is a nested result of the object lists. How can I do it? Thanks for … -
Updating multiple checkboxes forms with Django
in my django website I'm trying to building a page in which there are multiple forms (In particular 3: the first is simply a checkbox, as the second one. The third one requires the entering of two text fields). I've already managed the presence of multiple forms and I've no problem when the user performs the first assignment. The problem is instead during the updating of the answers that the user gave the first time: there are no problems when adding new instances of the text fields of the third form, while instead if I've selected one checkbox of the first two forms and I want to change them unchecking them it seems like django doesn't save the new values. Any idea of why it's happening? Here's the view associated: def new_4e2(request, pk, var=None): if Specifiche.objects.filter(ID_rich = pk).exists(): specs = Specifiche.objects.filter(ID_rich = pk) choicesp =[] lista =[] for spec in specs: choicesp+=[(spec.id, str(spec.rif))] lista+=[spec.id] att = MAIN.objects.get(id=pk) unform = FormUn(instance=att) data = {'ID_rich': pk} form = UnicitaForm(initial=data) form.fields['rifext'].choices = choicesp if Unicita.objects.filter(rifext__in = lista).exists(): uns=Unicita.objects.filter(rifext__in = lista) context={ 'att': att, 'uns': uns, 'var':var, 'specs': specs } else: context = { 'att': att, 'var':var, 'specs': specs, } form = UnicitaForm(initial = … -
how to completely hide a particular form field for users in django
I want to completely hide the fields in the form, now only the field is hidden, but the name of the field remains. I don't want the name or anything to show about the field. take a look at my code. class RechargeDataForm (forms.ModelForm): def __init__(self, *args, **kwargs): from django.forms.widgets import HiddenInput hide_condition = kwargs.pop('hide_condition',None) super(RechargeDataForm, self).__init__(*args, **kwargs) if hide_condition: self.fields['idnetwork'].widget = HiddenInput() self.fields['idplan'].widget = HiddenInput() # or alternately: del self.fields['fieldname'] to remove it from the form altogether. class Meta: model = RechargeData fields = '__all__' exclude = ('user', 'user', 'type', ) this code below brought the same outcome too- the field disappears why field name remains #widgets = { # 'idplan': forms.TextInput(attrs={'type': 'hidden'}), #} models.py file. class RechargeData(models.Model, Main): networks = models.ForeignKey(Networks, default=1,on_delete=models.CASCADE, verbose_name="networks") circle = ChainedForeignKey( "Circle", chained_field="networks", chained_model_field="networks", show_all=False, auto_choose=True, sort=True ) plans = ChainedForeignKey( "Plans", chained_field="circle", chained_model_field="circle", show_all=False, auto_choose=True, ) user = models.ForeignKey(User, default=1,on_delete=models.CASCADE) mobile_number = models.CharField( max_length=11, blank=True, null=False) # validators should be a list timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) idnetwork = ChainedForeignKey( "IdNetwork", chained_field="networks", chained_model_field="networks", show_all=False, auto_choose=True, sort=True ) idplan = ChainedForeignKey( "IdPlan", chained_field="circle", chained_model_field="circle", show_all=False, auto_choose=True, sort=True ) I want the field remove permanetly without affecting my form validation. something like this refused to … -
Formset saved duplicate entries
My system allows user to add questions to form when clicking on Add More button. I am using formset to create and add new question. I am trying to save the formset to database however, when saving to database i noticed that there are duplicated entries. How to prevent duplicate entries/ save only the new entries from the formsets. add_quiz_questions.html {% load crispy_forms_tags %} <div class="container-fluid p-5"> <!-- Main Content Here --> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ questionformset.management_form }} <div id="question-form-list"> {% for question in questionformset %} <script type="text/javascript" src="/static/selectable/js/jquery.dj.selectable.js"></script> <div class="card shadow mb-4"> <div class="question-form"> <div class="card-body"> {{ question|crispy }} </div> </div> </div> {% endfor %} </div> <div id="empty-form" style="display: none;"> <div class="card shadow mb-4"> <div class="card-body"> {{ questionformset.empty_form|crispy }} </div> </div> </div> <button type="button" class="btn btn-info" id="add-more"> Add Question</button> <button type="submit" class="btn btn-primary">Save</button> </form> </div> <!-- /.container-fluid --> </div> <script> $('#add-more').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#question-form-list').append($('#empty-form').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); </script> views.py def createQuizQuestion(request,pk): user_id = Users.objects.get(user=request.user) quizzes = Quiz.objects.get(id=pk) for row in QuizQuestion.objects.filter(quiz=quizzes).reverse(): if QuizQuestion.objects.filter(quiz_id=row.quiz_id, question=row.question).count()>1: print(row) question = QuizQuestion.objects.filter(quiz=quizzes) QuestionFormSet = modelformset_factory(QuizQuestion, form=QuizQuestionForm, extra=0) questionformset = QuestionFormSet(request.POST or None, queryset=question) if request.method == "POST": questionformset = QuestionFormSet(request.POST or None, queryset=question) if questionformset.is_valid(): … -
Color table cells for reservation system Django
I am trying to develop a reservation system based on a Django project. My final goal is to have something like that: Until now, what I was able to achieve is to have the table with the times of the day and the column (which are aicrafts). My final goal is to have my reservations displayed as "legs", meaning that, for example a reservation from 09:00 until 11:00 is displayed in the aircraft cells between 09:00 up to 11:00. In fact, what I'd need to achieve is to have each single table cell or group of cells colored to advise that the airplane is booked for that period of time. So far my code is something like that: models.py class AirportTime(models.Model): aerodrome = models.ForeignKey(Aerodrome, on_delete=models.CASCADE, blank=True, null=True) opening_time = models.TimeField() closing_time = models.TimeField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.opening_time) + ' ' + str(self.closing_time) class Booking(models.Model): aircraft = models.ForeignKey(Aircraft, on_delete=models.CASCADE) student = models.ForeignKey( Student, on_delete=models.CASCADE, blank=True, null=True) instructor = models.ForeignKey( Instructor, on_delete=models.CASCADE, blank=True, null=True) date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.aircraft.registration + ' ' + str(self.date) + ' ' + str(self.start_time) + ' ' … -
How to filter by year, month, or day in django graphene query
I am building a django graphql api with graphene for photography events. Each event has a location, photographer and event date. I want to be able to filter all events by year, month or day, e.g. return all events happening in April 2022 or all events that happen on Thursdays. I would also like to filter for future events only. The model: # models.py class Event(models.Model): STATUS = ( ("Scheduled", "Scheduled"), ("Cancelled", "Cancelled"), ("Available", "Available"), ("Complete", "Complete"), ) location = models.ForeignKey( Location, on_delete=models.SET_NULL, null=True, related_name="location_events" ) photographer = models.ForeignKey( Photographer, on_delete=models.SET_NULL, null=True, related_name="photographer_events", ) event_date = models.DateField() status = models.CharField(max_length=50, choices=STATUS, default="Scheduled") created = models.DateTimeField(auto_now_add=True) class Meta: constraints = [ models.UniqueConstraint( name="location_event", fields=("location", "event_date") ) ] def __str__(self): return f"Event {self.location}, {self.event_date}, {self.status}" # schema.py from graphene_django import DjangoObjectType from graphene import relay, ObjectType from graphene_django.filter import DjangoFilterConnectionField from events.models import Event class EventNode(DjangoObjectType): class Meta: model = Event filter_fields = { "event_date": ["exact", "year", "month", "day"], "status": ["exact"], } interfaces = (relay.Node,) class EventsQuery(ObjectType): event = relay.Node.Field(EventNode) all_events = DjangoFilterConnectionField(EventNode) Using this set up, when I try to run this query on graphiql browser interface: query filterEvents{ allEvents(eventDate:"2022-02-14"){ edges{ node{ id eventDate photographer{ firstName lastName } location{ id name … -
Not able to get all the columns while using group by in Pandas df
controller.py def consolidated_universities_data_by_country(countries,universities): cursor = connection.cursor() query = None if countries == str(1): query = f""" @sql_query@ """ result_data=cursor.execute(query) result=dict_fetchall_rows(result_data) consolidated_df_USA=pd.DataFrame(result).fillna('NULL').replace( {True : 1, False : 0}).groupby('CourseId')['ApplicationDeadline'].apply(', '.join).reset_index() return consolidated_df_USA With the mentioned code i am able to get desired output i.e., i wanted to merge n rows deadline in one row for given courseid, but i am not able to get rest of the columns. consolidated_df_USA=pd.DataFrame(result).fillna('NULL').replace( {True : 1, False : 0}).groupby('CourseId')['ApplicationDeadline','CourseName'].agg(', '.join).reset_index() return consolidated_df_USA With this i am able to get some columns but some of the columns are getting depricated. Also getting below warning. FutureWarning: Dropping invalid columns in SeriesGroupBy.agg is deprecated. In a future version, a TypeError will be raised. Before calling .agg, select only columns which should be valid for the aggregating function. How to get all the columns which is given by sql query? -
Is it possible to get the name of IntegerChoices
I have IntegerChoices like this class Action(models.IntegerChoices): SYSTEM_START = 1 SYSTEM_STOP = 2 and model has this as the member class ActionLog(BaseModel): log_action = m.PositiveSmallIntegerField( choices=Action.choices,null=False) def action_name(self): // can I get the name such as SYSTEM_START here? then I want to return the readable name in action_name function of model. Is it possible?? or I should not use models.IntegerChoices? If so what should be used in this case? -
how to update record and same record create in other table in django form
i have 2 model one is Tempdriver and other one is Hiring, i am register new customer in Tempdriver table, i need when i edit tempdriver record and status is (accept) and when i save this record then need to same record create on hiring table with matching column with status=(Applied on app) rest column should be null in hiring table models.py class Tempdriver(BaseModel): name = models.CharField(max_length=255) mobile = models.CharField(max_length=20,unique=True,null=True, blank=True) alternate_number = models.CharField(max_length=20, null=True, blank=True) date = models.DateField(null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) status = EnumField(choices=['Accept','Reject','Hold'], null=True) class Hiring(BaseModel): STATUS_CHOICES = (('', 'Type...'), ('HR Interview Pass', 'HR Interview Pass'), ('HR Interview Fail', 'HR Interview Fail'), ('Allocation Completed', 'Allocation Completed'), ('Applied on app','Applied on app') ) name = models.CharField(max_length=254, null=True, blank=True) mobile = models.CharField(max_length=20,unique=True,null=True, blank=True) city = models.ForeignKey(City, models.CASCADE, verbose_name='City', null=True, blank=True) age = models.PositiveIntegerField(null=True, blank=True) status = models.CharField(max_length = 255,choices=STATUS_CHOICES, null=True, blank=True) forms.py class TempDriverForm(forms.ModelForm): class Meta: model= Tempdriver fields='__all__' views.py def edit_temp_driver(request,id=0): tempdr=Tempdriver.objects.get(pk=id) form= TempDriverForm(request.POST or None, request.FILES or None, instance=tempdr) if form.is_valid(): edit = form.save(commit=False) edit.save() messages.success(request,'Driver data updated successfully!') return redirect('/fleet/tempdr') return render(request, 'hiringprocess/edit_tempdriver.html', {'form':form}) -
Django FormWizard done function saves each step (form) as a separate instance in DB
I've searched all over for a solution to this but just can't figure it out. I feel the solution is quite simple but... I have a formwizard - class FormWizardView(SessionWizardView): template_name = "requests/data_change_requests.html" form_list = [dc_step1, dc_step2] def done(self, form_list,**kwargs): for form in form_list: form.save() return HttpResponseRedirect ('success.html') when the Done function is run, each step in the form is saved as a separate instance in the DB. how can I tie both form instances together and then save that so it is all in the instance? Thanks -
Django templates Could not parse the remainder
I have this template, I am looping through all choices in a question, and I want to default check the question user previously selected. selected_choice variable is coming from my view and I got have it ok in my template. {% extends 'base.html' %} {% block content %} <div id="detail" class=""> <form hx-post="{% url 'main:vote' question.id %}" hx-trigger="submit" hx-target="#detail" hx-swap="outerHTML"> {% csrf_token %} <fieldset> <legend><h1>{{ question.question_text }}</h1></legend> {% if error_message %}<p> <strong>{{ error_message }}</strong> </p> {% endif %} {% for choice in question.choices.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" {% if selected_choice and choice.id==selected_choice %}checked{% endif %}> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} </fieldset> <button type="submit">Submit</button> </form> </div> {% endblock content %} I get this error Could not parse the remainder: '==selected_choice' from 'choice.id==selected_choice' -
Django ReactJS web app Icons and Images Inside Public Folder Not Showing
I'm trying to deploy a small Django/ReactJS web app to heroku. I'm having an issue with the static images used as background and icons (the images folder is inside the public folder). The images do not show. However, when I deploy only the frontend part as a static app, the images show correctly. All the Django/ReactJS project I've been able to access so far have images imported inside App.js, it's not what I want to do. I want to use the urls to the images as for example: background: "url(/images/somemage.png)" Website without backend: https://base-apparel-coming-soon-react.herokuapp.com/ Website with backend: https://base-apparel-coming-soon-dr.herokuapp.com/ Git repository: https://github.com/.../base-apparel-coming-soon-DRF.../ -
Reservation system Djangop [closed]
I am trying to develop a reservation system based on a Django project. My final goal is to have something like that: Until now, what I was able to achieve is to have the table with the times of the day and the column (which are aicrafts). My final goal is to have my reservations displayed as "legs", meaning that for example a reservation from 09:00 until 11:00 is displayed in the aircraft cells between 09:00 up to 11:00. So far my code is something like that: models.py class AirportTime(models.Model): aerodrome = models.ForeignKey(Aerodrome, on_delete=models.CASCADE, blank=True, null=True) opening_time = models.TimeField() closing_time = models.TimeField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.opening_time) + ' ' + str(self.closing_time) class Booking(models.Model): aircraft = models.ForeignKey(Aircraft, on_delete=models.CASCADE) student = models.ForeignKey( Student, on_delete=models.CASCADE, blank=True, null=True) instructor = models.ForeignKey( Instructor, on_delete=models.CASCADE, blank=True, null=True) date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.aircraft.registration + ' ' + str(self.date) + ' ' + str(self.start_time) + ' ' + str(self.end_time) views.py def index(request, date): if date is None: date_obj = datetime.now().date() else: date_obj = datetime.strptime(date, '%Y-%m-%d') next_day_obj = date_obj + timedelta(days=1) next_day_link = next_day_obj.strftime('%Y-%m-%d') prev_day_obj = date_obj - timedelta(days=1) …