Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        
How to change model attribute value from another model method
in my e commerce website , i need to make cart model active attribute value changed to False once order instance is saved so user can start a new cart after order has saved or in whatever case i determine here are my snippets: class Order(models.Model): user = models.ForeignKey(User,null=True, blank=True, on_delete=models.CASCADE) shipping_address = models.ForeignKey(Address, on_delete='CASCADE',related_name="shipping_address",null=True, blank=True) order_id = models.CharField(max_length=120, blank=True) cart = models.ForeignKey(Cart,on_delete=models.CASCADE) status = models.CharField(max_length=120, default="created", choices=ORDER_STATUS_CHOISES) shipping_total = models.DecimalField(default=5.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) active = models.BooleanField(default=True) date_posted = models.DateTimeField(default=timezone.now) # objects = OrderManager() def __str__(self): return self.order_id #self.__class__.classAttr def save(self): super(Order, self).save() if not self.cart.active ==False: self.cart.active =False self.save() class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) products = models.ManyToManyField(Product, blank=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) def checkout_home(request): cart_obj, cart_created = Cart.objects.get_or_create(user=request.user, active=True) order_obj = None if cart_created or cart_obj.products.count() == 0: return redirect("carts:home") login_form = LoginForm() address_form = AddressForm() shipping_address_id = request.session.get("shipping_address_id", None) address_qs = None if request.user.is_authenticated: address_qs = Address.objects.filter(user=request.user) order_obj, order_obj_created = Order.objects.get_or_create(active=True,user=request.user, status='Created',cart=cart_obj) if shipping_address_id: order_obj.shipping_address = Address.objects.get(id=shipping_address_id) del request.session["shipping_address_id"] order_obj.save() context = { "object": order_obj, "login_form": login_form, "address_form": address_form, "address_qs": address_qs,} return render(request, "carts/checkout.html", context) this … - 
        
Django: Retrieving the private key of selected dropdown option in Ajax call
I have two models like this: class ScenarioMarket(models.Model): title = models.CharField(max_length=50, default="") description = models.TextField(default="") b = models.IntegerField(default=100) cost_function = models.IntegerField(default=0) open = models.BooleanField(default=True) def __str__(self): return self.title[:50] def get_absolute_url(self): return reverse('market_detail', args=[str(self.id)]) class Scenario(models.Model): description = models.TextField(default="") current_price = models.DecimalField(max_digits=5, decimal_places=2, default=0.00) share = models.IntegerField(default=0) market = models.ForeignKey( ScenarioMarket, on_delete=models.CASCADE, related_name='scenarios', default=None) def __str__(self): return str(self.description) In my template, I have a dropdown menu that loops over (the descriptions of) all the scenarios available on the scenario market in question, with each option taking the pk of the relevant scenario as its value: <form action="" method="GET" id="scenario-dropdown"> {% csrf_token %} <select> {% for description in scenariomarket.scenarios.all %} <option value="{{ scenario.id }}"> {{ description }} </option> {% endfor %} </select> </form> What I then want to do is pick up the pk of the selected option in the dropdown menu in an Ajax call. I thought I would be able to it this way: var scenario_id = document.getElementById("scenario-dropwdown").value But looking in the console, I get Uncaught TypeError: Cannot read property 'value' of null, so clearly it's not working - likely with respect to the <form>. What am I doing wrong? - 
        
Django: Save objects with circular references
I'm using Django with the PostgreSQL backend. Now, I've two models with circular references: Thread exists of a startpost of type Post Post exists of a thread of type Thread My problem is that I cannot create any of the two objects because they are dependent on each other. One solution to that problem is the DEFERRABLE INITIALLY DEFERRED constraint that is also supported by PostgreSQL. After some research I found the following post: https://www.reddit.com/r/django/comments/72qwr6/why_does_the_postgresql_backend_make_foreignkeys/ So it looks like that Django also supports this and, as long as you create your objects in a transaction, it should work. However, when I test it I get an IntegrityError, it looks like my Django did not create the DEFERRABLE INITIALLY DEFERRED constraint. I'm confused. Can someone clarify the situation? Did I miss something? - 
        
