Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"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 … -
Problems Loading Static Files into Django Dev Environment
I am trying to load static files into my Django project and it just isn't working. Inside my settings.py file I have defined the below: STATIC_URL = '/static/' STATICFILE_DIRS = os.path.join(BASE_DIR,'static') This is a screenshot around how my project structure is setup: When the template is rendered only the text shows up - no image. HTML below to show the syntax behind static file loading: <!doctype html> {% load static %} <html class="no-js" lang=""> <head> </head> <body> <h1>Test</h1> <img src="{% static 'test.png' %}" alt=""> </body> </html> Any help is really appreciated -
django python accessing additional fields
I am new to Django and trying to access the custom fields but dont have any luck. Models.py class UserProfile(models.Model): user = models.OneToOneField(User) bio = models.CharField(max_length=400) def __str__(self): return self.user.username forms.py class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) bio = forms.CharField(widget=forms.Textarea(attrs={'cols':50, 'rows': 5})) class Meta: model = User fields = ('username', 'email', 'password', 'bio') views.py def register(request): registered = False if request.method == "POST": user_form = UserForm(data=request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() registered = True login(request, user) else: print(user_form.errors) else: user_form = UserForm return render(request, 'accounts/register.html', {'user_form':user_form, 'registered': registered}) @login_required def current_user(request): current = request.user # profile = User.objects.get(username=current.username) return render(request,'accounts/profile_detail.html',{"username":current.username, "email":current.email,"id":current.id, "bio":current.bio}) I am trying to access the bio of a user. It keeps saying the field doesnt exist. What I want to do is access bio in the html file: {{ bio }} Not sure what I am missing here. Thanks -
Filter in range of two date fields
I have something like this: class Model(models.Model): start = models.DateTimeField() end = models.DateTimeField() and I want to get all models that follow the following constraints: given two query parameters qstart, qend model.end > qstart model.start < q.end which would give all Model objects that lie between in the range of the two dates. I saw you can do Model.objects.filter(date__range=[qstart, qend]) however, that operates on a single field, where as I need to operate on 2 separate fields. -
How to allow an inactive user to log in and use the /user/ endpoint
I am using rest-auth and I want to allow the users reactivate their accounts by their own. I managed to allow the inactive user to log in by using AllowAllUsersModelBackend in settings.py AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.AllowAllUsersModelBackend", ] And then I disallowed rest-auth to check respond with an error message by deleting these lines from the LoginSerializer: if not user.is_active: msg = _('User account is disabled.') raise exceptions.ValidationError(msg) I also customized the UserDetailSerializer to allow deactivation and activation by adding is_active field of the user model. Now I can log in using a deactivated user and it sends me a JWT back, but when I try to use the /user/ endpoint it respond with that error: { "detail": "User account is disabled." } I want to allow them to use this endpoint to reactivate their account but without allowing them to use any other custom endpoint that requires authentication. -
Format a float to justify to the right
I am adding a float value to the template and I am trying to get it to justify to the right. Currently, I am trying {{ float|floatformat:2|rjust }}, but it keeps throwing up a TemplateSyntaxError. Is it even possible to do this via the template system, or will I just have to use some CSS styling for this? -
Referring to forms and models in views.py with variables
When a user signs up on my site, they select a template that they'd like to see as part of the User Profile. In this case, because they want to see the 'green' profile, user.userprofile.color is equal to 1. I've built a specific model (called model1) for the green template as well as a specific form (called form1) for that model. When the user selects 'green' in the UserProfile form and submits the form, an instance of the model1 is assigned to the user automatically Within views.py, I'd like to create a generic view that takes the user.userprofile.color value and uses it to establish a) what form to serve the webpage b) what model the form is based on Rather than hardcoding the form and model value like this: def homepagetemplate(request): if request.method == 'POST': form = form1(request.POST, request.FILES, instance=request.user.model1) if form.is_valid(): form.save() return redirect('/accounts/') else: form = form1(instance=request.user.model1) args = {'form': form} return render(request, 'homepage.html', args) Within the function rather than specifying 'form1' and 'model1', I'd like form and model values to equal to 'form'+i and 'model'+i where i equals the value of user.userprofile.color (i.e. 1). Any help with this would be greatly appreciated!