Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Filter: "Sort By" Feature
I want to sort the products based on boolean field "is_featured", date creation, and price. My goal: This is what i want to achieve. Images shows a website that I am taking ideas from. I currently have a checkbox filter (implemented through django-filter) for users to filter based on brand and category. You can see my "draft" here https://ecommercelsm.herokuapp.com/product/ I want to add a sort_by dropdown menu like the one in the attached image so that users can sort the orders of the products by featured, price or date creation after filtering or without. I do not know how to go about this. Can someone help? I feel like i need to add more fields to my ProductFilter. models.py class Product(MPTTModel): bool_choices = ( (True, 'Yes'), (False, 'No'), ) parent = TreeForeignKey('self', blank = True, null = True, related_name = 'children', on_delete=models.CASCADE) name = models.CharField(max_length=50) slug = models.SlugField(unique=True, null=False) category = TreeManyToManyField(Category, blank = True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name="product") price = models.DecimalField(max_digits=9, decimal_places=2) image = models.ImageField(blank = True, upload_to = 'images/') is_featured = models.BooleanField(choices=bool_choices) created_at = models.DateTimeField(auto_now_add = True) class Meta: db_table = 'product' class MPTTMeta: order_insertion_by = ['name'] class Brand(models.Model): name = models.CharField(max_length=30) class Category(MPTTModel): bool_choices = ( … -
Why does I am getting the following error[2020/08/16 12:10:47] HTTP GET /ws/ 503 [61.62, 127.0.0.1:41300]
[2020/08/16 12:10:47] HTTP GET /ws/ 503 [61.62, 127.0.0.1:41300] I'm using websockets for realtime data and when I run my server i get 503 error. -
How to load image in background of jumbotron in my django project?
I have been stuck in this for quite a while now. I am doing a project in Django in which I need to put an image in the background in the jumbotron. home.html {% extends 'blog/base.html' %} {% load static %} {% block content %} <header> <style> .jumbotron { background-image: url('{{STATIC_URL}}blog/home-bg.jpg'); background-size: cover; } </style> </header> <!-- JUMBOTRON --> <div class="jumbotron text-center"> <div class="container"> <h1>Welcome To CodeBlog</h1> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor</p> <a href="{% url 'blog-about' %}" class="btn btn-primary">Read More</a> </div> </div> //some more lines of code {% endblock %} home-bg.jpg is present in the static/blog/home-bg.jpg settings.py STATIC_URL = '/static/' But still, I am not getting what is expected. I am using Bootstrap4 and Django 2.2 -
my pdf download results, not showing an image, django
i have a problem, when i download the pdf, my image is not come out this is my html <img src="https://www.qries.com/images/banner_logo.png" height="120cm" width="121cm"> and this is my views.py def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = io.BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result, encoding='UTF-8') if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return HttpResponse('We had some errors<pre>%s</pre>' % escape(html)) def myview(request): #Retrieve data or whatever you need postingan_list = Pengajuan_SKTM.objects.filter() return render_to_pdf( 'pengurusan/surat.html', { 'pagesize':'A4', 'postingan_list' : postingan_list, }) -
Send json data with window.location.href
I try to write a function login to change page when user input user, password and touch login button. After fetch, I get the json file {user:'user', password:'password', status:'1'}. If status==1, then go to the home page, but in my case, I cannot get the json file in home page. Is it possible to send data with window.location.href? <script> function login(){ data = { user : document.getElementById('user').value, password : document.getElementById('password').value } package = { method: 'POST', body: JSON.stringify(data) } fetch("/account/do/login/", package) .then(function(response){ json = response.json() return(json) }) .then(function(json){ if(json.status==0){ window.location.href = "/account/login/" } if(json.status==1){ window.location.href = "/account/home/" } }) } </script> -
Why django listview couldn't get url parameter
I'm trying to implement a feature that shows events registered for the day by sending the year-month-day to url. But go to [http://127.0.0.1:8000/calendar/2020-08-16/] Reverse for 'calendar' with objects '(') not found. ['calendar/(?)P\d{4}-\d{2}-\d{2})/$'] error shows. I keep getting this kind of error. What's wrong with the listview? I need your help. urls.py url(r'^(?P<date>\d{4}-\d{2}-\d{2})/$', views.CalendarView.as_view(), name='calendar'), path('event/new/',views.event, name='event_new'), path('event/edit/<int:event_id>',views.event_edit, name='event_edit'), views.py class CalendarView(generic.ListView): model = Event template_name = 'cal/calendar.html' context_object_name = 'today_list' def get_queryset(self, **kwargs): queryset = { 'today_list_items': Event.objects.all().filter(profile=self.request.user.user_profile).filter(start_time__date=self.kwargs['date']), 'today_list_rating_sum': Event.objects.all().filter(profile=self.request.user.user_profile).filter(start_time__date=self.kwargs['date']).aggregate(Sum('rating')).values(), } return queryset def get_context_data(self, **kwargs): if self.request.user.user_profile is None: return render(self.request, 'cal/calendar.html', {'error': '프로필을 작성해주세요'}) context = super().get_context_data(**kwargs) d = get_date(self.request.GET.get('month', None)) cal = Calendar(d.year, d.month) html_cal = cal.formatmonth(self.request.user, withyear=True) context['calendar'] = mark_safe(html_cal) context['prev_month'] = prev_month(d) context['next_month'] = next_month(d) context['date'] = self.date day = get_specifiec_date(self.request.GET.get('day', None)) context['prev_day'] = prev_day(day) return context -
How to install TailwindCSS to a Django project?
How to install Tailwind css in a Django project? I didn't succeed by using the installation tutorial in official TailwindCSS website. After some research I found answer to my problem. -
Getting a input value in django view after inserting html by AJAX
In my html, i insert a code by ajax request like: if (document.getElementById("div3").className == "active"){ for (var [name, value] of Object.entries(institutionsByName)){ document.getElementById("institution-checkbox").innerHTML += '<label name="organization_label">' + '<input type="checkbox" name="organization" value="' + value + '" id="institution-key"/>' + '<span class="checkbox radio"></span>' + '<span class="description">' + '<div class="title">'+ name + '</div>' + '<div class="subtitle">' + '</div>' + '</span>' + '</label>' } } Then i try to get a 'organization' value by django view like: institutions1 = request.POST.get('institution-key') However it returns None, How can i get the id of my institution/organization in a correct way in my django view? In html code, one of them looks like: <input type="checkbox" name="organization" value="9" id="institution-key"> -
React frontend + graphene Django backend SPA deployment
I want to deploy a SPA on only one VM, with debian 10. What I wanted to do is all routes to go to index.html of my static react app, except /admin/* and /graphql/* which should lead to the corresponding django pages. I have tried using Caddy, setting up a reverse proxy for /admin/* and /graphql/* but I end up with a working frontend and a working admin page (but the style of this page is not loaded for some reason). However, the graphql page does not work at all (blank page) and the frontend cannot make request to the backend. Do you know how I should do it? I was wondering if I'd rather go with nginx and uWSGI instead of using Caddy, with which I had to use gunicorn, but then I would need help to configure nginx properly. Or maybe the way I wanted to do it is a dead-end and I should totally change it? Thanks for your help! -
Django new version 3.1, the settings file have some changes
On Django new version 3.1, the settings file have some changes, and I came to ask how I have to proceed to set my static files? The way that I usually did doesn't work more. Last versions: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) Version 3.1: from pathlib import Path BASE_DIR = Path(__file__).resolve(strict=True).parent.parent I usually set my static files like this: STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root') If I insert the import os will work, but is it the right practice? What is the best practice to set this? Thank you? -
Visibility problem for static files -- django
I connected static files in django, but they won't connect, can you help? settings: STATICFILES_DIRS = [ "web_page/static", ] STATIC_URL = '/static/' STATIC_ROOT = '/static/' index.html: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="{% static "css/standart_template.css" %}" rel="stylesheet" type="text/css" > <title>HouseVOP</title> </head> urls - projects: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('web_page.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urls - app: from django.urls import path from .views import FormListView, Success from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', FormListView, name = 'home'), path('success/', Success, name = 'success') ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Before turning here, I searched many sites, so now I may simply not see something. In the first version of the code, I laid the path to the static files along with os.path.join (BASE_DIR, etc., but it did not work ... -
How to return to the same point after performing a function in django
I am making a social media app using django. I added a like function to the posts but in my code, when the user clicks the like button, it reloads the page and the user is back to the top of the page. I want that after clicking the like button, user returns to the same post on the page. how do i do that?? please help. Thanku. This is my views.py def likepost(request, post_id): user = request.user post_connected = post.objects.get(id=post_id) mypost = like_post.objects.filter(user=user, liked=post_connected) if mypost.exists(): mypost.delete() post_connected.likes -= 1 post_connected.save() else: mylike = like_post.objects.create(user=user, liked=post_connected) mylike.save() post_connected.likes += 1 post_connected.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) This is my template view <form action="/like/{{posts.id}}/" method="POST"> {% csrf_token %} <button style="background-color: inherit; border:none; outline:none; margin-left:-10px; width:4%;"> {% if posts in myliked %} <span style="font-size:17px;"> <i class="fa fa-heart" aria-hidden="true" style="color: red;"></i> </span> {% else %} <span style="font-size:17px;"> <i class="fa fa-heart" aria-hidden="true" style="color: lightgrey;"></i> </span> {% endif %} </button> {{posts.likes}} </form> This is my urls.py path('like/<int:post_id>/', views.likepost, name='like'), -
how to get random 1/2 data from database in jinj2 template in Django?
<table> {% for field in fields %} <tr> <td>{{ field.name }}</td> <td>{{ field.value }}</td> </tr> {% endfor %} </table> here we will get all the data from fields . but i want to only get randomly 1/2 (i can specified how many) data in jinja2 template from backend ? How to do this ? -
Django: AttributeError: <Model> object has no attribute '_meta'
NOTE:- I have referred to SO links & other tutorials but I am unable to get past this error. Django version:django-3.1 Context:- I have a product which will can have multiple images attached to it against p_id(PK). TODO:- Use django-admin to upload multiple images against a product code Error:AttributeError: 'PhotoInline' object has no attribute '_meta' models.py from django.db import models from django.urls import reverse from django.utils import timezone # Create your models here. class Product(models.Model): """ 1. **product** | Column-Name | Type | | ------------ | ---------- | | p_id | NUMERIC-AI | | product_name | VARCHAR | | COST | NUMERIC | """ p_id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=250) cost = models.FloatField(default=0) created_on = models.DateField(default=timezone.now) def get_absolute_url(self): return reverse('product:index') def __str__(self): return self.product_name class Meta: db_table = 'product' verbose_name = 'Product List' def img_upload_location(p_id, filename): p_id = f"{p_id.p_id_id}".replace(" ", "-") file_name = filename.lower().replace(" ", "-") return f"pimages/{p_id}/{file_name}" class Pimage(models.Model): """ | Column-Name | Type | | ----------- | ------- | | p_id(FK) | NUMERIC | | img | VARCHAR | """ p_id = models.ForeignKey(Product, on_delete=models.CASCADE) # img = models.ImageField(upload_to='images/') img = models.ImageField(upload_to=img_upload_location) def get_absolute_url(self): return reverse('pimage:index') # def __str__(self): # # return Product.objects.get(p_id=f'{self.p_id}').product_name # return f'{self.p_id}' def __unicode__(self): return … -
Body not Posting in Django Rest API call using Javascript fetch
I am using Django RestFramework API in my Node.js App. I am using Javascript fetch API to send some data to backend of my Project which is configured in Django. But the data is not getting posted. It runs fine in PostMan but not using fetch. my API class is as follows: class ProfileList(APIView): def get(self, request): ProfileObjects = Profile.objects.all() serializer = ProfileSerializer(ProfileObjects, many=True) return Response(serializer.data) def post(self, request, **kwargs): print(request.POST) print(self.request.POST) ProfileObjects = Profile.objects.all() serializer = ProfileSerializer(ProfileObjects, many=True) return Response(serializer.data) The fetch call looks like this..: function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); fetch('http://127.0.0.1:8000/API/', { method: 'post', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json', 'Authorization': csrftoken }, body: JSON.stringify({data: "your data"}) }).then(res => res.json()) .then(res => console.log(res)); Well according to the API class view it should print {data: "your data"} but it isn't. Instead this is being printed out while using fetch call <QueryDict: {}> <QueryDict: {}> … -
keyerror in Django REST Framework Serializer.save() and validated_data
I'm new on Django Rest Framework and when I want to POST data and I get this error KeyError at author=self.validated_data['author'], KeyError: 'author' Here's my code: in my models.py class Question(models.Model): #author author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) #question question=answer=models.TextField(default='Write your question') #answer answer=models.TextField(default='write your answer') #paragraph paragraph=models.ForeignKey(Paragraph,on_delete=models.CASCADE) #date published_date = models.DateTimeField(verbose_name='published_date', auto_now_add=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return "{} - {} - {} - {}".format(self.author, self.question, self.answer,self.paragraph) and my views.py def question_view(request): if request.method == 'POST': serializer = ParagraphSerializer(data=request.data) data = {} if serializer.is_valid(): post = serializer.save() data['author'] = post.author data['question'] = post.question data['answer'] = post.answer data['paragraph'] = post.paragraph else: data = serializer.errors return Response(data) and at the end my Serializers.py class ParagraphSerializer(serializers.ModelSerializer): paragraph=serializers.SlugRelatedField( many=True, read_only=True, slug_field='title' ) author=serializers.SlugRelatedField( slug_field=Account.email, required=False, read_only=True ) class Meta: model = Question fields = ['author','question', 'answer','paragraph'] def save(self): post=Question( author=self.validated_data['author'], question=self.validated_data['question'], answer=self.validated_data['answer'], paragraph=self.validated_data['paragraph']) post.save() return post -
django multiple model and formset ina single view only saves last value for the formset
all the required files i am getting issue with the formset section it only saves the last row's value and keeps the rest data blank i am not able to solve this issue it would be great if any one can help me out with this code model.py from django.db import models class Rfq(models.Model): rfq = models.IntegerField() def __int__(self): return self.rfq class General(models.Model): #General Information supplier_name = models.CharField(max_length=300) suppler_manufacturing_location =models.CharField(max_length=300, blank=True, default='') rfq_tracking = models.CharField(max_length=300, blank=True, default='') supplier_dunns =models.CharField(max_length=300, blank=True, default='') rfq = models.ForeignKey(Rfq, null=True, on_delete=models.CASCADE) def __str__(self): return self.supplier_name class Material(models.Model): #Material material_description = models.CharField(max_length=300) gross_material_weight = models.CharField(max_length=300, blank=True, default='') blank_size = models.CharField(max_length=300, blank=True, default='') rfq = models.ForeignKey(Rfq,related_name = "materials", null=True, on_delete=models.CASCADE) def __int__(self): return self.rfq class Meta: db_table = "materials" class Purchased(models.Model): #Purchased Components & Outside Processing material_item_process_description= models.CharField(max_length=300) quantity_per_assembly = models.FloatField() unit_of_measure = models.CharField(max_length=300, blank=True, default='') cost_unit_of_measure = models.FloatField() rfq = models.ForeignKey(Rfq, null=True, on_delete=models.CASCADE) def __str__(self): return self.material_item_process_description class Processing(models.Model): annual_volume = models.CharField(max_length=300) set_up_time = models.FloatField(blank=True, default='') set_up_persons = models.CharField(max_length=300, blank=True, default='') rfq = models.ForeignKey(Rfq, null=True, on_delete=models.CASCADE) def __str__(self): return self.annual_volume class Packaging(models.Model): #Packaging, Logistics, Amortization, Duties & Customs packaging_cost = models.FloatField() freight_cost_1 = models.FloatField(blank=True, default='') freight_cost_2 = models.FloatField(blank=True, default='') freight_cost_3 = models.FloatField(blank=True, default='') rfq = models.ForeignKey(Rfq, … -
Django handle errors in class based views
I am trying to build a URL shortener, but I hit a wall. models.py from django.db import models from hashlib import md5 # Create your models here. class Url (models.Model): url = models.URLField(unique = True,max_length=500) clicks = models.IntegerField(default=0) url_hash = models.CharField(unique=True,max_length=8) short_url = models.URLField(unique=True,default="https://myurl.com/s") create_at = models.DateTimeField(auto_now_add=True) def clicked(self): self.clicks += 1 self.save() def save(self, *args, **kwargs): if self._state.adding: self.url_hash = md5(self.url.encode()).hexdigest()[:8] self.short_url = "myurl.com/s/" + self.url_hash def get_absolute_url(self): from django.urls import reverse return reverse('shortener_detail', args=[str(self.id)]) relevant view class CreateShortyView(CreateView): model = Url template_name = 'shortener/home.html' form_class = UrlShortenerForm def get_context_data(self, **kwargs): kwargs['object_list'] = top10 = Url.objects.order_by('-clicks')[:10] return super(CreateShortyView,self).get_context_data(**kwargs) and form class UrlShortenerForm(forms.ModelForm): url = forms.URLField(max_length=500,widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Your long URL'}),label=False) class Meta: model = Url fields = ['url'] When invalid form data gets supplied django rerenders my template and adds a <ul> with the errors. I want to do the following things: When an Url entry already exists simply redirect to my detail template When a non Url is supplied render them myself somewhere on the page not as a <ul> Help is really appreciated! -
How to reset password using Django and gmail
I am trying to make user allows to reset their forgotten password I got this error (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError 77sm14812049pfx.85 - gsmtp', 'webmaster@localhost') I have some following codes.# settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') and urls.py path('password-reset', auth_views.PasswordResetView.as_view(template_name='register/passwords/password_reset.html'), name='password_reset'), path('password-reset/done', auth_views.PasswordResetDoneView.as_view(template_name='register/passwords/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(template_name='register/passwords/password_reset_confirm.html'), name='password_reset_confirm'), path('password-reset-reset', auth_views.PasswordResetCompleteView.as_view(template_name='register/passwords/password_reset_complete.html'), name='password_reset_complete'), -
Django - BooleanField - checkbox
I'm working on a web app. This web app should let people add links to a list and then press a button to open all the links at once. So far I have this: Each link can be set to either True or False, when I clink on 'open links' only the links that are set to True will open. Now, I would like to add a checkbox next to 'Delete link'. When the checkbox is ticked the value will be True and when I untick the checkbox the value will change to False. Any help will be much appreciated, thank you! My code so far: models.py from django.contrib.auth.models import User class Site(models.Model): """A site that will be opened""" name = models.CharField(max_length=200) link = models.URLField(max_length=200) selected = models.BooleanField(default=True) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): """Return a string representation of the model.""" return self.name forms.py from .models import Site class SiteForm(forms.ModelForm): class Meta: model = Site fields = ['name', 'link', 'selected'] labels = {'name':'Name','link': 'Link', 'selected': 'Selected'} urls.py from django.urls import path from . import views app_name = 'links' urlpatterns = [ # Home page. path('', views.index, name='index'), # Show all links. path('links/', views.links, name='links'), # Page for … -
Django not saving all data passed via POST
I am trying to save request.POST in the model but unfortunately - i am not getting all data saved. For fields "carrier" and "spot" - when i render a template it shows me None altough in QueryDict in command prompt i am seeing both values passed. code from command prompt (when POST is printed) <QueryDict: {'csrfmiddlewaretoken': ['38kuFlpIUMbmwXJ77qKaz2wWPOuqnM1IaYpKZdmaFVdEmVcuuu7hzf0wr0fEEO8o'], 'currency': ['USD'], 'pickup': ['1'], 'origin_cust': ['1'], 'origin_hand': ['11'], 'airfreight': ['234'], 'dest_cust': ['234'], 'dest_hand': ['234'], 'delivery': ['32'], 'screening': ['342'], 'dgfee': ['342'], 'Submit': ['Submit'], 'carrier': [1], 'spot': [1]} views.py def offer_spot(request): my_p = Stakeholder.objects.get(user=request.user) print(my_p) form = OfferForm() if request.method == 'POST': request.POST._mutable = True request.POST['carrier'] = my_p.pk request.POST['spot'] = 1 print("print", request.POST) form = OfferForm(request.POST) if form.is_valid(): form.save() return redirect('/offers') else: print(form.errors) context = {'form': form} return render(request, 'spotrequesting/offer_spot.html', context) models.py class Offer(models.Model): currency = models.CharField( validators=[RegexValidator(regex='[A-Z]{3}', message='Currency is three letters')], max_length=3,null=False) pickup = models.FloatField(default=0) origin_cust = models.FloatField(default=0) origin_hand = models.FloatField(default=0) airfreight = models.FloatField(default=0) dest_cust = models.FloatField(default=0) dest_hand = models.FloatField(default=0) delivery = models.FloatField(default=0) screening = models.FloatField(default=0) dgfee = models.FloatField(default=0) carrier = models.ForeignKey(Stakeholder,null = True,on_delete=models.CASCADE) spot = models.ForeignKey(Spot,null = True,on_delete=models.CASCADE) What is strange - when i type "default = 1" in Offer model for both Foreign Keys - application is saving what is really under … -
How to access a list in a dictionary in django template
I build a dictionary that contain a list. I want to access the list in my django template by index I access my dictionary with a custom tag @register.filter(name='keyvalue') def keyvalue(dict, key): return dict[key] and in html {% for p in participant %} <tr> <td>{{ p }}</td> <td>{{p.eMail}}</td> <td>{{p.participantNationality}}</td> <td>{{p.participantStreet}} {{p.participantStreetNumber}}, {{p.participantZipcode}}, {{p.participantCity}} </td> <td>{{p.participantCountryResidency}}</td> <td>{{p.participantSpecialNeeds}}</td> <td>{{p.participant_fee_no_reduction}}€</td> <td> <p style="line-height : 10px">{{discounts|keyvalue:p.pk}}</p> </td> {% if totalAmount == 0 %} <td>Free</td> {% else %} <td>{{p.participantFee}}€</td> {% endif %} </tr> {% endfor %} The code like that work, it return the right list for the right participant except that its a plain python list. I want to access the values in the list by index. When i try {{discounts.discount_list.1|keyvalue:p.pk}} i have string index out of range as the list is considered like a string. Any idea how to do it ? Thanks -
How to pass a location path to the imagefield in django model?
I want to save the image in the imagefield of my model by passing the location of the image. My serializer: class UserModelSerializer(serializers.ModelSerializer): password = serializers.CharField() confirm_password = serializers.CharField() class Meta: model = User fields = ['image','email','fullname','dob','phonenumber','passportnumber','username','password','confirm_password'] My Model: class CustomUser(AbstractUser): image = models.ImageField(upload_to='images/',blank=True,null=True) email = models.EmailField(_('email address'), unique=True) fullname = models.CharField(null=True,max_length=40) dob = models.DateField(default=date.today) phonenumber = models.CharField(max_length=10, blank=True) passportnumber = models.CharField(max_length=10, blank=True) My View: class UserRegistrationAPIView(generics.CreateAPIView): serializer_class = UserModelSerializer permission_classes = [permissions.AllowAny] renderer_classes = [TemplateHTMLRenderer] # renderer_classes = [JSONRenderer] template_name = 'accounts/api_register.html' def get(self, request): serializer = UserModelSerializer() print("Reaching Get") # return Response({'serializer':serializer.data}) return Response({'serializer': serializer}) def post(self, request): draft_request_data = request.data.copy() # print(draft_request_data.image) # print("**********************") # print(type(draft_request_data)) #print(draft_request_data) #draft_request_data.pop('image') #draft_request_data.pop('confirm_password') print(draft_request_data) serializer = self.get_serializer(data = draft_request_data) print(serializer.is_valid()) if not serializer.is_valid(): print(serializer.errors) return Response({'serializer': serializer}) # print("serializer+++++++++++++++") # print(serializer.data.pop('confirm_password')) # print(serializer) serializer.save() return redirect('/login/') The data which I passed to the serializer is : <QueryDict: {'csrfmiddlewaretoken': ['72YZOX1hiXdcBMjp5wTAv8WNwLNjC8ebUPVNihiQwdsZn7wmSoEBMFQEWR3a5Lpx'], 'image': ['images/Screenshot from 2020-07-26 21-30-52.png'], 'email': ['ran@gmail.com'], 'fullname': ['ran'], 'dob': ['1995-11-06'], 'phonenumber': ['7395905243'], 'passportnumber': ['SIFNFHK'], 'username': ['ran'], 'password': ['Singo1995'], 'confirm_password': ['Singo1995']}> As you can see I am passing the image location to the image key as /images/Screenshot from 2020-07-26 21-30-52.png This is where the problem occurs the serializer.is_valid() in views.py transforms the … -
How to get a value in a database and display on django form
I have a DuesLevy model with a field called user which happen to be a foreign key to my User model. I want to display email value from the User model to my form AddMemberDuesForm() The reason is this I want to get the email and amount value and pass it to my payment processor. I am using class based views to process my form below is my code forms.py class AddMemberDuesForm(forms.ModelForm): class_of_dues = forms.CharField(required=False, widget=forms.Select(choices=options.CLASS_OF_DUES, attrs={'class':'form-control'})) payment_circle = forms.CharField(required=False, widget=forms.Select(choices=options.PAYMENT_CIRCLE, attrs={'class':'form-control'})) payment_option = forms.CharField(required=False, widget=forms.Select(choices=options.PAYMENT_OPTION, attrs={'class':'form-control'})) payment_channel = forms.CharField(required=False, widget=forms.Select(choices=options.PAYMENT_CHANNEL_TYPE, attrs={'class':'form-control'})) amount = forms.DecimalField(widget=forms.NumberInput(attrs={'class':'form-control'})) payment_date = forms.DateField(widget=forms.DateInput(attrs={'class':'form-control', 'type':'date'})) description = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control'})) class Meta(): model = DuesLevy exclude = ('date_recorded', 'start_date', 'end_date', 'transaction_id') views.py class AddMemberDues(LoginRequiredMixin, CreateView): login_url = '/backoffice/' model = DuesLevy template_name = 'dashboard/add-edit-member-dues.html' form_class = AddMemberDuesForm context_object_name = 'member_form' def post(self, request, *args, **kwargs): form = AddMemberDuesForm(request.POST) if form.is_valid(): form = AddMemberDuesForm() form.user.email = form.user.cleaned_data['email'] self.template_name = 'dashboard/payment.html' form.save() return render(request, self.template_name, {'email': form.cleaned_data['email'], 'amount': form.cleaned_data['amount']}) def get(self, request, *args, **kwargs): initial = {'email':request.user.email} form = AddMemberDuesForm(initial=initial) return render(request, self.template_name, {'email': form.cleaned_data['email']}) I get this error in the 'AddMemberDuesForm' object has no attribute 'cleaned_data' Internal Server Error: /backoffice/add-member-dues/ Traceback (most recent call last): File "C:\Users\Benedict\Miniconda3\envs\mycda\lib\site-packages\django\core\handlers\exception.py", line 34, … -
How do you handle video in Django for elearning site
I am a learner in django and i have been trying to create a paid elearning site , the problem comes to handling the video courses , all i have got from research on Youtube and tutorials is if you host the courses locally someone can go directly to the url and get the resource .I need help on the way to do it