TemplateDoesNotExist Django Version: 2.2.3
I'am learning django and building a page,I get the TemplateDoesNotExist error, I don't know how to fix this.But I don't know show what part's of the code. TemplateDoesNotExist at / Leaning_logs/base.html Request Method: GET Request URL: http://localhost:8000/ Django Version: 2.2.3 Exception Type: TemplateDoesNotExist Exception Value: Leaning_logs/base.html Exception Location: D:\learning-note\ll_env\lib\site-packages\django\template\backends\django.py in reraise, line 84 Python Executable: D:\learning-note\ll_env\Scripts\python.exe Python Version: 3.7.3 Python Path: ['D:\learning-note', 'C:\Users\qingting_bailihua\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\qingting_bailihua\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\qingting_bailihua\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\qingting_bailihua\AppData\Local\Programs\Python\Python37', 'D:\learning-note\ll_env', 'D:\learning-note\ll_env\lib\site-packages'] Server time: Thu, 1 Aug 2019 10:45:39 +0000 - 
        
How to get the related model class name from a ManyToOneRel object?
I have a class structure like the following: class Parent(models.Model): some_fields = ... def get_related_child_file_models_info(self): """ This return a generator containing all the related file model info for each child """ links = ( [f.name, f] for f in self._meta.get_fields() if (f.one_to_many or f.one_to_one) and f.auto_created and not f.concrete and "files" in f.name ) return links class ChildFileA(models.Model): ... parent = models.ForeignKey( on_delete=models.CASCADE, related_name="child_a_files" ) file = models.FileField() ... class ChildFileB(models.Model): ... parent = models.ForeignKey( on_delete=models.CASCADE, related_name="child_b_files" ) file = models.FileField() ... If I use this generator inside a for loops I get ['child_a_files', <ManyToOneRel: app_name.childfilea>] and ['child_b_files', <ManyToOneRel: app_name.childfileb>] The goal is to handle a complex files upload process where I have around 30 different models to store some files for each parents. And I try to avoid having to manually create the code for each. How to get the class name ChildFileA and ChildFileB from the ManyToOneRel object? - 
        
