Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pagination using ListView and a dynamic/filtered queryset
I have a class based view that I am using to display a queryset in a table. I am also using a couple formsets to filter this queryset. I am using the get_queryset() method provided as part of the generic.ListView class to filter the diplayed results. Here is basically what my class looks like: from django.views import generic class UnifiedSingleSearch(generic.ListView): template_name = 'app/foo.html' model = MyModel paginate_by = 30 def get_queryset(self): if self.request.POST: # If we got here because of a search submission, filter return MyModel.objects.filter('Some stuff base on the POST data') return MyModel.objects.all() # Otherwise, just show everything Because I am using a formset to submit multiple search criteria, I have to use a POST request. Upon initial submission of the form, the page reloads with a correctly filtered querset. However when I try to use my pagination controls, the POST request is thrown away and the page acts as if I am going to page#2 of MyModel.objects.all() instead of my filtered down subset. How can I retain my filtered queryset when using pagination controls? Here is the HTML for the pagination controls: {% if is_paginated %} <nav aria-label="Pagination nav"> <ul class="pagination"> {# Back a page #} {% if … -
PyCharm No usages found in Project Files
I've opened my Django project in PyCharm, as I want to use a proper IDE instead of a text editor to better manage the project. When I run Find Usages on a function in /projectroot/app/views.py it says "No usages found in Project Files," but when I run CMD + SHIFT + F it finds 34 matches in 13 files. As suggested in this answer, I marked /projectroot/ directory as Sources Root did File > Invalidate Caches / Restart... in Find Options... I also tried to searching in All Places If I run Find Usages on some other functions in /projectroot/app/helpers.py it seems to work. Any ideas what else I could try? -
Django: Transactions and how to avoid wrong counting?
I am currently struggling with a topic connected to transactions. I implemented a discount functionality. Whenever a sale is made with a discount code, the counter redeemed_quantity is increased by + 1. Now I thought about the case. What if one or more users redeem a discount at the same time? Assuming redeemed_quantity is 10. User 1 buys the product and redeemed_quantity increases by +1 = 11. Now User 2 clicked on 'Pay' at the same time and again redeemed_quantity increases by +1 = 11. Even so, it should be 12. I learned about @transaction.atomic but I think the way I implemented them here will not help me with what I am actually trying to prevent. Can anyone help me with that? view.py class IndexView(TemplateView): template_name = 'website/index.html' initial_price_of_course = 100000 # TODO: Move to settings def check_discount_and_get_price(self): discount_code_get = self.request.GET.get('discount') discount_code = Discount.objects.filter(code=discount_code_get).first() if discount_code: discount_available = discount_code.available() if not discount_available: messages.add_message( self.request, messages.WARNING, 'Discount not available anymore.' ) if discount_code and discount_available: return discount_code, self.initial_price_of_course - discount_code.value else: return discount_code, self.initial_price_of_course def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['stripe_pub_key'] = settings.STRIPE_PUB_KEY discount_object, course_price = self.check_discount_and_get_price() context['course_price'] = course_price return context @transaction.atomic def post(self, request, *args, **kwargs): stripe.api_key = settings.STRIPE_SECRET_KEY … -
django tests - Test login and permissions
I have the following setup: I have a view and two possible permission groups. I want to test if my view is reachable in all possible scenarios. Meaning: Not logged in Logged in with wrong group Logged in with correct group My permisson control works via a Mixin: class PermissionMixin(object): group_list = None def in_groups(self, u): if u.is_authenticated(): if u.is_superuser or bool(u.groups.filter(name__in=self.group_list)): return True return False def dispatch(self, request, *args, **kwargs): if self.in_groups(request.user): return super(PermissionMixin, self).dispatch(request, *args, **kwargs) return render(request, '403.html', status=403) My urls look like this: url(r'^my-view/$', login_required(views.MyView.as_view()), name='my-view-view') When I try to use RequestFactory test, I always get status 200 instead of 403 oder 302 (redirect to login): self.factory = RequestFactory() request = self.factory.get(reverse('my-view')) request.user = AnonymousUser() response = MyView.as_view()(request) self.assertEqual(response.status_code, 302) When I try Client(), it works but it takes a couple of seconds to process the request. When I want to test all my views I'll want to kill myself when waiting for the CI-pipeline. Any ideas why the RequestFactory is not working corretly? Or how I can solve my problem? Thanks! -
Wagtail redirect max length too short
Our migration into Wagtail involves creating redirects for very long urls e.g. urls in Arabic. These do not seem to be supported by the Wagtail redirects system. Any workarounds for this? Migration script error: django.db.utils.DataError: value too long for type character varying(255) Database console error: db_1 | 2018-08-24 13:19:06.000 UTC [134] ERROR: value too long for type character varying(255) db_1 | 2018-08-24 13:19:06.000 UTC [134] STATEMENT: INSERT INTO "wagtailredirects_redirect" ("old_path", "site_id", "is_permanent", "redirect_page_id", "redirect_link") VALUES ('https://www.opendemocracy.net/5050/atiaf-zaid-alwazir/%D9%88%D9%85%D8%A7-%D9%8A%D8%B2%D8%A7%D9%84-%D8%A7%D9%84%D8%B7%D8%B1%D9%8A%D9%82-%D8%B7%D9%88%D9%8A%D9%84%D8%A7-%E2%80%93-%D8%A8%D9%82%D9%84%D9%85-%D8%A3%D8%B7%D9%8A%D8%A7%D9%81-%D8%B2%D9%8A%D8%AF-%D8%A7%D9%84%D9%88%D8%B2%D9%8A%D8%B1', 1, true, 9528, '') RETURNING "wagtailredirects_redirect"."id" (note: even removing the domain from the url still leaves us with a utf-8 string of 257, which is too long) -
Django Authorization Backends always showing login even after logged in
I'm using Authorization Backends in order to use my own database with username and password (our own encrypted techniques). Now when i run the sever, its giving me login button. Even after successfull login its displaying login action only instead of username and logout. Can any one please help me out, where i'm doing wrong. New to Django. Thanks in Advance. -
Connect a series of embedded TypeForm urls to a django backend
I created a series of different forms on typeform.com that are part of a questionnaire. The forms can be embedded in an iframe, e.g <body> <iframe id="typeform-full" width="100%" height="100%" frameborder="0" src="https://typeform.com/to/xxxx1"></iframe> <script type="text/javascript" src="https://embed.typeform.com/embed.js"></script> </body> I need to catch the information entered in each of the forms, process them in a python backend and open the next typeform url by passing on response values that I obtained from the backend. So far, I have set up a local django project where I saved the first embedded iframe in an html template and connected it to a django get view, e.g localhost:8000/start/. Upon form submission, the values are sent to an ngrok url via webhook and caught in another viewset, where I process the JSON. Is there any way that I can catch the webhook AND reroute to the next form with the processed values? Is there a better way to set this up? (e.g. websockets) -
How to have models.UUIDField field without dash
I tried to have models.UUIDField without dash, by using default=uuid.uuid4().hex (Instead of default=uuid.uuid4()) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) api_key = models.UUIDField(default=uuid.uuid4().hex, editable=False, unique=True) subscription = models.IntegerField( choices=[(s.value, s.name) for s in Subscription], null=False, blank=False ) def __str__(self): return str(self.api_key) However, the resultant result still come with dash. django=# select * from users_profile; id | api_key | secret_key | subscription | user_id ----+--------------------------------------+------------+--------------+--------- 1 | 9da3546c-660c-46c6-adc4-6a13e6ee202b | | 0 | 1 2 | 9cbc3a68-7f50-4b18-9e61-7b009f22a0e8 | | 0 | 2 (2 rows) May I know how to have models.UUIDField field without dash? -
How to deploy or host django web application from windows server
I developed django web application and want to host this website on windows server 2016. Can anyone know which steps are the simple and best ways? Thanks. -
filtering a queryset based on another queryset
I have a model called UserCommunityProfiles Structured as follows class UserCommunityProfile(models.Model): owner = models.ForeignKey( User, on_delete = models.CASCADE) (...) and a model called subscriptions structured : class subscriptions(models.Model): subscriber = models.ForeignKey( User, on_delete = models.CASCADE, related_name='subscriber' ) subscribed_to = models.ForeignKey( User, on_delete = models.CASCADE, related_name='subscribed_to' ) and what i am trying to achieve is display the profiles of every user which is not in the query set subscriptions as a subscribed_to and the subscriber is request.user what i did is in the views i did subs = subscriptions.objects.filter(subscriber=request.user) profiles = UserCommunityProfile.objects.exclude(owner=subs) but i get an error saying Cannot use QuerySet for "subscriptions": Use a QuerySet for "User". what should i do ? -
Can I get the context passed to a notification in a Django test?
In a Django test, if I want to inspect the context that was used to render an HTTP response, I can access response.context: response = self.client.get(url) self.assertTrue(response.context['foo']) Can I do the same thing with e-mail notifications, i.e. when accessing mail.outbox? -
Django 1.11 Allauth google token authetication and token validation
I have Django rest framework (DRF) setup with allauth to allow google authentication as external authentication I am not using any built in authentication like register user and so on. In my DRF I do have protected resource which I intend to use to protect them using auth_token received for that respective user. I can see after hitting google Oauth URL I am able to login and I can see Django Admin backend that following tables like “SocialAccounts” I can see user there and in “Social Application Token” table I can see user and respective authe_token with refresh token along with expiry timing. My use cases are as following In my Django views I want to use that auth_token for that user to create session Upon expiry of auth_token it should be auto refresh so that client should not every time re authenticate them self. Is it possible to use Auth_token in as JWT token pass along with header for protected resources in DRF so that it will not be accessed unwanted users. If someone can guide me to any documentation or use case scenario would be great help. settings.py import os # Build paths inside the project like this: … -
Select related foreign key value in the dropdown menu in the Add/Change page of Django Admin
models.py class Doctor(models.Model): name = models.CharField(max_length=255) class Album(models.Model): doc = models.ForeignKey(Doctor) name = models.CharField(max_length=255) class Video(models.Model): doc = models.ForeignKey(Doctor) album = models.ForeignKey(Album) src = models.CharField(max_length=500) As show above, in the Video Admin add/change page, there are two dropdown menu for selecting: Album and Doctor. However, when I choose an Album (e.g. album.id=1 and belongs to doctor.id=5), the Doctor dropdown menu display all Doctors, but I only wanna the only one who related to the Album that I choose. I tried django-smart-selects, it didn't work. And, I add autocomplete_fields = ['doc'] under class VideoAdmin(admin.ModelAdmin, ExportCsvMixin), it didn't work too. Anyone can give me a hand? Thanks VEry veRY much! -
Remove label_suffix of django.contrib.auth.forms
I am developing my Django application. I want to use django.contrib.auth.forms, but I want to remove label_suffix(: after label_tag). I searched several times, many articles say to make the new form and add the code below to __init__. kwargs.setdefault('label_suffix', '') But I don't want to make new Authentication forms, so anyone knows how to set label_suffix for django.contrib.auth.forms? -
Django and docker: outputting information to console
I'm using Django, which I run in a Docker container. There is something happening in my view that I can not understand. There are some for statements and conditional statements and I'd like to see exactly where things go awry. The easiest way for me to do this, is if I can output some variables to the console. Is this possible in Django? Something like: for item in items: output-to-console("Running item ")+str(item.id) if item.active: output-to-console(str(item.id) + " is active") Is this possible? I know there are debugging tools but it seems overkill in my situation if some output-to-console tool exists... -
Heroku cannot import name 'login'
Since I deployed my django application to heroku I am getting an error when opening the project. It works just fine localy but after pushing to django the following error is appearing: ImportError at / cannot import name 'login' Request Method: GET Request URL: https://blooming-headland-56472.herokuapp.com/ Django Version: 2.1 Exception Type: ImportError Exception Value: cannot import name 'login' Exception Location: /app/Clientes/urls.py in <module>, line 5 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.6 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Sex, 24 Ago 2018 11:32:30 +0000 My urls.py looks like this: from django.urls import path from . import views from django.conf import settings from django.contrib.auth import views as auth_views from django.contrib.auth.views import ( login, logout, password_reset, password_reset_done, password_reset_confirm ) from django.conf.urls.static import static app_name = 'client' urlpatterns = [ path('register/', views.register, name='register'), path('login/', login, {'template_name': 'Clientes/login.html'}, name='login'), path('mail/', views.mail, name='mail'), path('profile/config', views.config_view, name="config"), path('profile/dashboard', views.dashboard_view, name="dashboard"), path('reset-password/', password_reset, name="reset_password"), path('reset-password/done/', password_reset_done, name="password_reset_done"), path('reset-password/confirm/', password_reset_confirm, name="password_reset_confirm"), path('profile/logout/', views.logout_view, name='logout'), path('profile/', views.ProfileView.as_view(), name='profile'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Django MultiSelectField with multiple fields per choice
I'm using MultiSelectField in my form, which allows the user to select multiple choices. However, I would like to add few additional fields per choice, e.g. min value, max value, units, etc (for the user to fill in, for each choice he makes). In some way, I feel like I'm looking for a different field type, which acts more like a table or array, for the user to fill. I couldn't find such a thing though.. Can you please guide me how to achieve that goal? Thanks ahead, Shahar -
Django Testing: No Matching Query even though it was created
I am receiving the following error when I run manage.py test: ====================================================================== ERROR: test_pokemon_detail_view (pokedex.tests.test_views.TestViews) Test the pokemon detail view and ensure the correct template was used ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/z/chbresser/pokedex/tests/test_views.py", line 32, in test_pokemon_detail_view response = self.client.get(reverse("pokedex:pokemon", args=[self.pokemon.id])) File "/home/z/test_env/lib/python3.5/site-packages/django/test/client.py", line 517, in get response = super().get(path, data=data, secure=secure, **extra) File "/home/z/test_env/lib/python3.5/site-packages/django/test/client.py", line 332, in get return self.generic('GET', path, secure=secure, **r) File "/home/z/test_env/lib/python3.5/site-packages/django/test/client.py", line 404, in generic return self.request(**r) File "/home/z/test_env/lib/python3.5/site-packages/django/test/client.py", line 485, in request raise exc_value File "/home/z/test_env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/z/test_env/lib/python3.5/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/z/test_env/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/z/test_env/lib/python3.5/site-packages/django/views/decorators/http.py", line 40, in inner return func(request, *args, **kwargs) File "/home/z/chbresser/pokedex/views.py", line 23, in pokemon poke = Pokemon(poke_id) File "/home/z/chbresser/pokedex/pokemon.py", line 152, in __init__ gender_obj = PokemonGenderRatios.objects.select_related('ratio').get(pokemon=self.id) File "/home/z/test_env/lib/python3.5/site-packages/django/db/models/query.py", line 403, in get self.model._meta.object_name pokedex.models.DoesNotExist: PokemonGenderRatios matching query does not exist. ---------------------------------------------------------------------- Which usually means that the database did not have a PokemonGenderRatios object in it, but I created it in the setUp function: def setUp(self): """ Set Up for testing """ self.pokemon = PokemonFactory(species__evolves_from_species=None) PokemonGenderRatioFactory( pokemon__species__evolves_from_species__evolves_from_species=None) Does anyone know why it is erroring out? I tried … -
Django template language to extract number from string
How to extract number from django string using django template language ? I've a variable like this {{ my_string }} here my_string is equal to something like "book123" and i only want 123 as output. Is there any way to this ? -
Nginx - 403 error only on static files
The project I'm using is written with Django 1.11. The stack is Ubuntu // Supervisor // Nginx <--> Gunicorn <--> Django There is the nginx file called /etc/nginx/sites-enabled/site.biz server { listen 80; listen [::]:80; access_log off; server_name site.biz; return 301 https://$server_name$request_uri; } server { listen 443 ssl; #listen 80 ssl; server_name site.biz; ssl_certificate /etc/letsencrypt/live/site.biz/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/site.biz/privkey.pem; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers HIGH:!aNULL:!MD5; #listen 80; gzip on; access_log /var/log/nginx-access.log; error_log /var/log/nginx-error.log; location /static/ { root /sitebiz/sitebiz; internal; } location /track { proxy_set_header X-Forward-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header GEOIP_COUNTRY_CODE $geoip_country_code; proxy_set_header GEOIP_COUNTRY_NAME $geoip_country_name; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://127.0.0.1:8899; break; } } location /income { proxy_set_header X-Forward-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header GEOIP_COUNTRY_CODE $geoip_country_code; proxy_set_header GEOIP_COUNTRY_NAME $geoip_country_name; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://127.0.0.1:8899; break; } } location / { proxy_set_header X-Forward-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header GEOIP_COUNTRY_CODE $geoip_country_code; proxy_set_header GEOIP_COUNTRY_NAME $geoip_country_name; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://127.0.0.1:8000; break; } } } I tried to change the /home/sitebiz/sitebiz/static/ directory and all of its content ownership to sitebiz user and to www-data , but none helped. Not even Django … -
Shortened link redirect
I'm making link shortener on django. I wonder how I can redirect shortened URL to it's original. For example I have a link 127.0.0.1:8000/ZY9J3y and I need it to transfer me to facebook.com. The question is what should I add in my url.py in order to redirect links like this to their original?? -
Django adding unwanted HTML Tags to template
Im busy doing multiple paginations on a single page, i have implemented my views and am calling a seperate template that im appending to the resource page using ajax in the main template. the ajax request is failing to append the html received from the view because(i think) django is adding a tags to the resources_cards.html template. below is my code and the response i receive. urls.py url( r'^more-use-cases/$', views.UseCasesListView.as_view( template_name='app/inclusion_tags/resource_cards.html', ), name='more-use-cases' ), views.py class DocumentsListView(generic_views.ListView): queryset = models.DocumentDetailPage.objects.live().order_by( '-first_published_at' ) paginate_by = 4 resource_cards.html {% load wagtailcore_tags wagtailimages_tags %} {% for item in object_list %} <li class="col-xs-12 col-sm-6 col-md-3"> <div class="media-card text-center"> {% image item.detail_image original %} <h5>{{ item.snippet }}</h5> <a href="{{ item.url }}">Read Article</a> </div> </li> {% endfor %} resources_page.html <ul id="document-list" class="row m-media-list-column"> {% for item in documents %} <li class="col-xs-12 col-sm-6 col-md-3"> <div class="media-card text-center"> {% image item.detail_image original %} <h5>{{ item.snippet }}</h5> <a href="{{ item.url }}">Read Article</a> </div> </li> {% endfor %} </ul> <a href="javascript:void(0)" data-page="2" id="next-documents" class="m-button m-button-havelock-blue">View More</a> resources_page.html ajax script <script type="text/javascript"> $("#next-documents").click(function() { var page = $(this).data("page") $.get("/more-documents/?page=" + page, function(data){ $("document-list").append(data); console.log("data", data) }); }); </script> Response <html><head></head><body><li class="col-xs-12 col-sm-6 col-md-3"><div class="media-card text-center"><img alt="cat.png" height="205" src="/media/images/cat.original.png" width="276"/><h5>Consequatur Distinctio Dolor … -
How to write a single view function to render multiple html from diferent urls path?
I am trying to avoid self coping of views functions but have no idea ho to do it. My views have a minor differences and there is definitely a way to render html pages with a single function in this case. I experimented with urls "name" value but failed. I just started with django and hope that experienced programers have a solution. Thank you for your help. urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('about/', views.about, name='about'), path('team/', views.team, name='team'), path('contacts/', views.contacts, name='contacts'), path('researches/', views.researches, name='researches'), path('publications/', views.publications, name='publications'), ] and views.py def index(request): return render(request, 'website/index.html') def about(request): return render(request, 'website/about.html') def team(request): return render(request, 'website/team.html') def publications(request): return render(request, 'website/publications.html') def researches(request): return render(request, 'website/researches.html') def contacts(request): return render(request, 'website/contacts.html') -
POST form data from third party website to Django
I’m hosting a Django website which stores information on users. However, i want to host forms on third party websites e.g. a newsletter signup. I'd like to be able to grab info from a queryset in the URL and post it back to my Django site. I have a small script which grabs the queryset info and places it into a hidden field on the form which then posts that data. However, this is currently done ON my site. If i were to host the form on someone else’s website, what would be the best way to go about it? Using Ajax? or just changing the action to the full URL of my Django website? Will i have any problems with cross site forgery etc? Ideally Ajax would be better as that way if the users clicks submit, the validation won’t refresh the page and lose the queryset in the URL. Any help would be appreciated :smile: -
Django add a variable value into {%static 'path' %}
In my django project i have to add a prefix into some path defined with %static like this: <link rel="stylesheet" href="{% static "css/animate.css" %}"> I have to add the {{ subpath }} value passed from my view, i try this: <link rel="stylesheet" href="{% static "{{ subpath }}/css/animate.css" %}"> but the variable was implemented like a text, also i tried: <link rel="stylesheet" href="{% static {{ subpath }}"/css/animate.css" %}"> but an error occurred. How can i add a variable value into my href correctly? Thanks in advance Luca