Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Upgrading Django 1.11 to 2.2 - Crispy form troubles
I've recently upgraded a project from Django 1.11 to 2.2, alongside upgrading all the necessary packages and python 3.5 to 3.7. I've managed to fix everything that needed to be changed to upgrade to 2.2 django. Among other packages I've also upgraded django-crispy-forms from 1.6 to 1.9 to be compatible with Django 2.2. The problem I am facing is that, my SplitDateTimeWidget I am using in all crispy forms across the project is not displaying properly. It is not utilizing bootstrap3 style as display below: Has anyone else faced with this issue when upgrading and what are the workoarounds? Thank you! -
TypeError at /accounts/register save() missing 1 required positional argument: 'self'
my error code is: save() missing 1 required positional argument: 'self' the exception loader shows the following message: E:\coding\fyp\travel\accounts\views.py in register, line 23 my views.py looks like: from django.shortcuts import render,redirect from django.contrib.auth.models import User # Create your views here. def register(request): if request.method=='POST': first_name=request.POST['first_name'] last_name=request.POST['last_name'] username=request.POST['username'] password1=request.POST['password1'] password2=request.POST['password2'] email=request.POST['email'] if password1==password2: if User.objects.filter(username=username).exists(): print("usernmae taken") return redirect('/') elif User.objects.filter(email=email).exists(): print("email taken") return redirect('/') else: user=User.objects.create_user(username=username,password=password1,email=email,first_name=first_name,last_name=last_name) line 23:- User.save() print("user created") return redirect('/') else: print("passwords not matching") return redirect('/') else: return render(request,'register.html') -
Django-rest-framework {"detail": "Authentication credentials were not provided." } using django-rest-knox
This is the code I am using for Login My Model: class User(AbstractBaseUser): STUDENT = 'STU' SCHOOL = 'SCH' INSTITUTE = 'INST' TUTOR = 'TUT' ACCOUNT_TYPE_CHOICES = [ (STUDENT, 'Student'), (SCHOOL, 'School'), (INSTITUTE, 'Institute'), (TUTOR, 'Tutor'), ] account_type = models.CharField( max_length=4, choices=ACCOUNT_TYPE_CHOICES, default=SCHOOL, ) name = models.CharField(max_length=255) email = models.EmailField(unique=True,max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name','account_type'] objects=UserManager() def __str__(self): return self.email def has_perm(self,perm,obj=None): return True def has_module_perms(self,app_label): return True @property def is_staff(self): return self.is_admin My serializers: from rest_framework import serializers from .models import User from django.contrib.auth import authenticate # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'account_type', 'name', 'email') # Login Serializer # I guess the validate function is not working . class LoginSerializer(serializers.Serializer): email = serializers.EmailField() password = serializers.CharField() def validate(self, data): user = authenticate(request=None,**data) if user and user.is_active: return user raise serializers.ValidationError("Incorrect Credentials") My Views: from rest_framework import generics, permissions,authentication from rest_framework.response import Response from knox.models import AuthToken from knox.views import LoginView as KnoxLoginView from .serializers import UserSerializer, RegisterSerializer, LoginSerializer from django.contrib.auth import authenticate,login # Login API class LoginAPI(generics.GenericAPIView): serializer_class = LoginSerializer # authentication_class=[authentication.BasicAuthentication] def post(self, request, *args, … -
Avoid circular reference when two columns in one table point to primary key in another table
I have two tables. First is Users table and second is Referrals table. Referrals table looks like this: | Referrals table columns | Points to | ----------------------- | --- | new_customer_id | user table's primary key | referred_by | user table's primary key The requirement is that if Person B (ID: 2) is referred by Person A (ID: 1), we should not be able to insert the other way around. In other words, the table should not have data like this: | new_customer_id | referred_by | | --------------- | ----------- | | 2 | 1 | <-- OK | 1 | 2 | <-- Both people refering each other should not be allowed Is it possible to check this during insert on database level. I'm using mysql. I read a bit about mysql CHECK constraint here, but cannot figure out how to implement this. I'm using django ORM and here is what I have tried but failed. class Referrals(models.Model): customer = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, db_index=True) referred_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, db_index=True) class Meta: constraints = [ models.CheckConstraint(check=models.Q(customer__lt=models.F('referred_by')), name='referrer_should_come_before_referee') ] If it is not possible with Django ORM but possible in database level with some query, that's fine also. However, +1 for django … -
Django form get_or_created with 3 different variable
I'm trying to created or update a django form. There's 3 unique identifier in that form, NRIC, MRN or Passport. User can fill any or all of them. the problem is how do I check with the database whether I need to create or update an existing one. so my code is like this: if request.method == 'POST': form = PatientForm(request.POST) if form.is_valid(): nric = form.cleaned_data['nric'] mrn = form.cleaned_data['mrn'] passport = form.cleaned_data['passport'] try: if nric: #if user filled in nric, check database by nric patient = Patient.objects.get(nric=nric) patient.nric = nric if mrn: patient = Patient.objects.get(mrn=mrn) patient.mrn=mrn if passport: patient = Patient.objects.get(passport=passport) patient.passport = passport patient.name = form.cleaned_data['name'] patient.save() except Patient.DoesNotExist(): form.save() The problem start when user filled another 1 of those 3 unique identifier, eg: there's already a record with Passport = 34234234, then user filled another MRN with new value..so 2 of 3 fields now have values, it will fail the check because of object.get(mrn=mrn). any ideas on how can I solve this? Thanks -
Multiplayer game using Django
I'm trying to know if it is possible or not to create an online multiplayer game using Django framework, python socket for TCP connection and Javascript for the animations. Is it possible to handle different server for each game launched? Write the functional script in python and using it with Javascript? I read a lot about Node.JS and this seems to be a much more suitable solution however I didn't use it yet. If this is the best solution, how many time do you think it will take to learn the basics of this framework? Thanks a lot for your help it is very appreciated. :) -
Extract image tag from content of database using django
I have this type of content stored in the database. This is saved via ckeditor. There are two ways to invoke the API: Sending HTTP requests and parsing the responses. Using........................................ What I want is to display the image only, in somewhere else in the same Django project. Is there any way to extract image only and display in my view file or what will be the best solution? Can I extract the path of image and display it ? So, how to extract the image tag from the content? It will be appreciated if someone helps. I am new to Django. -
Does fetch api in javascript send a get request if the post request fails
I was trying to build a Django app with javascript in the frontend. The POST request from the fetch API was failing if I did not add the CSRF token in the headers. However, it sent a GET request instead. When I added the CSRF token, it worked normally. But in the future, I want to avoid sending GET requests in case the POST fails. It is the default behavior? How do I prevent it? -
Django - Login required for specific user type
I extended the user login from Django with AbstractUser like this: class User(AbstractUser): pass class Seller(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) verified = models.BooleanField(default=False) money = models.IntegerField(default=0) def __str__(self): return str(self.user) I would like now to create a view and a form that can only be access by the "Seller" user, like this in views.py: @login_required def account(request): return render(request= request, template_name='main/account.html', context = {}) Any idea on how can I do it? Thank you -
Django. Language prefix in URL patterns
Language prefix in URL patterns I have done Translation of the website in 2 languages. It reads the language setting of the browser and automatically switches to the correct language. I want to add a language menu to the website and language prefix in URL patterns. Sorry, I have here difficulties and earnestly speaking do not understand what needs to be changed in the main urls.py. I am talking about this application only app_name = 'rsf' Please help. main urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.i18n import i18n_patterns urlpatterns = [ path('auswertung/', include('auswertung.urls')), path('rsf/', include('rsf.urls')), path('admin/', admin.site.urls), ] local urls.py from django.contrib import admin from django.urls import path from . import views app_name = 'rsf' urlpatterns = [ path('f_size_water/', views.f_size_water, name = 'f_size_water'), path('f_size_water_fin/', views.f_size_water_fin, name = 'f_size_water_fin'), ] Thank you -
error while installing virtual environment
I'm following official django tutorial on their webpage. When I run command "py -m pip install virtualenvwrapper-win", I get the the following errors. Please see the screenshot. I have Anaconda installed. The same error occurs on my other computer where I have only Python installed. What am I missing? Thanks -
i am using crispy for django and my success message works properly but my validation error messages show normal black text when it should be in red
so when i fill the login info correctly i get a message 'successfully added (username)' but when i fill in the wrong info i just shows plain black text but i want it to show error message in red color the tutorial .I followed a tutorial (by correy schafers) exactly the same but somehow i cant get the error message to show up in red color but my my success message shows up in green. register.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already Have An Account? <a class="ml-2" href="#">Sign In</a> </small> </div> </div> {% endblock content %} base.html {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> {% if title %} <title>Django Blog - {{ title }}</title> {% else %} <title>Django Blog</title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div … -
TWILIO API ERROR Credentials are required to create a TwilioClient django
I am trying to include TWILIO API to my project. It should send sms. I have finished tutorial, but then i get error Credentials are required to create a TwilioClient. I have credentials in .env file and then i try to import them to settings and then get this credentials from settings to views. This is when i get error. .env TWILIO_ACCOUNT_SID= 'xxxxxxxxxxxxxxxxxxxxxx' TWILIO_AUTH_TOKEN= 'xxxxxxxxxxxxxxxxxxxxxxx' TWILIO_NUMBER= 'xxxxxxxxxxxxxxxxxx' settings.py import os TWILIO_ACCOUNT_SID = os.getenv('TWILIO_ACCOUNT_SID') TWILIO_AUTH_TOKEN = os.getenv('TWILIO_AUTH_TOKEN') TWILIO_NUMBER = os.getenv('TWILIO_NUMBER') SMS_BROADCAST_TO_NUMBERS = [ '+111111111', ] views from django.conf import settings from django.http import HttpResponse from twilio.rest import Client def broadcast_sms(request): message_to_broadcast = ("Have you played the incredible TwilioQuest " "yet? Grab it here: https://www.twilio.com/quest") client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN) for recipient in settings.SMS_BROADCAST_TO_NUMBERS: if recipient: client.messages.create(to=recipient, from_=settings.TWILIO_NUMBER, body=message_to_broadcast) return HttpResponse("messages sent!", 200) and here is when code work, but i want to import this from settings.. # def sms(request): # TWILIO_ACCOUNT_SID = "xxxxxxxxxxxxxxxxxxxxxxx" # TWILIO_AUTH_TOKEN = "xxxxxxxxxxxxxxxxx" # TWILIO_NUMBER = "xxxxxxxxxxxxx" # message_to_broadcast = ("Have you played the incredible TwilioQuest " # "yet? Grab it here: https://www.twilio.com/quest") # # client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) # for recipient in settings.SMS_BROADCAST_TO_NUMBERS: # if recipient: # client.messages.create(to=+xxxxxxxxx, # from_=+xxxxxxxxxx, # body=message_to_broadcast) # return HttpResponse("messages sent!", 200) … -
Python Django - HTML for REST API JSON data in Async
I am making a Django web app. So far I have used templates for creating HTML in response to a POST request. I use 'context' to pass data to the template and fill the HTML with that data. This does not require any client-side work. Now I added a REST API to the app to be used Async, and I want all data to be processed by the API and return only in JSON format. This creates a problem, I cant use the templates anymore since I can't use 'context' to fill in the data in the HTML, I have to use client-side JS to do the filling but now I am missing the HTML appropriate to the data received. What are the ways in Django for generating HTML for an API JSON response in Async architecture? Are there any solutions, frameworks, JS libraries? I do not want to return HTML via API to keep things client mobile app/browser independent. -
Why I can't pass categories to my template in Django
I have a header.html file in my partials under template directory. I have a section for categories which I need to fetch from database. Therefore, I've created a custom templatetag in my app folder. I have written the tag for the latest dropdown article and categories. Well, somehow the articles are being fetched from the database but categories are not. models.py from django.db import models from django.utils.text import slugify from django.urls import reverse from ckeditor_uploader.fields import RichTextUploadingField from datetime import datetime class Category(models.Model): label = models.CharField(max_length=15, unique=True) def __str__(self): return self.label class Article(models.Model): title = models.CharField(max_length=80, unique=True, help_text='Max Length: 80') category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) banner_image = models.ImageField(upload_to='photos/%Y/%m/%d/', help_text='Banner Image', default=None) description = models.TextField(max_length=200 ,help_text='Short descirption about the post') content = RichTextUploadingField(help_text='Site Content') published = models.BooleanField(default=True) date_created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) views = models.BigIntegerField(default=0) featured = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse('article', kwargs={'category': self.category, 'post': self.title}) my custom tempalte tag from django import template from articles.models import Article, Category register = template.Library() @register.inclusion_tag('partials/_header.html') def recent(): category = Category.objects.all() #not being fetched recents = Article.objects.filter(published=True).order_by('-date_created')[:9] trendings = Article.objects.filter(published=True).order_by('-views')[:9] return { 'recents': recents, 'trendings': trendings, 'category': category, } ** my header.html file ** <div id="asmCategoryContents" class="asm-Category_Contents"> {% for cat … -
Compare the new and old field values in django, then update the old value
In the data is being pulled from the URL. Which is being stored in the database. Now I would want to only update the data that is being changed. hostandservicelisturl = 'http://192.168.232.133/query=servicelist' userpwd = ('xxx', 'xxx') data7 = requests.get(hostandservicelisturl,auth = userpwd).json() data8 = data7['data']['servicelist'] mylistik1 = [] for ik1 in data8: print(ik1) mylistik1.append(ik1) for x in mylistik1: for y in data8[x]: print(y) z = data8[x][y] Data.objects.update_or_create(hostname=ik1,service=y,servicestatus=z) class Data(models.Model): hostname = models.CharField(max_length=200, null=True, editable=False) service = models.CharField(max_length=200, null=True, editable=False) servicestatus = models.IntegerField(null=True, editable=False) Value In URL: "linksys-srw224p": { "PING": 2, "Port 1 Bandwidth Usage": 8, "Port 1 Link Status": 16, "Uptime": 16 Note : the number like 2 8 16 changes accordingly from the api pull. As of now i have seen field tracker() with pre save but I am not able to figure out how too as the documentation is not clear. -
i want to download number of media like 10 or 20 downloads per request but dont know how?
posts = [] links = driver.find_elements_by_tag_name('a') for link in links: post = link.get_attribute('href') if '/p/' in post: posts.append(post) print(posts) download_url = '' for post in posts: driver.get(post) shortcode = driver.current_url.split("/")[-2] type = driver.find_element_by_xpath('//meta[@property="og:type"]').get_attribute("content") if type == 'video': download_url = driver.find_element_by_xpath('//meta[@property="og:video"]').get_attribute("content") urllib.urlretrieve(download_url, '{}.mp4'.format(shortcode)) else: download_url = driver.find_element_by_xpath( '//meta[@property="og:image"]').get_attribute("content") urllib.urlretrieve(download_url, '{}.jpg'.format(shortcode)) print(download_url) -
django-admin startproject doesn't do anything
I use command "django-admin startproject myapp" and it doesn't do anything When I use this command again it says "CommandError: 'C:\Users\User\Desktop\djangotest2\myapp' already exists" I tried disabling my antivirus and I tried using absolute path to django-admin.py and django-admin.exe file -
Python HTTP server for shell commands
I look for Python package to expose shell command from a linux server. At this moment I use Django and ThreadPoolExecutor to asynchronously launch submit execution. Clients receives job id and 202 Accepted as HttpResponse. It feels like i re-invent a wheel. Is there python3 framework which can help me to expose and orchestrate running commands on a server through HTTP? launch a shell command by triggering http endpoint (returns 202 and launch-id) commands must run asynchronously and will have own side-effects (e.g. write something to db) obtain status of running command by launch-id log stderr and stdout of subprocess so later i can find the output in logs -
Stripe Variable amount checkout & Django
I am trying to implement variable amount checkout using Stripe, so that users can donate a chosen amount. The donation should then link to a customer id created using dj stripe (set up for recurring donations). So far, I have got the follwoing, however currently clicking the donate button does not load the stripe checkout page Views.py: customer, created = djstripe.models.Customer.get_or_create(subscriber=user) @require_http_methods(['POST']) def create_singlesession(): #read request data data = json.loads(request.data) # create checkout session with API api_key=stripe_key, session = stripe.checkout.Session.create( customer=customer.id, success_url='charity_app/success?id={CHECKOUT_SESSION_ID}', cancel_url='charity_app/cancel?id={CHECKOUT_SESSION_ID}', payment_method_types = ['card'], submit_type = 'donate', line_items = [{ 'amount': data['amount'], 'currency': 'gbp', 'quantity': 1, 'name': 'Single Donation', 'images': [], }], payment_intent_data = { 'metadata': { 'Charity': data['Organisation'], }, }, metadata={ 'Charity': data.get('Organisation') } ) return JsonResponse(session) Session.sync_from_stripe_data(create_singlesession) urls: url(r'^create-singlesession/$',views.create_singlesession,name='create_singlesession'), Template: <button id="donate-button">Donate</button> <script src="https://js.stripe.com/v3/"></script> <script charset="utf-8"> var stripe = Stripe('pk_test_jcFUmV2P0IREALGYggK6w2tT007W8QUaqd'); var amount = document.getElementById('amount-input'); var charity = document.getElementById('charity'); var button = document.getElementById('donate-button'); button.addEventListener('click', function(e) { /*alert( "Handler for .click() called." );*/ e.preventDefault(); createSessionAndRedirect(); }); function createSessionAndRedirect() { // 1. Pass the amount and organisation to server to create session fetch('/charity_app/create-singlesession/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ amount: amount.value, cause: charity.value, }), }) .then((response) => response.json()) .then((session) => { // 2. Redirect to … -
How to correct repeating code in view-functions?
I looked at one Django course on a site that starts with the letter U and at the end I have such a code. There is a lot of duplication and I show just one of them. On each page, I publish the same type of information, it hurts to look at it. So while I thought about two solutions to fix this: Create Global Variables Define a function that will return all these duplicate variables main.view def home(request): ''' index.page ''' site, _ = Main.objects.get_or_create(pk=1) # (1) news = News.objects.all().order_by('-pk') # (2) subs = SubCat.objects.all() # (3) lastNews = News.objects.all().order_by('-pk')[:3] popNews = News.objects.all().order_by('-show') bottomPopNews = News.objects.all().order_by('-show')[:3] # (5) trends = Trending.objects.all().order_by('-pk') # (6) # group Subcategories in each Category tags = SubCat.objects.values('catid', 'catid__name').order_by('catid').annotate(count=Count('catid')) # (4) Tracker.objects.create_from_request(request, site) return render(request, 'front/home.html', {'site' : site, 'news' : news, 'tags' : tags, 'subs' : subs, 'lastNews':lastNews, 'popNews' : popNews, 'bottomPopNews':bottomPopNews, 'trends':trends}) def about(request): ''' About page ''' site, _ = Main.objects.get_or_create(pk=1) # (1) popNews = News.objects.all().order_by('-show')[:3] news = News.objects.all().order_by('-pk') # (2) subs = SubCat.objects.all() # (3) bottomPopNews = News.objects.all().order_by('-show')[:3] # (5) tags = SubCat.objects.values('catid', 'catid__name').order_by('catid').annotate(count=Count('catid')) # (4) trends = Trending.objects.all().order_by('-pk') return render(request, 'front/about.html', {'site' : site, 'popNews':popNews,'bottomPopNews':bottomPopNews,'tags':tags,'subs' : subs,'news' : news,'trends':trends,}) def … -
Update nested field if a path to it isn't constant
I'm working on Django which uses MongoDB. One of collections has the following structure: { "inspectionType" : { "id" : "59a79e44d12b52042104c1e8", "name" : "Example Name", "inspMngrsRole" : [ { "id" : "55937af6f3de6c004bc42862", "type" : "inspectorManager", "is_secret_shoper" : false } ], "scopes" : { "56fcf6736389b9007a114b10" : { "_cls" : "SomeClass", "id" : "56fcf6736389b9007a114b10", "name" : "Example Name", "category" : "Example Category" }, } } } I need to update field "_cls" ("inspectionType.scopes.._cls") for all documents in the collection. The problem is the scope_id is dynamic and unique for each scope. Is it possible to use db.collection.update for that? And how should the path to the field look like? -
Проблема с созданием миграций для Django 2.11 [closed]
Стартанул новый проект на Django 2.11. Из кастомных моделей ничего еще не успел сделать. Создал только первое приложение, прописал базовые настройки (http://joxi.ru/ZrJ9zN4CMN7pMA). Пробую накатить базовые миграции Django командой python manage.py migrate. Получаю ошибку: File "E:\DjangoEnv\api_for_django22_env\lib\site-packages\django\apps\registry.py", line 155, in get_app_config return self.app_configs[app_label] KeyError: 'accounts' "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'accounts.Accounts' that has not been installed -
How to implement Django Form Live Validation?
Are there any packages to perform client-side validation over django forms? I'm Not really experienced with AJAX and Javascript. -
Custom User Authentication using DRF
Want to create a Web RESTful API with Django. For that I'm using Django REST Framework. What are the necessary steps to get the authentication using a custom User model (subclassing AbstractBaseUser) exposing the endpoints to be used?