Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Google OAuth2 Whitelist, remove not authorized from list
I have a Django/python site and have set up Python Social Auth to allow for authentication with a google account, actually specific to my domain. We have a domain that is hosted through google accounts. I have set the whitelist to only accept email accounts from my domain. That is working correctly. However, when I go to the authentication window it shows all of the google accounts I have - there are two gmail accounts that cannot authenticate due to the whitelist option, but the accounts still show. The user will not know they can't use the other accounts until they try and get a nasty error message "AuthForbidden: Your credentials aren't allowed." Any way I can limit the list that they see to accounts that they can actually use? I have a coworker who set this up for a different website that runs on ColdFusion and he set the meta content headers to something for the whitelist and ran the login through javascript, which allowed him to specify the domain using scope and that did limit the accounts visible to only those of the specified domain. Thanks in advance. -
Set value for dropdown in django forms from static database
I have a database table sheets and that table is created manually.Now I am using a django-python Project.and I need to get the values in form.py from a table sheets based on a condition, And I dont want to create a new model class.without model class how can I get the values from database tables. Please help me. Thanks in advance -
Query local time
For a shop, I would like store opening and closing times in local time for that given shop. Example: Shop1 opens at 8.00 (t1), and closes at 16.00 (t2) local time. Shop1 is located in Europe/London (tz). Shop2 opens at 8.00 and closes at 16.00 local time. Shop2 is located in Europe/Copenhagen. The question: How do I at a given time select shops that are open? I need to take into account DST: In this example in the summer, Shop1 open time will be 08:00+01:00, Shop2 open time will be 08:00+02:00 while in the winter, this will be 08:00+00:00 for Shop1 and 08:00+01:00 for Shop2. Will be selecting from a table with many rows, hence I need this to be indexed. Using Django + PostgreSQL. -
Django querying DB returns Queryset with swapped values
I am querying a PostgreSQL db within django, the problem is the following: If I have columns with values - id = 1, username = blah, desc = smth in the db, the query returns queryset of the right objects but with values - id = smth, username = 1, desc = blah Tho I can easily append the right values to something it is a problem when I try to delete the object because on id it expects an int not a charfield. I will be glad if someone can explain to me what is happening and how to fix it. Here is my code: waiting_users = OnlineUsers.objects.all() print(waiting_users) # If there are waiting users connect to one of them if waiting_users.exists(): print("There are people on the list") user_topair = waiting_users.first() pair = PairUsers() print(user_topair.username) print(user_topair.reply_channel_name) print(user_topair.id) pair.username_a = username pair.username_b = user_topair.reply_channel_name pair.reply_channel_a = reply_channel_name pair.reply_channel_b = user_topair.id pair.save() # user_topair.delete() -
Login required always render to home page
when I am using login required it does not rendering to appropriate url it always render to home page only login view def login_view(request): print(request.user.is_authenticated()) w="Welcome" title = "Login" form = UserLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) login(request, user) messages.success(request, "Successfully Logged In. Welcome Back!") return HttpResponseRedirect("/") return render(request, "registration/login.html", {"form":form, "title":title}) settings.py file LOGIN_URL = '/login/' LOGIN_REDIRECT_URL = '/' I applied login required on contact us but when i am logging in then it is rendering to home page. contact us view @login_required def contactformview(request): form = ContactForms(request.POST or None) if form.is_valid(): form.save() return HttpResponse(' Thanks For Contacting WIth Us We Will Get Back To You Within 24 Hours') return render(request, 'contact-us.html', {'form':form}) -
django-admin: How to redirect to another URL after Object save?
In Django Admin, saving an Object always goeas back to it's List of Objects. Now i want to go to the List of A-Objects upon saving a B-Object. B-Object = Payment A-Object = Invoice I tried several things: In admin.py: @receiver(post_save, sender=Payment) def custom_redirect(sender, instance, **kwargs): return HttpResponseRedirect('/admin/sales/invoice') OR class PaymentAdmin(VersionAdmin, admin.ModelAdmin): def change_view(self, request, object_id, extra_context=None): return HttpResponseRedirect('/admin/sales/invoice') Instead of HttpResponseRedirect i tried using redirect() , but also with no effect. On inserting wrong code into post_save i get an error message - so it does get triggered, but the redirect does not happen. Any hints would be very apreciated - as i'm stuck for days on this "simple" problem. Thanks -
Logout not working Django 1.9
I'm building a Django website, but my logout is not working. The site consists in two apps, the main app that is public and the student app that is private. In my student app i've put the @login_required decorator in every method, except the logout method. But when i click the logout link in the student app, my page is not redirected to the main app, it goes to another view inside the student app, and when i reload the page, the content is still available although i've put the @login_required decorator. Here is my code: website/urls.py from main_app import urls as main_urls from student_app import urls as std_urls urlpatterns = [ url(r'^index/', include(main_urls)), url(r'^student-area/', include(std_urls))] website/settings.py LOGIN_URL = '/index/login/' LOGIN_REDIRECT_URL = '/student-area/' main_app/urls.py ... urlpatterns = [ url(r'^$', views.index, name='index'), ...] student_app/urls.py ... urlpatterns = [ ... url(r'^logout/', views.user_logout, name='user_logout') ] student_app/views.py from django.contrib.auth import logout from django.shortcuts import redirect ... def user_logout(request): logout(request) redirect('index') student_app/templates/student_area.html ... <a href={% url 'user_logout' %} class="btn btn-default">Logout</a> ... I am lost in this problem, thank you in advance. -
How to filter values in a drop down list django
I am populating my drop down box with values from my model, I have five values in my model, I only want to show three of these values in this particular instance how would I achieve this. forms.py class namesForm(forms.Form): names = forms.ModelChoiceField( queryset=Names.objects.order_by('name').exclude(name='Josh','Tom'), label = "Name:", widget = Select(attrs={'class': 'span6 small-margin-top small-margin-bottom'}), empty_label = "Select a Name", required=True ) -
Error in admin: __str__ returned non-string (type NoneType)
The admin returns this error when trying to add an instance to one of my models. The model itself has a correct str() method and contains no instances yet. Also tried replacing the str() method with a static method or removing it altogether. No luck. The error seems to point towards something going wrong in the history part of the admin. Stacktrace points to line 33. Error during template rendering In template /Users/snirp/juis/snirpdrive/glotto/venv/lib/python3.6/site-packages/django/contrib/admin/templates/admin/change_form.html, error at line 33 __str__ returned non-string (type NoneType) 23 {% endblock %} 24 {% endif %} 25 26 {% block content %}<div id="content-main"> 27 {% block object-tools %} 28 {% if change %}{% if not is_popup %} 29 <ul class="object-tools"> 30 {% block object-tools-items %} 31 <li> 32 {% url opts|admin_urlname:'history' original.pk|admin_urlquote as history_url %} 33 <a href="{% add_preserved_filters history_url %}" class="historylink">{% trans "History" %}</a> 34 </li> 35 {% if has_absolute_url %}<li><a href="{{ absolute_url }}" class="viewsitelink">{% trans "View on site" %}</a></li>{% endif %} 36 {% endblock %} 37 </ul> 38 {% endif %}{% endif %} 39 {% endblock %} 40 <form {% if has_file_field %}enctype="multipart/form-data" {% endif %}action="{{ form_url }}" method="post" id="{{ opts.model_name }}_form" novalidate>{% csrf_token %}{% block form_top %}{% endblock %} 41 <div> 42 {% … -
Need to access the username in a view that is not a request
I am using the django web framework and need to access a username in a view that is not a request. This probably isn't a good idea... but I need it just to assign a class dependent on whether the data belongs to the user, or someone else. So the request view is separate, the view in question is just for rendering the calendar. As follows: @login_required def holiday(request): #i want this later on user = request.user #some stuff to make the calendar cal = HolidayCalendar(my_holidays).formatmonth(year, month) # more stuff context = { "calendar": mark_safe(cal), } return render(request, "tande/calendar.html", context) And here is the HTML calendar that I need to access the user in class HolidayCalendar(HTMLCalendar): def __init__(self, holiday): super(HolidayCalendar, self).__init__() self.holiday = self.holiday_days(holiday) def formatday(self, day, weekday, user): #do some stuff... if holiday_object: # links to holiday object body.append('<a href="%s"><center>' % holiday_object.get_absolute_url()) body.append(esc(holiday_object.person_id)) body.append('</center></a>') # I NEED THE USER HERE if holiday_object.person_id == user: body.append('<hr class="holiday">') else: #want to have a different hr class And I don't know how to pass the user to this function.... I tried sessions but that also didn't work without a request. Any ideas? Thanks! -
Django/Django Rest Framework - Disable CSRF
Im looking for a simple way to disable all the CSRF validation to can test my API in Postman. Till now I have tried add @decorator csrf_exempt without success. I also tried create a disable.py file inside the app, but didn't work also. Also I want desactivate for all requests, so some way to dont have to add the decorator everywhere. This a project that I just got, is already in Production, but I want to start to write Tests first in Postman, later TestCases. All my views are using a "api_generics.CRUDGeneric", the declaration of that class is: class CRUDGeneric(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): thanks is advice -
What means the serialize=False on Primary-key field?
I didn't found in the Django docs the reason for serialize=False on primary key fields. Is there a special reason to set it? Thanks -
Can not figure out the correct way to implement Django Filters
My problem is I have to query database for users for certain fields which are des, gender, min_age, max_age. When I was usind multiple values it was working fine using filter_queryset. And then I used multiple values for gender its working but when I don't include the gender in my url the code break basically because split doesn't work. So I thought using multiple if/else which will have different queryset.filter(des__in=[], gender__in=[]) or gender not available then query -> queryset.filter(des__in=[]). I am missing many things here. please help API - /v1/users/query_users?des=1,2&gender=Male,Female&min_age=2&max_age=4 class ProductFilter(django_filters.rest_framework.FilterSet): min_age = django_filters.DateRangeFilter(name="dob", lookup_expr="gte") max_age = django_filters.DateRangeFilter(name="dob", lookup_expr="lte") class Meta: model = UserProfile fields = ['des', 'gender', 'min_age', 'max_age'] class QueryUserGroup(generics.ListAPIView): queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer filter_backends = (django_filters.rest_framework.DjangoFilterBackend,) filter_class = ProductFilter permission_classes = [permissions.IsAuthenticatedOrReadOnly] def filter_queryset(self, queryset): des_list = self.request.GET.getlist("des") gender_list = self.request.GET.getlist("gender") des_ids = des_list[0].split(',') gender_ids = gender_list[0].split(',') return queryset.filter(des__in=des_ids, gender__in=gender_ids) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) serializer = UserProfileSerializer(queryset, many=True) return JSONResponse({'data': serializer.data}, status=HTTP_200_OK) -
pass a parametar to the service function
I'm trying to pass currency and statistics list from my custom function to views.py so I can parse it in the template but I'm not getting any result, table in the template is empty, can someone help me understand what I'm I doing wrong here, thanks calculation: @staticmethod def statistics_calculation(statistics_list): end = timezone.now() start = Project.objects.all().order_by('created').first().created statistics = OrderedDict() for year in range(start.year, end.year, 1): statistics[year] = OrderedDict() for month in range(1, 12): statistics[year][month] = { "label": calendar.month_name[month] + " " + str(year), "price_total": 0, "cost_total": 0, "profit_total": 0, } statistics[year]['total'] = { "is_highlighted": True, "label": str(year) + " total", "price_total": 0, "cost_total": 0, "profit_total": 0, } statistics['total'] = OrderedDict() statistics['total']['total'] = { "is_highlighted": True, "label": "Total", "price_total": 0, "cost_total": 0, "profit_total": 0, } default_currency = Rate.EUR for project in Project.objects.iterator(): year = project.created.year month = project.created.month project_currency = project.currency price = CurrencyConversionService.convert_source_to_target( project_currency, default_currency, project.price_aux) cost = CurrencyConversionService.convert_source_to_target( project_currency, default_currency, project.cost_aux) profit = CurrencyConversionService.convert_source_to_target( project_currency, default_currency, project.profit_aux) statistics[year][month]["price_total"] += price statistics[year][month]["cost_total"] += cost statistics[year][month]["profit_total"] += profit statistics[year]["total"]["price_total"] += price statistics[year]["total"]["cost_total"] += cost statistics[year]["total"]["profit_total"] += profit statistics["total"]["total"]["price_total"] += price statistics["total"]["total"]["cost_total"] += cost statistics["total"]["total"]["profit_total"] += profit statistics_list = [] for statistics.year_stats in statistics.values(): statistics_list.extend(statistics.year_stats.values()) and my view: def get_context_data(self, **kwargs): context … -
Getting AttributeError while registering my model to Django admin?
What i am trying to do: Trying to registering my model to django admin What problem do i get: I am getting the following error: My Code: admin.py: from django.contrib import admin from .models import UserProfile, Post admin.site.register(UserProfile,Post) model.py: from django.contrib.auth.models import User from django.db import models class UserProfile(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) avatar = models.ImageField(upload_to='static/media/',max_length=100) class Post(models.Model): title = models.CharField(max_length=120) content = models.TextField() urls.py: from django.conf.urls import url from .import views urlpatterns = [ url(r'^register/$',views.registerUser), url(r'^$', views.index, name="Index"), url(r'^validateRegisterForm/$',views.validateRegisterForm), url(r'^validateLoginForm/$',views.validateLoginForm), url(r'^article/$', views.article, name="Article"), url(r'^Login/$',views.loginUser, name="Login"), url(r'^Logout/$',views.logoutUser, name="Logout"), ] Note: I am new to django so, don't know much about it. -
How to translate certain string from lib?
django-registration is missing some translations for german. See github Search for "". Translations are were but "broken". I don't want to fork or change localization files localy. Is it possible to provide translation for some strings in my app/project? -
How to view database and schema of django sqlite3 db
I am new to django framework. I tried to create a simple blog by following djangogirls tutorials. Here by default we get sqlite3 as default database Engine DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } I tried some ORM queries also, Even performed some row sql queries At my django project I have this db.sqlite3 file blog db.sqlite3 env manage.py mysite My Question: How to knew the schema that django created in this db.sqlite3(I knew mysql where I can see details about each database and tables,so here I just want to know more things in sqlite) I have sqlite3 in my system and I tried .database command,but it just shows me seq name file --- --------------- ---------------------------------------------------------- 0 main -
Does Python/Django guarantee that the objects from foreign key will stay in the same order?
Suppose I have the following models: class Case: case_name = models.CharField(max_length=200) class SubTask: subtask_name = models.CharField(max_length=200) case = models.ForeignKey(Case, on_delete = models.CASCADE) Suppose I create four objects of SubTask st1,st2,st3, and st4 in this order and set their case attribute to the Case instance C. Now my question is, when I do this loop: for subtask in SubTask.objects.filter(case=C): #Do something to subtasks Is it guaranteed by python or Django that the objects in this loop will appear in the order st1,st2,st3, then st4? Or does it only guarantee that the four objects will be looped over in any order? Note: I did try it and they were in the order of instantiation, However, I want to make sure that this behavior is guaranteed since the ordering matters. -
Profiling a Django App
I am debugging a Django app right now. This is the profiler report. Can you tell me what this "{built-in method poll}" or "{issubclass}" means? Whats the best way to debug this? Thanks very much! Matthias 3897321 function calls (3801877 primitive calls) in 3.184 seconds Ordered by: internal time List reduced from 1313 to 100 due to restriction <100> ncalls tottime percall cumtime percall filename:lineno(function) 1 1.686 1.686 1.686 1.686 {built-in method poll} 95634/31362 0.437 0.000 0.782 0.000 pprint.py:243(_safe_repr) 712783 0.131 0.000 0.131 0.000 {method 'write' of 'cStringIO.StringO' objects} 25176/2086 0.090 0.000 0.953 0.000 pprint.py:132(_format) 350302/350286 0.044 0.000 0.045 0.000 {issubclass} 661723 0.037 0.000 0.037 0.000 {method 'isalpha' of 'str' objects} 286836 0.031 0.000 0.093 0.000 {repr} -
Django - $(document).ready(function() {} does not trigger, but JQuery is loaded
my template: {% extends "base.html" %} {% block content %} {% load static %} <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.js"> $(document).ready(function() { alert("I am an alert box!"); }); $(function() { $( ".datepicker" ).datepicker({ changeMonth: true, changeYear: true, }); }); </script> <form action="{% url 'transaction_create' %}" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" name="save" value="Save transaction"> </form> {% endblock %} The google chrome inspector shows that JQuery loads, but no alert box appears nor does the datepicker work (the class on the field is set correctly). Why does the Javascript not work? -
Doing some processing locally before uploading
I am new to Django and doing a small project where the user logs into a Django powered website and can then upload some images. These images will need to have some preprocessing on them before it can be used by the remote services. What I would like to do is perform the preprocessing on the client side and I have some python code that does it. However, I am not sure how I can setup Django so that the user can grant it permissions to run some code locally (and generate some files in the temporary directory). So, for example, one of my view is as follows: class UploadImageView(APIView): permission_classes = (IsAuthenticated, ) authentication_classes = (JSONWebTokenAuthentication, ) # Create your views here. def post(self, request): image = request.FILES['image'] study = int(request.data.get('study').strip()) if image is None: return Response(status=status.HTTP_400_BAD_REQUEST) # Check study ID and Image type exists s = StudyModel.objects.filter(pk=study).first() if s is None: return Response(status=status.HTTP_412_PRECONDITION_FAILED) try: _ = ImageModel.objects.create(path=image, study=s) except: return Response(status=status.HTTP_417_EXPECTATION_FAILED) return Response(status=status.HTTP_200_OK) Now currently, the user needs to run some code locally manually to generate this transformed image and then call the ReST API to upload it. What would be nice is the user selects the raw … -
When using ajax and how to manage page caching without reloading the page on back/forward button from browser
I'm using an ajax call for filtering vehicles on my page. I need to filter vehicle based on "make","model","variant","colour". So I have these filters on left side of my page and by selecting any of these I want to update my right side of page section to display filtered vehicles. Here is my template structure category.html --> main html file category.html is divided into 2 filters.html vehicles.html I have used ajax call based on filters selected in filters.html, till here it perfectly works fine. It gives me the filtered vehicle records on my right section of page. Here I have also used pushState() to display the url which I would like to show, now just the issue is when I press back button from browser it doesn't affect my page anything where I'm expecting that it should just display the previous page state. Here is my ajax snippet $(".c_filter").click(function() { var filt_key = $(this).attr('name'); var filt_val = $(this).attr('value'); $.ajax({ type: "POST", url: "{% url 'c_ajax' %}", data: { 'filt_key': filt_key, 'filt_val':filt_val, 'csrfmiddlewaretoken': '{{ csrf_token }}', }, success: function(data) { $('.aj').html(data); window.history.pushState("","<url>/vehicles/?model=Yamah"); } }); }); I have also used the onpopstate event to get the previous url but using this I'm … -
Redirecting with middleware
I have a written a (new style) Django middleware to redirect a user to a specific view if a condition is not met. In this case, request.session['sms_verified'] needs to be true: class SMSVerificationMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.user.is_authenticated and request.user.email_verified: if not request.session.get('sms_verified'): verification_code = random.randint(100000,999999) print('SMS verification code: ' + str(verification_code)) request.user.sms_verification_code = verification_code request.user.save() return redirect('users:sms_verification') else: print('SMS verified') return self.get_response(request) else: return self.get_response(request) It redirects to the SMS verification view when needed, but this view throws an error: AttributeError at /sms_verificatie/ 'NoneType' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:8000/sms_verificatie/ Django Version: 1.11a1 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'get' Exception Location: C:\Users\Administrator\SVN\venvs\venv_valportal\lib\site-packages\django\middleware\clickjacking.py in process_response, line 32 Python Executable: C:\Users\Administrator\SVN\venvs\venv_valportal\Scripts\python.exe Python Version: 3.6.0 Python Path: ['C:/Users/Administrator/SVN/valportal', 'C:\\Program Files (x86)\\JetBrains\\PyCharm 2016.3.2\\helpers\\pydev', 'C:\\Users\\Administrator\\SVN\\valportal', 'C:\\Program Files (x86)\\JetBrains\\PyCharm 2016.3.2\\helpers\\pydev', 'C:\\Users\\Administrator\\SVN\\venvs\\venv_valportal\\Scripts\\python36.zip', 'C:\\Users\\Administrator\\SVN\\venvs\\venv_valportal\\DLLs', 'C:\\Users\\Administrator\\SVN\\venvs\\venv_valportal\\lib', 'C:\\Users\\Administrator\\SVN\\venvs\\venv_valportal\\Scripts', 'c:\\python36-32\\Lib', 'c:\\python36-32\\DLLs', 'C:\\Users\\Administrator\\SVN\\venvs\\venv_valportal', 'C:\\Users\\Administrator\\SVN\\venvs\\venv_valportal\\lib\\site-packages'] Server time: di, 14 Feb 2017 13:35:29 +0100 Environment: Request Method: GET Request URL: http://127.0.0.1:8000/sms_verificatie/ Django Version: 1.11a1 Python Version: 3.6.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'frontend', 'users', 'public', 'patient', 'pharmacy', 'manager'] Installed 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', 'users.middleware.SMSVerificationMiddleware'] Traceback: File "C:\Users\Administrator\SVN\venvs\venv_valportal\lib\site-packages\django\core\handlers\exception.py" in inner … -
'django.db.models': Referential Integrity: Enforcing 'RESTRICT'ed DELETES AND CASCADEing UPDATES
I am following through with the Django documentation, but decided to "improve" the referential integrity of the underlying Db Schema, by restricting deletes as follows: from django.db import models # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.PROTECT, on_update=models.CASCADE) choice_text = models.CharField(mac_length=200) votes = models.IntegerField(default=0) When I run python manage.py makemigrations polls, I got the error: TypeError: init() got an unexpected keyword argument 'on_update' How do I implement restrictions on BOTH UPDATES and DELETES? -
Set limit per user to view posts in django ORM
models.py: class Post(models.Model): author = models.ForeignKey('User') text = models.TextField(max_length=320) created_date = models.DateTimeField(default=timezone.now) I want to Get newest posts which just show 3 or less posts per day from each user, For example : User1 published 3 posts today. User2 published 20 posts today. I want a Django ORM command that limit to show just 3 posts each user per day. This query should get 6 posts: 3 posts from Users1 3 posts from Users2