Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Looping in Django Templates
<body> {% for topic in topics %} <p>Topic:<br></p> <h3>{{ topic.text }}:</h3> <p>date added: {{ topic.date_added }} </p> {% entries = topic.enrty_set.all %} <<---- this is line 12 (error line) {% for entry in entries %} <p>{{ entry }}</p> {% endfor entries %} {% endfor topic %} </body> TemplateSyntaxError at / Invalid block tag on line 12: 'entries', expected 'empty' or 'endfor'. Did you forget to register or load this tag? How do I make inner for loop? Looks like I can't assign quarry set to a variable like this. How do I do this? I can't really do it in views ether. The Goal is to display all the Entries for every Topic I have. code works in: $ python manage.py shell -
Django query on shell_plus
how do you know if certain function belongs to certain model. I have this model 'Student' without foreign key record to model 'OtherRecord'. How ever if I did this student = Student.objects.filter(pk=123) and I went to shell_plus recipient is giving me otherrecord_set() student.otherrecord_set() which is a little bit confusing to me why OtherRecord is available on Student model. Thank you in advance. -
Django Two Factor Authentication - Remove Token Generator Option From Wizard
I've been playing with Django Two Factor authentication for the last two days or so, and I have it partially working. I am trying to figure out a way to remove the QR Token Generator. I have tried subclassing the setup view, but the form wizard is causing me some grief. The wizard is confusing me. I know in a regular form, how to remove radio buttons, but in this case, I can't seem to locate the source of the Token Generator. The SetupView... @class_view_decorator(never_cache) @class_view_decorator(login_required) class SetupView(IdempotentSessionWizardView): """ View for handling OTP setup using a wizard. The first step of the wizard shows an introduction text, explaining how OTP works and why it should be enabled. The user has to select the verification method (generator / call / sms) in the second step. Depending on the method selected, the third step configures the device. For the generator method, a QR code is shown which can be scanned using a mobile phone app and the user is asked to provide a generated token. For call and sms methods, the user provides the phone number which is then validated in the final step. """ success_url = 'two_factor:setup_complete' qrcode_url = 'two_factor:qr' template_name … -
error while using a variables taken from html forms in django
I have created a variable which gets the value from HTML Form now I want to use the variable in different python file and return the value from that different python file and print it on web page using Django but while I'm doing that it is showing me an error I'm not sure how to go forward from django.shortcuts import render, redirect, render_to_response def contact_view(request): print(request.method) if request.method == "POST": name = request.POST.get("name") email=request.POST.get("email") message=request.POST.get("message") print(na,email,message) return redirect("/redirect/") return render(request, "index.html", {}) def home(request): from myapp.namer import bob return render(request, "other.html", { "var1":bob}) def red(request): return render(request, "redirect.html", {}) namer is basically namer.py on which I'm doing operations now how to use the variable 'name' or 'email' and bob is the function which will return the value that I want to print what's should be the import in namer please help I've just started learning Django -
What should I do when migrate in django does not work?
I have a problem with creating models in Django. I want to create new model, so I write code: class Image(models.Model): title = models.CharField(max_length=100) image = models.ImageField() In the next step, I write those commad "python manage.py makemigrations , python manage.py migrate". I got this result: from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myfirstapp', '0008_delete_image'), ] operations = [ migrations.CreateModel( name='Image', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=100)), ('image', models.ImageField(upload_to='')), ], ), ] but I don't have access to Image's table in Django administration. Does anyone know what should I do? Or can see an error, know of tips, or other ways to help? -
Django Rest-Framework Session Authentication
I'm Working with object-level permissions via customized permission class. I've created several users using the Django's interactive shell. I want to use the default rest-framework Login view to login and test my api's but it's not redicrte me to the login page. Base URLs.py: urlpatterns = [ path('', include('RunKeeper.urls')), path('api-auth/', include('rest_framework.urls')),] rest-framework URLs.py: urlpatterns = [ path('', include('RunKeeper.urls')), path('api-auth/', include('rest_framework.urls')),] Whenever i press the login button in the browsable API i got ""GET /api-auth/login/?next=/api-auth/login/ HTTP/1.1" 200 5415" : enter image description here My sittings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'RunKeeper.apps.RunkeeperConfig', 'rest_framework', 'django_filters', ] REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'RunKeeper.custompagination.LimitOffsetPaginationWithUpperBound', 'PAGE_SIZE': 4, 'DEFAULT_FILTER_BACKENDS': ( 'django_filters.rest_framework.DjangoFilterBackend', 'rest_framework.filters.OrderingFilter', 'rest_framework.filters.SearchFilter', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ) } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'restful01.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Identify what model belongs a unique field (primary key)
I would like with an unique field, to obtain the name of the model where it belongs. I was trying to use the get_model but it has another purpose. Suppose that you have a school with multiple classrooms (each classroom is a model), and you wan to search a student with just the ID of him, receiving the name of the classroom where the student is. So you type the ID (primary key) and the function will return you the class (model) where the student belong -
GET Request not Getting Saved When Navigating Over Views-- Django
When I navigate to my first view, the GET request is saved as a session variable. def index(request): if request.method == 'GET': symbol = request.GET.get('symbol', 'none') request.session['symbol'] = symbol return render(request, 'backtests/yieldcurve.html', {'symbol' : symbol}) Then, when I navigate to another page via the sidebar, the GET request still shows up. def yieldcurve(request): symbol = request.session.get('symbol', 'none') return render(request, 'backtests/yieldcurve.html', {'symbol' : symbol}) Yet, when I navigate back to the index from the sidebar, the GET request is not saved. Is there a way to do this? Thanks! -
Passing a class instance to session in Django
I created a custom class in my view and tried to add it to the session using this code: request.session['class_instance'] = Class() Django raise an error: Object of type user_authorization is not JSON serializable When I replace the class with an integer, it works fine and I can get it in other views. Is it possible to pass a class in Session to be available in different apps? -
How can I get all fields from the model address?
I was able to display some information of the model, but I'm trying to get the fields from the address and is only giving me the names of the addresses, this is the model: class Address(models.Model): # users = models.ManyToManyField(Profile, blank=True) name = models.CharField(max_length=100, blank=False) address1 = models.CharField("Address lines 1", max_length=128) address2 = models.CharField("Address lines 2", max_length=128, blank=True) city = models.CharField("City", max_length=64) state = USStateField("State", default='FL') zipcode = models.CharField("Zipcode", max_length=5) user = models.ForeignKey(Profile, on_delete=models.CASCADE, blank=False) class Meta: verbose_name_plural = 'Address' def __str__(self): return self.name This is what I've tried: def billingSettings(request): currentUser = request.user currentUser_userName = currentUser.username currentUserId = currentUser.id address_listNames = Address.objects.all().filter(user__user__username=currentUser_userName) stuff = address_listNames.objects.all() # user_id = Address.objects.all().filter(user=currentUser.id) # for address in address_listNames: # print (address.id) addressX_listNames = Address.objects.all().filter(user__user__username=currentUser_userName) for address in stuff: print (address) if request.method == 'POST': user_AddressForm = AddressForm(request.POST, instance=request.user.profile) else: user_AddressForm = AddressForm(instance=request.user.profile) context = { 'address_listNames': address_listNames, 'user_AddressForm': user_AddressForm } return render(request, 'users/billing.html', context) This lines: for address in stuff: print (address) will only display the current names of my address: Work, Home, testAddress, ... so in my html, when I do: {% for address in address_listNames %} {{ address }} {% endfor %} It just again displays the names. I'm trying to … -
Page not found on Django - Empty paths
I'm trying to run this library. I downloaded and copied it on my desktop, then i tried to run it using: py -3.7 manage.py runserver I got: Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. But when i go to that url i keep getting this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in django_google_authenticator.urls, Django tried these URL patterns, in this order: ^admin/login/$ ^admin/ The empty path didn't match any of these. I don't understand what's wrong, can someone help me? Thanks in advance! -
ERR_TOO_MANY_REDIRECTS when I go to domain: Nginx, Daphne, Django, Digital Ocean
Frequent poster here, still can't figure it out. I'm running a Django Channels app on Digital Ocean, Ubuntu 16.04 using Daphne and Nginx. Followed this post. Nginx will only be used as a proxy for your django application, your django application will be running with daphne. And you should have daphne running on 127.0.0.1:8001 (or change the port to your likings). I have enabled LetsEncrypt SSL for my page and told all http requests to be redirected to https. My page is showing the error myapp.com redirected you too many times. I'm running daphne on 127.0.0.1:8001. daphne -b 127.0.0.1 -p 8001 myapp.asgi:application My nginx config file server { server_name myapp.com www.myapp.com; server_tokens off; return 301 https://$server_name$request_uri; listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/myapp.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/myapp.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.myapp.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = myapp.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name myapp.com www.myapp.com; return 404; # managed by Certbot root /home/me/myapp/src/myapp; location = /favicon.ico { access_log off; log_not_found off; } location /static/ … -
change my url from depending on id to title | django
I've a url for checking books by its id: path('book/<int:book_id>', views.book, name='book'), view: def book(request, book_id): book = get_object_or_404(Book, pk=book_id) context = { 'book': book } return render(request, 'media/book.html', context) but my client asked me to change it for the title instead but I tried it and it didn't seem to work, there are no examples for it in the docs either. -
In django admin showing a child of a child forms
Hi I would like to display the entire tree structure of a resource in the django admin. How would I go about doing this? My models look like this class A(models.Model): pass class B(models.Model): a = models.ForeignKey(A) class C(models.Model): b = models.ForeignKey(B) I would like to display all the children of B that belong to A in the same django admin from. When I add a CAdminInline to A's AdminModelAdmin I get a <class 'CInline'>: (admin.E202) 'C' has no ForeignKey to 'A' Exception. So django is doing some magic and looking for a FK on C. Is there I can override this? Thank you! -
Constructing Q objects dynamically, or NOP
I am trying to construct filter dynamically based on passed query parameters. Code below. Because the filter might end up empty, in which case all objects need to be returned, this is coming out very ugly. Is there a way to do this cleanly? Maybe if there is a default Q that means 'do not nothing'? def get(self, request, *args, **kwargs): q = None for field, value in request.GET.items(): if field not in Project._meta.fields: continue if q is None: q = Q(**{'{}'.format(field): value}) else: q &= Q(**{'{}'.format(field): value}) if q is None: projects = get_objects_for_user(request.user, ['api.view_project', 'api.edit_project', 'api.owner_project'], any_perm=True) else: projects = get_objects_for_user(request.user, ['api.view_project', 'api.edit_project', 'api.owner_project'], any_perm=True).filter(q) ser = ProjectSerializer(projects, many=True) return Response(ser.data, status=status.HTTP_200_OK) -
how to store my entered data from the form in the mysql database using xampp in django?
the main issue is I m not able to store my data in the database. I will show all the files here. app name= signup models.py from django.db import models Create your models here. class User1(models.Model): firstname = models.CharField(max_length=10) lastmname = models.CharField(max_length=10) email = models.CharField(max_length=30) phone = models.CharField(max_length=10) bdate = models.CharField(max_length=10) username = models.CharField(max_length=30) password = models.CharField(max_length=15) enter code here views.py from django.shortcuts import render from django.http import HttpResponse from .models import * Create your views here. def register(request): return render(request,'signup/register.html') def signup(request): if request.method == 'POST': firstname = request.POST('fname') lastname = request.POST('lname') email = request.POST('email') phone = request.POST('phone') bdate = request.POST('bdate') username = request.POST('uname') password = request.POST('pword') user1=User1(firstname=firstname,lastname=lastname,email=email,phone=phone,bdate=bdate,username=username,password=password) user1.save() #user = authenticate(username=username, password=password) #login(request, user) return render(request,'app1/index.html') template/signup/register.html { %csrf_token %} Register: Name: Contact Info: Birthday: Login Info: Previous Next var currentTab = 0; // Current tab is set to be the first tab (0) showTab(currentTab); // Display the current tab function showTab(n) { // This function will display the specified tab of the form... var x = document.getElementsByClassName("tab"); x[n].style.display = "block"; //... and fix the Previous/Next buttons: if (n == 0) { document.getElementById("prevBtn").style.display = "none"; } else { document.getElementById("prevBtn").style.display = "inline"; } if (n == (x.length - 1)) … -
Django :: Validation Error in not displaying
recently I am validating a from using Django. But I am not getting validation error when i enter wrong inputs. please provide some suggestion where i have done wrong. Below is my code, Views.py def contact_page(request): contact_form = ContactForm(request.POST or None) context = { "title":"contact page", "content":"Welcome to Contact page", "form": contact_form } if contact_form.is_valid(): print(contact_form.cleaned_data) return render(request, "contact/view.html", context) Forms.py from django import forms class ContactForm(forms.Form): fullname = forms.CharField( widget=forms.TextInput( attrs={ "class":"form-control", "placeholder" :"Your name " } ) ) email = forms.EmailField( widget=forms.EmailInput( attrs={ "class":"form-control", "placeholder" :"Your Email " } ) ) content = forms.CharField( widget=forms.Textarea( attrs={ "class":"form-control", "placeholder":"Your text" } ) ) def clean_email(self): email = self.cleaned_data.get("email") if not "gmail.com" in email: raise forms.ValidationError("Email has to be gmail.com") return email -
How to validate using CBV django
I am building a pastebin like app. Upto this point most of the basic features are working well. I wanted to add password feature to the paste but these type CBV examples are not shown in django documentation. I am using CBV and my detail view is : class DetailPaste(DetailView): template_name = 'pastebin/detail_view.html' def get_queryset(self): pk = self.kwargs['pk'] qs = PasteInstance.objects.filter(pk=pk) if qs.exists() : if qs[0].public_view: return qs elif self.request.user.is_authenticated: return qs else: raise Http404() else: raise Http404() I know i can define a view using def method procedure but I was wondering if any elegant method is present to do this using CBV. my model is : class PasteInstance(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField(max_length=400) timestamp = models.DateTimeField(auto_now_add=True) public_view = models.BooleanField( default=False, verbose_name='Make this paste public?') password = models.CharField( max_length=15, blank=True, verbose_name='Protect with password ?') -
Waypoints Infinite scroll for loading old messages (up scrolling)
I am trying to use Waypoints Infinite scrolling for loading old chat messages in Django. I have been successful in implementing the normal (down scrolling) version, but I cannot find any good docs/API for up scrolling. The container option in Infinite scroll says: Default: 'auto'. Newly loaded items are appended to the container. The default value of 'auto' means the container will be the same element as the element option. The element option, in congruence with the offset option, make up the waypoint that triggers the next page to load. So, is there no way to prepend the old chat messages while scrolling up? This is the code I have for normal scroll (paginator used in view): <div id="itemList" class="infinite-container"> {% for item in items %} <div class="infinite-item"> ........ </div> {% endblock %} {% if items.has_next %} <a class="infinite-more-link" href="?page={{ items.next_page_number }}"></a> {% endif %} </div> <script src="{% static 'js/waypoints/lib/jquery.waypoints.min.js' %}"></script> <script src="{% static 'js/waypoints/lib/shortcuts/infinite.min.js' %}"></script> <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0] }); </script> -
Django readmore display filter
I'm using a templatetag based filter to expand some text-areas on my site. Now i also wanted to use this tag onto a public PGP-Key wich is indeed a bit diffrent formated then normal text and it seems my filter does not work properly at this point. "more" always gets displayd after a word or two but the whole text does not fold right ther way it should. Its seems that the whole PGP-key is interpreted as a single very very long word. Is there a practical workaround for this? I guess the simple answere is making the js part not word based but character based. The problem for me is that i have no idea on JS and this is likely the only peace of JS code i using at this project. Is there maybe somebody that can help me out here :D template.html {% load readmore %} ... <h4>{{ user.pubpgp|readmore:10|safe|linebreaks }}</h4> ... readmore.py from django import template from django.utils.html import escape from django.utils.safestring import mark_safe register = template.Library() import re readmore_showscript = ''.join([ "this.parentNode.style.display='none';", "this.parentNode.parentNode.getElementsByClassName('more')[0].style.display='inline';", "return false;", ]); @register.filter def readmore(txt, showwords=15): global readmore_showscript words = re.split(r' ', escape(txt)) if len(words) <= showwords: return txt # wrap the … -
Django Query / MySQL Database Optimization
This is kind of a two-fold question -- I'm pretty new to Django. My app uses Django to interface with a MySQL database and servicing data to a ReactJS frontend. I'm trying to make a query that will grab the latest entry (by time) off of a certain column value. For example: class Cake(models.Model): bakery = models.CharField(Bakery) baked_at = models.DateTimeField() baker = models.ForeignKey(Baker) buyer = models.ForeignKey(Buyer) If I wanted to find all the latest cakes per given bakery name in one QuerySet, what would be a good query to run? Currently I have something like: subquery = Cake.objects.filter(bakery=OuterRef('bakery')).order_by('-baked_at') latest_cakes = Cake.objects.filter(baked_at=Subquery(subquery.values('baked_at')[:1])) My second question is about database/serialization optimization. Say even if I'm just serializing all the cakes or just the latest_cakes, how should I optimize if I'm dealing with up to 10,000+ entries? -
Wagtail (Django) snippet with inline object - Custom validation for relational-dependent input data
I have a Wagtail snippet, with a model related by a parental key. I want to do cleaning and validation based on both models. In this instance, I want to be able to add regions to images that display content blurbs when hovered over. How can I clean the inline model while accessing attributes from the parent model? @register_snippet class ImageMap(ClusterableModel): image = models.ForeignKey( 'wagtailimages.Image', on_delete=models.SET_NULL, null=True, blank=True, related_name='+', ), panels = [ ImageChooserPanel('image'), InlinePanel('regions', heading='Hoverable regions', min_num=1, ), ] class ImageRegion(Orderable): image_map = ParentalKey('info_site.ImageMap', related_name='regions') blurb = RichTextField(max_length=2000) left = models.IntegerField() top = models.IntegerField() right = models.IntegerField() bottom = models.IntegerField() panels = [ FieldPanel('blurb'), MultiFieldPanel([ FieldPanel('left'), FieldPanel('top'), FieldPanel('right'), FieldPanel('bottom'), ], )] def clean(self): super(ImageRegion, self).clean() image_width = self.image_map.image.width image_height = image_width = self.image_map.image.height if any([ self.top > self.bottom self.top > image_height, self.bottom > image_height, ]): raise ValidationError( 'Coordinate top must be less than coordinate bottom; both must be less that image height of %s px' % image_height) -
Deploy Django Application on Cloud, but even cannot get access to ip_address:8000
I am a beginner on Django. And try to deploy a testproject on cloud server to check if it works or not. Server: Ubuntu 16.04 And after I create virtualenv on the server with nginx installed. I execute below: python manage.py runserver 0.0.0.0:8000 And then I go to the browser to access my server's http://ip-address:8000. But it failed to show anything of my application. I already added the ip-address to ALLOWED_HOST. But still not working. Are there any thoughts for this situation? -
My ajax post request gets 403 forbidden by django
I was trying to implement on keyup search with django and jquery following this video but when I try the code everytime it returns forbidden 403! the html page: <div class="search-input"> <form> {% csrf_token %} <button>بحـث</button> <input type="text" name="q" id="search" placeholder="Est: Game of thrones, Vikings or Deadpool" /> </form> </div> <div class="search-results"></div> urls.py: path('search/', views.search_titles, name='search') views.py: def search_titles(request): if request.method == 'POST': search_text = request.POST['search_text'] else: search_text = '' search_results = Media.objects.filter( is_published=True, title__contains=search_text)[:5] context = { 'search_results': search_results } return render(request, 'partials/_search_results.html', context) the jquery file: $("#search").on("keyup", function() { $.ajax({ type: "POST", url: "/search/", data: { search_text: $("#search").val(), csrfmiddlewaretoken: $("input[name=csrfmiddlewaretoken]").val() }, success: searchSuccess, dataType: "html" }); }); function searchSuccess(data, textStatus, jqXHR) { $("search-results").html(data); } }); search_results.html ( that i don't even know the reason of ) {% if search_results.count > 0 %} {% for result in search_results %} <li> <a href="#">{{ result.title }}</a> </li> {% endfor %} {% else %} <li>Nothing to show</li> {% endif %} -
Why is Django showing a KeyError?
I've been looking at the Django docs for an example on how to add CSS classes to model form inputs. When I use the solution, though, Django raises a KeyError, and I can't really pinpoint the source, because the line of code the debug screen shows is a completely irrelevant CSS class in the template. The solution: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['title', 'content', 'category'].widget.attrs.update({'class': 'form-control'}) self.fields['content'].widget.attrs.update(size='100', height='50') The error message: KeyError at /new/ ('title', 'content', 'category') Request Method: GET Request URL: http://localhost:8000/new/ Django Version: 2.1.7 Exception Type: KeyError Exception Value: ('title', 'content', 'category') Exception Location: /home/bob/python-virtualenv/blog/bin/blog/posts/forms.py in __init__, line 11 Thanks in advance!