Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError at /account/register/
Can anyone help me figure this out? I keep getting a valueError saying my view isn't returning an HttpResponse! I'm not sure what could be causing the error. I checked my indentations, as well as all of my urls. I'm using the redirect(reverse()) function to call the url in my views. here's the traceback: Internal Server Error: /account/register/ Traceback (most recent call last): File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 198, in _get_response "returned None instead." % (callback.__module__, view_name) ValueError: The view accounts.views.register didn't return an HttpResponse object. It returned None instead. Here are my accounts/views.py from django.shortcuts import render, redirect from django.urls import reverse from accounts.forms import ( RegistrationForm, EditProfileForm ) from django.contrib.auth.models import User from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm from django.contrib.auth import update_session_auth_hash from django.contrib.auth.decorators import login_required def register(request): if request.method =='POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect(reverse('home:home')) else: form = RegistrationForm() args = {'form': form} return render(request, 'accounts/reg_form.html', args) def view_profile(request, pk=None): if pk: user = User.objects.get(pk=pk) else: user = request.user args = {'user': user} return render(request, 'accounts/profile.html', args) def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect(reverse('accounts:view_profile')) else: form = EditProfileForm(instance=request.user) args = … -
Testing that Django templates render correctly
I have an index.html that includes a nav.html which has a url tag that points to a rout name that doesn't exist. When I run the index view test the response code is 200 and the test passes. If I manage.py runserver and navigate to the index in my browser I get a NoReverseMatch error message page. When I remove the include from index.html and put the contents of nav.html directly into index.html the test fails as expected. How do I write a test that will catch the problem in the included template? nav.html {% url 'project:wrong_name' %} index.html {% include 'project/nav.html' %} views.py def index(request): return render(request, 'project/index.html') tests.py def test_index_view(client): response = client.get(reverse('project:index') assert response.status_code == 200 virtualenv (abbreviated): python==3.6.1 Django==1.11 pytest-django==3.1.2 -
Page not found (404) - Django
I have a strange behavior when I try to test my Django on the webpage. I see what is the error, but I have no clue from where it comes. What I try to do is : I have project called stockmarket I have application called stockanalysis the problem is : when I try to open 'domain/stockmarket I get this: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8888// When I try to open 'domain/stockmarket/stockanalysis' I get this: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8888//stockanalysis/ The issue is clear to me. In both cases I have two slashes (//) instead of one (/). The issue is - I do not know from where it comes. Any ideas? -
Three way modeling django
I want to model a schema for an award function in django. I have a User model, a show model and an award model. A user can get one award for a show. I can simply say User 'aaa' gets award 'bbb'. but then that award cannot be associated with other user for another show. I think there is three way modeling required for User, show and Award. Is there any sophisticated way of doing it? I know about 'through' but dont think this can be a good tool here. If it is could you please guide me how to? -
is it possible to call manage.py directly from windows cmd?
I need to run manage.py runcrons from windows cmd. So i created batch file cd c:\django\myenv\Scripts\activate myenv\Scripts\activate cd ghotel manage.py runcrons The problem is that after activation it starts python shell and batch file stops executing because he can execute in python shell and i cant run manage.py. Is there any workarounds ? -
Update non model field class variables i Django models
I have a django model which has a JSONField, it stores all the neccessary things. I have to use JSONField to collect data insted of normal fields. My model looks like this. class MyModel(models.Model): json_content = JSONField(default=dict) def __init__(self, *args, **kwargs): self.value1 = self.json_content self.value2 = self.json_content I want to have some class variables (value1, value2) , which I want to update during model initialisation. I will use this as : m = MyModel() m.value2 = 'some thing' But json_content is not taking JSONField data during initialisation. How to fix this. -
Django-- Get model fields in template only for current user
First of all, I know there are lot of questions about accessing model in template but let me explain why this is different. I want profile page where User can see their details. I am able to do that but with one little bug. If there are 3 Users(say A, B,C) and User A want to see his profile he sees it three time. Like this: How do I stop the loop after one iteration so that the User only get's his profile information once. This is my URL: url(r'^profile/$', views.IndexView.as_view(), name='profile'), Views.py: class IndexView(generic.ListView): template_name = 'profile.html' def get_queryset(self): return Profile.objects.all() and profile.html: {% if user.is_authenticated %} {% for profile in object_list %} <h1>{{ request.user }}'s Profile</h1> <table> <tr> <td>Username:</td> <td>{{ user.username }}</td> </tr> <tr> <td>First Name:</td> <td>{{ user.first_name }}</td> </tr> <tr> <td>Last Name:</td> <td>{{ user.last_name }}</td> </tr> <tr> <td>Email:</td> <td>{{ user.email }}</td> </tr> <tr> <td>Personal Info:</td> <td>{{ user.profile.personal_info }}</td> </tr> <tr> <td>Job Title:</td> <td>{{ user.profile.job_title }}</td> </tr> <tr> <td>Department:</td> <td>{{ user.profile.department }}</td> </tr> <tr> <td>Location:</td> <td>{{ user.profile.location }}</td> </tr> <tr> <td>Expertise:</td> <td>{{ user.profile.expertise }}</td> </tr> <tr> <td>Phone Number:</td> <td>{{ user.profile.phone_number }}</td> </tr> <tr> <td>Contact Skype:</td> <td>{{ user.contact_skype }}</td> </tr> <tr> <td>Contact Facebook:</td> <td>{{ user.contact_facebook }}</td> </tr> <tr> <td>Contact … -
Idiomatic way to use urlize filter with blocktrans in Django template
I recently discovered a neat trick to avoid polluting the gettext translation files for Django with unnecessary markup. If you want to make an email address clickable, you can use the urlize filter after the trans string argument, like this: {% trans "Contact us at foo@bar.com"|urlize %} Is there any way to apply the same trick to the result of a blocktrans tag? -
Django Authentication - Filter only user-created (not all) records in View
I am using Python 3.6 and Django 1.11 I have a working app (for learning purposes) that authenticates users, then allows the user to create "things" in a Django form, based on a model. In this case, users can "quit" something, like smoking or drinking, and specify their Quit Date, etc. The home page currently displays a list of all "things" created by ALL users. Anybody in the world can view these. What I'd like to do is limit this View so that 1) only authenticated users can view 'things' from the database, and 2) authenticated users can view ONLY their "things". How I imagine this would be accomplished is starting in the app/views.py file. Cuurently, the home page view (a list of all things) looks like this: def something_list(request): things = Thing.objects.filter(quit_date__lte=timezone.now()).order_by('quit_date') return render(request, 'quit/something_list.html', {'things': things}) This defines a View which orders by 'quit date', and sends it to my 'something list' template. By searching online, it seems possible to specify only seeing the user's data by adding a parameter to the Thing.objects.filter(). Everything I have tried thus far is causing errors, including this: things = Thing.objects.filter(owner=request.user).filter(...) and this things = Thing.objects.filter(owner=request.user, quit_date__lte=timezone.now()).order_by('quit_date') Here is my model, just … -
Getting data from form into Django not working
I'm trying to write a simple app that let users to login, in Django. I've downloaded a pretty bootstrap login template, but I can't hook it up to my Django project. When I click submit, nothing happens, Here's the code: HTML: https://gist.github.com/ma-sadeghi/031bfa10b28f4d34bdb55629e51d2a6e JS: https://gist.github.com/ma-sadeghi/c53c78875212984e27dec8fec2dbd7a3 Please see the comments for CSS/views.py/urls.py Thank you very much in advance! -
Python Django: how to override validation on MultipleChoiceField
I'm trying to save multiple checkbox selections on a Charfield, but I cannot bypass the message: Select a valid choice. ['...', '...', '...'] is not one of the available choices. I want to save the selected values with pipe separed values in a single attribute in the database. I have already created "clean" methods for the 2 MultipleChoiceFields, but still no success. Here is the code I'm using: estomatologia_form.py class EstomatologiaForm(forms.ModelForm): sinais_e_sintomas_locais = forms.MultipleChoiceField( choices=Estomatologia.TIPOS_SINAIS_E_SINTOMAS, widget=forms.CheckboxSelectMultiple(), label='Sinais e Sintomas locais (marque todas as opções válidas) *', ) ... def __init__(self, *args, **kwargs): if 'instance' in kwargs: if kwargs['instance'] is not None: kwargs['initial'] = {} ssl = kwargs['instance'].sinais_e_sintomas_locais.split('|') cp = kwargs['instance'].comorbidades_paciente.split('|') kwargs['initial']['sinais_e_sintomas_locais'] = ssl kwargs['initial']['comorbidades_paciente'] = cp super(EstomatologiaForm, self).__init__(*args, **kwargs) #OBS: campos para MultipleChoiceField não devem receber esses valores em 'class'. #Do contrario os checkbox não são desenhados corretamente for field_name in self.fields: if field_name != "sinais_e_sintomas_locais" and field_name != "comorbidades_paciente": self.fields[field_name].widget.attrs.update({ 'class': 'form-control form-dinamico', }) def clean_sinais_e_sintomas_locais(self): import ipdb ipdb.set_trace() ssl = self.cleaned_data['sinais_e_sintomas_locais'] self.cleaned_data['sinais_e_sintomas_locais'] = '|'.join(ssl) return self.cleaned_data['sinais_e_sintomas_locais'] def clean_comorbidades_paciente(self): import ipdb ipdb.set_trace() cp = self.cleaned_data['comorbidades_paciente'] self.cleaned_data['comorbidades_paciente'] = '|'.join(cp) return self.cleaned_data['comorbidades_paciente'] def save(self, *args, **kwargs): import ipdb ipdb.set_trace() instance = super(EstomatologiaForm, self).save(*args, **kwargs) instance.sinais_e_sintomas_locais = self.cleaned_data['sinais_e_sintomas_locais'] instance.comorbidades_paciente = self.cleaned_data['comorbidades_paciente'] instance.save() … -
How to integrate django-toolbar to django-rest-swagger?
Can you help me please? how to integrate django-toolbar to django-rest-swagger from django-rest-framework? -
Django: Preventing automatic deletion of model data after each test
I've simplified my code to show the effect here. class AccountTests(APITestCase): def test_post_account(self): """ Ensure we can create a new account object """ # code that adds one user object and one signup confirmation object ... ... # test we have one user and one confirmation code # THIS PASSES OK. self.assertEqual(User.objects.count(), 1) self.assertEqual(SignupConfirmationCode.objects.count(), ) def test_post_confirmation_code(self): """ test sending confirmation code for an account just created """ # THIS FAILS self.assertEqual(User.objects.count(), 1) self.assertEqual(SignupConfirmationCode.objects.count(), 1) I know test_post_account is running first and passes OK. test_post_confirmation_code is running second and asserts on account of the User and SignupConfirmataionCode "magically" losing their content between the two test methods. How do I prevent the disappearance of data between the time the first test ends and the second begins? -
Django ORM object sequence when using a list as filter condition
Does Django ORM guarentee the filter sequence when we use a list as filter condition? result = Model.objects.filter(id__in=id_list, user__id=user.id) The id_list is like: [1, 2, 3, 4, 5] Does the result always keep the sequence followed by id_list? Where is the Django Document mention about this? Thank you! -
how to execute python scripts from browser
i have several python scripts that plot maps based on some data stored in a postgresql database ( i use matplotlib for this), i need to execute these scripts from a web browser, knowing that the user should have the ability to visualize the result he needs ( i mean the map) according to the conditions he specifies, for example in the web page there have to be a form that specifies the date, the zone... of data , there have to be interactions with the database. so is it possible ? how can i proceed ? shall i use a framework like django ? any ideas ? -
The path is variable
In a team project, we have the following method : @property def signature_url(self): #Be aware that the question of relative and absolute path #is quite important here (i.e. file://) absolute_path = '/home/jeremie/Projects/24-django' return absolute_path + self.contract_signature.url Locally, this method worked pretty well for me. The problem is located when someone else of me want to test out signature_url(). In fact Project/24-django is common to anyone in the project. The problem is located with /home/jeremie/. I could use successfully that method, but if George want to use it from his computer, it will certainly failed, because the path should be /home/jeremie/Projects/24-django. How could I fix the method signature_url()? -
How to retrieve objects simultaneously from database?
I'm building a social analytics website with Django. Here is one of my use cases: "Users" of the site analyze social media "profiles" (from Snapchat, Instagram, Twitter, etc...). Each social media "profile" is only analyzed once (and not more). I have an SQL query that retrieves profiles in a queue. For instance, the first 5 profiles that are returned (when I repeat this query 5 times) are: xmax123, darcy67, shop_hallmary10, christmas_shop987, lilybend_09 After the user analyzes the profile xmax123, xmax123 will no longer appear for other users to analyze. My problem is when multiple users call this SQL query concurrently, the same social media profile (xmax123) is returned for all users. In other words, when two users (user 1 and user 2) call this SQL query at the same time, the same social media profile (xmax123) is returned for both of them. This means that xmas123 will be analyzed twice by 2 different users, which is a problem. I want to ensure that user 1 gets xmax123 and user 2 gets darcy67, even when both users call this SQL query concurrently. What are some strategies to handle this problem? -
Modify authentication in Django REST with ouath2
I'm using Django REST with Ouath2 (Django OAuth Toolkit). I need to modify the way users authenticate, basically I need to allow authentication to users only if they belong to a certain group. I know how to create and use permissions classes in the views of Django REST. I tried (for testing purposes) to set: 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAdminUser', ) but the user can login without being staff. I looked all the way from my endpoint: url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')) to oauth2_provider\urls.py file: url(r'^token/$', views.TokenView.as_view(), name="token"), and finally to oauth2_provider\views\base.py class TokenView(CsrfExemptMixin, OAuthLibMixin, View): ... problem is that this class is outside of the project, so I shouldn't modify it Is there any way to do this? -
celery - will --max-memory-per-child restart workers instantly or allow them to finish the task?
Once a worker process crosses the --max-memory-per-child limit, does it get killed and restarted instantly? or does celery allow it to finish the current task (even if it has to consume some more memory while finishing) and then restart it? -
is it possible to access already running virtualenv in windows
is it possible to access already running virtualenv in windows by external tools ? I need this to run cron like tasks by executing python manage.py dosometing of running instance of django. For this I thought I would setup windows task that will execute something like cmd.exe C:\django\manage.py dosometing but I dont understand how to do this if django is running inside virtualenv -
Django + Django REST Framework + PostgreSQL queries and serialization is very slow - yet not a "N+1" case
I like Django + DRF combination and I have used them for a long time, but this problem has bugged me for a while. The problem is that queries + serialization take lots of time when there are ManyToMany or OneToMany relations and nested objects. There are plenty of similar questions in StackOverflow and usually the problem has been some form of "N + 1" problem (or not solved). e.g. Django REST Framework Serialize extremely slow Badly affecting performance in populating ManyToMany field values in rest api (using django rest framework) Django REST framework is slow Also, suggestion to not load that many objects at once.. probably applies here, though I need all items at once. How to optimize the django rest serializer with method field? Handling queries is a big part of the problem in this case also, but there are not too many queries and queries themselves are fast. I'm using prefetch_related to limit number of queries and what I'm seeing from DB queries everything is looking Okay..ish (?). I get one query for each prefetch_related property + the original query for serialized objects. There are lots and lots of IDs included in prefetch_related queries, but I guess … -
Replace list value 'None' with zero in python
I have a list like this: a_list = [['a', 1], ['b', 4], ['c', None]] I need to replace all 'None' value with '0' and replace any value not in None to 'None'. So above list will become: modified_a_list = [['a', None], ['b', None], ['c', 0]] I have code like this: a_list = [['a', 1], ['b', 4], ['c', None]] b_list = a_list modified_a_list = [] for item in b_list: if item[1]==None: item[1]=0 modified_a_list.append(item) else: item[1] = 0 modified_a_list.append(item) print a_list, modified_a_list My output becomes: a_list = [['a', None], ['b', None], ['c', 0]] modified_a_list = [['a', None], ['b', None], ['c', 0]] modified_a_list looks OK. But why a_list is changed as well? -
Python Social Auth for Django raises Authforbidden exception
I am stuck with for the past 2 days unable to find a solution. I am using Django 1.10 with python 2.7 and social-auth-app-django (1.2.0). It is part of the Python Social Auth library. I wish to restrict login to only the domain ID of my company I've therefore used this setting from the library. SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS=['mycompany.in'] Now if you try to login with any other domain as expected it throws an error. My goal is to catch this exception and show a custom page to the user. But for the life of me I am unable to do so. If I set Debug to False it redirects the user to my LOGIN_ERROR_URL='/' page but am unable to pass my custom message to the user This is part of my setting.py DEBUG = False 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', 'social_django.middleware.SocialAuthExceptionMiddleware', ] #social auth SOCIAL_AUTH_GOOGLE_OAUTH2_KEY= "9******6.apps.googleusercontent.com" SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET="W*****x" SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS=['mycompany.in'] LOGIN_URL = 'login' LOGIN_REDIRECT_URL = 'upload_file' LOGOUT_URL = 'logout' LOGIN_ERROR_URL='logout In my view I've this code to handle the exception from social_django.middleware import SocialAuthExceptionMiddleware from social_core.exceptions import AuthForbidden class SocialAuthExceptionMiddleware(SocialAuthExceptionMiddleware): def process_exception(self, request, exception): print "exception occured" if hasattr(social_exceptions, 'AuthForbidden'): print "hello two" return HttpResponse("I'm a exception %s" % … -
Avoid going to the database for every for loop iteration
I want to export data to Excel file in Django. First I get all members: members_list = Member.objects\ .exclude(deleted=True) \ .annotate(num_calculations=Count('user__calculations'))\ .order_by("-user__date_joined") then I loop through members and add them to an excel file: for row in members_list: row_num += 1 ws.write(row_num, 0, row.number or "", font_style) ws.write(row_num, 1, row.user.first_name or "", font_style) ws.write(row_num, 2, row.user.last_name or "", font_style) ws.write(row_num, 3, row.address or "", font_style) col_num = 3 for calculation in calculations_per_month_last_12_months(row.number): col_num += 1 ws.write(row_num, col_num, calculation['total_calculations'] or "", font_style) The function calculations_per_month_last_12_months is as follows: items = list(Calculations.objects .filter(user__member__number=member_number) .filter(price_date__gte=datetime.datetime.now().today() - relativedelta(months=12)) .annotate(date=TruncMonth('price_date')) .values('date') .annotate(total=Count('id')) .values('date', 'total') .order_by('date')) result = [] for month in range(12): date = timezone.now() - relativedelta(months=month) month_results = list(filter(lambda i: date <= i['date'] + relativedelta(months=1) < (date + relativedelta(months=1)), items)) month_result = 0 if month_results: month_result = month_results[0]['total'] result.append({ 'total_calculations': month_result }) return result Everything works fine, but the problem is if I have a large number of members. The calculations_per_month_last_12_months function goes to the database for every member. That is what I don't want. If I have for example 5000 members, then it will go 5000 times to the database. Any advice how could I avoid it? -
Django:1045, "Access denied for user
I have already read a lot of stack overflow questions for two days, but I can't figure it out the problem(I am using Mac). I did : mysql -u root -p. so it asked for the password, and root password is blank, no just an enter get me into mysql monitor and I received the message: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is xxx Server version: 5.7.18 Homebrew then: mysql> CREATE DATABASE concon CHARACTER SET utf8;. so: mysql>CREATE USER 'concon'@'localhost' IDENTIFIED BY 'thepassword';. finally: mysql> GRANT ALL ON concon.* TO 'concon'@'localhost'. So I exit mysql and run sudo python manage.py runserver the problem is I receive: django.db.utils.OperationalError: (1045, "Access denied for user 'concon'@'localhost' (using password: YES)") my dataBase is(in settings.py): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'concon', 'USER': 'concon', 'PASSWORD': 'thepassword', 'HOST': 'localhost', 'PORT': '', } }