Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to extract base64 extension without using lib imghdr
I have a view that works perfectly for receiving base64 images. My problem is that in some rare cases it doesn't recognize the sent jpg image. It looks like None. Looking on the internet I saw that the problem is the lib imghdr. I tried to use OS lib to extract the extension and even use the lib pillow, but I couldn't. Does anyone have any tips? Here is an example of how I use imghdr: def get_file_extension(self, file_name, decoded_file): import imghdr extension = imghdr.what(file_name, decoded_file) if extension == "jpeg": extension = "jpg" return extension -
Django Payfast API Errors - Cancelling Subscription (GET/PUT Request)
I am attempting to cancel subscriptions with the payfast api through a website. I have read through this question but as you can see, no solution is provided and it is not Django specific. That answer does mention that you should not use CORS which I took to mean that the server itself should send the request and so I am using the following Django view: def cancel_payfast(request, token): timestamp = datetime.now().astimezone().isoformat() signable_fields = {"merchant_id":str(conf.MERCHANT_ID), "version":"v1", "timestamp":timestamp,} text = urlencode(signable_fields, encoding='utf-8', errors='strict') signature = md5(text.encode('ascii')).hexdigest() r = requests.put('https://api.payfast.co.za/subscriptions/%s/cancel?testing=true'%token, data = {'merchant_id':conf.MERCHANT_ID,'version':"v1",'timestamp':timestamp,'signature':signature}) return HttpResponse(r) The return provided by Payfast is {"code":401,"status":"failed","data":{"response":"Merchant not found.","message":false}} but I have confirmed that the Merchant ID I am using is correct (Payfast sandbox). I decided to try the perhaps simpler task of getting a ping to work, using the same code but replacing "requests.put" with "requests.get" and "cancel" with "ping" but then I get an error from Google(?) saying: "400. That’s an error. Your client has issued a malformed or illegal request. That’s all we know." I will continue to try to fix this, any help is appreciated. -
Is there any way to exclude some field of InlineModel in django admin?
I have two models Gift and Checkout, each Gift has Checkout_id as a foreign key. In the Checkout section of my Django admin, I want to show Checkout properties and related Gifts. Here's what I did: class GiftInline(admin.TabularInline): model = Gift exclude = ('sender_session_token') class CheckoutAdmin(admin.ModelAdmin): list_display = ('id', 'amount', 'retailer_id', 'is_paid', 'requested_at', 'paid_at') inlines = [GiftInline,] admin.site.register(Checkout, CheckoutAdmin) But I want to exclude some fields in the inline view. what can I do? -
Saving form data from a FormView to session
I am trying to capture the POST request data for each field and store it in the session so that I can use the data in another view. But I am getting errors in the other view because the session variables are returning 'None'. Before, I had written the code using a non-class based view and fetched the values with request.POST.get('name') and this worked. What should I be doing here? class TripsView(FormView): """ A view to show all trips and receive trip search data """ template_name = "products/trips.html" form_class = SearchTripsForm def form_valid(self, form): """ Takes the POST data from the SearchTripsForm and stores it in the session """ trip_choice = form.cleaned_data["destination"].id self.request.session["destination_choice"] = trip_choice self.request.session["searched_date"] = "26-12-2021" self.request.session["passenger_total"] = form.cleaned_data[ "passengers" ] return super(TripsView, self).form_valid(form) def get_context_data(self, **kwargs): """ Adds to the context the Product objects categorized as trips """ context = super().get_context_data(**kwargs) context["destinations"] = Product.objects.filter(category=3) return context def get_success_url(self): """ Overides the success url when the view is run """ return reverse("selection") -
Django 'Query' object has no attribute 'contains_column_references'
I am new in Django and i am having trouble on how to configure this error, so that is why i decided to post a question of some of my code, i hope you guys help me on this problem. did i miss or i did wrong in my code? please bear with me. thanks. Error 'Query' object has no attribute 'contains_column_references' Traceback Traceback: File "/home/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/unidaweb/unidaproject/Homepage/views.py" in updateperiod 2289. V_insert_data.save() File "/home/lib/python3.6/site-packages/django/db/models/base.py" in save 741. force_update=force_update, update_fields=update_fields) File "/home/lib/python3.6/site-packages/django/db/models/base.py" in save_base 779. force_update, using, update_fields, File "/home/lib/python3.6/site-packages/django/db/models/base.py" in _save_table 870. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/lib/python3.6/site-packages/django/db/models/base.py" in _do_insert 908. using=using, raw=raw) File "/home/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/lib/python3.6/site-packages/django/db/models/query.py" in _insert 1186. return query.get_compiler(using=using).execute_sql(return_id) File "/home/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql 1334. for sql, params in self.as_sql(): File "/home/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in as_sql 1278. for obj in self.query.objs File "/home/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in <listcomp> 1278. for obj in self.query.objs File "/home/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in <listcomp> 1277. [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields] File "/home/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in prepare_value 1208. if value.contains_column_references: Exception Type: AttributeError at /updateperiod/ Exception … -
Python3: Pydub export function returns NoneType
Consider the following code: from pydub import AudioSegment from django.core.files import File def slice_audio(start, duration, audio_file): ''' Returns sliced mp3 audio file. ''' start = int(start) * 1000 # Convert to miliseconds duration = int(duration) * 1000 # Convert to miliseconds end = start + duration fade_in = 100 fade_out = 500 segmented = AudioSegment.from_file(audio_file) sliced = segmented[end:].fade_in(fade_in).fade_out(fade_out) return File(sliced.export(format="mp3")) slice_audio(10, 10, 'myfile.mp3') The problem i currently facing is the that return value is NoneType. Now if i change the return code to return File(sliced.export('newFile.mp3', format="mp3")), a file is indeed produced but fails to wrap in the File(). Thus having a NoneType returned My django model field: audio_snippet_file = models.FileField(null=True, upload_to=upload_Music_AudioSnippets) -
How to add filtering for function based views in Django Rest Framework
I'm trying to add filters to my function-based views. Using Class Based Views I was able to add filters to views. But I'm curious if I can add filtering to this function based views. I need to filter subject by it's name through a web search. How I can achieve that @api_view(['GET']) @permission_classes([IsAuthenticated]) def TeacherSubject(request): teacher = TeacherProfile.objects.get(user=request.user) subject = Subject.objects.filter(author=teacher).order_by('-id') paginator = PageNumberPagination() paginator.page_size = 5 result_page = paginator.paginate_queryset(subject, request) serializer = SubjectSerializer(result_page,many=True) return paginator.get_paginated_response(serializer.data) -
Bad Request on File upload
I have setup my python project using nginx and gunicorn as described in this tutorial https://djangocentral.com/deploy-django-with-nginx-gunicorn-postgresql-and-lets-encrypt-ssl-on-ubuntu/ so far everything works perfectly fine. My project is in /root/project_folder/ I want to upload files via the admin page, but I get a bad request error 400. The media folder I want to add the files to is /var/www/my_domain/media (owned by the group www-data). This is also properly configured since I can see the images when I move them manually into that folder. Do you guys maybe have any idea why the issue may be ? the main problem is when uploading I need to save the image to the media root: /var/www/domain/media/images/dad/ProfilePicture/offline_screen.png But when I send request to view the image the web server returns the following: /media/var/www/domain/media/images/dad/ProfilePicture/offline_screen.png The upload_to path needs to be images/dad/ProfilePicture/offline_screen.png for correct request but then the image is uploaded to the wrong folder Any ideas ? Thanks in advance! -
how to store third party access token to database to my profile model from views.py django
i'm trying to store a session id and an access token from a third party website's API to my users profiles i've been trying for days and searching but i couldn't find anything like this i tried to import profiles instances so that i can save the data to the users profiles instances but i didn't find out how , here is my code #views.py from bs4 import BeautifulSoup import xml.etree.ElementTree as ET from django.contrib.auth.decorators import login_required import urllib.parse from django.views.generic import View from users.models import Profile from django.contrib.auth.models import User def profile_view(request): RuName= 'driss_aitkassi-drissait-crm-SB-ijuzzy' r= { 'RuName': RuName } response = api.execute('GetSessionID', r) print(response) res =response.text tree= ET.fromstring(res) #here is my session id from the website's api for node in tree.iter('{urn:ebay:apis:eBLBaseComponents}GetSessionIDResponse'): SessionID= node.find('{urn:ebay:apis:eBLBaseComponents}SessionID').text #i tried this : s=Profile(session_id=SessionID) s.save() # and also tried this # and also this: Profile.objects.update(session_id=SessionID) Profile.objects.model.save() here is the Models.py file: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User,related_name='profile' , on_delete=models.CASCADE) token = models.TextField(max_length=500, blank=True) session_id=models.TextField( max_length=500, blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) please help me with this or just point me at … -
Boolean field is not updated on ajax call to a DRF viewset
As title says, boolean field is not updated on PATCH request to a DRF viewset. It returns 200 and correct data: {id: 18, score: "", questions_answered_amount: 3, is_completed: true,........} and all values are proper, despite this boolean is_completed, which value remains false. My model: ... is_completed = models.BooleanField(default=False) ... The viewset: class UserPassedTestViewSet(viewsets.ModelViewSet): queryset = UserPassedTest.objects.all() serializer_class = UserPassedTestSerializer permission_classes = [permissions.IsAuthenticated] @action(detail=False, methods=['patch'], permission_classes=[permissions.IsAuthenticated]) def add_option(self, request): option_id = request.POST.get('option_id') relation_id = request.POST.get('relation_id') option = Option.objects.get(id=option_id) relation_object = UserPassedTest.objects.get(id=relation_id) if not relation_object.questions_answered.filter(id=option.question.id).exists(): relation_object.questions_answered.add(option.question) relation_object.selected_options.add(option) relation_object.questions_answered_amount = F('questions_answered_amount') + 1 relation_object.save() else: existing_option = relation_object.selected_options.get(question_id=option.question.id) relation_object.selected_options.remove(existing_option) relation_object.selected_options.add(option) return JsonResponse({'success': 'added'}) Ajax call: $.ajax({ headers: { 'X-CSRFTOKEN': token }, url: 'http://127.0.0.1:8000/api/v1/userpassedtest/' + relation_id + '/', type: 'patch', dataType: 'json', data: {'is_completed': 'True'}, success: function(data) { console.log(data) } }) I have tried changing it to just true, to not be a string, or to 1 but it doesn't work. -
Elastic Beanstalk - When Browsing the site from custom Domain- DNS_PROBE_FINISHED_NXDOMAIN
I have hosted my website on AWS elastic beanstalk and purchased a domain from GoDaddy. Afterward I did all required configuration as required to change nameservers and other configurations in Route 53. I also apply a SSL certificate. I works fine. But I try to browse my website 8 out of 10 times it works but the other 2 times it shows a error in browser- DNS_PROBE_FINISHED_NXDOMAIN. Until I wait for few minutes or reconnect my internet. The internet is not the problem, I have tried on different networks. I am using a file to re-config apache to redirect my every website request to HTTPS://WWW files: "/etc/httpd/conf.d/ssl_rewrite.conf": mode: "000644" owner: root group: root content: | RewriteEngine On <If "-n '%{HTTP:X-Forwarded-Proto}' && %{HTTP:X-Forwarded-Proto} != 'https'"> RewriteRule (.*) https://www.%{HTTP_HOST}%{REQUEST_URI} [R,L] </If> May be this is causing the problem. Website loads fine every time I load it from the URL provided by elastic beanstalk as health of instance is fine. The problem only arises when I try to use the custom domain to browse the website. -
error when installing django-heroku on mac
I'm making a website using django framework. A problem occurred when I was trying to install django-heroku, using pip install django-heroku in virtual environment. I have tried many things I found in internet but nothing helped. Here you can see a full text of the error I get: ERROR: Command errored out with exit status 1: command: /Users/ankhodyrev/Desktop/learning_log/ll_env/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/tmp/pip-install-b2m2_6rg/psycopg2/setup.py'"'"'; __file__='"'"'/private/tmp/pip-install-b2m2_6rg/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/tmp/pip-record-aynjh8w4/install-record.txt --single-version-externally-managed --compile --install-headers /Users/ankhodyrev/Desktop/learning_log/ll_env/include/site/python3.8/psycopg2 cwd: /private/tmp/pip-install-b2m2_6rg/psycopg2/ Complete output (151 lines): running install running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.8 creating build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/_json.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/extras.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/compat.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/errorcodes.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/tz.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/_range.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/_ipaddress.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/_lru_cache.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/__init__.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/extensions.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/errors.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/sql.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/pool.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 running build_ext building 'psycopg2._psycopg' extension creating build/temp.macosx-10.9-x86_64-3.8 creating build/temp.macosx-10.9-x86_64-3.8/psycopg gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -DPSYCOPG_VERSION=2.8.6 (dt dec pq3 ext lo64) -DPG_VERSION_NUM=130001 -DHAVE_LO64=1 -I/Users/ankhodyrev/Desktop/learning_log/ll_env/include -I/Library/Frameworks/Python.framework/Versions/3.8/include/python3.8 -I. -I/usr/local/include -I/usr/local/include/postgresql/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.9-x86_64-3.8/psycopg/psycopgmodule.o gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 … -
Django | REST | Add of top level JSON field breaks filtering option
I have to work ListAPIView view, via which I can filter via django-filter values. But I need to add an object in JSON (because AMP HTML needs that) and when I add this, It will break this filtering. When I use this view, filtering is works great: class TypeAPIView(generics.ListAPIView): permission_classes = (AllowAny, ) queryset = Type.objects.all() serializer_class = TypeSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ('code', ) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) But when I want to add a top level JSON object, it will breaks a filtering option: class TypeAPIView(generics.ListAPIView): permission_classes = (AllowAny, ) queryset = Type.objects.all() serializer_class = TypeSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ('code', ) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(queryset, many=True) # --- modified from here --- custom_data = { 'vehicles': serializer.data } return Response(custom_data) # --- END modified from here --- Is possible to add a top-level JSON object and keep the filtering of django-filter working? Thank you! -
Django bulk_update with select_for_update in rows lock
Is that be locked for all users rows with last_name='Smith' one time? or lock only one row every time? Will bulk_update work in this lock? with transaction.atomic(): users = list(urs.select_for_update().filter(last_name='Smith').only('updated')) for user in users: user.updated = '2020-12-01' UserReceiver.objects.bulk_update(users) -
django-datatable-view==0.9.0 Django 3.1.3: ImportError: cannot import name 'FieldDoesNotExist'
I am using the latest package django-datatable-view 0.9.0 in django 3.1.3 (upgrading from django 1.8.6) When a I run manage.py run server I get the following error: File "/usr/local/lib/python3.6/site-packages/datatableview/__init__.py", line 3, in <module> from .datatables import Datatable, ValuesDatatable, LegacyDatatable File "/usr/local/lib/python3.6/site-packages/datatableview/datatables.py", line 12, in <module> from django.db.models.fields import FieldDoesNotExist ImportError: cannot import name 'FieldDoesNotExist' Upgrading the package is not an option as I am already using the latest package. What can I do to fix the error? Thank you for your help -
How do I find active directory information for ldap?
I was tasked with implementing Django LDAP and I'm lost. For one, I'm trying to search for users anonymously with: AUTH_LDAP_BIND_DN = "" AUTH_LDAP_BIND_PASSWORD = "" AUTH_LDAP_USER_SEARCH = LDAPSearch( "ou=??,dc=something,dc=somethingelse,", ldap.SCOPE_SUBTREE, "(uid=%(??)s)" ) What should I put for the organizational unit? I know it's a container of the active directory, but how do I find that out - what our organization uses? -
Reverse for 'action' with arguments '('',)' not found
I have error that seemed to happen to some other people, still I didn't figure out what am I doing wrong, so asking you all for help. Can you please support me with my code? views.py: def index(request): context = {'cards': Card.objects.all()} return render(request, 'mtg/index.html', context) def lookup(request, card_name): context = {'card_lookup': Card.objects.all()} return render(request, 'mtg/index.html', context) def action(request, card_name): card = get_object_or_404(Card, pk=card_name) # 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('mtg:tmpl', args=card_name)) urls.py: app_name = 'mtg' urlpatterns = [ path('', views.index, name="index"), path('<str:card_name>/img', views.lookup, name='img'), path('<str:card_name>/action', views.action, name='action'), ] index.html: <body> <form class="wrap" action="{% url 'mtg:action' card.name %}" method="post"> <input class="searchTerm"/> <button class="center" name="search">Search for synergy</button> <button class="center" name="lookup">Lookup a card</button> </form> {% if lookup_card %}<div>{{ card_lookup }}</div>{% endif %} </body> -
Database error conection using django-mssql-backend
I have to update an old django proyect that use django 1.8, pyodbc 3.0.10 and django-pyodbc-azure 1.8.3.0 with python 2.7.11. For the new version I need to use django 3.1.3, pyodbc 4.0.30 and django-mssql-backend 2.8.1 with python 3.9.0 the main difference is the use of django-mssql-backend 2.8.1 instead of django-pyodbc-azure 1.8.3.0, my settings.py have this configuration: 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'dn_name', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'host\instance', 'PORT': '1433', 'OPTIONS': { 'driver': 'SQL Server Native Client 11.0', 'unicode_results': True, }, }, Using the old version the connection works correctly but when I update the proyect gives me this error: ('08001', '[08001] [Microsoft][SQL Server Native Client 11.0]TCP Provider: No connection could be made because the target machine actively refused it. (10061) (SQLDriverConnect); [08001] [Microsoft][SQL Server Native Client 11.0]Login timeout expired (0); [08001] [Microsoft][SQL Server Native Client 11.0]Invalid connection string attribute (0); [08001] [Microsoft][SQL Server Native Client 11.0]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (10061)') For what I know I have the correct … -
Django understanding uniq constraint on nested models
Having the following model class Department(models.Model): name = models.CharField(max_length=10) class Person(models.Model): name = models.CharField(max_length=10) class Position(models.Model): name = models.CharField(max_length=10) person = models.ForeignKeyField(to=Position) department = models.ForeignKeyField(to=Department) I would like to assure that a person is unique in one department (means can only have one position in one department). My aproach would be to use a constraint on position, but I cannot figure out What Q statement to use for condition. class Position(models.Model): name = models.CharField(max_length=10) person = models.ForeignKeyField(to=Position) department = models.ForeignKeyField(to=Department) class Meta: constraints = UniqueConstraint(fields=['person'], condition=Q(???)) I would expect there to be something like Q(<all_departments>) which i could not find -
How to accept a django.http.HttpResponse object containing a csv file in Ajax?
When I click a button on the html page, I want to trigger a query in backend database, creating a csv file specific to the request and then download it. I managed to pass data to django, however, I cannot find a way to trigger download as I click the button and I don't know how to make ajax accept django.http.HttpResponse containing csv. Meanwhile I find everything is ok if I visit the url directly, but when I use ajax it's not the case. For illustration, My urls.py is: url('export/',views.export) My views.py is: def export(request): if request.method == 'GET': export_list = json.loads(request.GET['id_list']) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' writer = csv.writer(response) writer.writerow(['column_1','column_2']) for id in export_list: item = Item.objects.get(id=id) witer.writerow([item.attr_1,item.attr_2]) return response And my html is <a class="btn btn-primary" id="export" rel="external nofollow" role="button" style="margin-left: 30px;">export to csv</a> $("#export").click( function(){ data.id_list = JSON.stringify(paperids); data.csrfmiddlewaretoken = '{{ csrf_token }}'; $.ajax({ url: '/export/', type: 'GET', data: data, dataType: "text/csv", headers:{ 'Accept': 'text/csv','Content-Type': 'text/csv' }; success: function(result){ console.log(result); }, error: fucntion(){ console.log("why"); } }) How can I manage to download the csv when clicking the button? -
Django 3.1.3 Field 'id' expected a number but got '{{ \r\nchoice.id }}'
I'm stuck at Django's official tutorial (see Writing your first Django app, part 4). https://docs.djangoproject.com/en/3.1/intro/tutorial04/ I get the following error: In this Django project, inside the poll app I'm making, we're supposed to make a vote() view in views.py which should process the POST request data of the poll and redirect us to the results() view (there's no template for the vote()view, it's just in charge of processing the data we send through the poll). At first I thought I had a typo error, but I then copy-pasted everything directly out of the documentation tutorial (which I linked at the beginning of this question) and the error persisted. Results.html <h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }} </li> {% endfor %} </ul> <a href="{% url 'polls:detail' question.id %}">Vote again?</a> Index.html {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} Detail.html <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice … -
Django form is not submitting, form valid method not working
Not sure why my form is not submitting. When i click the submit button nothing happens and there is no POST request. I've tried changing the button and the html with no real avail. Perhaps the form valid method is not working? Any help would be appreciated, also if anyone knows how to properly prevent multiple form submissions in django that would help me a lot! heres my view from forms.py import SignUpForm class RegisterKeyView(CreateView): form_class = SignUpForm template_name = 'accounts/RegisterKeyView.html' def get(self,request,*args,**kwargs): ... return render(request, self.template_name, {'form': self.form_class }) def form_valid(self,form, **kwargs): ... form.instance.save() ... login(self.request, self.request.user) return redirect('user-dashboard') heres my form class SignUpForm(UserCreationForm): username = forms.CharField(max_length=30) email = forms.EmailField(max_length=200) class Meta: model = User fields = ('username', 'email','school', 'password1', 'password2', ) heres my template {% extends "accounts/base.html" %} {% load crispy_forms_tags %} {% block content %} <form method = "POST" class="form-signin border rounded "> {% csrf_token %} {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Profile Info</legend> {% crispy form %} </fieldset> <div class="form-group"> <button class="mt-4 btn btn-lg btn-primary btn-block" type="submit">Login</button> </div> </form> {% endblock content %} -
Why Django Form is not empty but invalid?
I fill the form then submit and see that it's invalid but when I print my form after submit I see that it's not empty. I don't understand why it's invalid. I tried using forms.ModelForm then forms.Form both of them ended up in the same result. print result of field_errors in my view at below: FIELD_ERRORS: [('İsim', []), ('Cins', []), ('Yeni Cins Ekleme', []), ('Cinsiyet', []), ('Ağırlık', []), ('Boyut', []), ('Yeni Boyut Ekleme', []), ('Renk', []), ('Yeni Renk Ekleme', []), ('Doğum Tarihi', []), ('Fotoğraflar', ['Bu alan zorunludur.'])] My forms.py from django import forms from .models import NewBorn,Size,Color,Breed class NewDogForm(forms.Form): name = forms.CharField(label='İsim',widget=forms.TextInput(attrs={'class':'form-control'})) breed = forms.ModelChoiceField(queryset=Breed.objects.all(),required=False,label = 'Cins',widget=forms.Select(attrs={'class':'form-control'})) yeni_cins_ekleme = forms.CharField(required=False,label = 'Yeni Cins Ekleme') gender = forms.CharField(label = 'Cinsiyet',widget=forms.TextInput(attrs={'class':'form-control'})) weight = forms.CharField(label = 'Ağırlık',widget=forms.TextInput(attrs={'class':'form-control'})) size = forms.ModelChoiceField(queryset=Size.objects.all(),required=False,label = 'Boyut',widget=forms.Select(attrs={'class':'form-control'})) yeni_boyut_ekleme = forms.CharField(required=False,label = 'Yeni Boyut Ekleme') color = forms.ModelChoiceField(queryset=Color.objects.all(),required=False,label = 'Renk',widget=forms.Select(attrs={'class':'form-control'})) yeni_renk_ekleme = forms.CharField(required=False,label = 'Yeni Renk Ekleme') date_of_birth = forms.DateField(label='Doğum Tarihi',widget=forms.DateInput(format='%d-%m-%Y')) photo = forms.CharField(label = 'Fotoğraflar',widget=forms.TextInput(attrs={'class':'form-control','type':"file",'multiple accept':'image/*'})) My views.py def yavruKopeklerDuzenleme(request): title = "Minik Patiler - Yavru Köpekler Düzenleme Sayfası" print("POST ÜSTÜ") if request.method == 'POST': form = NewDogForm(request.POST, request.FILES) print("IS_VALID ÜSTÜ") print("FORM: ",form) field_errors = [ (field.label, field.errors) for field in form] print('FIELD_ERRORS: ',field_errors) if form.is_valid(): print("I'm HERE") … -
Placeholder not coming in django forms
When I'm trying to build out a django form, the placeholder for the input field that I'm specefiying does not come. Here is my forms.py code: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ('username','email','password1','password2') widgets = { 'username':forms.TextInput(attrs={'placeholder':'SamyakJain2509'}), 'email':forms.EmailInput(attrs={'placeholder':'youremail@example.com'}), 'password1':forms.PasswordInput(attrs={'placeholder':'not-crackable'}), 'password2':forms.PasswordInput(attrs={'placeholder':'not-crackable'}), } I should get a placeholder for all my form fields, but I only get the placeholder for my username field. Here is the output: What is the problem? -
Form Field Calculations in Template
I am creating a stock market site and would like to show the total purchase value live as the user is typing rather than as an error during form clean. The calculation involves multiplying two fields. The first is a quantity field which is just a number the user inputs. The second is the stock which is a drop down for a foreign key. The user selects a stock and an attribute of the stock is the price. I would like to multiply these fields and display the result each time a user alters a field. I would also like to do this with a model form if possible. I have tried using {{ form.field.value }} within the template to get one the fields but I cannot get it to update for a change. For the stock field, I think my best bet is to create a matching array in javascript and once I can get a live updating form value match it to the stock price from the array. Another possibility may be using getElementById with the field id but I have been unable to get that to work so far as well. Here is an example not made …