Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django==2.1.4 - Blog
Wish happy new 2019 I am doing django project 2.1.4 and getting the below errors, i searched and it seems that i fix errors one by one , but i managed to solve some. However these i could find any clue. Error after runserver or migrate. (myenv) C:\Users\Users\Desktop\blog_project\mysite>python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001EC9271A0D0> Traceback (most recent call last): File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\core\management\commands\runserv er.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 3 79, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 3 66, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\core\checks\registry.py", line 7 1, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\core\checks\urls.py", line 13, i n check_url_config return check_resolver(resolver) File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\core\checks\urls.py", line 23, i n check_resolver return check_method() File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\urls\resolvers.py", line 396, in check for pattern in self.url_patterns: File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\utils\functional.py", line 37, i n __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\urls\resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\utils\functional.py", line 37, i n __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\urls\resolvers.py", line 526, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Users\Anaconda3\envs\myenv\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File … -
Make a view and template for showing sorted information from several models in Django
I have one model for registering projects, where the user input som data about the project. Another model is for time registered when working with the project, and one last model for type of activity when working on the project. There are two forms used, one for the project information and one for both time and type of activity. When registering time, the user also has to choose from the list of project to connect it to that project. The user is registering several times on each project, and With several types of activities. How can I make a view and a template that can show this information grouped on project and summed for each activity? -
rest_framework.authtoken refresh on change password
I have successfully(hopefully) managed to implement a change_password action. However, after I change the password, the client automatically logsout. (token is probably not valid anymore) I would like the API Client to remain logged in after a password reset to make other requests with the new token. Is there an equivalent for update_session_auth_hash(request, self.object) ? Serializers: class PasswordSerializer(serializers.Serializer): """ Serializer for password change endpoint. """ old_password = serializers.CharField(required=True) new_password = serializers.CharField(required=True) API View @action(methods=['put'], detail=True) def change_password(self, request, pk): serializer = PasswordSerializer(data=request.data) if serializer.is_valid(): user = get_object_or_404(User, pk=pk) if user != request.user: return Response({'error': "Cannot change other user's password"}, status=status.HTTP_403_FORBIDDEN) else: if not user.check_password(serializer.data.get('old_password')): return Response({'old_password': ['Wrong password.']}, status=status.HTTP_400_BAD_REQUEST) user.set_password(request.POST.get('new_password')) user.save() else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({'details': 'Success'}, status=status.HTTP_200_OK) -
Redefine class method for entire project
I have a class in my Django project that I want to redefine, without touching the delivered code. The class is this (example): class DjangoAdminClass: def method_a(self, parm1, parm2): pass So I want to redefine the method_a for the entire project. How could I do that? I thought to create a new class: class DjangoAdminClass(DjangoAdminClass): def method_a(self, parm1, parm2): do_a_cool_stuff But it didnt work.... my method is not called by the code that is using DjangoAdminClass -
Query which orders users by last message sent in Django Private Chat
I want to create a queryset which retrieve users efficiently ordered by the create date of the last Message they sent OR received (like most of the chat interfaces do). I am using Django Private Chat, which uses this simple model for messages. I simply don't know how writing the order_by statement considering the previous model. Maybe annotate, Subquery or other query expressions would be convenient in this case. users = User.objects.filter(username__icontains=user, id__in=request.user.followers).order_by( ????? ) -
Django model - Foreign Key / Float pair
Is there any way to have a foreign key/float pair in a model? I have an Item model and an Enemy model currently, and would like to add a field to the Enemy that is essentially a chance of getting an item from defeating it. I would like to be able to define, for example, a 10% chance to get Item A and a 1% chance to get Item B when you defeat an Enemy. -
Can't access current CustomUser in Django View but works in Template
I'm building a project in Django starting with DjangoX and am simply trying to get the currently logged in username or userid. I've tried all kinds of combinations and approaches, some of them I've left in comments, based on other on-line questions and answers and not getting this to work. views.py: from django.views.generic import TemplateView, CreateView from requests import request # <-- tried this, didn't help got AttributeError no 'user' from django.contrib.auth import get_user_model from django.conf import settings class HomePageView(TemplateView): # get user model and current user information umodel = get_user_model() # current_user = request.user # produces NameError: name 'request' is not defined # u = user # get error that user is not defined # u = umodel.id # <django.db.models.query_utils.DeferredAttribute...blah blah blah> template_name = 'pages/home.html' ... in my .html file, I can use this to display exactly what I'm trying to access in my View! home.html (this works) <p>user = {{ user }}</p> <p>user.id = {{ user.id }}</p> urls.py ... urlpatterns = [ path('', IndexPageView.as_view(), name='index'), path('home/', HomePageView.as_view(), name='home'), ... -
Cannot access reverse relationship in Django OneToOneField Models
I am trying to extend the user model by following the instructions here and here. I am having a model named Profile like this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.TextField(max_length=30) last_name = models.CharField(max_length=30) email = models.CharField(max_length=300) country = models.CharField(max_length=30) city = models.CharField(max_length=30) organization = models.CharField(max_length=30) I would expect to be able to access the model like: >>>> user = User.objects.get(pk=23) >>>> user.profile Instead I am getting the error described here(a bit long to paste): https://pastebin.com/NRQVM0NK Do you have any hints to unstuck me? Thanks a lot -
Migrating from Laravel/Php to Python/Django
I'm using currently laravel with vuejs components and want to migrate my project to Django. Two reasons why I want to switch: 1) I want to learn more about python. 2) I want the website to be easily convertible into a mobile app. So is it a good idea to switch? What's the best way to work with django and vue so that I can convert it then into a mobile app? -
Can't iterate and create a list from Django filter Query
In my project I have a Transaction model with a one to many relationship with the Coin model. Each transaction has a buy_price and unit_number (number of units). With the nested for loop in views.py below I am expecting to generate a list of multiple buy_prices within each coin dictionary. The query on it's own (with the coin name hardcoded) outputs the multiple buy_prices data I am expecting - which is indeed what is in the database. But once I put all the code together, all I am ever getting is just one buy_price for each coin with - print(coin_list) What am I doing wrong? views.py: from django.shortcuts import render import requests from .models import Coin, Transaction from decimal import Decimal def index(request): coin_list = [] coins = Coin.objects.all() url = 'https://api.coingecko.com/api/v3/coins/{}?localization=false&tickers=false&market_data=true&community_data=false&developer_data=false&sparkline=false' for coin in coins: db_coin_name = coin.name coin_data = requests.get(url.format(db_coin_name)).json() api_current_price = Decimal(coin_data['market_data']['current_price']['eur']) coin_dict = { 'official_name': coin_data['name'], 'symbol': coin_data['symbol'], 'image': coin_data['image']['large'], } transactions = Transaction.objects.filter(coin__name=f"{db_coin_name}") for t in transactions: buy_prices = [] buy_prices.append(t.buy_price) print(buy_prices) coin_dict['transactions'] = { 'buy_prices': buy_prices } coin_list.append(coin_dict) print(coin_list) context = {'data': coin_list} return render(request, 'cryptodashboard/index.html', context) Terminal output from print(buy_prices) - the first two belong to zcash and the second two belong to … -
Reverse for 'details' with arguments '('',)' not found. 2 pattern(s) tried:
Help, i am seeing the error above and i have tried many edits to no avail. #template <header class="w3-container w3-blue"> <h1><a href="{% url 'details' Jeans.pk %}">{{Jeans.Title}}</h1> </header> #my urls re_path('<Jeans_pk>/d+', views.detail.as_view(), name='details'), #my views.py class detail(DetailView): model = Jeans template= 'details.html' def TestimonyDetailView(request, Jeans_pk): Jeans = get_object_or_404(Testimony, pk=Jeans_pk) return render(request, self.template, context={'Testimony': Testimony}) -
Slow Django Admin change view
I've a model with approximately 150K rows. It takes 1.3s to render the ListView for this model. When I click the change link in the ListView I takes almost 2 minutes to render the change view. Other models have normal render times for the edit view. Any ideas how to speed this up? -
How to revoke refresh token on password reset?
I am using django-rest-framework-simplejwt to get access token and refresh token . The problem is that refresh token is not becoming invalid if I change the password of the user. Basically I can continue to send refresh token and get new access tokens even after user has changed password. What I would like instead is to ask user to re-submit the username and new password to get a new pair of access and refresh tokens. How would I accomplish this? PS: Just because I am curious, shouldn't this be the default behaviour of the library? In what case would we want to retain the refresh token after credentials have changed? -
How to disable fields validation if we want to go to the previous step?
I am using the django's form wizard in the authentication system. I have 2 form wizards steps. In the second, I have two buttons: the Prev Step button and the Submit button. When the Prev Step button is used to go backwards, I get the django's warning to fill out the field. How do I disable validations for the Prev Step button and keep the validations for the Submit button? I already disabled the javascript validations for the Prev Step button. My html: <!-- Forms --> {{ wizard.management_form }} {% for field in wizard.form %} <div class="wrap-input100 rs1-wrap-input100 validate-input m-b-20"> {{ field }} <span class="focus-input100"></span> </div> {% endfor %} <!-- Buttons --> {% if wizard.steps.next %} <div class="container-login100-form-btn"> <button type="submit" value="{{ wizard.steps.next }}" class="login100-form-btn">Next step</button> </div> {% else %} <div class="container-login100-form-btn"> <div class="split-left"> <button type="submit" value="{{ wizard.steps.prev }}" class="login100-form-btn" formnovalidate>Prev step</button> </div> <div class="split-right"> <button type="submit" class="login100-form-btn">Sign up</button> </div> </div> {% endif %} views: class signup(SessionWizardView): template_name='accounts/signup.html' form_list = [UserCreationForm_1, UserCreationForm_2] def done(self, form_list, **kwargs): form_step = [form for form in form_list] # step 1: ModelForm user = form_step[0].save() auth_login( self.request, user ) # step 2: Form user = form_step[1].save() return redirect( 'home' ) forms: class UserCreationForm_1(forms.ModelForm): password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'input100', … -
Django Users Management (login as another user)
I have website on Django 1.8 and Python 2.7 but i can't impossible to add manage users for login as another user. I tryed other libary's but it's cannot compotible with my versions. Maybe you have a working solution.... -
I can not customize error field by field using bootstrap
I'm setting up this form, and I do not want to simply use {{forms}}, since I'm using fields with measures of various sizes, I wanted the error leaving marked in red or success in green to be done in each field separately, but not I am getting it <div class="form-row"> <div class="form-group col-md-6"> {{ form.nome | bootstrap }} </div> <div class="form-group col-md-6"> {{ form.sobrenome | bootstrap}} </div> </div> <div class="form-row"> <div class="form-group col-md-6"> {{ form.email | bootstrap}} </div> <div class="form-group col-md-6"> {{ form.email | bootstrap}} </div> </div> <div class="form-row"> <div class="form-group col-md-6"> {{ form.cpf | bootstrap}} </div> <div class="form-group col-md-6"> {{ form.telefone | bootstrap}} </div> </div> -
Editing dictionary in population function to auto populate views, likes
Working on Tango with Django, exercises at the end of Chapter 5 (database). Using Django 2.1 and Python 3.7. Goal is to change a population script so that "likes" and "views" are added attributes of "categories." Changed my models already, that is working fine (can see zero likes and views in admin, first link to code works). Original code, works: https://pastebin.com/Q09XJtvX cats = {"Python": {"pages": python_pages}, "Django": {"pages": django_pages}, "Other Frameworks": {"pages": other_pages} } and def add_cat(name, views=0, likes=0): c = Category.objects.get_or_create(name=name)[0] c.views=views c.likes=likes c.save() return c Code as modified (lines 42-51 and 74 modified), not working: https://pastebin.com/gqsAd8iS cats = { {"Python": {"pages": python_pages}, "views":128, "likes":64}, {"Django": {"pages": django_pages}, "views":64, "likes":32}, {"Other Frameworks": {"pages": other_pages}, "views":32, "likes":16} } and def add_cat(name, views, likes): c = Category.objects.get_or_create(name=name)[0] c.views=views c.likes=likes c.save() return c If I keep curly brackets around the categories, I get the error "unhashable type: dict." If I change them to square brackets, I get the error "list" object has no attribute "items" Someone else, in a previous version of Django seemed to just manually create each entry (i.e., similar question but not the answer I am seeking here: Python/Django TangoWithDjango Models and Databases). To me, there should be a … -
Django forms and browser back button
Unable to go back to the form page after form submission using browser back button. hi all!!, i have a products page. which contains three products. /all_products/ <a href=“/product1”> product1 </a> <a href=“/product2”> product2 </a> <a href=“/product3” > product3 </a> once i click on on of the buttons, product1 in this case, I’m taken to the product details page, where i am able to submit product to the shopping cart. /product1/ <form action=“/shopping-cart/“ method="GET"> <input type="submit" name=“product1” value=“product1”> </form> in the case of the above example. after the form submission product1 is added to the cart and am redirected to the same product page, in this case /product1/ . now, if i push back button on my Browser I’m not taken back to the /all_products/ page . instead, first browser back button push takes me back to the /product1/ page. second browser back button takes me back to the /all_products/ page. example Django view def shopping-cart(request): return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) my question is: is it possible to implement browser back button functionality that takes you back to the /all_products/ page after form submission with single back button push only in django, without using javascript ? -
{% for blog in blogs.all %} is printed on html page
enter image description here This is my part of code when i run it I m getting {% for blog in blogs.all %} printed on html page what should i do? Atleast tell what should i do to prevent it from displaying on html pageenter image description here I tried Writing the entire code again and seeing if those are in h tags but nothing could solve it -
Function based views specifically for ajax calls
I've setup a number of function based views that are ONLY called by ajax calls. These ajax calls only pass a portion of the form data into the view. I've got a couple of questions regarding this. 1) I implemented an 'if form.is_valid()' after checking to see if request.is_ajax(). if request.is_ajax(): if form.is_valid(): all of my code in this Function Base View The including of the form.is_valid() conditional prevented my code from running. How important is checking if the form is valid? Can this validation be done when I'm only passing some form fields into the view? 2) My ajax call is a POST call. How important is it to put if request.METHOD == 'POST' above my code in the function based view? I believe that the call will always be POST, so is there a reason to check for it? Does not checking for it represent a security concern? Thanks! -
Django RestFramework - NOT NULL constraint failed
My Model: class Wishlist(models.Model): home = models.ForeignKey(Home, on_delete=models.CASCADE, null=False, blank=False) user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) def __str__(self): return "{} - {}".format(self.user.username, self.home.address) class Meta: ordering = ('user',) My serializer class WishlistSerializer(serializers.ModelSerializer): home = serializers.RelatedField(required=True, queryset=home_models.Home.objects.all()) user = serializers.RelatedField(required=True, queryset=User.objects.all()) class Meta: model = Wishlist fields = ('id', 'user', 'home',) My View class WishlistAdd(CreateAPIView): """ Add a new Home in User wishlist """ serializer_class = serializers.UserWishlistSerializer queryset = Wishlist.objects.all() When I try to do a POST request to create the new record I receive the following error: IntegrityError at /user/wishlist/ NOT NULL constraint failed: user_wishlist.home_id All of these happens after a git merge, but i don't notice any differences between the branches -
Using select widget in Django to get data from Postgres database
I am very new to Django, to Stackoverflow and to coding in general, so I'd appreciate any help. I am trying to add a form to my website, which would have only select fields. After a user selects all options, I want to redirect them to another page, where I return different information in several tables from my database, based on all selects (all selected options together influence information shown in the tables). I know this example is awkward, this is all made up just to give an idea of what I want to achieve in the end. An example: First page has 3 options: book genre city age Redirected page has three tables: Most read books in this genre in this city by people around this age List of libraries in this city, sorted based on how many books in this genre are there How to sign up to top 3 libraries A user does not modify the database in any way, so I suppose the form can have GET method. So my question is what would be the best way to get values from the user and get a unique value based on that from the database? I … -
CSFR error on signup page,even on successful
I have the following files: #views.py from django.views.generic.edit import FormView from django.views.generic.base import TemplateView from braces.views import AnonymousRequiredMixin, CsrfExemptMixin #exempting from Csfr as the worst it can do is making lots of new users class LogonView(CsrfExemptMixin, AnonymousRequiredMixin, FormView): "the page to create a new user" from .forms import LogonForm as form_class template_name = "registration/logon.html" from django.urls import reverse_lazy authenticated_redirect_url = reverse_lazy("success") success_url = authenticated_redirect_url def form_valid(self, form): u = form.save(commit=False) u.set_password(form.cleaned_data["password"]) u.save() from django.contrib.auth import login login(self.request, u) return super().form_valid(form) class SuccessView(TemplateView): template_name = "registration/success.html" #forms.py from django import forms as f class LogonForm(f.ModelForm): "The form to create a new user" # repeat the password form password2 = f.CharField( label="Please repeat your password", widget=f.PasswordInput, ) class Meta: from django.contrib.auth.models import User as model fields = ("username", "email", "first_name", "last_name", "password") widgets = {"password": f.PasswordInput, } def clean(self): c = super().clean() pwd = c.get("password") if pwd and pwd == c.get("password2"): return c raise f.ValidationError( "You need to repeat the passwords identically") #urls.py from django.urls import path, include from .views import * urlpatterns = [ path('', include('django.contrib.auth.urls')), path("logon/", LogonView.as_view(), name="logon"), path("success/",SuccessView.as_view(),name="success") ] When I try to access /logon and fill the resulting form,it gives me a 403 CSFR error. The weird thing … -
django admin/xadmin how to create popup windows?
I want to make a popup window to choose some options, but how to do... This problem has been bothering me for a long time. I have not found any useful information or examples on the Internet. -
Catch exception when adding to manytomany field in django
So I am adding a list of items to my manytomany field. If item1 already exists in myModelInstance.myM2MField, it does not add it again. myItems = [item1, item2] try: myModelInstance.myM2MField.add(*myItems) except Exception as e: return e I would like to catch the list of items which were not added and return it. Is that possible?