Django Management Command : 'Command' object has no attribute 'META'
I have a Management command, that prints out a function output. But after execution it gives an error. What is the error and how to resolve it? (VE) C:\Users\Bitswits 3\Desktop\LCRProject\LeastCostRouting>python manage.py my_dest_commands {'48': ['Tata', ' 0.531', 'Tata', ' 0.531', 'Tata', ' 0.531', 'Tata', ' 0.531', 'Tata', ' 0.531', 'Tata', ' 0.531'], '23': ['Tata', ' 4.150', 'Tata', ' 4.150', 'Tata', ' 4.150', 'Tata', ' 4.150', 'Tata', ' 4.150', 'Tata', ' 4.150', 'PTCL', ' 0.888', 'PTCL', ' 0.888', 'PTCL', ' 0.888', 'PTCL', ' 0.888', 'PTCL', ' 0.888', 'PTCL', ' 0.888'], '96': ['Tata', ' 1.260', 'Tata', ' 1.260', 'Tata', ' 0.205', 'Tata', ' 0.205', 'Tata', ' 0.030', 'Tata', ' 0.030', 'Tata', ' 0.305', 'Tata', ' 0.305', 'Tata', ' 1.260', 'Tata', ' 1.260', 'Tata', ' 0.205', 'Tata', ' 0.205', 'Tata', ' 0.030', 'Tata', ' 0.030', 'Tata', ' 0.305', 'Tata', ' 0.305', 'Tata', ' 1.260', 'Tata', ' 1.260', 'Tata', ' 0.205', 'Tata', ' 0.205', 'Tata', ' 0.030', 'Tata', ' 0.030', 'Tata', ' 0.305', 'Tata', ' 0.305', 'PTCL', ' 0.150', 'PTCL', ' 0.150', 'PTCL', ' 0.005', 'PTCL', ' 0.005', 'PTCL', ' 0.305', 'PTCL', ' 0.305', 'PTCL', ' 0.150', 'PTCL', ' 0.150', 'PTCL', ' 0.005', 'PTCL', ' 0.005', 'PTCL', ' 0.305', 'PTCL', ' 0.305', 'PTCL', ' 0.150', … - 
        
How to assign the object or model to the child model which is Generic Foriegn key
i have a model which i made it as a generic foriegn key and i want to apply the related parent model to it in the views while posting the form my models: class ContactDetails(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE,blank=True) object_id = models.PositiveIntegerField(null=True) content_object = GenericForeignKey('content_type', 'object_id') address = models.TextField() telephone = models.CharField(max_length=15, blank=True) mobile = models.CharField(max_length=15, blank=True) email = models.EmailField(blank=True) class Supplier(models.Model): name = models.CharField(max_length=100) mobile = models.CharField("Primary Mobile", max_length=15, unique=True) email = models.EmailField() my views.py def supplier_registration(request): details_formset = generic_inlineformset_factory(ContactDetails, form=ContactDetailsForm, ct_field='content_type', fk_field='object_id',extra=1) if request.method=="POST": form = SupplierForm(request.POST) formset = details_formset(request.POST) if form.is_valid() and formset.is_valid(): f = form.save() fs = formset.save(commit =False) for i in fs: i.content_type = Supplier i.object_id = f.id i.save() return redirect('/suppliers/') else: form = SupplierForm() formset = details_formset() return render(request , 'single_form.html',{'form':form,'formset':formset}) i am getting error : 'NoneType' object has no attribute '_meta' - 
        
AWS S3: image is uploading to bucket but file is not showing in heroku Django
Image is uploading to bucket, but it is not showing in the app when it runs. Please help here Iam using Employee.objects.all() function to fetch the details from database. Please have a look on it and please help me site adress is : https://mttemployee.herokuapp.com you can test it using, user name: first and emp Id: 1 please help me fast settings.py file import os import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') SECRET_KEY = '=^tpe+kln3xg-_kclfay62+4l6c@_l%fj_^k@h0xc5%(0cp^h9' DEBUG = True ALLOWED_HOSTS = ['mttemployee.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'manager', 'storages' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'empmanagement.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'empmanagement.wsgi.application' # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'empmanage', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'USER': 'postgres', 'PASSWORD': '1234', 'HOST': 'localhost', } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ … - 
        
Dockerfile configuration for apache serving django project
Currently i'm trying to deploy my django app via docker. I just started to learn the hole thing, so now I want to build an image based on httpd official image that creates new blank django project (just to try) and serves it by apache. (I am using ubuntu 18) My Dockerfile: FROM httpd RUN apt-get update && apt-get upgrade -y RUN apt-get remove --purge apache2 apache2-utils \ && apt-get install -y --reinstall apache2 apache2-utils RUN apt-get install -y libapache2-mod-wsgi-py3 RUN apt-get install -y python3 python3-pip python3-venv RUN mkdir /home/django_project ENV VIRTUAL_ENV=/home/django_project/venv RUN python3 -m venv $VIRTUAL_ENV ENV PATH="$VIRTUAL_ENV/bin:$PATH" WORKDIR /home/django_project RUN . venv/bin/activate \ && pip install django==2.1 \ && django-admin startproject new \ && chown :www-data new/ RUN . venv/bin/activate && python new/manage.py migrate RUN chown :www-data new/db.sqlite3 && chmod 664 new/db.sqlite3 COPY django-site.conf /etc/apache2/sites-available/django-site.conf RUN a2ensite django-site.conf && a2dissite 000-default.conf && a2dissite default-ssl.conf EXPOSE 80 And django-site.conf (apache configuration for new site): <VirtualHost *:80> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static "/home/django_project/new/static" Alias /media "/home/django_project/new/media" <Directory "/home/django_project/new/static"> Require all granted </Directory> <Directory "/home/django_project/new/media"> Require all granted </Directory> <Directory "/home/django_project/new/new"> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / "/home/django_project/new/new/wsgi.py" WSGIDaemonProcess example.com python-path="/home/django_project/new" python-home="/home/django_project/venv" WSGIProcessGroup example.com </VirtualHost> after … - 
        
Django set ManytoManyField to default user model
I need to set a manytomany relation to default django user table.Is there any way to implement it rather than using AbstractUser method of django (extending User Model)? - 
        
Unable to Pass SQL Object From Python to Javascript in Django
I am trying to send a single SQL object to my Javascript in Django using json.dumps however I get the error: Object of type List is not JSON serializable when I run the following code: user_data = List.objects.get(user=request.user.username) context['list'] = json.dumps(user_data) return render(request, "template.html", context) The SQL Object has three fields, the first is a username and the other two are lists. Please can you tell me how to convert this to JSON correctly. - 
        
Display group name of user with a template
For the staff members of my website, I am displaying a list of all users registered and I want to display their group. It's working except that I get <QuerySet [<Group: UserGroup>]> instead of UserGroup. Tried to use group = form.cleaned_data['group_name'] but I get this error: invalid literal for int() with base 10: 'Viewers' at user.groups.add(group). forms.py: class RegisterForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False) last_name = forms.CharField(max_length=30, required=False) Group = [('Viewers', 'Viewers'), ('Editors', 'Editors'), ('Creators', 'Creators'), ('Staff', 'Staff'), ] group_name = forms.ChoiceField(choices=Group) is_active = forms.BooleanField(initial=True, required=False) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'group_name', 'is_active', ) views.py: @login_required @group_required('Staff') def registerView(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = form.save() group = Group.objects.get(name=request.POST.get('group_name')) user.groups.add(group) return redirect('accounts:users') else: form = RegisterForm() return render(request, 'accounts/register.html', {'form': form}) # Display all active users in a table class UserView(LoginRequiredMixin, GroupRequiredMixin, ListView): template_name = 'accounts/display_users.html' group_required = ['Staff'] queryset = User.objects.filter(is_active=True) display_users.html: {% block main %} <table class="table"> <thead class="thead-dark"> <p> <tr> <th scope="col"># id</th> <th scope="col">Username</th> <th scope="col">Group</th> <th scope="col">Email address</th> <th scope="col">First name</th> <th scope="col">Last name</th> </tr> </thead> {%for instance in object_list%} <tbody> <tr> <td>{{instance.id}}</td> <td><a href = "{% url 'accounts:update' instance.id %}">{{instance}}</a></td> <td>{{instance.groups.all}}</td> <td>{{instance.email}} … - 
        
How to update a single field in a model using UpdateAPIView from Djangorestframework?
I'm learning generic views and creating some Api's. How can I update the field: "mobile" from Model :"Contacts"? I want to get the user id from url(mobile/update/user_id). But while creating the queryset its not working. I want to do something like mentioned here(#queryset = Contacts.objects.filter(id=Usertab.objects.filter(id=self.kwargs['id']).first().contact.id)) '''python class UpdateMobileAPIView(generics.UpdateAPIView): queryset = Contacts.objects.filter(pk=Usertab.objects.all()) serializer_class = ContactsSerializer lookup_field = 'pk' def update(self,instance,request): instance = self.get_object() serializer= self.get_serializer(instance,data=request.data,partial=True) if serializer.is_valid(): serializer.save() return Response({"message":"mobile number updated successfully"}) else: return Response({"message":"failed"}) ''' These are models class Contacts(models.Model): mobile = models.IntegerField(null=False) Landline = models.IntegerField(null=False) whats_app = models.IntegerField(null=False) class Usertab(models.Model): username = models.CharField(max_length=255,null=False,blank=False) address = models.CharField(max_length=255,null=False,blank=False) pin_code = models.CharField(max_length=255,null=False,blank=False) contact = models.ForeignKey(Contacts,related_name="contacts_user") class Email(models.Model): user = models.ForeignKey(Usertab,related_name="user_email") email = models.CharField(max_length=255,null=False,blank=False) is_verified = models.BooleanField(default=False) ''' '''this is the serializer class ContactsSerializer(ModelSerializer): class Meta: model = Contacts fields = '__all__' def update(self, instance, validated_data): instance.mobile = validated_data.get('mobile', instance.mobile) instance.save() return instance ''' TypeError: update() got an unexpected keyword argument 'pk' - 
        
Editing an existing form
This is what my merchant_edit is. If i dont pass an args into form.save(), I get this error "Django - missing 1 required positional argument: 'request'", so I pass 'request' as an args i.e form.save(request) to escape from that error. Now my merchant_edit view creates a new data i.e new data are added instead of them to be edited, how can I make edit an exisitng form instead of creating a new form. And I get pointed to the exact pk url's i.e http://127.0.0.1:8000/merchant/10/edit for edit but it creates a new form and a new pk for the new data. def merchant_edit(request,pk): template_name = 'merchants/edit.html' merchant=Merchant.objects.get(pk=pk) if request.method=='POST': form=CreateMerchantForm(request.POST, instance=agent) if form.is_valid(): form.save(request) messages.success(request,'data Updated Successfully.') return HttpResponseRedirect(reverse_lazy('merchant')) else: form=CreateMerchantForm(instance=agent) return render(request, template_name, {'form':form}) urls.py path('merchant/<int:pk>/edit', views.merchant_edit, name='merchant_edit'), - 
        
How to store KMeans object in Django database?
I am storing a tree in the Django database, whose nodes each contains a K means object. How do I store a K means object in Django data field? Also, for saving a tree to a database, for the left and right of the node is it possible to use foreign keys which point back to the same database? Thanks for your help. I saw something called pickle which saves to a machine learning model to a file and loads it later, but was wondering if there's another way of serializing. - 
        
How to iterate properly in django template with this specific data
I have these variables called: srodki (simple list with 2 values), roles (array of arrays with some roles) and formsets (array of arrays with some formsets) i've separated them this way because I want the template to look like this: srodki.name role formset The thing is, that my codes iterates like this: srodki.name role formset formset These formsets have certain initial values passed to them, but instead of outputting the correct formset it just shows both of them because i dont know hot to iterate 2 of these at the same time inside another for loop (that is looping through srodki) I though about use of dictionaries but couldn't implement it correctly My views: def EventSily(request, event_id): event = Event.objects.get(pk=event_id) srodki = SiSvalue.objects.filter(event=event) roles_count = 0 SilyFormset = modelformset_factory(EventWork, fields=('event', 'role', 'worker', 'start_time', 'end_time')) roles = [] formsets = [] for each in srodki: roles_array = [] formsets_array = [] srodki_sis = each.sis role_srodka = Roles.objects.filter(srodek=srodki_sis) for role in role_srodka: roles_array.append(role.name) roles_count += 1 print(role) formset = SilyFormset(initial=[{'event' : event, 'role' : role}]) formsets_array.append(formset) roles.append(roles_array) formsets.append(formsets_array) if request.method == "POST": for formset in formsets: formset = SilyFormset(request.POST) mylist = zip(srodki, roles, formsets) context = { 'event' : event, 'mylist' : … - 
        
fetch data with condition
I am doing a movie booking project in which i want to time of particular cinema def movies(request, id): cin = Cinema.objects.filter(shows__movie=id).distinct() movies = Movie.objects.get(movie=id) show = Shows.objects.filter(movie=id) context = { 'movies':movies, 'show':show, 'cin':cin, } return render(request, "movies.html", context ) movies.html HTML file can i do something to get time of cinema <div class="card"> <img class="card-img-top" src="{{movies.movie_poster.url}}" alt="Card image cap"> <div class="card-body"> <h4 class="card-title">{{movies.movie_name}}</h4> <p class="card-text">{{movies.movie_rating}}</p> </div> <ul class="list-group list-group-flush"> {% for cin in cin %} <li class="list-group-item"><b>Cinema {{cin}}</b></li> {% for show in show %} <li class="list-group-item"> Time : {{show.time}}</li> {% endfor %} {% endfor %} </ul> </div> models.py file so you can get detail of my database structure ( i just want to fetch movie with its show but based on cinema separate ) class Cinema(models.Model): cinema=models.AutoField(primary_key=True) role=models.CharField(max_length=30,default='cinema_manager') cinema_name=models.CharField(max_length=50) phoneno=models.CharField(max_length=15) city=models.CharField(max_length=100) address=models.CharField(max_length=100) user = models.OneToOneField(User,on_delete=models.CASCADE) def __str__(self): return self.cinema_name class Movie(models.Model): movie=models.AutoField(primary_key=True) movie_name=models.CharField(max_length=50) movie_des=models.TextField() movie_rating=models.DecimalField(max_digits=3, decimal_places=1) movie_poster=models.ImageField(upload_to='movies/poster', default="movies/poster/not.jpg") def __str__(self): return self.movie_name class Shows(models.Model): shows=models.AutoField(primary_key=True) cinema=models.ForeignKey('Cinema',on_delete=models.CASCADE) movie=models.ForeignKey('Movie',on_delete=models.CASCADE) time=models.CharField(max_length=100) seat=models.CharField(max_length=100) price=models.IntegerField() def __str__(self): return self.cinema.cinema_name +" | "+ self.movie.movie_name +" | "+ self.time Output i am getting now (image attached) - 
        
AWS django Invalid HTTP_HOST header
I'm depolying my app onto Elasticbeanstalk. When I visit the url, I get Invalid HTTP_HOST header:'mysite.com'. I've added my url to my settings.py. This is my settings file: ALLOWED_HOSTS = ['mysite.com/','.mysite.com/', '127.0.0.1:8000', '127.0.0.1', 'localhost', 'localhost:8000', '13.59.177.101', '127.0.0.1'] This is my python.config file: `container_commands: 01_migrate: command: "source /opt/python/run/venv/bin/activate && python manage.py migrate" leader_only: true 02_collectstatic: command: "source /opt/python/run/venv/bin/activate &&python manage.py collectstatic --noinput" option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "project.settings" PYTHONPATH: "$PYTHONPATH" "ALLOWED_HOSTS": ".elasticbeanstalk.com" "aws:elasticbeanstalk:container:python": WSGIPath: "/opt/python/current/app/project/wsgi.py" StaticFiles: "/static/=www/static/" packages: yum: postgresql95-devel: []` My code works locally without any problem. Not sure what to do. Please help! - 
        
Django deserialize two fields into one using custom field
Hi I am trying to patch or update a data in Django using serializers. I want to make use of Custom Field to deserialize a PointField from a data with latitude and longitude. I want to parse longitude and latitude from my data and pass it to a Point object and in turn save it my model's PointField(). #test.py from django.test import Client class CaptureTests(TestCase): def test_patch(self): c = Client() response = c.post('/admin/login/', {'username': 'admin', 'password': 'adminpass'}) location = { "type": "Point", "coordinates": [120.20, 18.20, 300.20] } included_meta = { 'location': location, 'processor': 'L1B' } response = c.patch( '/captures/CAM-01/', data=json.dumps(included_meta), content_type='application/json') response = c.get("/captures/CAM-01/") results = response.json() print("RESULTS!", results) #serializers.py from django.contrib.gis.geos import Point class PointFieldSerializer(serializers.Field): # Point objects are serialized into "Point(X, Y, Z)" notation def to_representation(self, value): return f'{"type": "Point", "coordinates": [{value.longitude}, {value.latitude}, {value.altitude}]}' # return f"{"type": "Point", "coordinates": [%d, %d, %d]}" % (value.longitude, value.latitude, value.altitude) def to_internal_value(self, data): data = json.loads(data) location = data['location']['coordinates'] longitude = location[0] latitude = location[1] altitude = location[2] return Point(float(longitude), float(latitude), float(altitude)) class CaptureUpdateSerializer(serializers.ModelSerializer): location = PointFieldSerializer class Meta: model = Capture fields = '__all__' class CaptureViewSet(CaptureFiltersMixin, viewsets.ModelViewSet): def partial_update(self, request, capture_id=None): data = request.data print("DATA!", data) # {'location': {'type': 'Point', 'coordinates': … - 
        
Error in vobject file when i use ajax form uploaded file in my python code
I am uploading vcf file by django form and want to convert into vobject but it will give error. When I have tried with take following code it will work... file = open('test.vcf', 'r') but in belowed code it is not working... file = request.FILES.get('vcf_file') with file as f: vc = vobject.readComponents(str(f.read()).encode('utf-8')) vo = next(vc, None) while vo is not None: fname = vo.contents.get('fn')[0].value email = vo.contents.get('email')[0].value if vo.contents.get('email') else '' numbers = [] if vo.contents.get('tel'): for v in vo.contents['tel']: no = v.value.replace("-", "") if no not in numbers and no[-10:] not in numbers[-10:]: numbers.append(no) print(fname, ', ', numbers, ', ', email) vo = next(vc, None) I except output like Pravin , ['+91971282123'] , VH Patel , ['+918511123341'] , but it through following error: File "/home/vahta/Desktop/phonebook/phonebook/views.py", line 151, in import_vcf vo = next(vc, None) File "/home/vahta/vhcshop_env/lib/python3.5/site-packages/vobject/base.py", line 1101, in readComponents vline = textLineToContentLine(line, n) File "/home/vahta/vhcshop_env/lib/python3.5/site-packages/vobject/base.py", line 925, in textLineToContentLine return ContentLine(*parseLine(text, n), **{'encoded': True, File "/home/vahta/vhcshop_env/lib/python3.5/site-packages/vobject/base.py", line 813, in parseLine raise ParseError("Failed to parse line: {0!s}".format(line), lineNumber) vobject.base.ParseError: At line 1: Failed to parse line: b'BEGIN:VCARD\r\nVERSION:3.0\r\nN:vdfn;Pravin;;;\r\nFN:Pravin vdfn\r\nTEL;TYPE=CELL:+919712823033\r\nTEL;TYPE=CELL:+919712823033\r\nEND:VCARD\r\n - 
        
I need to implement rating feature , in which listing space can be rate , i need urgent help ,kindly help me
i need to implement rating feature in my fyp project, to rate listing kindly help me i dont know how to implement rating with stars. tommorow is my submission kindly help . i tried many api but didnot work for me class Comment(models.Model): RATING_RANGE = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5') ) listing = models.ForeignKey (Listing, on_delete=models.CASCADE,related_name='rates') user = models.ForeignKey (User, on_delete=models.CASCADE,default=1 ) content = models.TextField(max_length=250) created_date = models.DateTimeField(auto_now_add=True) approved_comment = models.BooleanField(default=False) rating = models.IntegerField(choices=RATING_RANGE, default='3') forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['content','rating'] widgets = { 'content': Textarea(attrs={ 'class' : 'input', 'class' : 'form-control', 'placeholder': ' Enter comment here !!', 'cols': 100, 'rows': 5}), } listing.html <div class="comments-content"> <div class="row"> <div class="col-lg-8 col-sm-12" ><h2> Reviews ( {{ comments.count }} ) </h2> </div> </div> <div class="row" style="margin-bottom:10px;"> <div class=" col-sm-12" > <div class=" read-more-content-wrapper"> {% for comment in comments %} {% if comment.user.profile.photo.url is not None %} <span> <img src=" {{comment.user.profile.photo.url}}"> <p class="mb-0"> {{comment.content}}</p> <p class="mb-0"> Rating From 5 : {{comment.rating}}</p> By <cite title="Source Title">{{comment.user | capfirst}}</cite></span> <hr class="col-lg-12 col-sm-12 no-gutter"> <p class="mb-0"> {{comment.content}}</p> <p class="mb-0"> Rating From 5 : {{comment.rating}}</p> By <cite title="Source Title">{{comment.user | capfirst}}</cite></span> <hr class="col-lg-12 col-sm-12 no-gutter"> {% … - 
        
How to inherit a variable from a class?
I have a two class. I need to inherit the technology field and redefine it in the child class. class SkillGroupCreateForm(forms.ModelForm): def __init__(self, *args, employee_pk=None, **kwargs): super(SkillGroupCreateForm, self).__init__(*args, **kwargs) self.fields['technology'].required = False if employee_pk is not None: self.fields['technology'].queryset = Technology.objects.exclude(skill__employee_id=employee_pk) My code class SkillCreatePLanguageForm(SkillGroupCreateForm): def __init__(self, *args, **kwargs): super(SkillCreatePLanguageForm, self).__init__(*args, **kwargs) self.fields['technology'].queryset = self.fields['technology'].filter(group__name="Programming language") gives out an error ModelChoiceField' object has no attribute 'filter' - 
        
How to add E-mail OTP generation and verification in django
Unable to Generate Email OTP verification in django through serializer I want to generate an otp that will be sent on Email and verified such that my user would be verified - 
        
Django: Is it possible to create two objects with one CreateView?
Assume I have the two models Thread and Post. There exists a circular reference: A thread has a field called startpost (Post) and each Post has a reference to a Thread. Now, when a user wants to create a new Thread one has to create both a Thread and Post object. I'd like to use a ThreadCreateView, but I'm not sure how I can do it. A CreateView can only have one model in the model property. Also I wonder if I can use a ModelForm or if I have to create a custom Form with fields of both Post and Thread, which means that I would have to duplicate the constraints (that would be automatically created by a ModelForm, like max_length for a field). So, I wonder what's the best way to tackle that problem. Because of the cirucal reference the creation of the objects definitely has to happen in a transaction, but that's something else. - 
        
Problem importing module for GRAPHENE setting 'SCHEMA' in Django 2.2
I am new to django(installed version 2.2 in my virtualenv) and graphql. I tried to follow the instructions for setting up graphql in django from the following site https://docs.graphene-python.org/projects/django/en/latest/installation/ When I try to run the server with the url http://127.0.0.1:8000/graphql/ I get the following error. ImportError at /graphql/ Could not import 'django_root.schema.schema' for Graphene setting 'SCHEMA'. ModuleNotFoundError: No module named 'django_root'. I followed the instructions carefully but I am unable to get this right. Please help. I checked similar questions but it didn't help.