Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Recover GET parameter from PasswordResetConfirmView
I'm trying to recover a GET parameter from the django template view django.contrib.auth.PasswordResetConfirmView. Basically when a user click on his password reset link (like http://127.0.0.1:8000/commons/reset/MQ/4t8-210d1909d621e8b4c68e/?origin_page=/mypage/) I want to be able to retrieve the origin_page=/mypage/ argument. So far my url.py looks like this: from django.urls import path from . import views app_name = 'commons' urlpatterns = [ path('reset/<uidb64>/<token>/', views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), ] And my views.py like this: from django.contrib.auth import views as auth_views class PasswordResetConfirmView(auth_views.PasswordResetConfirmView): template_name = 'commons/password_reset_confirm.html' success_url = '/commons/reset/done/' def get(self, request, *args, **kwargs): self.extra_context = { 'origin_page': self.request.GET['origin_page'] } return super().get(request, *args, **kwargs) As you can see I'm trying to get my origin_page with 'origin_page': self.request.GET['origin_page'] but it doesn't work. It throws me a MultiValueDictKeyError. I even used the debugger to inspect every objects from the class/method but none of them seems to contains my origin_page variable. Any idea? Thanks -
How to introduce non-model, write-only field to a modelserializer
I have the following ModelSerializer: class MaintProtoSerializer(serializers.ModelSerializer): class Meta: model = MaintenanceProtocol fields= ('warranty_card_number', 'warranty_id', 'machine_id', 'inner_body_id', 'outter_body_id', 'warranty', 'date', 'seller', 'inner_cleanup', 'outter_cleanup', 'turbine_cleanup', 'filter_condition', 'pressure', 'outer_air_temp', 'inlet_air_temp', 'other_problems', 'propuski', 'client_notes', 'electricity') and its model: class MaintenanceProtocol(models.Model): warranty_card_number = models.CharField(max_length=100) warranty_id = models.CharField(max_length=100) machine_id = models.CharField(max_length=100) inner_body_id = models.CharField(max_length=100) outter_body_id = models.CharField(max_length=100) warranty = models.BooleanField() date = models.DateField() seller = models.CharField(max_length=100) inner_cleanup = models.BooleanField() outter_cleanup = models.BooleanField() turbine_cleanup = models.BooleanField() filter_condition = models.TextField() pressure = models.IntegerField() outer_air_temp = models.IntegerField() inlet_air_temp = models.IntegerField() other_problems = models.TextField() electricity = models.IntegerField() propuski = models.TextField() client_notes = models.TextField() It's deserializing an object based on the following json passed to it: { "warranty_card_number": "profi-1234", "warranty_id": "fji-0938", "machine_id": "fuji", "inner_body_id": "outter-2349", "outter_body_id": "inner-2349", "warranty": "yes", "date": "2017-12-20", "seller": "maga`zin", "inner_cleanup": "no", "outter_cleanup": "yes", "turbine_cleanup": "yes", "filter_condition": "so-so", "pressure": "4", "outer_air_temp": "5", "inlet_air_temp": "23", "electricity": "45", "propuski": "some", "other_problems": "none", "client_notes": "n/a", "sigb64": "alkjhsdfpas8df,a;lsejf,p0394" } So the sigb64 field is not really part of the model (and it mustn't be persisted to the database), however I'd like to access it from the created model by the serializer. What's the correct way to achieve that? -
Access data from other model in a ListView
Good morning, how can I access data from another model in my ListView ? Right now I have a model called Project and I I am using ListView in order to render a a list of all current projects. My Project is linked to another models call Team that has multiple Members and each members has an attribute called Response_set. I would like that in my HTML template if Response_set is not empty for each member put a Green Mark else put a red mark. The thing is I do not know and do not find the answer on how to loop through my list within the view; class HRIndex(generic.ListView): #import pdb; pdb.set_trace() template_name = "HR_index.html" model = Project ordering = ['-created_at'] def get_context_data(self, **kwargs): import pdb; pdb.set_trace() context = super(HRIndex,self).get_context_data(**kwargs) status_dict = {} for project in object_list: proj_team_id = project.team_id proj_memb = proj_team_id.members.all() open_close = 1 for memb in proj_memb: if not list(memb.response_set.all()): status = False else: status = True open_close = open_close*status status_dict.update({project.id:open_close}) context['status_dict'] = status_dict return context I tried using object_list like in the template but it not working How can I loop through my list in my view ? Thx you -
Why Django DecimalField let me store Float or string?
I don't understand the behaviour of Django DecimalField. It's defined as: A fixed-precision decimal number, represented in Python by a Decimal instance. However, with the following model: class Article(models.Model) unit_price = DecimalField(max_digits=9, decimal_places=2) I can create an article in at least 3 ways: article = Article.objects.create(unit_price="2.3") type(article.unit_price) >>> str article = Article.objects.create(unit_price=2.3) type(article.unit_price) >>> float article = Article.objects.create(unit_price=Decimal('2.3')) type(article.unit_price) >>> decimal.Decimal Why Django DecimalField is able to return something else than Decimal type? What would be the best way to ensure my app never deals with floats for prices? Thanks. -
Django not running after restarting AWS AMI Elastic Beanstalk
I was recently fixing an Apache issue on an AWS AMI Elastic Beanstalk instance, I created an image and hence it restarted. After restarting, the application is not working. Do I have to run any command after restarting? -
fatal: destination path '.' already exists and is not an empty directory
I'm getting this error when I try to git clone my Bitbucket repo from my remote Digital Ocean server. The server directory I'm trying to clone the repo into is not empty, as I'm setting up my Django project in it (env, static, manage.py etc are all in there). So how do I clone the repo into this directory that is not empty? I've already tried a reccommended answer which said use git fetch and git checkout -t origin/master -f - and that didn't work - I got this error: fatal: A branch named 'master' already exists Any suggestions what I can do? -
"mkvirtualenv command not found" within vagrantbox
I am trying to set up a django project using vagrant, but I am getting this error: Welcome to Ubuntu 16.04.3 LTS (GNU/Linux 4.4.0-112-generic x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/advantage Get cloud support with Ubuntu Advantage Cloud Guest: http://www.ubuntu.com/business/services/cloud 0 packages can be updated. 0 updates are security updates. Last login: Sun Jan 28 08:21:28 2018 from 10.0.2.2 vagrant@ubuntu-xenial:~$ mkvirtualenv profiles_api --python=python3 mkvirtualenv: command not found In my vagrant file I have the following : sudo pip install virtualenvwrapper if ! grep -q VIRTUALENV_ALREADY_ADDED /home/ubuntu/.bashrc; then echo "# VIRTUALENV_ALREADY_ADDED" >> /home/ubuntu/.bashrc echo "WORKON_HOME=~/.virtualenvs" >> /home/ubuntu/.bashrc echo "PROJECT_HOME=/vagrant" >> /home/ubuntu/.bashrc echo "source /usr/local/bin/virtualenvwrapper.sh" >> /home/ubuntu/.bashrc fi I have python 3.6,3.5 and anaconda installed, if that matters. Thank you for the help -
Django site move to another sever
I have copied one django site source code and move it to another server, then did the following steps on new server: Install python 2.7.9 Install Django 1.8.6 Set the environment variable make a website in IIS and create fast CGI handler and mappings. But when running the site it showed the following error any help: Error occurred while reading WSGI handler: Traceback (most recent call last): File "E:\websitecode\wfastcgi.py", line 711, in main env, handler = read_wsgi_handler(response.physical_path) File "E:\websitecode\wfastcgi.py", line 568, in read_wsgi_handler return env, get_wsgi_handler(handler_name) File "E:\websitecode\wfastcgi.py", line 551, in get_wsgi_handler raise ValueError('"%s" could not be imported' % handler_name) ValueError: "django.core.wsgi.get_wsgi_application()" could not be imported StdOut: StdErr: -
django socket with react-native
We have a django backend with Django Rest Framework for our api, and our frontend is built with React Native (android). What is the best way to go about creating a socket between two users? We would like to implement chat/video and allow users to send data like current geolocation to each other. Also, is it possible to create a socket between the server and frontend to listen for DB updates (instead of sending requests from the front end to the api at set intervals) ? -
submit new record to db give me invalid literal for int
guys im working on django-rest-framwork . now im creating some new record to db at( store_product ) table when im submitting new data when i press POST button i get this error why i get this error ? !! ValueError at /store/ invalid literal for int() with base 10: '' Request Method: POST Request URL: http://localhost:8000/store/ Django Version: 2.0.1 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: '' Exception Location: /home/mohammadreza/www/html/academy/uenv/lib/python3.6/site-packages/django/db/models/fields/__init__.py in get_prep_value, line 947 Python Executable: /home/mohammadreza/www/html/academy/uenv/bin/python3 Python Version: 3.6.4 Python Path: ['/home/mohammadreza/www/html/academy/api/academy', '/home/mohammadreza/www/html/academy/uenv/lib/python36.zip', '/home/mohammadreza/www/html/academy/uenv/lib/python3.6', '/home/mohammadreza/www/html/academy/uenv/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6', '/home/mohammadreza/www/html/academy/uenv/lib/python3.6/site-packages'] Server time: Sun, 28 Jan 2018 11:54:13 +0330 INFO here is my serializer.py file from rest_framework import serializers from .models import Product class StoreSerializer(serializers.ModelSerializer): class Meta: model = Product fields = [ 'product_id', 'author', 'category', 'title', 'description', 'filepath', 'created_date', 'updated_date', ] read_only_fields = ['product_id', 'created_date', 'updated_date','author'] def validate_title(self,value): qs = Product.objects.filter(title__iexact=value) if self.instance: qs.exclude(pk=self.instance.pk) if qs.exists(): raise serializers.ValidationError("this title is already used") return value and here is my view.py file from rest_framework import generics from .serializers import StoreSerializer from .models import Product class StoreCreateApiView(generics.CreateAPIView): lookup_field = 'pk' serializer_class = StoreSerializer def get_queryset(self): return Product.objects.all() def perform_create(self, serializer): serializer.save(author = self.request.user) and it is my model for this … -
Python 3 - Django 1.9 One Create Request Causing Multiple Creation Attempts?
I was adding a successful or unsuccessful message to when a post is created on a learn to make a blog project when I started getting that post creations were both successful and unsuccessful at the same time: The contents of the message are defined using if/else statements and the only thing I can think might be happening is when I click submit on my post creation form it is being submitted multiple times causing an initial successful attempt and then two unsuccessful attempts but I don't see a reason for this to be happening in views.py, post_form.html, or post_detail.html files. Does anyone have a clue on how to fix this? views.py: from django.contrib import messages from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from .forms import PostForm from .models import Post def post_create(request): form = PostForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, "Successfully Created") return HttpResponseRedirect(instance.get_absolute_url()) else: messages.error(request, "Not Successfully Created") context = { "form": form, } return render(request, "post_form.html", context) post_form.html: <!--DOCTYPE html --> <html> <head> <title></title> </head> <body> <h1>Form</h1> <form method="POST", action="">{% csrf_token %} {{ form.as_p }} <input type="submit" name="Create Post"/> </body> </html> post_detail.html: <!--DOCTYPE html --> <html> <head> <title></title> </head> {% … -
No login and redirection with Python Social Auth, mobile Chrome (PWA or normal)
I have a problem with login and redirection using python-social-auth. The documentation says I can do using next in link: <a href="{% url 'social:begin' 'facebook' %}?next={{ request.path }}">Login with Facebook</a> It works okay for Firefox and Chrome on desktops. However on mobile phones I have different behavior. Mobile Firefox is working without problems. On mobile Chrome (PWA mode or normal mode) I cannot login and I am redirected to /accounts/login page without any errors. social-auth-core 1.6.0 social-auth-app-django 2.1.0 Any ideas are welcome. -
Why is my try catch solution not working as I expect it
I am trying to validate a form in a django project and part of the validation is to check if a project exists. The Environment: python 3.6.3 django 1.10.8 python-keystoneclient 3.14.0 I have this check currently def clean_projectname(self): submitted_data = self.cleaned_data['projectname'] newproj = "PROJ-FOO" + submitted_data.upper() keystone = osauth.connect() try: project = keystone.projects.find(name=newproj) raise forms.ValidationError('The project name is already taken') except NotFound: return submitted_data The try section will return either a project object or it will have a 404 not found Exception. I have tried to except on the NotFound but Django gives me an error name 'NotFound' is not defined I would appreciate help with this. -
NoReverseMatch at / django python:Reverse for '*' not found. tried
Reverse for 'details' with arguments '('',)' not found. 1 pattern(s) tried: ['details/(?P[.\-\w]+)$'] I am getting this error when I open the home page. All other pages seem to work. urls.py app_name = 'main' urlpatterns = [ url(r'^$', views.home, name='home'), url(r'ask-question/$', views.question, name='ask-question'), url(r'^details/(?P<slug>[.\-\w]+)$', views.details, name='details'), ] views.py for the home page def home(request): questions = Question.objects.all().order_by("-date") numbers = Question.objects.all().count() numbers2 = Answer.objects.all().count() total_users = User.objects.all().count() # counting answers on specific questions results = Question.objects.annotate(num_answers=Count('answer')).order_by("-date") # PAGINATION =============================== page = request.GET.get('page', 1) paginator = Paginator(results,10) try: results = paginator.page(page) except PageNotAnInteger: results = paginator.page(1) except EmptyPage: results = paginator.page(paginator.num_pages) # end of counting empty = [] for a in Answer.objects.all(): idd = a.id question_id = (a.question_id) empty.append(str(question_id)) repeatition = Counter(empty) # i = 0 # trend_list = [] # for x in range(len(repeatition)): # new = repeatition.most_common()[i][0] # trend_list.append(new) # i += 1 # if len(trend_list) != 0: # trend = Question.objects.get(id=trend_list[0]) # else: # trend = 'No Trending Category' # getting the answers to all questions in the front page # search the questions ============ query= request.GET.get("q") if query: short_list = Question.objects.all() questions = short_list.filter(title__icontains=query) resulted = questions.annotate(num_answers=Count('answer')) counted = questions.count() context1 = { 'questions': questions, 'query': query, 'counted': counted, … -
Mock gives "raise except" error
I am trying to unit test my program. I have a side effect in my mock object from models import MyObject mock_obj.objects.get.side_effect = mock.Mock(side_effect=MyObject.DoesNotExist) The test works and passes when I have this in the function that I am testing: import models try: obj = models.MyObject.objects.get(id=1) except Exception: return True However when I change this to: import models try: obj = models.MyObject.objects.get(id=1) except models.MyObject.DoesNotExist: return True It gives me this instead of returning True: > Traceback (most recent call last): > File "/home/test/test_my_function.py", line 40, in test_get_job_not_exist > response = my_function.my_function(request_mock, 1) > File "/home/handlers/my_function.py", line 35, in get_job_with_id > obj = MyObject.objects.get(id=id) > File "/local/lib/python2.7/site-packages/mock/mock.py", line 1062, in __call__ > return _mock_self._mock_call(*args, **kwargs) > File "/local/lib/python2.7/site-packages/mock/mock.py", line 1118, in _mock_call > raise effect > DoesNotExist Why is this happening? MyObject is a Django model object -
Django server close on closing browser tab
I want to close my running django server(CMD) on closing browser tab. After some few minute research i tried below codes. using windows, django 1.9, and python 3.6 -as s very 1st step i added onbeforeunload js script inside my header template so that every page that contains my web app will have that event handler in header. {% block js %} //close ui on tab click window.onbeforeunload = function(){ $.ajax({ // Ajax call type: "POST", url: "closeui", success: function(k){ alert('Good bye'); return false; }); return "Do you really want to close?"; }; {% endblock js %} For routing i added url as closeui On views i created closeui function which will perform closing cmd. def closeui(): import os from win32com.client import GetObject WMI = GetObject('winmgmts:') processes = WMI.InstancesOf('Win32_Process') for p in WMI.ExecQuery('select * from Win32_Process where Name="cmd.exe"'): print("Killing PID:", p.Properties_('ProcessId').Value) os.system("taskkill /pid "+str(p.Properties_('ProcessId').Value)) return True So id didn't get any desired result for this. If anyone could correct me where did i went wrong that would greatly appreciated. -
Web Design Tool Assets
How do copyright laws apply to the assets (pictures, html,css, etc) that are used in various web design tools that WordPress or GoDaddy provide? I have been using a tool of that nature to design a website but I would like to take all the assets that the tools have provided and host them elsewhere with a django server. Is this something that falls under fair use or open source policies? -
I am missing something with Django's url paths
I have an app in django that has a webpage with buttons to travel to another page via a menu and 8 hrefs. When I travel to the first page and try to click on another, I will encounter a 404 error. Page not found (404) http://127.0.0.1:8000/index.html/contact Here is my url.py urlpatterns = [ path('index.html/', views.homepage), path('contact.html/', views.contact), path('about.html/', views.about), ] Views as well def customers(request): return render(request, 'customers.html') def about(request): return render(request, 'about.html') def contact(request): form_class = ContactForm return render(request, 'contact.html', { 'form': form_class, }) I do not want http://127.0.0.1:8000/index.html/contact I want http://127.0.0.1:8000/index or http://127.0.0.1:8000/contact How do I keep my URLs basic? -
Wagtail vs Mezzanine, which is better for building a customised CMS?
Wagtail and Mezzanine are good open source CMS platforms. But, which one is better to be extended and used to build a Django web app with CMS included? -
Dropbox API with Django - Authentication
I'm trying to learn Dropbox API and want to use OAuth 2 for authorization. I'm getting following error: dropbox_auth_start() missing 1 required positional argument: 'request' Here is my code: Views.py from dropbox import DropboxOAuth2Flow from django.shortcuts import redirect def get_dropbox_auth_flow(web_app_session): redirect_uri = "https://www.my-dummy-url.com" APP_KEY = 'my-app-key' APP_SECRET = 'my-app-secret' return DropboxOAuth2Flow( APP_KEY, APP_SECRET, redirect_uri, web_app_session, "dropbox-auth-csrf-token") def dropbox_auth_start(web_app_session, request): if request.method == 'GET': authorize_url = get_dropbox_auth_flow(web_app_session).start() return redirect(authorize_url) urls.py urlpatterns = [ path('dropbox/', views.dropbox_auth_start, name='dropbox') ] -
Why is extending the user model causing an http 400 error?
I followed the Django documentation to try to extend my user model to add a field called authentication_key. It is resulting in an HTTP 400 error when I test the site locally. My models: class AuthenticationKey(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) authentication_key = models.CharField(max_length=100) My Admin: class AuthenticationKeyInline(admin.StackedInline): model = AuthenticationKey can_delete = False verbose_name_plural = 'AuthenticationKey' # Defines a new User admin class UserAdmin(BaseUserAdmin): inlines = (AuthenticationKeyInline, ) # Re-register UserAdmin admin.site.unregister(User) admin.site.register(User, UserAdmin) And how I'm referring to the field in my views.py @login_required(login_url='/login/') def home_page(request): u_id = request.user.authenticationkey I'm thinking the error may be how I'm referring to the field in views but I can't figure out quite what's wrong. -
How to use the OAuth2 toolkit with the Django REST framework with class-based views?
I'm trying to add an API using the Django REST framework to an existing codebase which uses the Django OAuth2 toolkit. The existing views make use of the fact that the OAuth2 toolkit's backend modifies the behavior of Django's login_required decorator so that it uses OAuth2 authentication. The function-based views look similar to the one in the tutorial example: from django.contrib.auth.decorators import login_required from django.http.response import HttpResponse @login_required() def secret_page(request, *args, **kwargs): return HttpResponse('Secret contents!', status=200) I'm trying to adapt the example given on https://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html to my situation, but I'm finding it's not an exact correspondence, because the example uses the DRF's ModelViewSet classes whereas my current view uses a (less-integrated) generic class-based view: from rest_framework import generics from ..models import Session from ..serializers import SessionSerializer class SessionDetail(generics.UpdateAPIView): queryset = Session.objects.all() serializer_class = SessionSerializer where I've set the default permission class to IsAuthenticated in settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } This should allow a Session object to be updated using PATCH requests, but it appears to return a 403 Forbidden response for use cases similar to the ones for the current views decorated with login_required. How can I update the SessionDetail view so that it behaves the … -
Access to model field through connected one
I have two models class Category(models.Model): name = models.CharField("category", max_length=200, null=True) discount = models.PositiveIntegerField(null=True) class Product(models.Model): name = models.CharField("product", max_length=200) price = models.DecimalField(max_digits=10, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="products", verbose_name="category") How to show discount value in admin panel? class ProductAdmin(admin.ModelAdmin): list_display = ['name', 'category', 'price', 'discount'] # not works list_filter = ['category', 'price'] list_editable = ['price'] -
Django pagination URL
I can get pagination to work at http://127.0.0.1:8000/ using the below code: {% if is_paginated %} <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="/?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="page-current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="/?page={{ page_obj.next_page_number }}">next</a> {% endif %} </span> </div> {% endif %} I would like to paginate a bunch of comments at http://127.0.0.1:8000/film id which is like a details page for each film. I think I just need to change these urls for it to work: <a href="/films?page={{ page_obj.previous_page_number }}">previous</a> <a href="/films?page={{ page_obj.next_page_number }}">next</a> But so far have not been able to do so. My hrefs are usually like <a href="{% url 'films:add_comment' film_id=film.id %}">Leave a comment</a> but I am not fussed how it is wrote as long as it works. -
Using JS to render Django form
I'm learning to utilize pure JS in Django projects. Being a server-side developer the concepts are relatively new for me, so need a hand. Imagine a form where a user can post text, and/or upload an image. Think of it as a simple Django form like so: class PostForm(forms.Form): image = forms.ImageField(required=False) reply = forms.CharField(required=False, widget=forms.Textarea(attrs={'cols':30,'rows':3,'class': 'cxl','autocomplete': 'off','autofocus': 'autofocus'})) def __init__(self,*args,**kwargs): super(PostForm, self).__init__(*args,**kwargs) self.fields['image'].widget.attrs['id'] = 'browse_image_btn' def clean(self): data = self.cleaned_data # perform cleaning return data If I were to render this form in HTML, something like the following would do: <form action="{% url 'post_content' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ post_form.reply }}<br> {{ post_form.image }} <label for="browse_image_btn" style="cursor: pointer;"><img alt="Select photo" src="{{ STATIC_URL }}img/upload.svg" width="70" height="70"></label> <input type="submit" value="submit"> </form> But how do I create this HTML solely via JS? Use-case: imagine a page that contains a long list of content, with a reply button under each. The form above only appears under specific content once the user has pressed the reply button. Moreover, pressing the same button toggles it off too. I can't seem to wrap my head around solving a problem like that. Please advise, preferably with an illustrative example. I'd prefer to understand the most …