Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to port a Django web app in mobile (iOS & Android)
We have a working WebApp developed with Django, Python and Vue.Js. The application is working ok when it is opened in Mobile devices but we need to do lot of tweaking UI to make it compatible to mobile devices everytime. So we are looking for a way to create a mobile app and also need to update the data irrespective of device that users use. Please let us know whether this can be achievable? Best regards, ~Alam -
Map Flask API and Django app to same database but different tables
I have a database model which is written in Django ORM and the same database is used by Flask using SQLAlchemy for another microservice (where I need only 2/3 new and 1 exiting table) to store and query some data. So when from my Flask API, I run this command- $ flask db migrate $ flask db upgrade I can see that from migrations/versions, it is trying to delete existing tables of my Django app which I don't want to do. So my question is how to run/use Flask SQLAlchemy ORM without touching existing tables of Django app? Also From my Flask app, I want to refer to some of the existing tables of the Django app but am not sure how to do those without creating models on the Flask app because those models are already created by Django APP. N.B For a particular reason I don't want to separate the Flask API to another database -
How to display default value for models.FileField() in template CreateView?
How do I display the default value for models.FileField()? (ref) class MyModel(models.Model): myfile = models.FileField(upload_to='mydocs', default='myfile.txt') FieldField has an undocumented feature that allows a default value to be set using default=. This is a reference to an existing file, usually in the static root. The default form widget for this field is a ClearableFieldInput (ref), which uses django/forms/widgets/clearable_file_input.html as a template: {% if widget.is_initial %}{{ widget.initial_text }}: <a href="{{ widget.value.url }}">{{ widget.value }}</a> {% if not widget.required %} <input type="checkbox" name="{{ widget.checkbox_name }}" id="{{ widget.checkbox_id }}"> <label for="{{ widget.checkbox_id }}">{{ widget.clear_checkbox_label }}</label> {% endif %}<br> {{ widget.input_text }}:{% endif %} <input type="{{ widget.type }}" name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}> However, if default is set (initial being blank), the default value is not shown in the template, which can be confusing to the viewer. They think the field is empty, then on create() the default value is set. I am assuming that the default value is not passed to the template? If so, how can I modify the FileField to pass it? If not, how can I reference it? -
Django - MultiValueDictKeyError request.POST
Im getting MultiValueDictKeyError on my update view, when i add i can add successfully but when i want to update i get this error. I used the same codes by duplicating 4 times, but this time I could not understand why I am having an error. models.py; class problemduyuru(models.Model): olusturulmatarihi = models.TextField(max_length=100, null=True) duyurutipi = models.TextField(max_length=100, null=True) incidentno = models.TextField(max_length=100, null=True) baslangiczamani = models.TextField(max_length=100, null=True) aciklama = models.TextField(max_length=100, null=True) views.py- update def def problemduyurusuupdate(request, id): problemmember = problemduyuru.objects.get(id=id) problemmember.duyurutipi = request.POST['duyurutipi'] problemmember.incidentno = request.POST['incidentno'] problemmember.baslangiczamani = request.POST['baslangiczamani'] problemmember.aciklama = request.POST['aciklama'] problemmember.olusturulmatarihi = request.POST['olusturulmatarihi'] problemmember.save() messages.success(request, 'Alarmlar was updated successfully!') return redirect('/problemduyurusu') html; <form class="form-horizontal" action="problemduyurusuupdate/{{ problemmembers.id }}" method="POST"> {% csrf_token %} <div class="bd-callout bd-callout-danger"> <div class="bd-calloutic bd-callout-dangeric "> <div class="dangericon"></div> <h4 id="asynchronous-methods-and-transitions" style="color: #e70800;"><b>Technology Announcements</b></h4> <h7 id="asynchronous-methods-and-transitions" style="color:red; font-weight: 400; ">Problem Duyurusu</h7></div> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-duyuru" id="inputGroup-sizing-default" style="font-weight: 500;">Duyuru Tipi:</span> </div> <input type="text" class="form-control" value="{{ problemmembers.duyurutipi }}" name="dduyurutipi" id="dduyurutipi" aria-label="Default" aria-describedby="inputGroup-sizing-default"> </div> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-duyuru" id="inputGroup-sizing-default" style="font-weight: 500;">Incident No:</span> </div> <input type="text" class="form-control" value="{{ problemmembers.incidentno }}" name="dincidentno" id="dincidentno" aria-label="Default" aria-describedby="inputGroup-sizing-default"> </div> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-duyuru" id="inputGroup-sizing-default" style="font-weight: 500;">Başlangıç Zamanı:</span> </div> <input type="text" class="form-control" value="{{ problemmembers.baslangiczamani }}" name="dbaslangiczamani" id="dbaslangiczamani" aria-label="Default" aria-describedby="inputGroup-sizing-default"> … -
How to update FileField data only if a new file has been chosen in django or to delete previous one before upload new one
I need your help ... I've got the same question but with another specific class... My needs is to delete previous file before update new one only if field is filled ... If no change regarding file ... 1- When I update with new picture file ... it's ok but it's created a new file with some caracters (moto.jpg > moto_msi2Kup.jpg) ... 2- When I update only with new name (no change on file) ... the image field in database change ... previous it was word/moto.jpg ... after update it changes to moto.jpg (we lost word directory information ... I hope you understood my needs ... in both case I need to unchange image field if FileField is empty ... If FileField is changed .. Delete previous file and upload new one (still with same name) Below views, models and forms.py and a screenshot too ... Thanks for your help ;) views.py def updateWord(request, pk): word = Word.objects.get(id=pk) form = WordForm(instance=word) if request.method == 'POST': form = WordForm(request.POST, request.FILES, instance=word) if form.is_valid(): document = form.save(commit=False) document.name = request.POST['name'] # if not form.data['image'] is None: if request.FILES.get('image'): print("On supprime le fichier") word.delete_file() document.save() message = "Mot ["+request.POST['name'] + "] edité avec … -
form-data not working for ManyToMany field django
I have 2 models - Module and Room. A module can have zero or multiple rooms and a room can be added into multiple modules. So, there is a simple many-to-many relationship between them. In post request, raw-data input works, but not form-data. module/models.py - class Module(models.Model): module_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() rooms = models.ManyToManyField(Rooms, blank=True) room_list = models.CharField(max_length = 100, blank=True) rooms/models.py - class Rooms(models.Model): room_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() level = models.CharField(max_length=100) module/serializers.py - class ModuleSerializer(serializers.ModelSerializer): rooms = RoomSerializerWrite(many=True) class Meta: model = Module fields = '__all__' def create(self, validated_data): rooms_data = validated_data.pop('rooms') module = Module.objects.create(**validated_data) for data in rooms_data: room = Rooms.objects.get(**data) module.rooms.add(room) return module def update(self, instance, validated_data): # Updating rooms rooms_data = validated_data.get('rooms') instance.rooms.clear() for room_data in rooms_data: room = Rooms.objects.get(**room_data) instance.rooms.add(room) # Updating other fields fields = [ 'title', 'desc', 'thumbnail', 'is_deleted', ] for field in fields: setattr(instance, field, validated_data[field]) instance.save() return instance rooms/serialier.py - class RoomSerialize(serializers.ModelSerializer): room_id = serializers.IntegerField() class Meta: model = Rooms fields = "__all__" module/views.py - class add_module(APIView): def post(self, request, format=None): # Adding the rooms to module from room_list new_request = request.data.copy() room_list=[] if 'room_list' in new_request: room_list_data = list(new_request['room_list'].split(" ")) … -
django datepicker format change
Im trying to change the datepicker format form mm/dd/yyyy to dd-mm-yyyy. So far I've added DATE_INPUT_FORMATS in settings.py to ['%d-%m-%Y'], but this didnt change anything. I also changing it via jquery based on proposed solution in this site but it didnt help also. <script type="text/javascript"> $(function () { $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' }); }); </script> Its quite a trivial problem but I cant seem to find a way how to solve it. forms.py class Calendar(forms.DateInput): input_type = 'date' class AdForm(forms.ModelForm): time_limit = forms.DateInput(format=['%d-%m-%Y']) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['time_limit'].widget.attrs.update({'class': 'form-control mb-3 datepicker'}) class Meta: model = Ad fields = ('time_limit') widgets = { 'time_limit': Calendar(), } The result is still as such: -
How to convert python/django string to dictionary? [closed]
I want to convert this "str" to dict ('UK', 'United Kingdom') Convert it to {'UK', 'United Kingdom'} -
Get the user's location with the help of Django and Python
I want to create a site where I can get the exact location of the user with Django and Python.Here 1 and 2 and 3 a few methods are listed, but they use the Google Maps API. I want to use Open Street Map API and I do not want to use Google Map API. Or they use an IP address that apparently does not give the exact location. They also use JavaScript. I want to get the user's location with the help of Django Python. How can I do this? Thanks -
How to add django-crontab in docker container with non-rooted user django project
Working on a Django project which is running on docker-container with python:3.9-alpine3.13 FROM python:3.9-alpine3.13 LABEL maintainer=<do not want to show> ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt COPY ./app /app COPY ./scripts /scripts WORKDIR /app EXPOSE 8000 RUN python -m venv /py && \ apk add --update --no-cache postgresql-client && \ apk add --update --no-cache --virtual .tmp-deps \ build-base postgresql-dev musl-dev gcc python3-dev bash openssl-dev libffi-dev libsodium-dev linux-headers && \ apk add jpeg-dev zlib-dev libjpeg && \ apk add --update busybox-suid && \ apk --no-cache add dcron libcap && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /requirements.txt && \ apk del .tmp-deps && \ adduser --disabled-password --no-create-home app &&\ mkdir -p /vol/web/static && \ chown -R app:app /vol && \ chmod -R 755 /vol && \ chmod -R +x /scripts ENV PATH="/scripts:/py/bin:$PATH" USER app CMD ["run.sh"] I used this tutorial for implementation and I don't this error is because of this because I am getting this error. sumit@LAPTOP-RT539Q9C MINGW64 ~/Desktop/RentYug/rentyug-backend-deployment (main) $ docker-compose run --rm app sh -c "python manage.py crontab show" WARNING: Found orphan containers (rentyug-backend-deployment_proxy_1) for this project. If you removed or renamed this service in your compose file, you can run this command with the … -
docker-compose error when deploying portainer
I was deploying django with Portainer. While deploying, the following error occurred in django image log. django.db.migrations.exceptions.InconsistentMigrationHistory: Migration account.0001_initial is applied before its dependency users.0001_initial on database 'default'. I deleted the migrations file and tried to migrate again and deploy, but the same error occurred. maybe I think the problem is probably caused by customizing the User model. What should I do? -
self.action is None in DRF
self.action is None in get_permissions() method. When a url is called that doesn't exist DRF doesn't throw 404 error. that's why somehow action is None in get_permissions() method. Here is the ModelViewSet: class UserViewSet(ModelViewSet): serializer_classes = { "list": UserSerializer, "retrieve": UserSerializer, "create": UserSerializer, "update": UserUpdateSerializer, } http_method_names = ["get", "post", "put"] def get_serializer_class(self): return self.serializer_classes[self.action] def get_permissions(self): if self.action is None: # here error raises when i call '.../accounts/blablabla/` endpoint in post request instead of 404? raise AssertionError("self.action cannot be None") if self.action in ["list", "retrieve"]: return [IsAuthenticated(), IsAdmin()] else: return [AllowAny()] Here is my discussion link #8199 in github. -
Django - return list of dictionaries
I am a beginner, just starting with django. I am working on a function which returns sub_total, tax_amount and grand_total. I have tried it but it is not working as it should. I think the parameters are not correct or maybe something else. Please review this and provide a complete solution if you can. Also I am trying to hit request on Postman. Is it correct: def branch_report(request, params): # branches = BusinessBranch.objects.filter(is_removed=False) # orders = Order.objects.filter(is_removed=False) branches = BusinessBranch.objects.filter(is_removed=False).annotate( sub_total=Sum('orders__sub_total', filter=Q(orders__is_removed=False)), grand_total=Sum('orders__grand_total', filter=Q(orders__is_removed=False)), tax_amount=Sum('orders__tax_amount', filter=Q(orders__is_removed=False)), ).order_by('name') branch_list = [] for branch in branches: branch_obj = {} branch_list_in = list(branch.business_branch.filter(is_removed=False).annotate( sub_total=Sum('business_branch__sub_total', filter=Q(business_branch__is_removed=False)), tax_amount=Sum('business_branch__tax_amount', filter=Q(business_branch__is_removed=False)), grand_total=Sum('business_branch__grand_total', filter=Q(business_branch__is_removed=False)).values('name', 'id', 'sub_total', 'tax_amount', 'grand_total',)).order_by('name') ) branch_obj['sub_total'] = branch.sub_total branch_obj['tax_amount'] = branch.tax_amount branch_obj['grand_total'] = branch.grand_total branch_obj['id'] = branch.id branch_obj['name'] = branch.name branch_obj['branch_list_in'] = branch_list_in branch_list.append(branch_obj) all_total = Order.objects.filter(is_removed=False).aggregate( all_sub_total=Sum('sub_total', filter=Q(is_removed=False)), all_tax_amount=Sum('tax_amount', filter=Q(is_removed=False)), all_grand_total=Sum('grand_total', filter=Q(is_removed=False)), ) all_obj = {} all_obj['all_sub_total'] = all_total['all_sub_total'] all_obj['all_tax_amount'] = all_total['all_tax_amount'] all_obj['all_grand_total'] = all_total['all_grand_total'] return response_format(SUCCESS_CODE, SUCCESSFUL_RESPONSE_MESSAGE, {'branches': branch_list, 'all_total': all_obj}) I want it to return this: { "code": 200, "message": "Request was Successfull", "data": { "branches": [ { "branch_list": [ { "name": "Wahdat", "id": 21, "sub_total": null, "tax_amount": null, "grand_total": null, } ] }, { "branch_list": [ { "name": "WAPDA", "id": … -
line 8: 'empty'. Did you forget to register or load this tag?
I was watching the django tutorial in youtube, and I follow the same step as the professor did. The error came out with the following error: line 8: 'empty'. Did you forget to register or load this tag? <h1>My To do list </h1> <table> <tr> <th>Items</th> </tr>{% for task in tasks % }<tr> <td>{{task.title}}</td> </tr> {% empty %} <h3>No items in list</h3> {% endfor %} </table> -
filer field not returning any image in Django-admin
I am trying to access Django-filer fields in the Admin panel but I am not getting images, i know the storage location set by filer is random, but obj.bg_image_one.image.url doesn't seem to work My Model class CustomFilters(models.Model): input_file = models.ImageField( upload_to='input/images/', blank=True, null=True) name = models.CharField(max_length=50) action = models.CharField(max_length=150, choices=ACTION_CHOICES) is_active = models.BooleanField(default=False) bg_image_one = FilerFileField(null = True,on_delete = models.CASCADE) bg_image_two = FilerFileField(null = True,on_delete = models.CASCADE,related_name="bg_image_two") bg_image_three = FilerFileField(null = True,on_delete = models.CASCADE,related_name="bg_image_three") bg_image_four = FilerFileField(null = True,on_delete = models.CASCADE,related_name="bg_image_four") bg_image_five = FilerFileField(null = True,on_delete = models.CASCADE,related_name="bg_image_five") Admin code class CustomFiltersAdmin(admin.ModelAdmin): list_display = ('name', 'is_active', 'action', 'Input_Image', 'Output_Image','bg_image_one') list_filter = ('name', 'is_active', 'action') search_fields = ('name', 'action', 'created_by') ordering = ('name',) autocomplete_fields = ('user',) readonly_fields = ['Input_Image', 'background_image_1', 'background_image_2', 'background_image_3', 'background_image_4', 'background_image_5', 'Output_Image'] def background_image_1(self, obj): return mark_safe('<img src="{url}" width="{width}" height="auto" />'.format( url=obj.bg_image_one.image.url, width=obj.bg_image_one.image.width, height=obj.bg_image_one.image.height, ) ) -
BigIntegerField becomes serial4 on Postgresql
Setting the type of primary keys as BigIntegerField id = models.BigIntegerField(primary_key=True) makes the type of the files serial4 at the Postgresql database. Also the foreign keys have type int4 instead of the expected bigint. BigIntegerField serial4 -
Update into existing database not working
I have a page where the users can add a new mco number, when the user click on the Add mco button, it will retrieve the id as shown below: but when the user add the new mco number and click on the submit button, it will create another row and not update into the id database as shown below, why is that so and how do I solve this issue? views.py @login_required() def AddMCO(request, id): photo = get_object_or_404(Photo, id=id) if request.method == "POST": form = AddMCOForm(request.POST) if form.is_valid(): mcoNum = form.cleaned_data['mcoNum'] form.save() return redirect('ViewMCO') else: form = AddMCOForm() context = { "form": form, "photo": photo } return render(request, 'AddMCO.html', context, ) forms.py class AddMCOForm(forms.ModelForm): mcoNum = forms.CharField( label='Enter MCO Number', widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Please enter MCO Number here..' } ) ) class Meta: model = Photo fields = ("mcoNum",) def __init__(self, *args, **kwargs): super(AddMCOForm, self).__init__(*args, **kwargs) self.fields['mcoNum'].widget.attrs.update({'class': 'form-control', 'placeholder': 'MCO Number'}) self.fields['mcoNum'].label = '' self.fields['mcoNum'].help_text = '' AddMCO.html <!DOCTYPE html> <html> <head> <script> $(function () { $("#datetimepicker1").datetimepicker(); }); </script> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <title>SCS Add MCO</title> <meta name='viewport' content='width=device-width, initial-scale=1'> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" … -
Django Login Authentication: I am able to SignUp new user and create new user as well but UNABLE to login as SignUp user
Django Login Authentication: I am able to SignUp new user and create new user as well but UNABLE to login as SignUp user My views.py for handlelogin def handlelogin(request): if request.method == 'POST': loginemail= request.POST['loginemail'] loginpass = request.POST['loginpass'] user = authenticate(request, username=loginemail, password=loginpass) if user is not None: print(loginemail, loginpass) login(request, user) messages.success(request, "Successfullly Logged-In") return redirect('/') else: messages.error(request, "Invalid Credentials, Please Try Again") return redirect('/') return HttpResponse('404 - Page Not Find') I have tried print() statement to check , and it do work in else statement only ,not in if user is not none. NOTE: THE SYNTAX IN QUESTION IS LITTLE BIT DISTURBED ...BUT IN CODE IT IS COMPLTELY FINE. -
get user location django
I want to create a site where I can get the exact location of the user with Django and Python.Here is a method, but it uses Google Maps. I want to use Open Street Map and I do not want to use Google Map. How can I do this? Thanks -
I want to create an inframe for all the products
My main objective is to create an iframe for all products page, like the iframe code will be stored in a textbox area from where the user can copy the code and paste it to their websites or in any of their other platform. The project is in python, django for web development. I want to create an iframe where the values will be as: There will be an image of the product There will be an Visit button below the image, and Anchor to the target link of the product details page. I tried to achieve but the iframe content is not been rendered or shown to the HTML page. Or, I have seen the iframe plugin in Django. Will it be more efficient to follow Django's iframe-plugin or the same will be as the element of HTML. -
having problem loading url from the views and url in django
I am building a webpage from a custom bootstrap template available freely in GitHub. I have tried to connect Django to the back end. I am facing problem using urls and views. I have mentioned perfectly but i am getting page not found. urls.py file from django.urls import path, include from django.conf.urls.static import static from . import views urlpatterns = [ path('', views.homepage, name='homepage'), path('publications', views.publications, name='publications'), path('alumni', views.alumni, name='alumni'), path('contact', views.contact, name='contact'), path('joinus', views.joinus, name='joinus'), path('phdstudents', views.phdstudents, name='phdstudents'), path('pi', views.pi, name='pi'), path('project1', views.project1, name='project1'), path('research', views.research, name='research'), path('researchers',views.researchers, name='researchers'), path('shiladit', views.shiladit, name='shiladit'), path('students', views.students, name='students'), path('team', views.students, name='team'), ] views.py from django.shortcuts import render def homepage(request): return render(request, 'lab/index.html') def publications(request): return render(request, 'lab/publications.html') def alumni(request): return render(request, 'lab/alumni.html') def contact(request): return render(request, 'lab/contact.html') def joinus(request): return render(request, 'joinus.html') def phdstudents(request): return render(request, 'phd_students.html') def pi(request): return render(request, 'lab/pi.html') def project1(request): return render(request, 'lab/project1.html') def publications(request): return render(request, 'lab/publications.html') def research(request): return render(request, 'lab/research.html') def researchers(request): return render(request, 'researchers.html') when i click on the navbar to redirect the page i am getting error. but when i give the url it is loading how to rectify this. -
Django websocket ValueError
When I access a websocket on a non-existent put (ws://127.0.0.1:8000/ws/dgd/), django raises an error Is this normal behavior or should I handle this case? 2021-10-04 11:35:46 ERROR server Exception inside application: No route found for path 'ws/dgd/'. Traceback (most recent call last): File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/routing.py", line 168, in __call__ raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'ws/dgd/'. routing.py websocket_urlpatterns = [ re_path(r'^ws/user/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/$', consumers.UserConsumer.as_asgi()), ] settings.py CHANNEL_LAYERS = { 'default': { "BACKEND": "channels.layers.InMemoryChannelLayer" }, } asgi.py application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( websockets.routing.websocket_urlpatterns ) ), }) -
How do I assign a value to a model field that is the concatenation of two other model fields?
I'm developing a booking system as part of my portfolio. It allows a user (company) to book time slots for deliveries that will be made to a distribution center (DC) on a specific date & time. Models.py from django.db import models from django.utils import timezone from django.urls import reverse import datetime as dt from django.contrib.auth.models import User # Create your models here. class Booking(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) qty_plts = models.PositiveSmallIntegerField(default=1) cbm = models.PositiveSmallIntegerField(default=1) created_date = models.DateTimeField(default=timezone.now()) delivery_date = models.DateTimeField() delivery_time = models.TimeField() booking_number = models.CharField(max_length=50) def __str__(self): self.booking_number = # How to concatenate delivery_date and delivery_time? return self.booking_number def get_absolute_url(self): return reverse("booking_detail",kwargs={'pk':self.pk}) forms.py from django import forms from bookmyslot.models import Booking from bootstrap_datepicker_plus import DatePickerInput import datetime as dt HOUR_CHOICES = [(dt.time(hour=x), '{:02d}:00'.format(x)) for x in range(7, 13)] class BookingForm(forms.ModelForm): class Meta: model = Booking fields = ('qty_plts','cbm','booking_date','booking_time') widgets = {'delivery_date':DatePickerInput(options={"daysOfWeekDisabled":[0,6]}), 'delivery_time':forms.Select(choices=HOUR_CHOICES)} What I would like to do is assign a value to the booking_number field that is a concatenation of the delivery_date and delivery_time fields. So, if the customer is able to successfully book a slot at the requested delivery date & time, a unique booking number is generated as per above. How can I do this? If possible, … -
POST for Django API but require multiple inputs while my model only have 1 field that is able to take in inputted data
I am facing a issue right now on API post for @api_view[('POST'). I have the following codes: models.py class Job(models.Model): datetime = models.DateTimeField(default=timezone.now) combinedparameters = models.CharField(max_length = 1000) serializers.py class JobSerializers(serializers.ModelSerializer): class Meta: model = Job fields = ['combinedparameters'] As you can see there is only 1 field. But i dont know how to set up my @api_view['(POST)'] to do the same thing as my html because my html for this looks like this: Upon clicking the save button, I have to get the individual inputs from the textbox, textarea, dropdown box and convert it into the following : Example - {'device': 177, 'configuration': {'port_range': 'TenGigabitEthernet1/0/1,TenGigabitEthernet1/0/2,TenGigabitEthernet1/0/3,TenGigabitEthernet1/0/4,TenGigabitEthernet1/0/5', 'port_mode': 'Access', 'port_status': 'Disabled', 'port_param1': 'Test\r\n1\r\n2\r\n3', 'port_param2': 'Test\\n1\\n2\\n3'}} But how do I do the same thing in my API view if it doesnt follow how my html look like with so much input areas? -
Why graphene enum returns value instead key for my ENUMS key?
When i post data it return the value of the enum For example when i choose PL it returns the "Poland".I want to get the key of the enum instead of the value. I need PL instead of "Poland. Here is the code **This is my models** class Candidate(models.Model): class CountryChoices(models.TextChoices): PL = "Poland" DK = "Denmark" FI = "Finland" ---------- **This is my enums** class CandidateCountry(graphene.Enum): PL = "Poland" DK = "Denmark" FI = "Finland" residence_country = models.CharField( max_length=100, choices=CountryChoices.choices, null=True, blank=True) ----------