Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Multiple database for read and write independent of app
How can we work with multiple databases on Django, under some specific conditions such as, 1. One DB for write purpose only ( db_for_write.sqlite3) 2. Two other DB for reading purposes (read_replica_1.sqlite3 ,read_replica_2.sqlite3) 3. All these 3 DB should be synchronized all the time (3 DB should contain same data all the time) 4. All the actions such as CRUD , migration etc are independent of app or model this is my Db_Router.py import random class ExampleDatabaseRouter(object): def db_for_read(self, model, **hints): db_list = ('db_for_read_1', 'db_for_read_2') return random.choice(db_list) def db_for_write(self, model, **hints): return 'db_for_write_only' def allow_relation(self, obj1, obj2, **hints): # I couldn't understand what would do this method return def allow_migrate(self, db, app_label, model_name=None, **hints): # sync all DB return Unfortunately, I couldn't understand the purpose of allow_relation() method. I hope someone could help me. -
In django, after a login how can I detect which auth backend authenticated the user?
I'm trying to distinguish between a couple of Django authentication backends (which are external packages and I preferably don't want to modify them) in my views. django.contrib.auth docs says auth backend will be tried in order and the first that does authenticate, will return and if any raises an exception, authentication is refused. But it does not say how can I distinguish between requests depending on which backend authenticated the user. Is this possible? and how? -
django how to load custom filters to xml files
I want to load a Django custom filter to my sitemap.xml to change the value of certain variables. However, I noticed that I can't have the {% load %} tag in front of the line. How do I handle this situation then? -
Django ConnectionAbortedError + TypeError + AttributeError
I am using Python 3.6.0 + django 1.11 + windows 7 64 bit my website is running fine but I am keep getting this errors. ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine TypeError: 'NoneType' object is not subscriptable AttributeError: 'NoneType' object has no attribute 'split' Why i am getting this ..? and how to fix these errors ? Traceback (most recent call last): File "C:\Python36\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Python36\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Python36\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Python36\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Python36\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "C:\Python36\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\Python36\lib\socketserver.py", line 775, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine [18/Sep/2017 12:25:10] "GET /api/dashboard/workorder_list/6/?format=json&_=1505708684218 HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 32251) Traceback (most recent call last): File "C:\Python36\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Python36\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Python36\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Python36\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Python36\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') … -
DRF Search on ArrayField
models.py from django.contrib.postgres.fields import ArrayField from django.db import models from djchoices import DjangoChoices, ChoiceItem class Customer(models.Model): ... phones = ArrayField(models.CharField(max_length=30)) filters.py import django_filters from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import FilterSet from rest_framework.viewsets import ModelViewSet from soken_web.apps.customers.api.serializers import CustomerSerializer from soken_web.apps.customers.models import Customer class CharInFilter(django_filters.BaseInFilter, django_filters.CharFilter): pass class CustomerFilter(FilterSet): phones = CharInFilter(name='phones', lookup_expr='contains') class Meta: model = Customer fields = ( ..., 'phones', ) class CustomerViewset(ModelViewSet): queryset = Customer.objects.all() serializer_class = CustomerSerializer filter_backends = (DjangoFilterBackend,) filter_class = CustomerFilter filter_fields = ( ... 'phones', ) References: https://groups.google.com/forum/#!topic/django-filter/ns7zx1C8HN8 AS IS: I have to search the exact match phone number of that customer. For example customer.phones = ['024382426', '024387269'] I have to filter with 024382426 to get that customers. Question: How to do put the phone number in short like 438 and get that customer? -
Sorry, but we’re having trouble signing you in. We received a bad request. (AADSTS50011: The reply address)
I'm building a django web app that allows users to sign in using their Office 365 account through allauth. However when I try to login I get the error "Sorry, but we’re having trouble signing you in. We received a bad request. Additional technical information: Correlation ID: [correlation-id] Timestamp: 2017-09-18 03:19:43Z AADSTS50011: The reply address 'https://localhost:8000/accounts/office365/login/callback/' does not match the reply addresses configured for the application: '[app_id]'. More details: not specified" However I did put the redirect URL in - see image. image link Not sure where my configuration error is. Thanks for your help -
foreign key serialization in python
I have appropriate models. App work on MacOS, but on linux I have mistake 'NoneType' object has no attribute 'id' When I add task from admin I get mistake like (1366, "Incorrect string value: '\xD0\xBE\xD1\x80\xD0\xBF...' for column 'title' at row 1") from rest_framework import serializers from users.models import User from task.models import Task class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name', 'user_type', 'balance') class TaskSerializer(serializers.ModelSerializer): assignee = serializers.SerializerMethodField() created_by = serializers.SerializerMethodField() class Meta: model = Task fields = ('id', 'title', 'description', 'money', 'assignee', 'created_by') def get_assignee(self, obj): return { 'id': obj.assignee.id, 'username': obj.assignee.username, 'first_name': obj.assignee.first_name, 'last_name': obj.assignee.last_name, 'user_type': obj.assignee.user_type, 'balance': obj.assignee.balance } def get_created_by(self, obj): return { 'id': obj.created_by.id, 'username': obj.created_by.username, 'first_name': obj.created_by.first_name, 'last_name': obj.created_by.last_name, 'user_type': obj.created_by.user_type, 'balance': obj.created_by.balance, } -
How can I convert the query_set list to a list that contains the dictionary?
As all we know, we can use the model_to_dict convert the query_set to a dictionary. from django.forms.models import model_to_dict u = User.objects.get(id=1) u_dict = model_to_dict(u) type(u) <class 'django.contrib.auth.models.User'> type(u_dict) <type 'dict'> But, I want to convert the query_set to a list that contains the dictionary. uers = User.objects.all() # there I will write a forloop to convert the query_set to convert to dictionary. then append to a list. So, whether there is a convenient way to convert the query_set list to my requirement? -
How to effectively query "any" in Django?
For example, the query is: a = request.GET['country'] b = request.GET['name'] c = request.GET['title'] ... result = models.Data.objects.filter('country' = a, 'name' = b, 'title' = c, ...) What should I do if one of these a b c is "Any"? I mean if I receive from the frontend, a="Any", how should I effectively free this limit in filter? -
Python Null Byte error
I am encountering an incredibly headaching error. I am not quite sure what I did but it has made it impossible to work on my Django project. I cannot runserver, makemigrations, or anything that has to do with my manage.py file. I always get a Null Byte error. When I try to runserver: C:\Users\Broja\Desktop\mynewenv\computersite>manage.py runserver Traceback (most recent call last): File "C:\Users\Broja\Desktop\mynewenv\computersite\manage.py", line 8, in <module> from django.core.management import execute_from_command_line File "C:\Users\Broja\AppData\Local\Programs\Python\Python35\lib\site- packages\django\__init__.py", line 3, in <module> from django.utils.version import get_version ValueError: source code string cannot contain null bytes So I attempted to uninstall Django in order to reset the framework, but when I input pip uninstall django In the command prompt, I get: C:\Users\Broja\Desktop\SportsReportingEnv\computersite>pip uninstall django Exception: Traceback (most recent call last): File "c:\users\broja\appdata\local\programs\python\python35\lib\site- packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\users\broja\appdata\local\programs\python\python35\lib\site- packages\pip\commands\uninstall.py", line 76, in run requirement_set.uninstall(auto_confirm=options.yes) File "c:\users\broja\appdata\local\programs\python\python35\lib\site- packages\pip\req\req_set.py", line 346, in uninstall req.uninstall(auto_confirm=auto_confirm) File "c:\users\broja\appdata\local\programs\python\python35\lib\site- packages\pip\req\req_install.py", line 694, in uninstall for path in pip.wheel.uninstallation_paths(dist): File "c:\users\broja\appdata\local\programs\python\python35\lib\site- packages\pip\wheel.py", line 534, in unique for item in fn(*args, **kw): File "c:\users\broja\appdata\local\programs\python\python35\lib\site- packages\pip\wheel.py", line 554, in uninstallation_paths for row in r: _csv.Error: line contains NULL byte I honestly do not know what to do. If I am … -
jquery date value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] when saving to dajngo?
my jquery code goes like ... $("#datepicker").on("change",function(){ selectedFrom = $(this).val(); fromDateInput.value = selectedFrom; }); function ajax_call(data){ data = { 'from_input' : fromDateInput.value } } my model is ... class Reservation(models.Model): res_from = models.DateTimeField(null=True, blank=True) then my view goes like ... def reservationview(request): if request.method == 'POST': from_input = request.POST.get('from_input') Reservation.objects.create(res_from = from_input) -
Select an item will filter the drop-down menus
I have different drop-down menus on that picture. Assume that Type contains a list of items, i.e., [object1, object2, objects3, object4, ...]. I would like if object1 is selected in the drop-down menu that only Period remains among all others (Product type, Product and Debit frequency). How could I code with JavaScript in considering I am working in a Django Project? A simple example should be sufficient to understand -
Django Notification System
So i'm trying to build a notification system in django for my school project. I wants to notify the user if someone has answered his question for which i'm doing something like this answers = Answer.objects.filter(question__user=request.user).order_by('-id') This is a simple way of notifying the user. Also, User will not know the new notifications they have received since last login. Here's the model for Notification app, class Notifs(models.Model): user = models.ForeignKey(User) timestamp = models.DateTimeField(null=True, blank=True) In order to do that i'm trying something like this, i'm saving the last time when user have opened the notifications page & comparing this time with the time of answer. So, if user have received a answer since their last opening of page I wants to notify them. In view i'm trying something like this, def notifications(request): new = Notifs.objects.filter(user=request.user) if new: new.update(timestamp=timezone.now()) else: Notifs.objects.create(user=request.user, timestamp=timezone.now()) last_seen = ??? count = Answer.objects.filter(question__user=request.user, timestamp__gte=last_seen).count() I don't know exactly how can i compare the time since user has opened the notification page & someone has answered his question since then. How can do that? Please helpme. Thank You :) -
Django image upload test error: "The attribute has no file associated with it"
I have a user profile app that allows a user to upload an avatar. I'm trying to test the image upload but am getting an error. Here are my relevant files: models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) avatar = models.ImageField(upload_to="media/", blank=True, null=True) views.py def userprofile(request): # some code omitted for brevity if form.is_valid(): form.save() return HttpResponseRedirect(userprofile.get_absolute_url()) tests.py class UserProfileTest(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create_user( username='testuser', email='test@test.test', password='testpassword', ) self.user.userprofile.first_name = 'John' self.user.userprofile.last_name = 'Doe' def test_image_upload(self): self.client.login(username='testuser', password='testpassword') with open('media/tests/up.png', 'rb') as image: self.client.post('/profile/', {'avatar': image}) print(self.user.userprofile.avatar.url) Error: File "userprofile/tests.py", line 110, in test_image_upload print(self.user.userprofile.avatar.url) ValueError: The 'avatar' attribute has no file associated with it. In the tests, I've printed the response.content and can see the avatar's URL in the template. The 'media/tests/up.png' file is on the server and is being uploaded successfully. My goal here is to delete the file at the end of the test because it uploads every time I run the tests. I was going to delete the file by getting its file path (Django appends random alpha-numeric characters to the end of the file name when there are duplicates), but I can't get … -
Email form wont display on template
I'm working on a site that would display some data on my database and a form where people can contact me. views.py from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from .forms import ContactForm from django.utils import timezone from .models import Logo, SkillLanguages, SkillAPI, SkillFrameworks, WorkPortfolio, PersonalPortfolio def index(request): logo=Logo.objects.all() skill_languages=SkillLanguages.objects.all() skill_api=SkillAPI.objects.all() skill_frameworks=SkillFrameworks.objects.all() work_portfolio=WorkPortfolio.objects.all() personal_portfolio=PersonalPortfolio.objects.all() return render(request, 'johann/index.html', {'logo': logo, 'skill_languages': skill_languages, 'skill_api': skill_api, 'skill_frameworks': skill_frameworks, 'work_portfolio': work_portfolio, 'personal_portfolio': personal_portfolio}) def email(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(name, message, from_email, ['myemail@notsuspiciousmailserver.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "johann/index.html", {'form': form}) def success(request): return HttpResponse('<script>alert("Success! Thank you for your message."); window.location = "https://pqdrl7qd.apps.lair.io/#contact";</script>') urls.py from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^$', views.email, name='email'), url(r'^success/$', views.success, name='success'), ] I found out that my problem lies in what I did to the first two URLs, if I switched the email URL and the index URL's places my template would then display my form instead of the data stored in my models and vice versa. What … -
Regular or Special product, but not both
forms.py StatisticalToolsLayout = \ Div( Row( Column('type_choice', css_class="s2"), ), Row( Column('period', css_class="s2"), Column('product_type', css_class="s2"), Column( 'from_regular_product', 'from_special_product', css_class="s4"), ), CardAction( Div( Button('apply', _('Apply'), css_class='waves-effect waves-light btn white-text'), css_class="right-align"), ), css_class='card-action' ) formlayouts.py class StatisticsBaseForm(forms.Form): type_choice = forms.ChoiceField(label=_("Type"), choices=settings.STATISTICS_TYPE_CHOICES, initial=0, required=False) period = forms.ChoiceField(label="Period", choices=settings.PERIODS, initial='week', required=False) from_regular_product = forms.ModelChoiceField( queryset=ProductConfig.objects.filter(pk=-1), required=False, label=_('Product')) from_special_product = forms.ModelChoiceField( queryset=ProductConfig.objects.filter(pk=-1), required=False, label=_('Product')) product_type = forms.ChoiceField( choices=settings.LOANWOLF_PRODUCT_TYPE_CHOICES, required=False, initial='regular', label=_('Product type')) def __init__(self, *args, **kwargs): super(StatisticsBaseForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_class = 'row' self.helper.layout = StatisticalToolsLayout company = get_current_company() regular_products = company.available_products.filter( is_active=True, product_type='regular') special_products = company.available_products.filter( is_active=True, product_type='special') self.fields['from_regular_product'].queryset = regular_products self.fields['from_special_product'].queryset = special_products if regular_products: self.fields['from_regular_product'].initial = \ settings.LOANWOLF_EXTERNAL_REQUEST_DEFAULT_PRODUCT_INDEX if special_products: self.fields['from_special_product'].initial = \ settings.LOANWOLF_EXTERNAL_REQUEST_DEFAULT_PRODUCT_INDEX class Meta: model = Statistics fields = '__all__' The result in considering the .html file give me : image On the picture, there are two 'Product' drop down menu. From the 'Product type', there are two possible choices : Regular or Special. I would like if Regular is chosen, then the first 'Product' drop down menu (regular_products) will be shown up and otherwise, the second 'Product' drop down menu (special_products) will be shown up. Actually, the two drop down menu are shown up in the same time. … -
my unittest passes but says zero percent coverage
I wrote a unittest for my model, the test passes but it says I have zero percent coverage. Any advice would be appreciated. -
Django JWT authentication with PUT request
I am trying to update the first_name field for a user using a JWT token for authentication, for some reason when I am doing it in a different table where there is no username and password field ,I can easily do it and update the details using JWT token. it keep asking me to include the username and password on the request(even thought I don't want to update them). here is the error I am getting when sending the request using postman { "username": [ "This field is required." ], "password": [ "This field is required." ] } even though I have the authorisation header set right and it works with any other request, but not when updating user details, I have included all the necessary and default authentication classes. any help is appreciated, been trying to solve this small thing for 4 days now. -
why is the user authentication unsuccessful?
i am trying to build login page using django authentication system below is the views from django.contrib import auth def auth_view(request): username = request.POST.get('username',''), password = request.POST.get('password',''), print request.POST user = auth.authenticate(username=username, password=password) #returns user object if match else None if user is not None: auth.login(request, user) #make user status as logged in now using django login function return HttpResponseRedirect('/todos') else: return HttpResponseRedirect('/accounts/invalid') The variable user returns None even if the user/password is correct.when i change this line user = auth.authenticate(username=username, password=password) to actual user and password eg. user = auth.authenticate(username="peter", password="P@$w0rD275") it is successfully logged in -
Structuring Django Project
I know that you're supposed to have a templates folder within each app folder, how I have two questions clarify further. 1, Should I have 2 base.html files (one in each app) that are identical? This seems like it's creating more files than need be... and 2. What about the static and media folders? Should I also have two of each or should they be at the project and app folders level? If there is supposed to be a static folder in each app folder then do I have two css files? I feel like that makes no sense since the css can cover things that overlap from app to app. I'm also wondering if have it setup the way I currently have it will effect anything, or if "best practice" is more so just for if you're working on a project with multiple people (which I'm not, in which case should I care?) Here is my current structure: /evverest/ /evverest/ /feed/ /users/ /blog/ /templates/ /base/ /feed/ /users/ /static/ /css/ /media/ /post_pics/ /profile_pics/ -
Django: Updating request.user Instance
Here's my model class Extra(models.Model): user = models.ForeignKey(User) timestamp = models.DateTimeField(null=True, blank=True) My view is something like def notifications(request): new = Extra.objects.filter(user=request.user) if new: Extra.objects.update(timestamp=timezone.now()) else: Extra.objects.create(user=request.user, timestamp=timezone.now()) I'm trying to save the Date-Time when a user has requested a specific page. As you can see if data about the user is already present in database then i'm updating it when user is requesting the page else i'm creating a new instance for that user. But this is not a good way to do so since it's updating the Entire database not just the specific instance related to the request.user as we can see in our view (4th line i guess). So, how can I use the variable 'new' since it already holds the data (if present) & update just request.user instance in database? Please helpme with this code. Thanks in Advance :) -
Django Admin site is base html (Django, Webfaction)
I recently hosted a django app on webfaction and the admin console is just base html, links and text. It looks like any css it had is now gone. Any guidance how to get the admin console back to normal? It looks normal running on the local host... -
django many-to-many recursive relationship
I want to implement a basic social network model in django, i.e., followers and followees class CustomUser(User): followers = models.ManyToManyField('self', related_name='followees', related_query_name='followee') and above is what I define.I think this will be enough because the manytomany field provide backtrack query. Do I still need to create a followees ManyToMany filed? And could anybody help write the function how to get the number of followers and followees, as well as followers list and followees list. I'm new to django So I'm confused about the many-to-many field -
Django: 2 slugs in a url
First i would like to say thanks. I am doing my own project, its a we-app to strore ftiness routines. the routines may be organize by instructor, sex and type(tipo in spanish) I can move forward on the code bacause i dont know how i can have 2 slugs or pk in a url, for example. This is the land page, its a list of instructors, when you do a click this will send you to the list of sex and the url will say /instructor/Manuel where Manuel is the slug. here is where i can note move, if i do a click to sex type, the pk or slug is not saved form instructor list and it will be an error because is a new webpage, what i try to do is that after i do a click on sex i will have a list of routine by instructor, sex and maybe type filters. at the end. note here that in url /instructor/masculino/sex/masculino is masculino 2 times, it is because i have been doind tests and in sexo_list its {{ url 'rutina_list' slug=sexo slug2=sexo }} bacause i dont know how to save previous slug. Here is the code: models.py … -
having trouble deploying on heroku
I am having trouble deploying my django app on heroku. The problem occurs because I am using python decouple library. I am using it as not to expose my API_KEYS. File "/app/weather/settings.py", line 20, in <module> API_KEY = config('API_KEY') File "/app/.heroku/python/lib/python3.6/site-packages/decouple.py", line 197, in __call__ return self.config(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/decouple.py", line 85, in __call__ return self.get(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/decouple.py", line 70, in get raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option)) decouple.UndefinedValueError: API_KEY not found. Declare it as envvar or define a default value. This is the error I am getting. I have stored all the variables in BASE_DIR + '/.env' file. And Added this file in .gitignore file. What is the solution to this problem ?