Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run perioduc tasks through django-celery on xampp windows?
I am trying to run periodic tasks for my django web application. I have my website running on xampp. During development, I used redis server and commands on commandline to start worker and beat. How do I integrate this with xampp server? -
when i vote one of the choices it shows error (can only concatenate str (not "int") to str) please help i am a newbie in programming
i am following django official documentation tutorial t make a poll app i am currently stuck on part 4.So when i select one of the choices it shows an error (can only concatenate str (not "int") to str). I cant understand am i trying to add a string to integer where is the problem in the code please herlp here is my code: views.py from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from .models import Choice, Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question': question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) urls.py from django.urls import path from . import views app_name = 'polls' … -
I want to query to get the details from the command line
In The Models.py file (I have this codebase) class Person(models.Model): sex_choices = ( ('Male', 'Male'), ('Female', 'Female') ) martial_choices = ( ('Single', 'Single'), ('Married', 'Married'), ('Divorce', 'Divorce'), ('Widowed', 'Widowed') ) name = models.CharField(max_length=200) sex = models.CharField(choices=sex_choices, max_length=50) martial_status = models.CharField(choices=martial_choices, max_length=50) age = models.IntegerField() def __str__(self): return self.name class DetailsOfEducationQualification(models.Model): type_choice = ( ("Government", "Government"), ("Private", "Private"), ("Anganwadi Center", "Anganwadi Center"), ) education_proximity_choice = ( ("0-5", '0-5km'), ('5-10', '5-10km'), ('10+', 'Above 10km'), ('Outside the state', 'Outside the state'), ) person = models.ForeignKey(Person, on_delete=models.CASCADE) course_class = models.CharField(max_length=50, blank=True) type_of_education_sector = models.CharField(choices=type_choice, max_length=50, blank=True) education_facility_proximity = models.CharField(choices=education_proximity_choice, max_length=50, blank=True) In The Admin.py file (I have this) from .models import ( Person, DetailsOfEducationQualification ) class DetailsOfEducationQualificationInline(admin.TabularInline): model = DetailsOfEducationQualification extra = 0 class PersonAdmin(admin.ModelAdmin): fieldsets = [ ( 'Personal Information', { 'fields':[ 'name', 'sex', 'age', 'martial_status' ] } ), ] inlines = [ DetailsOfEducationQualificationInline ] In query shell, I want to get the person 'course_class' since the DetailsOfEducationQualification model is related to Person: like in he query: person = Person.objects.get(id=1) person.course_class this code gets an error, saying person does not have the attribute... How do I access the DetailsOfEducationQualification date from the Person model? -
Django, ho to set queryset to zero value if empty
I have the following code in my views.py, that give me the iva_debito_totaleThat I figure out in my templates as table. But if the Ricavi models are empty, also my iva_debito_totale is empty. I have the necessity to have anyhow iva_debito_totalealmost equal to zero, even if Ricavi is empty. This is my code defaults = list(0 for m in range(13)) iva_debito = dict() for year, month, totale in(Ricavi.objects.values_list( 'data_contabile__year', 'data_contabile__month'). annotate(totale=ExpressionWrapper(Sum(F('quantita') * F('ricavo')*(F('iva')+0)), output_field=FloatField())).values_list('data_contabile__year', 'data_contabile__month', 'totale')) : iva_debito[id]=list(defaults) index=month iva_debito[id][index]=totale iva_debito_totale={'IVA a Debito Totale': [sum(t) for t in zip(*iva_debito.values())],} -
Sort a QuerySet by ManyToManyField in Django
I have a model like this: class my_model(models.Model) foo = models.ManyToManyField(My_other_model) I want to get all Objects of my_model sorted by the number of objects in the foo field. In this Question A friendly Guy from russia says, that you should use django-annontation. I tried the following: my_model.objects.all().order_by("-foo") and it works fine. Is there any reason I should go the longer way with annotations?? Thx for help and stay healthy! -
Django serializer one-to-many relationship to array
Is it possible to get the nested relationship as an array from the django rest framework serializer? The response is now: [ { "location": "xxx", "text": "xxx", "starttime": "2018-04-26T21:46:25.311000", "action": [ { "eventaction": "Silenced" }, { "eventaction": "Notification Expired" }, { "eventaction": "Announced" } ] } ] But I want it like this: [ { "location": "xxx", "text": "xxx", "starttime": "2018-04-26T21:46:25.311000", "action": ["Silenced", "Notification Expired", "Announced"] } ] How can I achieve this? -
JSONField in Django continues to remain empty even after POST request
I have a model with a JSONField in Django. If I issue POST through the browser using Django Rest UI, the data gets entered into the model with no issues. However,when I use Python's requests.post in my application, everything except the JSONField data stores in the model. Here is my model from django.db import models from django.contrib.postgres.fields import JSONField class Scans(models.Model): Name = models.CharField(max_length=20) Server = models.CharField(max_length=20) Results = JSONField(default=dict) Report_Url = models.URLField(max_length=30)` Here is my Serializer from rest_framework import serializers from .models import Scans class ScansSerializer(serializers.ModelSerializer): class Meta: model = Servers fields = '__all__' Here is my view class ScansData(APIView): def get(self, request): scans = Scans.objects.all() serializer = ScansSerializer(scans, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def post(self, request): serializer = ScansSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request): scans = Scans.objects.all() scans.delete() return Response(status=status.HTTP_204_NO_CONTENT) Here is my request data = { "Name": "dodo", "Server": "ubuntu", "Report_Url": "https://127.0.0.1:8000/about/" } jsonval = { "Results": { "Severity_High": 8, "Severity_Medium": 7, "Severity_Low": 5 } } requests.post('http://127.0.0.1:8000/scans/', data=data, json=jsonval) URL urlpatterns = [ path('scans/', ScansData.as_view()), ] What I see after using requests.post { "id": 10, "Name": "dodo", "Server": "ubuntu", "Results": {}, "Report_Url": "https://127.0.0.1:8000/about/" } -
How to add hidden parameter to ModelForm?
How to add hidden parameter to ModelForm? forms.py class ModelForm(forms.ModelForm): class Meta: model = Model fields = ['field'] -
Add points from json to mapbox in django not working
I would like to push data from a json file into mapbox in Django. For this i copied the json in views.py and pushed the data to default.html as context. views.py def default_map(request): mapbox_access_token = 'I put my token here'; context = { 'vessels': Vessels } return render(request, 'default.html', { 'mapbox_access_token': mapbox_access_token }, context ) #Copy pasting JSON files Vessels = [ { "vessel": "A La Marine", "date": "20/Apr 13:18", "lon": 7.88499997456869, "lat": 53.9, "speed": 13.8999996185303, "course": "0", "type": "NoonReport" }, { "vessel": "Barcelona Express", "date": "22/Apr 06:04", "lon": 11.8683216666667, "lat": 41.5915366666667, "speed": 18, "course": "139.7", "type": "CM" }, In default.html i tried different things: 1)Putting marker in for loop & 2)Putting all markers after the for loop default.html <body> <h1>{{vessels.lon}}</h1> <div id='map' class='map' width="100%" style='height:800px'></div> <script> mapboxgl.accessToken = '{{mapbox_access_token}}' <!-- {{mapbox_access_token}} --> var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v10' }); var geojson = { type: 'FeatureCollection', features: [ {% for vessel in vessels %} { type: 'Feature', geometry: { type: 'Point', coordinates: [{{vessel.lon}}, {{vessel.lat}}] }, properties: { title: '{{ vessel.vessel }}', description: '{{ vessel.type }}' } var marker = new mapboxgl.Marker() .setLngLat(coordinates) .addTo(map); }, {% endfor %} ] }; //Test Marker var marker = new mapboxgl.Marker() .setLngLat([52,3]) … -
How to add a variable within a variable in a Django template
I have a Django template with a variable as follows: {{ results_coin_data.market_data.current_price.usd }} I'm looking to change the 'usd' portion at the end by doing something like this: {{ results_coin_data.market_data.current_price.{{ currency }} }} (Obviously that doesn't work.) Where {{ currency }} is a selected currency that the user chooses from a dropdown select form. The template is then refreshed with the variable changed showing a price in the chosen currency. I can't send it to the view with a form GET request because the API endpoint doesn't have an option for a currency parameter. The currency option is part of the JSON results, so I have to chain it to the end like .current_price.usd or .current_price.gbp thank you! -
Showing an exception while adding product to admin panel
django.db.utils.OperationalError: no such column: "mfg_date" models.py from django.db import models '#Create your models here. class Product(models.Model): prod_id = models.AutoField prod_name = models.CharField(max_length=30) prod_des = models.CharField(max_length=100) mfg_date = models.DateField() admin.py from django.contrib import admin from .models import Product Register your models here. admin.site.register(Product) views.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('index/',views.index,name='shopindex'), path('aboutus/',views.aboutus,name='aboutus'), path('contactus/',views.contactus,name='contactus'), path('search/',views.search,name='search'), path('productview/',views.productview,name='productview'), path('tracker/',views.tracker,name='tracking'), path('checkout/',views.checkout,name='checkout') ] Image of error [image of error][1] -
Too many values to unpack (expected 2) in Django
`I want to render the checkbox in the template goals.html, what am i doing wrong here? Models.py from django.db import models # Create your models here. there would be a set of goals and there should be 2 check boxes associated with them there would be a set of goals and there should be 2 check boxes associated with them there would be a set of goals and there should be 2 check boxes associated with them there would be a set of goals and there should be 2 check boxes associated with them there would be a set of goals and there should be 2 check boxes associated with them there would be a set of goals and there should be 2 check boxes associated with them there would be a set of goals and there should be 2 check boxes associated with them there would be a set of goals and there should be 2 check boxes associated with them there would be a set of goals and there should be 2 check boxes associated with them there would be a set of goals and there should be 2 check boxes associated with them there would be a … -
angular and django issue on refresh token (jwt)
I have a django backend whith authentication based on JSON Web Token using the package djangorestframework-simplejwt. My Angular 9 frontend successfully obtain the access and refresh token after login using this function loginUser(email: string, password: string) { return this.httpClient.post<Token>(`${this.baseService.baseUrl}auth-token/`, { email, password }, this.baseService.httpOptions); } The problem comes in when I try to fetch the refresh token. This is the function I use to request the refreshing getNewAccessToken(refreshToken: string){ return this.httpClient.post<Token>(`${this.baseService.baseUrl}auth-token-refresh/`, { refresh: refreshToken }, this.baseService.httpOptions); } I keep get 401 Unauthorized as response. Both functions use the same httpHeader which is httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', }) }; I test my backend refresh endpoint with Postman using refresh: refreshtokenstring... in the body and everything works perfectly. I do not understand what's going wrong with Angular -
Django Admin: How to customize autocomplete_fields width to adapt to the content?
I'm trying to customize the widget rendered by autocomplete_fields for a ForeignKey Model field. Basically the problem is that the widget is too narrow for the content and it's breaking in two lines inside the select: I have seen that the JS library or JQuery plugin is called Select2 and it has a "dropdownAutoWidth" to make it adapt to the parent element size that kind of works but I'm completely clueless on how to set that option from admin.py since it seems that options are never passed in the code at django.contrib.admin.widgets.AutocompleteMixin.media: def media(self): extra = '' if settings.DEBUG else '.min' i18n_name = SELECT2_TRANSLATIONS.get(get_language()) i18n_file = ('admin/js/vendor/select2/i18n/%s.js' % i18n_name,) if i18n_name else () return forms.Media( js=( 'admin/js/vendor/jquery/jquery%s.js' % extra, 'admin/js/vendor/select2/select2.full%s.js' % extra, ) + i18n_file + ( 'admin/js/jquery.init.js', 'admin/js/autocomplete.js', ), css={ 'screen': ( 'admin/css/vendor/select2/select2%s.css' % extra, 'admin/css/autocomplete.css', ), }, ) -
Django Prefetch_related is not giving any attribute values
I have following models. They are not completed, but it should be enough for this issue I think.. class Device(models.Model): name = models.CharField(max_length=250, null=True, blank=True) site = models.ForeignKey( Site, on_delete=models.SET_NULL, related_name="devices", null=True, blank=True ) class GatewayDevice(models.Model): gateway = models.ForeignKey( Gateway, on_delete=models.CASCADE, related_name="devices" ) device = models.ForeignKey( Device, on_delete=models.CASCADE, related_name="gatewaydevices" ) When I do this query in my view, to get all the devices/gateways from a gatewaydevice. It gives me the device (and the pk), but not the attributes of it, they are all "None". Same for gateway. gateway_devices = ( GatewayDevice.objects.filter(end_date__isnull=True) .select_related("gateway") .prefetch_related( Prefetch( "device", queryset=Device.objects.prefetch_related( "site__users", "software_update_history", "supplier", "name", "site", "installation_date", ), ) ) ) serializer_class = self.get_serializer_class() serializer = serializer_class(gateway_devices, many=True) devices_data = serializer.data This is the serializer: class AdminDeviceInfoSerializer(AdminDeviceSerializer): site = serializers.SerializerMethodField() owner = serializers.SerializerMethodField() country = serializers.SerializerMethodField() supplier = serializers.SerializerMethodField() class Meta(AdminDeviceSerializer.Meta): fields = AdminDeviceSerializer.Meta.fields + [ "site", "owner", "country", "supplier", ] @staticmethod def get_site(gateway_devices): if not gateway_devices.device.site: return None return SiteSimpleSerializer(gateway_devices.device.site).data @staticmethod def get_owner(gateway_devices): if not gateway_devices.device.site or not gateway_devices.device.site.users: return None owner = gateway_devices.device.site.get_owner() return UserAdminSerializer(owner).data if owner else None @staticmethod def get_country(gateway_devices): if gateway_devices.device.site: return gateway_devices.device.site.country return None @staticmethod def get_supplier(gateway_devices): if gateway_devices.device.supplier: return SupplierSerializer(gateway_devices.device.supplier).data return None Am I doing anything wrong or … -
Why is my Heroku deployment not recognising my Procfile?
I'm trying to deploy my app using Heroku. I tried via CLI and also graphically in their user portal. I get this problem in the build log: Procfile declares types -> (none) It's not reading my Procfile. Here's some of the latest lines of my error logs: 2020-05-08T04:32:57.546072+00:00 app[api]: Deploy 02e1e06c by user djrgrey@gmail.com 2020-05-08T04:32:57.546072+00:00 app[api]: Release v7 created by user djrgrey@gmail.com 2020-05-08T04:33:05.475821+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=herokudanslist.herokuapp.com request_id=ff88cf27-54c2 -4611-b611-ce36c41b09f6 fwd="118.149.66.76" dyno= connect= service= status=503 bytes= protocol=https 2020-05-08T04:33:06.086210+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=herokudanslist.herokuapp.com request_id=a4 690f93-c8e3-4256-b46b-a8d1e69109c1 fwd="118.149.66.76" dyno= connect= service= status=503 bytes= protocol=https 2020-05-08T04:33:13.000000+00:00 app[api]: Build succeeded 2020-05-08T10:04:32.000000+00:00 app[api]: Build started by user djrgrey@gmail.com 2020-05-08T10:05:04.414084+00:00 app[api]: Release v8 created by user djrgrey@gmail.com 2020-05-08T10:05:04.414084+00:00 app[api]: Deploy 92e0c7b1 by user djrgrey@gmail.com 2020-05-08T10:05:37.245718+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=herokudanslist.herokuapp.com request_id=9cb80bd2-7cb6 -4e20-ad8a-e61aeeab0e02 fwd="118.149.66.76" dyno= connect= service= status=503 bytes= protocol=https 2020-05-08T10:05:39.210072+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=herokudanslist.herokuapp.com request_id=a2 9bf337-c13a-4eb7-83ef-e221bc69b6b7 fwd="118.149.66.76" dyno= connect= service= status=503 bytes= protocol=https 2020-05-08T10:05:40.000000+00:00 app[api]: Build succeeded I apologise for the bad formatting. How do I throw in logs? The code formatting wouldn't like it and was finnicky. -
Django : the content of post is not showing
hi am working on a project where user-added the post onto the site and driver check his post and give him offer ( price) to ship their load .when the driver submits the post(price) ....at the admin level the selected post and which driver adds the price is working properly, however when the same user logged in (which added the post earlier)and want to see the price of his post-offer by a particular driver. so how can I show to the front end with filtration of the particular user? this is my user post model class Loader_post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="Loader") pick_up_station = models.CharField(max_length=150) destination_station = models.CharField(max_length=150) sender_name = models.CharField(max_length=150) phone_number = PhoneNumberField(null=False, blank=False, unique=True) receiver_name = models.CharField(max_length=150) def __str__(self): return self.user.username def get_absolute_url(self): return reverse("Loader:my_job", kwargs={"pk": self.pk}) here is the price added to the post class price(models.Model): my_post = models.ForeignKey(Loader_post, related_name='prices',on_delete=models.CASCADE, null=True, default='') user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, default='') driver_price = models.CharField(max_length=150, null=True) driver_name = models.CharField(max_length=150, null=True) approved_price = models.BooleanField(default=False) status = models.BooleanField(default=False) def get_absolute_url(self): return reverse("Driver:Driverview") def __str__(self): return self.driver_price this is the view of the user post(views.py) class Loader_post_view(CreateView, LoginRequiredMixin): form_class = forms.Loader_post_form model = Loader_post template_name = "post_detail.html" success_url = reverse_lazy("Loader:my_job") def form_valid(self, form): print(form.cleaned_data) … -
Python, dictionary sum value
I have a dictionary obtained as following: test= {'Test': [sum(t) for t in zip(*data.values())],} And suppose that the test values as the following: test={ 'Test': [ t1, t2, t3, t4, t5 ] } I want to obtain the following result: results={ 'Test': [ r1=s1 , r2=r1+t2 , r3=r2+t3 , r4=r3+t4 , r5=r4+t5 ] } How could I get it? -
Why I send data to Django POST but fetch them in GET?
I am new to Django and built a simple test today. def login_web(request): request.encoding = "utf-8" print("body : ", request.body) print("POST : ", request.POST) print("GET : ", request.GET) username = request.POST.get("username") password = request.POST.get("password") print(username) print(password) user = auth.authenticate(username=username, password=password) if user is not None and user.is_active: print("YR1") auth.login(request, user) return JsonResponse({"foo": "bar1"}) else: print("IM2") return JsonResponse({"foo": "bar2"}) I used Postman to send post request to it. But the result is very confusing. body : b'' POST : <QueryDict: {}> GET : <QueryDict: {'username': ['chivier'], 'password': ['Chivyham07313']}> None None IM2 I should get them in request.POST but why they appear in request.GET. -
Values Are not print in my html table django 3
I want to show the values in an html table but the if elif condition not work or not compare with no_of_days. no_of_days is database table field. {% for item in all_reciept_vouchers %} <tr> {# <td>{{ }}&nbsp;</td>#} <td>{{ item.job_no}}&nbsp;</td> <td>{{ item.invoice_no}}&nbsp;</td> <td>{{ item.party_name}}&nbsp;</td> <td>{{ item.module}}&nbsp;</td> <td>{{ item.invoice_amount}}</td> {% if item.no_of_days >= 0 and item.no_of_days <= 30 %} <td>{{ item.reciept_net_amount}}</td> {% elif item.no_of_days >= 31 and item.no_of_days <= 60 %} <td>{{ item.reciept_net_amount}} </td> {% elif item.no_of_days >= 61 and item.no_of_days <= 90 %} <td>{{ item.reciept_net_amount}} </td> {% elif item.no_of_days >= 91 and item.no_of_days <= 120 %} <td>{{ item.reciept_net_amount}} </td> {% endif %} -
Photo not displaying in django html
I spent a few hours trying to find out what is going on but I can`t see why the photo is not displayed in my html file. Goal: Display the profile photo of each user Issue: Photo not displaying in django html detail.html <div class="col-sx-1 col-sm-5 text-right"> <a href="{% url 'contacts:detail' contact.id %}"> {% if contact.photo %} <img src="/{{ contact.photo.url }}" class="img-responsive"> {% else %} <h3>No image to display</h3> {% endif %} </a> </div> views.py def create_contact(request): form = ContactForm(request.POST or None, request.FILES or None) if form.is_valid(): contact = form.save(commit=False) contact.user = request.user contact.photo = request.FILES['photo'] file_type = contact.photo.url.split('.')[-1] file_type = file_type.lower() if file_type not in IMAGE_FILE_TYPES: context = { 'contact': contact, 'form': form, 'error_message': 'Image file must be PNG, JPG, or JPEG', } return render(request, 'contacts/create_contact.html', context) contact.save() return render(request, 'contacts/detail.html', {'contact': contact}) context = { 'form': form, } return render(request, 'contacts/create_contact.html', context) urls.py urlpatterns = [...] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Contact(models.Model): photo = models.ImageField(upload_to='profileimage', blank = True) settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Many Thanks, -
Python+Django - can't see my product image, name and price when I do those changes :
<div class="cart-row"> <div style="flex:2"><img class="row-image" src="{% static 'images/placeholder.png' %}"></div> <div style="flex:2">Product 1</div> <div style="flex:1">$20</div> <div style="flex:1"> <p class="quantity">2</p> <div class="quantity"> <img class="chg-quantity" src="{% static 'images/arrow-up.png' %}"> <img class="chg-quantity" src="{% static 'images/arrow-down.png' %}"> </div> </div> <div style="flex:1">$40</div> </div> THIS IS THE CODE I HAVE AND BELOW WHAT I HAVE CHANGED : {{**item.product.name**}} ${{**item.product.price|floatformat:2**}} {{**item.quantity**}} $40 -
Troubleshouting when query with date object in django
I followed the guide from django documentation and my code like this: riyou_date__range=(from_date_obj, to_date_obj) i printed the query and got sql like: `RIYOU_DATE` BETWEEN 2000-01-01 AND 2020-01-01 My expect query is `mei_cr`.`RIYOU_DATE` BETWEEN **'2000-01-01'** AND **'2020-01-01'** What should i do to get query like above. Thank you very much! -
(can only concatenate str (not "int") to str) this is the error i am getting why is it saying that i am trying to add string and int?
i am following django official documentation tutorial t make a poll app i am currently stuck on part 4.So when i select one of the choices it shows an error (can only concatenate str (not "int") to str). I cant understand am i trying to add a string to integer where is the problem in the code please herlp here is my code: views.py from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from .models import Choice, Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question': question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) urls.py from django.urls import path from . import views app_name = 'polls' … -
Django 2.0.8 crashes when resetting passwords are unequal
On of web projects that use Django 2.0.8. I forgot my password. So I decided to reset it using the "Forgotten password" wizard. After receiving the mail and opening the link, I got to the form where I need to insert my new password (field password1) and confirm it again (password2). As I made a mistake with writing two unequal passwords (password1=MyNewPass123), (password2=MyNewPass12), the app crashed with the error: ValueError at /auth/password/reset/confirm/<CODE>/set-password/ Need 2 values to unpack in for loop; got 17. <PATH>\lib\site-packages\django\template\defaulttags.py in render, line 202 So I went back and tried again, this time using two equal (valid) passwords which were successful. I repeated the password-reset step, using a new password (again 2 unequal inputs) and yet, it crashed. Searching for any bugs or related issued did not return any result. What is the main question here: Why does ForNode render in defaulttags.py receive so many items, just because of two unequal values.. What could be the solution for this? ForNode in defaulttags.py: class ForNode(Node): child_nodelists = ('nodelist_loop', 'nodelist_empty') def __init__(self, loopvars, sequence, is_reversed, nodelist_loop, nodelist_empty=None): self.loopvars, self.sequence = loopvars, sequence self.is_reversed = is_reversed self.nodelist_loop = nodelist_loop if nodelist_empty is None: self.nodelist_empty = NodeList() else: self.nodelist_empty = nodelist_empty …