Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework custom token authentication
I want a custom authentication which will authenticate the token in my model.I have a model called User_Auth where there is a field called 'secret_token'. I want the Django Rest Framework to Authenticate token through that model. I had followed the docs on django rest framework website but didnt work for me. Please help me to solve this issue. models.py class User_Auth(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User_Master, on_delete=models.CASCADE) secret_token = models.CharField(max_length=2000, null=True, blank=True) authentication.py class UserAuthentication(authentication.TokenAuthentication): def authenticate(self, request): key = request.META.get('Authorization') if not secret_token: return None try: ua = User_Auth.objects.get(secret_token=secret_token) except ua.DoesNotExist: raise exceptions.AuthenticationFailed('Unauthorized') return (ua, None) views.py class User(viewsets.ModelViewSet): authentication_classes = (UserAuthentication,) permission_classes = (IsAuthenticated,) I am passing the token through the Header. Authorization: 'Token a7c14fc808b58533e4d1651cd2375c3b41a38ef5d120254a1cb4bbd90b3be1534215516b023818e4' Still its returning { "detail": "Authentication credentials were not provided." } Please help me. -
Django: show 'Password Reset Done' page only after redirect (avoiding direct access by URL)
I am using Django's standard built-in PasswordResetDoneView and PasswordResetCompleteView to deal with the password reset workflow. I want to make my URL path password-reset/done/ to be available only after redirect, i.e.: If a customer requests password reset → redirect to password-reset/done/. If a customer enters the URL address password-reset/done/ in their browser → redirect to 404. This is only an issue of aesthetics, but I want to figure out if there is any other way to deal with that, except for using request.session. -
the import sentence got errors:from oauth2client.contrib.django_util.models import CredentialsField in models.py
I use ubuntu in AWS for deploy a django project. when I run the"python3 manage.py runserver" cmd, error occurs: from oauth2client.contrib.django_util.models import CredentialsField File "/usr/local/lib/python3.6/dist-packages/oauth2client/contrib/django_util/__init__.py", line 233, in <module> from django.core import urlresolvers ImportError: cannot import name 'urlresolvers' I use Django 3.0.11. How to solve my problem? -
Django allows model object with empty fields to be saved
Below is the model named 'Dataset' containing three fields name, desc and data_file. class Dataset(models.Model): name = models.CharField(max_length=256) desc = models.TextField() data_file = models.FileField(upload_to='datasets/') I created a model object with python command. >>> d = Dataset() >>> d.save() >>> d.name, d.desc, d.data_file ('', '', <FieldFile: None>) Django allowed this object to be saved. Even when blank = False is the default for every field. How can I may sure that dataset objects cannot be created with these three fields empty ? Below is the sqlite3 schema: CREATE TABLE IF NOT EXISTS "datasets_dataset"( "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(256) NOT NULL, "data_file" varchar(100) NOT NULL, "desc" text NOT NULL ); -
JSONDecodeError in json.loads(request.body)
I am getting JSONDecodeError in data=json.loads(request.body) cart.js: function updateUserOrder(productId, action) { console.log('User is authenticated') var url = '/update_item/' fetch(url, { method: 'POST', headers: { "Content-Type": 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({'productId': productId, 'action': action}) }) .then((response) => { return response.json() }) .then((data) => { console.log('Data: ', data) location.reload() }); } In views.py: def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] I am getting this error. JSONDecodeError at /update_item/ Expecting value: line 1 column 1 (char 0) Request Method: GET Request URL: http://127.0.0.1:8000/update_item/ Django Version: 3.1.3 Exception Type: JSONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0) Python version: Python 3.8.6 Django version: 3.1.3 I tried following other posts in stackoverflow and tried using cherrypy and various other ways for json.loads(request.body). Please resolve this error. -
Django - ask user for menuitem choices on each menu item
I am developing a simple restaurant app in django and mysql and after days of googling and research, i wasn't able to find a suitable answere for this particular problem, here is my django Model class MenuItem(models.Model): menu_category = models.ForeignKey(MenuCategory, to_field='slug', on_delete=models.CASCADE) name = models.CharField(max_length=30) image = models.ImageField(upload_to='uploads/menu/') slug = models.SlugField(null=True, blank=True, unique=True) price = models.DecimalField(max_digits=9, decimal_places=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name and here is the problem: for example i have a menuItem "MEXICAN BURGER" i would like to ask the user their choice of meat.. ie either chicken or beef, or their choice of bread, white or brown, or i might be having a MenuItem "OMELETTE COMBO" and i would like to ask the user the type of omellete they'd like to have eg ('spanish omelete', 'spinach and mushroom omelete') or i might be having a MenuItem "ESPRESSO" and i would like them to choose between ('single', 'double') one menuitem can have multitple choices related to it, ie burger item can have choice of bread as well as choice of meat -
Can I create a session login by django?
basically, I want to allow an anonymous user to login to the website and not create a profile, but can save the session if wants, and revisit anytime -
Setting an Authorization Header in Django without the use of a client
Is there a way possible to set a header in the server and not from the client? Probably an example will be me trying to set an Authorization Header with a token to the server and not from the client because the client can't access that token as it's made with a httponly cookie. Tried something in a Django view. request.META['HTTP_AUTHORIZATION'] = f'Token {....}' And it works in the sense that I can see that key and value in the header but for some reasons it seems not to work as it should be like using a client will this logic will make the request an authenticated one, but doing this from the server doesn't seem to do that.. It's like it's tricking me to believe it works by showing me the object in the header, but there is no functionality of it. -
Exclude a QuerySet from a pre-existing filtered QuerySet based on a One-to-One relationship
I have a Django application with three models: class Strategy(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ... class Version(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) strategy = models.ForeignKey(Strategy, on_delete=models.CASCADE) ... class Tool(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) version = models.OneToOneField(Version, on_delete=models.CASCADE) ... On the Tool model's corresponding ToolForm, I filter the QuerySet for the 'version' field, so that the User only sees the strategy versions they submitted: def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['version'].queryset = Version.objects.filter(strategy__user=user.id) I now want to filter this QuerySet further to exclude Versions which already have Tools. The Version to Tool relationship is One-to-One, and I only want the User to see Versions which still require Tools to be submitted. I have tried numerous approaches, but I keep coming back to versions of: Version.objects.filter(strategy__user=user.id).exclude(Tool.objects.filter(version__strategy__user=user.id).values('version_id')) Version.objects.filter(strategy__user=user.id).exclude(Tool.objects.filter(version__strategy__user=user.id).values_list('version_id')) Respectively, the responses I get are: 'dict' object has no attribute 'split' 'tuple' object has no attribute 'split' What am I missing? How can I exclude Versions from my ToolForm 'version' field that already have the One-to-One relationship established? -
Django makemigrations is creating migrations for model with managed = False
While Django documentation https://docs.djangoproject.com/en/3.1/ref/models/options/#managed mentions the use of managed = False field in meta is used to not create migrations I am still getting migrations when I call makemigrations. This is the meta of the model: class FieldOpsBooking(models.Model): . . class Meta: managed = False db_table = 'field_ops_booking' And I am getting this after makemigrations python manage.py makemigrations Migrations for 'user_analysis': user_analysis/migrations/0001_initial.py - Create model FieldOpsBooking - Create model RewardManagementLeads Migrations for 'od_engagement': od_engagement/migrations/0001_initial.py - Create model NormalisedTonnage And it creates 0001_initial.py file with all migrations to apply as well. Any help is appreciated -
How to update Django model fields in MySQL database
I created a model for posts in Django and I'm trying to update one of the fields in the database (MySQL). I have the following block of code: model.py class Post (models.Model): title = models.CharField() preamble = models.CharField() body = models.TextField () createdAt = models.DateTimeField(auto_now_add=True, blank=True) I want to add another field called author author=models.ForeignKey(User, on_delete=models.CASCADE Also, I want to change the name of one of the fields from preamble to introduction Whenever I run the command python manage.py makemigrations and then python manage.py migrate, I get an error which terminates the migration process. it's telling me that the field preamble which I have in my database is not recognized. Is it possible to update preamble to introduction? -
Django search the wrong directory for index template
Hi I'm new at Django and i have 2 app named home and blog. my home project urls.py is urlpatterns = [ path('',include('home.urls')), path('blog/',include('blog.urls')), path('admin/', admin.site.urls), ] blog apps urls.py is app_name= 'blog' urlpatterns =[ path('',views.index, name = 'index'), path('<int:post_id>/',views.postpage, name ='postpage') ] home apps urls.py is app_name= 'home' urlpatterns = [ path('', views.index, name='index'), ] and when i try to render index.html in home app, django search in blog app however it must search in home app. more detail my home views.py is def index(request): return render(request,'home/index.html') and page return TemplateDoesNotExist at / django.template.loaders.app_directories.Loader: /home/caglarbingol/Documents/Projects/caglarbingol/blog/templates/home/index.html (Source does not exist) two app have both index.html page in dir blog/templates/blog/index.html and home/templates/home/index.html what am i doing wrong? -
GETTING AN ERROR "THE SITE CAN'T BE REACHED " AFTER DEPLOYING DJANGO PROJECT ON APP ENGINE
I am following the documentation for deploying Django project on Google App Engine. And after following all the instructions and deploying the sample code provided by google cloud with command "gcloud app deploy" on Google cloud SDK I am getting an error "This site can't be reached". Please resolve my issue I really need that. -
uploading csv file into Django model
I'm working on a Django app and need to import a CSV file into the Django model. What's the proper way to get around this? I was planning to use pandas to read the CSV and then saving into models with bulk_create. But not sure if there will be any performance issues as the dataset can get bigger. Any help would be appreciated. -
how can i apply ajax to an online ide made in django?
github link:https://github.com/SkvProgrammer/online-ide-django Please help me applying ajax to this django app -
I want to subtract available_quantity to user_give_quantity
A manager stock 500 products in his stock. But when he give 400 product a SR then it will be subtract and available quantity is 100. But when manager give same product 50pics to another SR then it will be subtract from 100 to 50 and manager can see his stock has 50 products. But i cannot solve this problem. My code is : class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) distribute_price = models.IntegerField() mrp_price = models.IntegerField(null=True) created_at = models.DateTimeField(auto_now_add=True) user_give_quantity = models.IntegerField(null=True) user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) def __str__(self): return self.product.item_name def available_quantity(self): return self.product.quantity - self.user_give_quantity if all([self.product, self.product.quantity, self.user, self.user_give_quantity]) else 0 def stock_quantity(self): return self.available_quantity() - self.user.user_give_quantity if all([self.user, self.user.user_give_quantity]) else 0 def amount(self): return self.mrp_price * self.user_give_quantity -
I'm getting 'module' object is not callable in Django Rest Framework
I'm trying to learn django rest framework for an api. I'm following the documentation and checked all the imports but I'm getting the typeerror: 'module' object is not callable Views.py from rest_framework import viewsets from .serializer import CategorySerializer from .models import CategoryModel class FirstView(viewsets.ModelViewSet): queryset = CategoryModel.objects.all().order_by('name') serializer_class = CategorySerializer serializers.py from rest_framework import serializers from .models import CategoryModel class CategorySerializer(serializers.ModelSerializer): class Meta: model = CategoryModel field = ['name', 'description'] urls.py from django.urls import path, include from rest_framework.routers import DefaultRouter from . import views router = DefaultRouter() router.register(r'', views.FirstView) urlpatterns = [ path('', include(router.urls)) ] -
Aligning toast messages in javascript
I'm working on a Toast message setup where, if multiple messages are active, they're not visible except for the one in the front (so maybe a margin of 15px between them would help) and display them on the bottom-corner of the screen (fixed), which doesn't change position when scrolling and make them disappear after 3 secs one by one. How do I go about solving this with JavaScript? //dont't know how to get this working let margin = 10; function myFunction() { var type = document.getElementById("toast-" + type); type = "success", "info", "warning", "error"; setTimeout(function(){ margin += toast.clientHeight + 5; }, 3000); } .color-green{ bottom: 0; position: absolute; background-color: #40ff00; box-shadow: 4px 4px 16px 0 rgba(0, 0, 0, 0.05); margin-bottom: 10px; margin-left: 15px; z-index: 4; border-radius: 4px; padding-left: 0.4em; } .color-blue{ bottom: 0; position: absolute; background-color: #0000ff; box-shadow: 4px 4px 16px 0 rgba(0, 0, 0, 0.05); margin-bottom: 10px; margin-left: 15px; z-index: 4; border-radius: 4px; padding-left: 0.4em; } .color-orange{ bottom: 0; position: absolute; background-color: #ffbf00; box-shadow: 4px 4px 16px 0 rgba(0, 0, 0, 0.05); margin-bottom: 10px; margin-left: 15px; z-index: 4; border-radius: 4px; padding-left: 0.4em; } .color-red{ bottom: 0; left: 0; position: absolute; background-color: #ff0000; border-radius: 4px; box-shadow: 4px 4px 16px 0 … -
Django Blog Post ordering? how to arrange by column
Django blog order is in a row, how to put the order in a column? -
How do can I creating and use a custom fields in Django
I am new to django and building a kinda of a package (Shipments) based app in Django and I have these models, class ShippingLocation(models.Model): latitude = models.IntegerField() longitude = models.IntegerField() class Shipping (models.Model): email = models.EmailField() location = models.ForeignKey(ShippingLocation , default=None, on_delete=models.CASCADE ) class Package(models.Model): name = models.CharField(max_length=30) supplier = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) to = models.ForeignKey(Shipping, default=None, on_delete=models.CASCADE ) this work okay for now but I wonder if can be able to remove the ShippingLocation model and use a custom field instead of at the location field in the Shipping model? If yes how do I create custom fields and how do I implement them? -
Django probelm with actions
Hi I am new to django and I have written a code to go from one html code to another when a button is clicked.but nothing happens when I click the button. can someone help? Below I have added my whole code and any hint is appreciated. here is urls.py from django.conf.urls import url from generator import views urlpatterns = [ url(r'', views.home), url(r'^password/', views.password, name='password'), ] here is views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return render(request, 'generator/home.html') def password(request): return render(request, 'generator/password.html') here is home.html <h1>Password Generator</h1> <form action="{% url 'password' %}"> <select name="length"> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> </select> <input type="submit" value="Generate Password"> </form> password.html is PASSWORD lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll -
Django-Channels - How to block more than one connection from same client (browser)
I am making a chat app in Django-Channels. When an authenticated (means non-AnonymousUser)user opens the same URL in two different tabs,two websocket connections are made for the same user. How to block the second connection made? Is there a way in Channels to know if a user is already connected to the server or not? -
Can I make django templates work the same way they would on react js components?
Currenlty i am working on a project where i want to reuse a piece of html - Which i understand i can do with {% include tags %} However, in the same html or component, I am also loading different data for different users, where {{ user }} is the user i am passing from the main template. For instance: competition_user_chart.html (Did not put the whole code for simplicity) window.onload = function() { let user = "{{ user|remove_everything_after_hashtag }}" console.log("damage-chart-" + user) initChart("damage-chart-" + user); initChart("kda-chart-" + user); initChart("placement-chart-" + user); createChart(chartId = "#damage-chart-" + user, label = "Damage per minute", color = "#3e25cd", title = "Damage over last games", xAxisLabel = "Matches", yAxisLabel = "Damage"); createChart(chartId = "#kda-chart-" + user, label = "KDA", color = "#f542ef", title = "Damage over last games", xAxisLabel = "Matches", yAxisLabel = "KD"); createChart(chartId = "#placement-chart-" + user, label = "Placement", color = "#f542ef", title = "Placements over last games", xAxisLabel = "Matches", yAxisLabel = "Placements"); }; In the main template i have the following (competition_scores.html): {% if team.player_1 != None %} <li>{{ team.player_1 }}</li> {% include 'competitions/competition_user_chart.html' with team_name=team user=team.player_1 %} {% endif %} {% if team.player_2 != None %} <li>{{ team.player_2 }}</li> … -
'NoneType' object has no attribute 'attname'
djongo model view'NoneType' object has no attribute 'attname' python: 3.8.0, Django: 3.0.5, Djongo: 1.3.3 class MetaData(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) meta_description = models.TextField(max_length=155, default=None, blank=True) class Meta: abstract = True class Article_Categories(models.Model): slug = models.SlugField(max_length=255, unique=True, blank=True) meta_data= models.EmbeddedField( model_container=MetaData ) objects = models.DjongoManager() def __str__(self): return self.slug class Meta: db_table= 'article_categories' -
Django wrap SQL as Command
i have a question, is it possible to wrap a SQL command on Django Command ? because i have this SQL, that need to be executed during deploy update car join car_manager manager_before on car.manager_id = manager_before.id and manager_before.shortname is null join car_manager manager_after on manager_after.name = manager_before.name and manager_after.shortname is not null set car.manager_id = manager_after.id