Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
User information in a model post_save email
I have a model into I send an email each time this model is edited, with post_save, nice! I can recover fields from my model to display them in the email, good. But I would display information about the user connected, logged (username...). I tried some syntaxes, without success, please can you help me? In model.py, at the end of my model related: @receiver(post_save, sender=User) def save(self, **kwargs): text = 'Hello\n%s %s has just been edited.' % (self.first_name, self.last_name) my_from = 'webmaster@hg-map.fr' my_subject = 'Prospect Edit (from test instance, home)' email = EmailMessage(my_subject, text, my_from, to=['xxx@xxx.fr']) email.send() -
Python getting 'elementwise comparison failed' warning when trying to filter dataframe in Django views
I am trying filter some data from the inputs I got from POST data. I have a dataframe data that contains information. views.py def xpage(request): if request.method == 'POST': form = regFrom(request.POST) if form.is_valid(): category = form.cleaned_data['category'] year = form.cleaned_data['year'] month = form.cleaned_data['month'] df = data.loc[(data['category'] == category) & (data['year'] == year)] ... code continues ... But warning occurs at df: /virtualenv/lib/python3.7/site-packages/pandas/core/ops/__init__.py:1115: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison It occurs when I try to filter the data dataframe with conditions using .loc and returns an empty dataframe. When I search them myself by assigning values to category and year, the data exists. How can I solve this problem? -
How to get the name of the Foreign Key tables for a model instance in Django?
I want to get the name of the tables that are foreign key fields for my model instance. For example, I know that I can get data about my fields by using instance._meta.concrete_fields or by getting the name of fields in instance._meta.get_fields but I do not have any idea about getting the foreign keys fields table names. I wonder if you help me. -
Access Django Form Method from Template
I would like to add some logic to a form. And display data by category: class CustomerType(models.Model): type = models.CharField(max_length=100) category = models.PositiveSmallIntegerField() def __str__(self): return self.type def getCategory(self): return self.category and would like to do something like this inside template: {% if field.getCategory == 0 %} {{ field }} {% else %} ... Is there any way to achieve this? Thanks! -
How do I serve my website from two machines?
I am trying to make my systems distributed, so that I can serve my website from two machines (that is how the distributed system works). I have coded my website in Django. I want to know the steps of making my same website to be served from 2 machines. That is how will the two systems know about each other, how will they be connected and whenever a request comes in one of the server will be chosen to process the request. What software or tool should I have to join my servers and which software will accept the request in this case so that it can decide which machine to send the request to and how should the database be configured in this case? -
How can I use a login form and a register form on the same page in Django?
I am working with the forms.py file and I want to have both login and register forms on the same page. I expected Django to handle <input> ids for each form. For instance, I want a username <input> inside <form id="register_form"> to become <input ... id="register_form_username">, but it becomes <input ... id="id_username">. Now, a username <input> inside <form id="login_form"> will also become <input ... id="id_username">. Because of that, my browser prints "[DOM] Found 2 elements with non-unique id #id_username" in the developer tools console. forms.py from django import forms class LoginForm(forms.Form): username = forms.CharField(label="Username", max_length=64) password = forms.CharField(label="Password", max_length=64, widget=forms.PasswordInput) class RegisterForm(forms.Form): username = forms.CharField(label="Username", max_length=64) email = forms.CharField(label="Email", max_length=64, widget=forms.EmailInput) password = forms.CharField(label="Password", max_length=64, widget=forms.PasswordInput) confirm = forms.CharField(label="Confirm Password", max_length=64, widget=forms.PasswordInput) views.index context = { "forms": { "login": LoginForm(), "register": RegisterForm(), } } return render(request, "orders/index.html", context) index.html <form id="register_form" method="POST" action="/register"> {% csrf_token %} {{ forms.register }} <button type="submit">Register</button> </form> <form id="login_form" method="POST" action="/login"> {% csrf_token %} {{ forms.login }} <button type="submit">Login</button> </form> How can I fix this issue? -
User login and django admin not working when deploying to heroku
I recently deployed a django app to heroku. Everything works fine in my local server. But when I try to login to the django admin in the app deployed on heroku I get the error: ProgrammingError at /admin/login/ relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... I have found this answer. But I am a beginner in django and I could not understand it. Any explanation would be helpful.Thaks in advance -
reduce duplicate queries in django modelform
I have a modelform to create model instances in my function based views. When create view renders the form template, it runs 6 queries which I want to reduce. Is there any way I can reduce qs or increase model create view's performance? models.py class Teacher(models.Model): name = models.CharField(max_length=150) photo = models.ImageField(upload_to='teachers', default='teacheravatar.jpg') date_of_birth = models.DateField(blank=True, null=True) designation = models.ForeignKey(Designation, on_delete=models.CASCADE) expertise = models.ManyToManyField( to=Topic, blank=True, related_name='expert_in') mobile = models.CharField(max_length=11, blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) joining_date = models.DateField(auto_now=True) class Meta: ordering = ['joining_date', 'name'] * forms.py * class TeacherForm(ModelForm): class Meta: model = Teacher fields = ['name', 'photo', 'date_of_birth', 'designation', 'expertise', 'mobile', 'email', ] * views.py * # THIS VIEW DUPLICATES QUEREIS # AND RUNS 6 QUERIES @login_required def add_teacher_view(request): """ :param request: :return: teacher add form """ if request.method == 'POST': form = TeacherForm(request.POST) if form.is_valid(): form.save() pk = form.instance.pk return redirect('teachers:teacher_details', pk=pk) form = TeacherForm() context = {'form': form} return render(request, 'teachers/add_teacher.html', context) -
How to send data from django template to my react component
I am trying to make my first fullstack app. I am using django as backend and react as frontend. I have got a problem with sending data from django template to react component. my views.py look like this views.py ` def proba(request): view="simple view" return render(request,'index.html',{'view': view}) def index(request): return render(request,'frontend/main.html') def index3(request): return render(request,'index.html') def register(request): if request.method =='POST': user_form=UserRegistrationForm(request.POST) if user_form.is_valid(): new_user=user_form.save(commit=False) new_user.set_password(user_form.cleaned_data['password']) new_user.save() return render(request,'registration/register_done.html',{'new_user':new_user}) else: user_form=UserRegistrationForm() return render(request,'registration/register.html',{'user_form':user_form}) class EventsView(ListModelMixin, CreateModelMixin,GenericViewSet ): queryset = Events.objects.all() serializer_class=EventsSerializer ` index.html <body> <div> {% block content %} <div id="root_calendar"> <script type="text/javascript"> let a="{{view}}" console.log(a); </script> </div> {% endblock %} </div> <script src="{% static "frontend/main.js" %}"></script> </body> I would like to put {{view}} in my react component App.js App.js import React, {Component} from 'react'; import ReactDOM from 'react-dom'; import ChooseStyle from './ChooseStyle'; class App extends Component{ render(){ return ( <> <ChooseStyle /> </> ); } } ReactDOM.render(<App />,document.getElementById('root_calendar')) -
How to override the migrations of a third-party django package
All the previous answers I came across are not clear or old. I have a third-party package installed and migrations ran. Problem is the third-party package uses an Interger field to reference users(based on the assumption that the app is using the default django user), but in my case I am using a uuid for user IDs package models.py class UserDashboardModule(models.Model): title = models.CharField(verbose_name=_('Title'), max_length=255) user = models.PositiveIntegerField(verbose_name=_('user')) column = models.PositiveIntegerField(verbose_name=_('column')) order = models.IntegerField(verbose_name=_('order')) collapsed = models.BooleanField(verbose_name=_('collapsed'), default=False) ... # Migrations of third-party package operations = [ migrations.CreateModel( name='UserDashboardModule', fields=[ ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)), ('title', models.CharField(verbose_name='Title', max_length=255)), ('module', models.CharField(verbose_name='module', max_length=255)), ('app_label', models.CharField(verbose_name='application name', max_length=255, blank=True, null=True)), ('user', models.PositiveIntegerField(verbose_name='user')), ] ), ] My user model is like this class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... this setup makes it impossible to use the third-party package and I will like to maintain my uuids on users table. What I want to do is to somehow override this migration and turn the user field to a uuid instead of an interger field. PS: I have tried creating an empty migration in my users app and wrote the migration but it didn't work. -
single button that perform two or more function in django
I need a button that execute views.py method and then redirect towards specific section of same page. I was trying to perform two functions from one button. First thing is that onclick button will call the views.py method. second thing is that after the completion of views.py method it will redirect towards the specific section of same page. index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post" action="/out"> {% csrf_token %} <textarea name="edit"></textarea> <button href="#simulator" id="t" onclick="location.href={% url 'index' %}">exe</button> <label> {{text1}} </label> </form> <br><br> <br><br> <br><br> <br><br> <br><br> <br><br> <br><br> <br><br> <br><br> <div id="simulator"> <form id="form1" action="/in"> <button id="up" onclick="location.href={% url 'display'%}" >dis</button> {{test1}} abc123 </form> </div> </body> <script src="https://code.jquery.com/jquery-2.2.1.min.js"></script> </html> urls.py from django.conf.urls import url from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), url(r'^$', views.home), url(r'^out', views.index, name='index'), url(r'^in', views.display, name='display'), ] view.py from django.shortcuts import render from django.views.generic import TemplateView param = {} def home(request): return render(request, 'index.html') def index(request): a = "abc" text = request.POST.get('edit', '') param.update({'text1': text}) print(a) print(param) return render(request, 'index.html', param) def display(request): txt = "Ali Hassan" param.update({'test1': txt}) print(param) return render(request, 'index.html', param) -
How to edit child models on one page
How to edit child models on one page with the parent model? I can display a child form on the parent view, create a child record, and display it on the same parent view page. This is because I know the current parent model pk and I can show all child objects for this specific parent model. My current view looks like this: def parent_detail(request, pk): parent = get_object_or_404(models.parent, pk=pk) children = child.objects.filter(parent=pk) # I call a function that creates a new child by using forms return render(request, 'parents/detail.html', { 'parent': parent, 'children': children, 'form': form }) If I do something like this in templates {% for child in children %} {{ child.text }} <form method="post" action="" novalidate> {% csrf_token %} <button type="submit" method="POST">Edit this child</button> {% endfor %} I see the “Edit” button next to each child entry, but I failed to associate each “edit” button with the entry previous to it. I would like to have the ability to edit the paren model and its children on the same view. Thank you in advance! I spent 2 days on it.. I will really appreciate if you help me -
How to make trailing slash optional in django
I have a django app. In the app I have url like:- path('url/', views.appmain, name="main") The problem is that trailing slash is required I want to make slash optional and accessible without slash and with slash both. I checked APPEND_SLASH but can't worked. What's the solution for it. -
Django extra button in a model's changelist for Django Admin
So I want to add an extra button in my Fun model's changelist_view which when pressed, performs a function and redirects me to a new page. I don't want to have this function for every app nor do I want for every model, only the Fun model. And I will be using Django Admin to view this changelist, just a side note. Can anyone suggest anything? Thanks. -
Django REST Framework API: Unable to Get String Value of a Field
I am a beginner in Django. Right now, I am working with the APIs. I am facing a problem. I can't view the string value one of the fields, called label, at http://127.0.0.1:8000/gameapi/. Instead of seeing "label_tag": "racing", I am seeing "label_tag": [2]. Here is the screenshot: Here are my codes of serializers.py located inside gamreview folder. from rest_framework import serializers from .models import Game, Tags # class TagSerializer(serializers.ModelSerializer): # class Meta: # model = Tags # fields = ['label'] class GameSerializer(serializers.ModelSerializer): # label_tag = TagSerializer(many=True) class Meta: model = Game # fields = ['id', 'title', 'developer', 'platform'] fields = ['id', 'title', 'developer', 'platform','label_tag'] def create(self, validated_data): label_tag_data = validated_data.pop('label_tag') game = Game.objects.create(**validated_data) for tags_data in label_tag_data: Tags.objects.create(game=game, **tags_data) return Game.objects.create(**validated_data) def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.developer = validated_data.get('developer', instance.developer) instance.platform = validated_data.get('platform', instance.platform) # instance.tag = TagSerializer(read_only=True, many=True) instance.save() return instance Here are my codes of models.py under gamreview folder: from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Tags(models.Model): label = models.CharField(max_length=20) def __str__(self): return self.label class Game(models.Model): title = models.CharField(max_length=100) developer = models.CharField(max_length=100) platform = models.CharField(max_length=50, default='null') label_tag = models.ManyToManyField(Tags) slug = models.SlugField(max_length=150, default='null') def __str__(self): return self.title def … -
save Blob to video file in database Django Rest Api
i am receiving a blob file from front end and want to save it into db in video format here is my views.py class VideoUploadViews(APIView): permission_classes = (IsAuthenticated, ) parser_classes = (MultiPartParser, FormParser ) def post(self, request, *args, **kwargs): try: # file = request.data['video'] # print(file) serializer = VideoSerializer(data=request.data) print("serializer", serializer) if serializer.is_valid(): res = serializer.save() if res: json = serializer.data # print("json", json) json['message'] = 'Video Uploaded Successfully' return Response(json, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except: print('no file') i am able to save the file into native blob format but i want it to be a video file. i don't know how to convert a blob to file format(video), please guide... any help will be appreciated... thanks in advance -
Get Current Sub Category MPTT In Django Template
My views: def categorylist(request): categorynodes = Category.objects.add_related_count(Category.objects.all(), Categories, 'category') context = { 'categorynodes': categorynodes, } return render(request, 'categorylist.html', context) def subcategory(request): categorynodes = Category.objects.add_related_count(Category.objects.filter(level__lte=1), Categories, 'category') context = { 'categorynodes': categorynodes, } return render(request, "subcategory.html", context) I have categorylist.html template: {% recursetree categorynodes %} <ul> {% if node.is_root_node %} <a href="{{ node.slug }}">{{ node.title }}</a> {% elif node.is_child_node and not node.is_leaf_node or node.is_second_node %} <a href="{{ node.slug }}">{{ node.title }}</a> {% endif %} {% if not node.is_leaf_node %} <li> {{ children }} </li> {% endif %} </ul> {% endrecursetree %} And I have subcategory.html template: {% recursetree categorynodes %} {% if node.is_root_node %} <h1>{{ node.title }}</h1> {% endif %} {% endrecursetree %} The tree of categories showing properly: Category1 Sub Category1.1 Sub Category1.2 Category2 Sub Category2.1 Sub Category2.2 How to print the title "Sub Category2.2" when I access link of Sub Category2.2 from categorylist.html? Right now, it showing same "Sub Category1.1" for all Sub Category. -
i am trying to deploy my django app but i get the following error
ValueError at / source code string cannot contain null bytes Request Method: GET Request URL: http://kratos224.pythonanywhere.com/ Django Version: 2.2.7 Exception Type: ValueError Exception Value: source code string cannot contain null bytes Exception Location: in _call_with_frames_removed, line 219 Python Executable: /usr/local/bin/uwsgi Python Version: 3.7.5 Python Path: ['/var/www', '.', '', '/var/www', '/home/Kratos224/.virtualenvs/myenv/lib/python37.zip', '/home/Kratos224/.virtualenvs/myenv/lib/python3.7', '/home/Kratos224/.virtualenvs/myenv/lib/python3.7/lib-dynload', '/usr/lib/python3.7', '/home/Kratos224/.virtualenvs/myenv/lib/python3.7/site-packages', '/home/Kratos224/CS_Dojo'] Server time: Sat, 30 Nov 2019 10:32:48 +0000 -
Trying to set up urls.py to direct to index.html
As the question implies, I am trying to set up my urls.py file to point towards my index.html file. Here is the structure of my project: -->mysiteX ---->.idea ---->mysite ------->migrations __init__ admin.py apps.py models.py test.py views.py ---->mysiteX -------->templates index ---->css ---->fonts ---->js ---->vendors __init__ settings urls wsgi ----->venv db.sqlite3 manage This is what my urls.py file looks like from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^index/', admin.site.urls), ] my views.py file from __future__ import unicode_literals def index_file(request): return render(request, "index.html") settings.py: import os, sys abspath = lambda *p: os.path.abspath(os.path.join(*p)) PROJECT_ROOT = abspath(os.path.dirname(__file__)) sys.path.insert(0, PROJECT_ROOT) TEMPLATE_DIRS = ( abspath(PROJECT_ROOT, 'templates'), ) When I run manage.py I get this page -
Django rest framework-delete user but Table doesn't exist
image to show error Hello, everybody, this is my first post. I tried to delete a user by using user.delete(). However, it didn;t find user from table auth_user. It looked for user from project.appname_user. I didn't create model user in my app and i writed "from django.contrib.auth.models import User" in top of my view file. here are all my code from django.contrib.auth.models import User from .head import * class UserDeleteView(APIView): def get(self, request): try: user_id = self.request.query_params.get('user_id') user = User.objects.get(id=user_id) user.delete() return Response(Return_msg()) except User.DoesNotExist: return Response(Return_msg(None, True, 'Failed, user does not exist!!!')) so, how can i fix it??? -
Update the text for making progress bar using Django
To show the progress on the web using Django, I want to show the progress using text on the web. In the code, there are few functions, I want to update the text on the web right after the function is completed I wonder, How can I solve this problem, is it possible to solve this problem by changing the code in views.py? [views.py] def post_list(request): print("start") functionA() print("function A is done") functionB() print("function B is done") return render(request, 'blog/post_list.html', {'posts' : "function A is Done}) Expected outcome: On web "Start" => function A is running => "Function A is done" => function B is running => "Function B is done" -
Django sending data to another server to start scraping with python
So I have this problem which I can't figure out how to go about it. I would be glad if someone can give me the best approach to solving the problem before I start writing the code. As they say, "First Solve The Problem Then Write The Code". Here is the problem. I want to have my django app in serverA e.g example.com - So registered users can post or start a scraping task. For example a user would fill a city form by entering say New York and on save or clicking start task, the data is sent to domain.com/user_base64_string/?property=New%20York which is a different server. domain.com accepts this request and trigger the python scraping script. On doing so the User would not be able to start another scraping task if he has 2 or 3 unfinished tasks running. During the scraping, domain.com sends status data using a get request to the example.com which get stored in database so user can running task, number of properties found. And of course see when task is completed. domain.com been server2 or scraping server stores the files locally and when would send it back to the user in example.com on request so it … -
Images(Media) not displaying on django-heroku server
I had uploaded my site Django app on Heroku server when I upload image file is successfully uploaded and image path as per settings also fetch properly but the image is not displaying it give error media file not found in a server this is settings media setting MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') this is in url.py urlpatterns = [ path('admin/', admin.site.urls), path('',include('UserView.urls')), path('caterer/',include('CaterView.urls')), ] # if settings.MediaAllow: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) this is models.py class TypeofFood(models.Model): tyf_id = models.AutoField(primary_key=True,auto_created=True) tyf_value = models.CharField(max_length=256) tyf_image = models.ImageField(upload_to="typeoffood/", null=True, blank=True,default='default.jfif') in template it fatch image like this <center><img src="{{i.tyf_image.url}}" class="img-responsive" style="height: 200px; width: 200px; border-radius:50%" alt="Image of Caterers"></center> -
Django API: Problem with Displaying a Field
I am a beginner in Django. Right now, I am working with the APIs. I am facing a problem. I can't view one of the fields, called label, at http://127.0.0.1:8000/gameapi/. Here is the screenshot: Here are my codes of serializers.py located inside gamreview folder. from rest_framework import serializers from .models import Game, Tags class TagSerializer(serializers.ModelSerializer): class Meta: model = Tags fields = ['label'] class GameSerializer(serializers.ModelSerializer): # label_tag = TagSerializer(many=True) class Meta: model = Game fields = ['id', 'title', 'developer', 'platform'] fields = ['id', 'title', 'developer', 'platform','label_tag'] def create(self, validated_data): label_tag_data = validated_data.pop('label_tag') game = Game.objects.create(**validated_data) for tags_data in label_tag_data: Tags.objects.create(game=game, **tags_data) return Game.objects.create(**validated_data) def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.developer = validated_data.get('developer', instance.developer) instance.platform = validated_data.get('platform', instance.platform) instance.tag = TagSerializer(read_only=True, many=True) instance.save() return instance Here are my codes of models.py under gamreview folder: from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Tags(models.Model): label = models.CharField(max_length=20) def __str__(self): return self.label class Game(models.Model): title = models.CharField(max_length=100) developer = models.CharField(max_length=100) platform = models.CharField(max_length=50, default='null') label_tag = models.ManyToManyField(Tags) slug = models.SlugField(max_length=150, default='null') def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) class Review(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) review = models.CharField(max_length=1000) date = … -
Cannot use User in Django Rest Framework Custom Request middleware using JWT token after created new middleware
I want to use request.user in Django Rest Framework custom middleware. It returns AnnonymousUser and I failed. I created new Custom middleware which returns real user. from django.contrib.auth.middleware import get_user from django.utils.functional import SimpleLazyObject from rest_framework_jwt.authentication import JSONWebTokenAuthentication class AuthenticationMiddlewareJWT(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): request.user = SimpleLazyObject(lambda: self.__class__.get_jwt_user(request)) return self.get_response(request) @staticmethod def get_jwt_user(request): user = get_user(request) if user.is_authenticated: return user jwt_authentication = JSONWebTokenAuthentication() if jwt_authentication.get_jwt_value(request): user, jwt = jwt_authentication.authenticate(request) return user Above middleware, jwt_authentication.get_jwt_value(request), this returns always None. How can I fix it and use request.user in custom middleware?