Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Tables 2 Filter field, but use the display name?
I've got this model: DRAFT = 'draft' IN_PROGRESS = 'in_progress' FINISHED = 'finished' STATUS_CHOICES = ( (DRAFT, 'Entwurf'), (IN_PROGRESS, 'In Arbeit'), (FINISHED, 'Erledigt'), ) class Invoice(TimeStampModel): status = models.CharField('Status', choices=STATUS_CHOICES, max_length=50) and this filter I've build with the django tables 2 plugin: class InvoiceFilter(django_filters.FilterSet): class Meta: model = Invoice fields = { 'name': ['icontains'], 'status': ['icontains'], } My filter gets rendered without a problem on my page and I can use it. The problem right now is though if I try to search for a status using the german word, like for example Entwurf the filter always returns me no item. BUT if I filter for draft I get all the items which have this status. So my question would be: how can I tell my filter to look for the display name of my status field? Or even better: would it be possible to just make a select out of the status field instead of a normal search? Thanks for any answers! -
How to enable setup python app on cpanel?
I want to start my new Django project on my server. so i install cpanel. but in software part, there is nothing related to python. Should i Do something in WHM? or install something in my server? thanks for helping me. -
How to apply filter on Many to many field without using for loop
I Model is like class Company(models.Model): name = models.CharField(max_length=400, blank=True, null=True) class Intership(models.Model): company = models.ForeignKey(Company) location = models.CharField(max_length=400, blank=True, null=True) class Student(models.Model): name = models.CharField(max_length=400, blank=True, null=True) intership = models.ManyToManyField(Intership,null= True, blank=True) I am looking forward to get all the student who done internship in a company with name "xyz". i have the code company_name = "xyz" stds for student in students: interships = student.intership.all() for intership in interships: if intership.company.name == company_name: stds.append(student) Is it possible to get it all this on a single query?? -
type object 'User' has no attribute 'objects django
i am trying to get list of user from api with jwt token so i generated the token and with email and pass and trying to make get request with token but i get this erro: File "/home/tboss/Desktop/environment/liveimages/backend/venv/lib/python3.7/site-packages/rest_framework_simplejwt/authentication.py", line 111, in get_user user = User.objects.get(**{api_settings.USER_ID_FIELD: user_id}) rest_framework.request.WrappedAttributeError: type object 'User' has no attribute 'objects' and i have created custom user views.py: from users.models import User from rest_framework import viewsets from rest_framework.decorators import api_view, permission_classes, authentication_classes from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.status import ( HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND, HTTP_200_OK) from . import serializers from rest_framework.response import Response from rest_framework.authentication import TokenAuthentication, SessionAuthentication class UserViewSet(viewsets.ModelViewSet): queryset = User.object.all() serializer_class = serializers.UserSerializers i'm using User.object its working fine but this error coming from jwt -
django admin like behaviour for app users
We have merchants with campaigns in our project. Currently, we - as superuser - manage all merchants' campaigns. However, some merchants require access to campaign management so that they can control the process and set new campaigns themselves. There is a possibility to create the second admin site and set permissions so that only merchants can log in. However, what we need is - to filter only the campaigns owned by logged in merchant and also, when creating a new one the merchant_id should be prefilled and readonly. Is it possible to do it using the second django admin site or should I create a special frontend interface for this purpose? Is it possible to set permissions per user-object pair (in django admin)? -
Is there a good way to mirror external (not model) DB table to django.contrib.auth.models.User?
I have a software that is written in Java that I can not modify. Because of it I'm making a wrapper in Django that will use said software's REST API. I'm new, but I learn as I go. I require exactly the same user ids and emails - they have to be mirrored from Java program's user table to django.contrib.auth.models.User. I thought about doing it by creating a database-side event that would periodically (every hour?) fill my django.contrib.auth.models.User with users that Java software created. I'm pretty sure this is not very efficient, since: It needlessly strains the database that is under a large stress as it is It's too slow, I would much prefer mirror to happen as soon as Java app creates an user Letting Django do it would probably be much cooler + would be more obvious for my replacement in case I leave my company That event will have to constantly move hundreds of users - this can't be good Does anyone have a better idea? Maybe I'm not looking at it correctly, or even overthinking it? -
Validation: clean() and clean_<fieldname> not working as expected
I have to validate a field if it's unique. I am not using unique=True in models. I am using clean() and clean_() in forms but are raising different errors. forms.py Case 1: clean() name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter Package Name', 'class': 'form-control'})) def clean(self): name = self.cleaned_data.get('name') if Package.objects.filter(name=name): raise ValidationError(_("Package with this package name already exist.")) return name case 2: clean_name() name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter Package Name', 'class': 'form-control'})) def clean_name(self): name = self.cleaned_data.get('name') if Package.objects.filter(name=name): raise ValidationError(_("Package with this package name already exist.")) return name views.py package.name = form.clean_name() or package.name = form.clean() in html template: <p style="color:red;">{{ form.non_field_errors.as_text }}</p> Problem: in case 1, validation is correct if I send duplicate name but if name is unique, this gives this error: 'str' object has no attribute 'get' In case 2: if name is valid, then everything ok. data is saving normally but if it's duplicate data, it's not showing error message. But validation is working as it's not submitting the form. -
Creating video thumbnails with imagekit and opencv
I have a model named "Post", which is going to refer to images and videos. I added ImageSpecField for thumbnail storage and created a function, that pulls the desired frame from uploaded video. Is there any way to use this function while generating thumbnail? Because right now ImageSpecField can only use FileField as an input. I have tried creating a new class inheriting from ImageSpecField, but I quickly realized that this is not going to work because this class was instanced only on server start, thus putting this function in constructor of it would not work. import cv2 as cv from django.conf import settings from django.db import models from imagekit.processors import ResizeToFit from imagekit.models import ImageSpecField def video_to_image(source, frame): vid_cap = cv.VideoCapture(settings.MEDIA_ROOT + source.__str__()) vid_cap.set(cv.CAP_PROP_POS_FRAMES, frame) success, image = vid_cap.read() vid_cap.release() return image class Post(models.Model): IMAGE = 'I' VIDEO = 'V' FILE_TYPES = [ (IMAGE, 'Image'), (VIDEO, 'Video') ] file_type = models.CharField(max_length=1, choices=FILE_TYPES) file = models.FileField(upload_to='post_images') thumbnail_frame = models.IntegerField(default=0) image_thumbnail = ImageSpecField(source='file', processors=[ResizeToFit(width=200, height=200)], format='JPEG', options={'quality': 60}) I want imagekit to generate thumbnail from video, and be able to get it via ImageSpecField. -
setting get_absolute_url when using a router
I'm working on a Comment app and I would like my Commentserializer to display the exact URL of each instance of Comment. I know that I have to use the get_absolute_url of the Comment model. But i cannot connect my viewnames from my router to the get_absolute_url. Here is my Model : class Comment(models.Model): content = models.TextField(max_length=150) author = models.ForeignKey( User, on_delete = models.CASCADE ) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField(blank=True) content_object = GenericForeignKey('content_type', 'object_id') parent = models.ForeignKey( "self", on_delete = models.CASCADE, blank=True, null=True ) datestamp = models.DateTimeField(auto_now_add=True) objects = CommentManager() def __str__(self): return str(self.content[:30]) def save(self): self.object_id = self.parent.id super(Comment, self).save() def children(self): return Comment.objects.filter(parent=self) def get_absolute_url(self): return reverse("comments-details", args=[str(self.id)]) @property def is_parent(self): if self.parent is None: return False return True and here is my router : router = router = routers.SimpleRouter() router.register('api/comments', CommentViewSet) urlpatterns = router.urls As you can see, I'm trying to use "comment-details" as a viewname. The end Goal is to display a JSON like that : { url : 'blabla/comments/{pk}/details } -
How to get parameter from user front-end in Django generic.ListView?
I am building an app where users will be able to search nearby locations. For this, I am using this function in my views.py: latitude = 23.734413 longitude = 90.4082535 user_location = Point(longitude, latitude, srid=4326) class NearbyServices(generic.ListView): model = Service context_object_name = 'services' queryset = Service.objects.annotate(distance=Distance('location', user_location)).order_by('distance')[0:6] template_name = 'services/nearby.html' I am currently using a hard-coded user location, but I want to let the users find nearby locations by first getting their location using the HTML5 GeoLocation API. Any help with how I can get their location from the front-end into the listview function would be really helpful! -
How to fix problem with ListView on django 2.4
I have a problem with ListView can't get queryset from the genre from movies. If i go to categories i can see movies from this category but if i wanna see movies from genre i see an empty list. sorry for my bad english. views.py class MovieListView(ListView): context_object_name = 'movies' def get_queryset(self): if self.kwargs.get('category') is not None: movie_list = Movie.objects.filter( category__slug=self.kwargs.get('category'), published=True, ) movies = movie_list elif self.kwargs.get('genre') is not None: movie_list = Movie.objects.filter( genre__slug=self.kwargs.get('genre'), published=True, ) movies = movie_list else: movies = Movie.objects.filter(published=True) return movies urls.py app_name = "movies" urlpatterns = [ path('', MovieListView.as_view(), name='movie_list'), path('<id>-<name>/', MovieDetailView.as_view(), name='movie_detail'), path("<slug:category>/", MovieListView.as_view(), name="category_post"), path("<slug:genre>/", MovieListView.as_view(), name="genre_list"), ] -
AttributeError at /basic_app/register/ : 'tuple' object has no attribute 'get'
I know this question have been asked alot and most of the time its due to render or HttpResponse in the views.py, i double checked mine but the code looks good to me, dont know where the problem is. This is a views.py file for a very basic django form but i can't get it to work def register(request): registered = False if request.method == 'POST': user_form = UserForm(data = request.POST) profile_form = UserProfileInfoForm(data = request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_from.save() user.set_password(user.password) user.save() profile = profile_form.save(commit = False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES['profile_pic'] profile.save() registered = True else: return (user_form.errors,profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request,'basic_app/register.html',{'user_form': user_form, 'profile_form':profile_form, 'registered':registered}) -
JSONField workaround on elasticsearch : MapperParsingException
How do we map Postgres JsonField of Django model to elastic search indexing? , Is there any workaround to make it work ?? Reference : https://github.com/sabricot/django-elasticsearch-dsl/issues/36 models.py class Web_Technology(models.Model): web_results = JSONField(blank=True,null=True,default=dict) web_results field format {"http://google.com": {"Version": "1.0", "Server": "AkamaiGHost"}} documents.py from elasticsearch_dsl import Index from django_elasticsearch_dsl import Document, fields from django_elasticsearch_dsl.registries import registry from .models import Web_Technology @registry.register_document class WebTechDoc(Document): web_results = fields.ObjectField() def prepare_content_json(self, instance): return instance.web_results class Index: name = 'webtech' class Django: model = Web_Technology fields = [] `→ python3 manage.py search_index --create -f Creating index '<elasticsearch_dsl.index.Index object at 0x7f368d6e4978>' Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.5/dist-packages/django_elasticsearch_dsl/management/commands/search_index.py", line 128, in handle self._create(models, options) File "/usr/local/lib/python3.5/dist-packages/django_elasticsearch_dsl/management/commands/search_index.py", line 84, in _create index.create() File "/usr/local/lib/python3.5/dist-packages/elasticsearch_dsl/index.py", line 254, in create self._get_connection(using).indices.create(index=self._name, body=self.to_dict(), **kwargs) File "/usr/local/lib/python3.5/dist-packages/elasticsearch/client/utils.py", line 84, in _wrapped return func(*args, params=params, **kwargs) File "/usr/local/lib/python3.5/dist-packages/elasticsearch/client/indices.py", line 105, in create "PUT", _make_path(index), params=params, body=body File "/usr/local/lib/python3.5/dist-packages/elasticsearch/transport.py", line 350, in perform_request timeout=timeout, File "/usr/local/lib/python3.5/dist-packages/elasticsearch/connection/http_urllib3.py", line 252, in perform_request self._raise_error(response.status, raw_data) File "/usr/local/lib/python3.5/dist-packages/elasticsearch/connection/base.py", line … -
How to fix "required parameter name not set" in django
I am having a problem adding amazon S3 in my Django app, and the server keeps returning "value error required parameter name not set".please I need help because I am about to quit. ValueError at /app/ Required parameter name not set Request Method: GET Request URL: http://127.0.0.1:8000/app/ Django Version: 2.0.13 Exception Type: ValueError Exception Value: Required parameter name not set Exception Location: C:\Python34\lib\site- packages\boto3\resources\base.py in __init__, line 119 Python Executable: C:\Python34\python.exe Python Version: 3.4.4 Python Path: ['C:\\Users\\Mustapha\\Desktop\\Myfirstapp', 'C:\\WINDOWS\\SYSTEM32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages'] Server time: Wed, 11 Sep 2019 01:20:16 +0000 templates required parameter not set: <img src="{{Blogger.image.url}}" width="70" height="70" class="c" /> -
add Formset for specific fields in a Django ModelForm
I have a form but I want to add Formset feature specific to fields. So how can I achieve this? model.py : class somemodel(model.): name=models.TextField(blank=True,null=True) somefield=models.TextField(blank=True,null=True) somefield=models.TextField(blank=True,null=True) somefield=models.TextField(blank=True,null=True) form.py: class somemodelForm(forms.ModelForm): name=forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class': 'form-control'})) #I want to give Formset feature for these bellow fields somefield=forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class': 'form-control'})) somefield=forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class': 'form-control'})) somefield=forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model=somemodel fields='__all__' So those are the information and I want to add Formset feature for only "somefield" fields, not to "name" field. -
How to do python setup in CPanel
python Already have a main website, e,g. example.com and I want to add a Django one within it, How to do this in CPanel tell me with that example? tnx to advance? -
Django Rest & React: lookup_field = 'slug' not returning item from db
I'm trying to return items from my sqlite db such that the url in the browser reflects the slug, rather than the unique post id. I had this working before by using the primary key, whereby items were returned from the db when clicking a hyperlink for item detail - but swapping everything out for slug is not working. I have a PostListView in react which lists my items from the db successfully, when I click on one of these the url field in the browser properly shows the slug. However, no data is returned from the db in the underlying detail view. I am using django 2.2.1, django rest framework and react. Back end - django and rest framework modules: Models.py class Post(models.Model): post_id = models.UUIDField( primary_key=True, default=uuid.uuid4, help_text='Unique ID for this post') title = models.CharField(max_length=100) content = models.TextField() publish_date = models.DateTimeField(auto_now=True) slug = models.SlugField(default='') api/views.py class PostListView(ListAPIView): queryset = Post.objects.all() serializer_class = PostSerializer class PostDetailView(RetrieveAPIView): queryset = Post.objects.all() serializer_class = PostSerializer lookup_field = 'slug' api/urls.py urlpatterns = [ path('', PostListView.as_view()), path('<slug>', PostDetailView.as_view()), ] api/serializers.py class PostSerializer(serializers.ModelSerializer): ''' Serialisers will convert our JSON from web into python model ''' class Meta: model = Post fields = ('post_id', 'slug', 'title', … -
How to do RDS IAM Authentication with Django?
I want my django application connect to RDS postgres using IAM authentication. That means the db password expires every 15min and should be re-generated. The problem is how can I change the database password in the runtime? Or should I update my database URL environment? -
Displaying data in template
Hello guys i cannot display this data on my template i have tried few methods but failed is there any solution views.py def list_page(request): qs = Add.objects.annotate(month=TruncDate('date') ).values('month').annotate( total_income=Sum('budget'), total_expense=Sum('expense') ).order_by('date') for i in xy: print (ws['month'],) x = {'qs':qs,} return render(request, 'list_page.html', x) printing only in console and not clearly printing in template. -
Error while installing mysqlclient for windows
While installing mysqlclient for python in windows10 using pip an error is raising.I already installed mysql db. pip install mysqlclient it is giving error like this Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/4d/38/c5f8bac9c50f3042c8f05615f84206f77f03db79781db841898fde1bb284/mysqlclient-1.4.4.tar.gz Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: 'h:\python3.7.2\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\varun\\AppData\\Local\\Temp\\pip-install-x8dma35a\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\varun\\AppData\\Local\\Temp\\pip-install-x8dma35a\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\varun\AppData\Local\Temp\pip-record-iljjp945\install-record.txt' --single-version-externally-managed --compile cwd: C:\Users\varun\AppData\Local\Temp\pip-install-x8dma35a\mysqlclient\ Complete output (24 lines): running install running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'h:\python3.7.2\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\varun\\AppData\\Local\\Temp\\pip-install-x8dma35a\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\varun\\AppData\\Local\\Temp\\pip-install-x8dma35a\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\varun\AppData\Local\Temp\pip-record-iljjp945\install-record.txt' --single-version-externally-managed --compile Check … -
Convert UTC time to local time in django
How can I convert to from UTC time to local time? Here is the format from frontend: Tue Sep 10 2019 00:00:00 GMT+0800 (Singapore Standard Time) This is the print result from Django: 2019-09-09T16:00:00.000Z This is how I convert to local time : def convert_to_localtime(utctime): # print(utctime) fmt = '%Y-%m-%d' utc = datetime.datetime.strptime(utctime,'%Y-%m-%dT%H:%M:%S.000Z' ).replace(tzinfo=pytz.UTC) localtz = utc.astimezone(timezone.get_current_timezone()) # print(localtz.strftime(fmt)) return localtz.strftime(fmt) this is the result from function: 2019-09-09 My expected result: 2019-09-10 -
Iterating list and collecting corresponding from model
I have model which consist of three fields and in the table should look something like this: drg_code | drg_kof | drg_count --------------------------------- A08A | 0.45 | 215 A08B | 0.75 | 656 B03A | 0.33 | 541 B03C | 0.22 | 125 Code for it models.py class DrgCode(models.Model): drg_code = models.CharField(max_length=4) drg_kof = models.DecimalField(max_digits=6, decimal_places=3) drg_count = models.IntegerField() def __str__(self): return self.drg_code I created form for user input which returns QuerySet of drg_code variables. It looks like this in in print: <QuerySet [<DrgCode: A05Z>, <DrgCode: A06A>, <DrgCode: A06C>]>. So I converted it into list. Now I need to iterate through that list and using drg_code variables, find corresponding model fields values, and store them in separate lists so in the end I should end with 3 lists: one for drg_code, one for drg_kof and one for drg_count (these list will be needed for future calculations). I tried using method from my earlier question, but I keep getting error AttributeError saying 'str' object has no attribute 'objects' or similar (depending on code variation I tried) on obj = DRGkodas.objects.first() line. My relevant view.py code: from catalog.models import DrgCode from catalog.forms import DrgCalculator #up to this part everything works so I … -
invitoBidForm' object has no attribute 'ProjectName'
Good days guys need help for my ForeignKey Relationship in my models, i want my foreignkey values is equal to the user choose Here's my model view class ProjectNameInviToBid(models.Model): ProjectName = models.CharField(max_length=255, verbose_name='Project Name', null=True) DateCreated = models.DateField(auto_now=True) def __str__(self): return self.ProjectName have relations to ProjectNameInviToBid class InviToBid(models.Model): today = date.today() ProjectName = models.ForeignKey('ProjectNameInviToBid', on_delete=models.CASCADE, null=True) NameOfFile = models.CharField(max_length=255, verbose_name='Name of File') Contract_No = models.IntegerField(verbose_name='Contract No') Bid_Opening = models.CharField(max_length=255, verbose_name='Bid Opening') Pre_Bid_Conference = models.CharField(max_length=255, verbose_name='Pre Bid Conference') Non_Refundable_Bidder_Fee = models.CharField(max_length=255, verbose_name='Non Refundable Fee') Delivery_Period = models.CharField(max_length=255, verbose_name='Delivery Period') Pdf_fileinvi = models.FileField(max_length=255, upload_to='upload/invitoBid', verbose_name='Upload Pdf File Here') Date_Upload = models.DateField(auto_now=True) This is my form view class invitoBidForm(ModelForm): class Meta: model = InviToBid fields = ('ProjectName','NameOfFile', 'Contract_No', 'Bid_Opening', 'Pre_Bid_Conference', 'Non_Refundable_Bidder_Fee', 'Delivery_Period', 'Pdf_fileinvi') and Lastly this my view Forms def project_name_details(request, sid): majordetails = ProjectNameInviToBid.objects.get(id=sid) if request.method == 'POST': form = invitoBidForm(request.POST, request.FILES) if form.is_valid(): majordetails = form.ProjectName form.save() messages.success(request, 'File has been Uploaded') else: form = invitoBidForm() args = { 'majordetails': majordetails, 'form': form } return render(request,'content/invitoBid/bacadmininvitoBid.html', args) but im have a error,, hope you can help me. thank you in advance -
how calculation be done in JSON object elements
I have declared instalment_2 as JSONField in Django model . My concern here is I am getting below error : string indices must be integers kindly help me how to solve this . I tried all ways which were available in internet . But no luck . "instalment_2":{"type":"instalment_2","mode":"cash","date":"1/09/2019","amount":"35000"} I am passing this JSON as Post request it should calculate paid n balance based on instalment amounts . Instalment_1 amount already in the table. Now I am trying to do below by passing instalment_2. . instalment_2={"type":body['instalment_2']['type'],"mode":body['instalment_2']['mode'],"date":body['instalment_2']['date'],"amount":body['instalment_2']['amount']} paid=int(obj.instalment_1['amount'])+int(obj.instalment_2['amount']) balance=int(obj.total)-paid -
Recommended Web Technology for an e-commerce product
I need help in choosing the right technology stack for my client's project. The website will provide services for pets by connecting the pet owner to the pet sitter. There will be no physical products to sell on the website. It will be just services like walking, grooming., etc for the customer to choose from the website. The website will primarily connect the pet walker or the pet sitter to the customer in getting these services. https://www.rover.com is a good example of what I am trying to build. We will also be building mobile apps for the same. My experience is mostly in Python and PHP. I have worked primarily on Django, Magento and Codeigniter based projects. But now I started learning NodeJs and I started liking it. So I thought of trying this new website using MEAN stack. But I am not sure if NodeJs is right for such a website. Or should I just stick to Django?