Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to sum FloatFields in django models
I am trying to sum 4 FloatField models (cow1,2,3&4) and put their result in sum. Here's my models.py: from django.db import models class cow(models.Model): date = models.DateTimeField(auto_now_add=True, null=True) time = models.CharField(max_length=200, null=True) cow1 = models.FloatField(null=True, blank=True) cow2 = models.FloatField(null=True, blank=True) cow3 = models.FloatField(null=True, blank=True) cow4 = models.FloatField(null=True, blank=True) sum = models.FloatField(null=True, blank=True) def save(self): self.sum = self.cow1 + self.cow2 + self.cow3 + self.cow4 return super(cow, self).save() def __str__(self): return str(self.date.strftime("%d-%m-%Y")) + ", " + self.time Here's what I get: Little help pls, THANKS! -
How to use ModelManager to update ForeignKey relations
here are some models. class Library(models.Model): id = Models.AutoField(primary_key=True) books = models.ManyToManyField(Book) class Book(models.Model): id = Models.AutoField(primary_key=True) status = models.CharField(max_length=1, choices=STATUS_CHOICES, default=STATUS_IDLE) uuid = models.UUIDField(default=uuid.uuid4, unique=False) updated_at = models.DateTimeField(auto_now=True) These are the tables to explain problem better Book id status updated_at uuid 1 Ready 2020-12-14 15:10:08 20e125fc4cff4d5398a485cf43c502a0 2 Idle 2020-12-13 14:43:03 20e125fc4cff4d5398a485cf43c502a0 3 Ready 2020-12-12 13:34:11 20e125fc4cff4d5398a485cf43c502a0 4 Done 2020-12-11 13:11:34 bc191c9d71054b6282f0371538171774 5 Done 2020-12-10 12:50:17 bc191c9d71054b6282f0371538171774 Library_books id library_id book_id 1 15 1 I have many books with the same uuids and they have unique id's. My Models has more fields than I wrote above but I just simplified them. What I want to do is to change status of a last updated Book among same uuid using library_id. I tried this: Get book_id with library_id. Get uuid with the book_id that you've got in step1 Get all book_ids which have some uuid Find last updated one. Change status this is how I do currently: class SomeLibraryLogic(): def __init__(self, library): self.library = library def update_book_status(self): updated_book_list = [] books = self.library.books.all() for book in books: updated_book = Book.objects.filter(uuid=books.values_list("uuid").get()[0].last()) updated_book_list.append(updated_book) if len(updated_book_list) != 0: self.Library.cases.set(updated_book_list) self.task.save() This seems very dirty to me. Is it the most optimal way to do … -
Django Get Logged In User Info Outsides Views.py
I have been working on DRF. I usually prefer writing business logic on another python file rather than views.py. I tried to get current logged in user in views.py using self.request.user But I don't know how can I get same user info in my business logic file here is what I have came upto now in Views.py class AddBusCompanyStaffView(generics.CreateAPIView): serializer_class = AddBusCompanyUserSerializer def get_bus_company(self): return GetBusCompanyUseCase(bus_company_id=self.kwargs.get('bus_company_id')).execute() def perform_create(self, serializer): print(self.request.user) return AddBusCompanyUserUseCase(serializer=serializer, bus_company=self.get_bus_company() ).execute() I want user in my business logic section here -->usecases.py User = get_user_model() class AddBusCompanyUserUseCase(BaseUseCase): """ use this to add bus company of specific bus company """ def __init__(self, serializer: bus_company_user_serializers.AddBusCompanyUserSerializer, bus_company: BusCompany): self.serializer = serializer self._data = serializer.validated_data self._bus_company = bus_company def execute(self): self._factory() def _factory(self): user_position = self._data.pop('position') user_password = self._data.pop('password') user = User(**self._data) user.set_password(user_password) user.save() bus_company_user=BusCompanyStaff(user=user, position=user_position, staff_of=self._bus_company, created_by= #logged in user here ) how can I get self.request.user in created_by? -
Django view isn't redirecting to another page
I'm trying to redirect to another page from view, but it isn't working. My View is as follows: @csrf_exempt def detail(request, tconst): movie = get_object_or_404(Movie, tconst=tconst) #for rating if request.method=="POST": print("In Post") rating = request.POST.get('rating') ratingObject = Myrating() print(rating) ratingObject.user = request.user ratingObject.movie = movie ratingObject.rating = rating ratingObject.save() return redirect('home') return render(request, 'web/detail.html', {'movie':movie}) Here, my view should have redirected me to the home view but it's not happening. My URL patterns are as follows: urlpatterns = [ path('', views.home, name='home'), path('<int:tconst>/', views.detail, name='detail') ] I tried to see if there is any error but my console isn't showing any error, Console output is as follows: [17/Dec/2020 14:56:08] "GET /4/ HTTP/1.1" 200 5330 In Post 4 [17/Dec/2020 14:56:12] "POST /4/ HTTP/1.1" 302 0 [17/Dec/2020 14:56:12] "GET / HTTP/1.1" 200 10374 Please help me in solving this issue! -
python2.7 use package which python3.x could suppoet
I have a django program which developed by python2.7。but a new requirement needs a package that python3.x can support.How could I do? -
A choice in previous question is unchecked if the user move to the next question and select a choice
I am new to Django and HTML! I am currently implementing a questionnaire form. In the questionnaire URL, it shows questions and choices well. However, if the user moves to the next question and clicks a choice, the choice in the previous question is unchecked. Below is my questoinnaire.html code. {% if latest_question_list %} <form action="{% url 'results' %}" method="post"> <ul> {% for question in latest_question_list %} {% csrf_token %} <fieldset> {{forloop.counter}} {{ question.question_text }} <hr> {% for choice in question.choice_set.all %} <input type="radio" name= "choice" id="choice{{forloop.counter}}" value={{choice.id}}> <label for="choice{{forloop.counter}}">{{choice.choice_text}}</label><br> </hr> {% endfor %} </fieldset> {% endfor %} <input type="submit" value="Result"> </form> </ul> {% else %} <p>No questionnaires are available.</p> {% endif %} My questionnaire models.py is class Question(models.Model): question_text = models.CharField(max_length=200) pub_date=models.DateTimeField('date published', null = True) def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime. timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length = 100, null = True) value = models.IntegerField(default = 0) def __str__(self): return self.choice_text And this is views.py def question(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'questionnaire/question.html', context) -
when i select other form droplist then i want appear one textbox
Hi i have a list of industry in that there is a option other when i click on other then the textbox for other will be appear . i don't understand how to do this i have tried the djangoajax but not worked <div class="col-md-6 col-lg-5 " style = "position:relative; left:180px; top:20px; "> <div class="form-group"> <label class="col-sm-4 control-label"> Sector </label> <div class="col-sm-8"> {{ form.industry }} <span class="help-block"> {{ form.industry.errors }}</span> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label" style = "top:20px; "> Others </label> <div class="col-sm-8" style = "top:20px; "> <!--{{ form.other }}--><input type="test" style="width: 350px;" id="model1234" > <span class="help-block">{{ form.other.errors }}</span> </div> </div> </div> -
django : Get the number of objects related to a model with foreign key
class Chapter(models.Model): title = models.CharField(max_length=100) class Lesson(models.Model): chapter = models.ForeignKey("Chapter", on_delete=models.CASCADE, related_name="lessons", related_query_name="lesson") I'm a beginner in Django. I want to get the number of lessons that are related to a Chapter with a foreign key and save that number as a field in the Chapter. I heard about select_related and prefetch_related but I didn't understand those completely. in my opinion, if I can get a list from : Chapter.objects.get(id=1).lessons My problem will be solved. but it returns <django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager at 0x7ffa57a31b80> Not a list. So I can't get the number of lessons from it. is there a solution? -
Django rest framework: How can I make a viewset that returns custom data from another app's model?
I have two django apps. My project directory looks like: /my-project /accounts __init__.py admin.py api.py apps.py models.py serializers.py tests.py urls.py views.py /apartments __init__.py admin.py api.py apps.py models.py serializers.py tests.py urls.py views.py /my-project __init__.py asgi.py settings.py urls.py wsgi.py manage.py Accounts is an user authentication app and uses the default django user model. Apartments app's files looks like: models.py: from django.db import models from django.contrib.auth.models import User class Apartment(models.Model): apartment = models.CharField(max_length=50) resident = models.CharField(max_length=100) floor = models.IntegerField() ei_rate = models.FloatField(default=0) fi_rate = models.FloatField(default=0) oi_rate = models.IntegerField(default=0) owner = models.ForeignKey(User, related_name="apartments", on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True) serializers.py: from rest_framework import serializers from apartments.models import Apartment class ApartmentSerializer(serializers.ModelSerializer): class Meta: model = Apartment fields = '__all__' api.py: from apartments.models import Apartment from rest_framework import viewsets, permissions from .serializers import ApartmentSerializer class ApartmentViewSet(viewsets.ModelViewSet): permission_classes = [ permissions.IsAuthenticated ] serializer_class = ApartmentSerializer def get_queryset(self): return self.request.user.apartments.all() def perform_create(self, serializer): serializer.save(owner=self.request.user) apartments/urls.py: from rest_framework import routers from .api import ApartmentViewSet router = routers.DefaultRouter() router.register('', ApartmentViewSet, 'apartments') urlpatterns = router.urls my-project/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/auth/', include('accounts.urls')), path('api/apartments/', include('apartments.urls')), ] I want to create a new django app in my project. For each user, I want to … -
Combine DetailView and SingleTableView in Django
How can I display a SingleTableView table together with a DetailView in django? What I want is to include or combine both into one. So that when calling DeviceDetailView i receive the device's details and a table of the devices's data (stored also in another model). Thank you class DataListView(SingleTableView): model = Data template_name = 'data/list.html' table_class = DataTable def post(self, request, *args, **kwargs): queryset = request.POST for i in queryset['list'].split(","): if queryset['action'] == 'delete': Data.objects.filter(data_id=i).delete() return HttpResponseRedirect('/data/') class DeviceDetailView(DetailView): template_name = 'devices/detail.html' def get_object(self): id_ = self.kwargs.get("id") return get_object_or_404(Device, id=id_) -
How to implement switch accounts option in Django
Consider an application where there is a company account and employee account. I want to add employees as admin of the company. Then the admin should be able to switch account with the company. Is it possible to do the switch account option? I am a beginner in Django. Can anyone help me with this problem? -
django set ModelChoiceField's "to_field_name" to multiple columns
I want to provide multiple field names in Django's modelChoiceField's to_field_name something like field1 = forms.ModelChoiceField(queryset=myModel.objects.all(), required=False, empty_label="--------", to_field_name=["col1, col2"], widget=forms.Select(attrs={'class':'form-control'}), ) is this possible?? Do I need to override some classes?? Any help would be appreciated... -
Django display images from database
I am trying to display a list of images on my development page but the only images I am getting are this white-blank image. Here are my Django codes settings.py STATIC_URL = '/static/' STATICFILES_DIRS =[os.path.join(BASE_DIR,"static")] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media_cdn') views.py def imgdownload(request): allimages = ImagefieldModel.objects.all() return render(request, 'main/show.html',{'images': allimages}) urls.py urlpatterns = [ .... .... path("show/", views.imgdownload, name="imgdownload"), .... ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class ImagefieldModel(models.Model): title = models.CharField(max_length = 200) img = models.ImageField(upload_to = "media") class Meta: db_table = "imageupload" show.html {% extends "main/header.html" %} {% load static %} {% block content %} <head> <title>Django Display Images</title> </head> <body> <div class="container"> <table class="table table-striped"> <thead> <tr> <th>Title</th> <th>Image</th> </tr> </thead> <tbody> {% for img in images %} <tr> <td>{{img.title}}</td> <td><img src="/{{ BASIC_DIR }}/{{img.img}}" width="120"/></td> </tr> {% endfor %} </tbody> </table> </div> </body> {% endblock %} I am not sure what is wrong since I have declared the MEDIA_URL correctly. Some help is much appreciated. -
how to deploy a ML model with django?
if we want to use our ML model with django to use in a website , how we can do that? or is there any better option to do that ? -
Django model viewset built-in delete method does not work
I have model viewset that I did not override it: class RolesAndPermissionsViewSet(ModelViewSet): queryset = RoleModel.objects.all() serializer_class = RoleSerializer the urls: router = routers.DefaultRouter() router.register(r'role', RolesAndPermissionsViewSet, basename='roles_and_permissions') urlpatterns = [] + router.urls serializer: class RoleSerializer(serializers.ModelSerializer): permissions = RequestPermissionSerializer(many=True) class Meta: model = Role fields = ( "id", "name", "permissions", ) def create(self, validated_data): permissions = validated_data.pop('permissions', []) print(permissions) role = super(RoleSerializer, self).create(validated_data) for permission in permissions: role.permissions.add(Permission.objects.get(id=permission['id'])) return role and in the postman: response but it doesn't delete the row from my django admin. Thank you for your help -
cannot call the second view from my template in django
I am creating a web app. In this one button is for getting the user data and another button is for adding a new user. I have successfully added the button which pressed shows the user but the second button is not working. this is my html {% extends "edit_parameter.html" %} {%block title %} <title>User Management</title> {% endblock %} {%block css %} table.table_font{ font-size:10%; } {% endblock %} {% block content %} <h1> <center>User Management Menu</center> </h1> <form method="POST" action="{% url 'get_user_data' %}" > {% csrf_token %} <table BORDER=0 style="float:left; margin-top:1px; margin-left:30px;"> <tr> <td> &nbsp;<label for="user_id">User ID:</label></td> <td>&nbsp;&nbsp;<input id="user_id" name="user_id" type="text" value="{{ user_id }}"><br></td> </tr> <tr> <td> &nbsp;<label for="user_name">User Name:</label></td> <td>&nbsp;&nbsp;<input id="user_name" name="user_name" type="text" value="{{ user_name }}"><br></td> </tr> </table> <button type="submit" class="btn btn-dark" >Get user data</button> <a href="success" class="btn btn-dark" role="button" aria-pressed="true">Menu</a> <button class="btn btn-danger" onclick="location.href={% url 'add_new_user' %}">add_new_user</button> </form> this is my views.py def get_user_data(req): #somecodehere return render('user.html') def add_new_user(req): #somecodehere return render('user.html') -
Why is request.GET always null in cloudfront
I am making website by django $.ajax({ type: "GET", dataType: "json", data: { "input": search__container__input.value, }, url: "{% url 'ko:search-item' %}", success: function (response) { if (response.msg == "success") { window.location.href = `/${response.target_category}/${response.target_item}` } else { Swal.fire("sorry.", "error") console.log(response) } }, error: function () { Swal.fire("sorry", "error") } }) This is my ajax code. def search_item(request): tmp = request.GET search_target = request.GET.get('input') and this is views.py search_target is always null value. this is not null value when i am not using AWS cloudfront. i choose all default option of cloudfront. what should i do -
Django testcase Python exited unexpectedly
Process: Python [909] Path: /Library/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python Identifier: Python Version: 3.7.8 (3.7.8) Code Type: X86-64 (Native) Parent Process: Python [899] Responsible: Python [909] User ID: 502 Date/Time: 2020-12-17 14:47:11.551 +0800 OS Version: Mac OS X 10.14.6 (18G103) Report Version: 12 Anonymous UUID: 2B41E719-4681-D496-6AC8-7309D3E78AFF Time Awake Since Boot: 360 seconds System Integrity Protection: disabled Crashed Thread: 0 Dispatch queue: com.apple.root.user-interactive-qos Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000110 Exception Note: EXC_CORPSE_NOTIFY Termination Signal: Segmentation fault: 11 Termination Reason: Namespace SIGNAL, Code 0xb Terminating Process: exc handler [909] -
I want to call a function from my views.py on my submit button
I want to call my email function from views.py on the submit button in the index.html file. P.S. I am a beginner at this!! Thanks. My submit line from index.html: <div class="row"> <div class="col-12 mt-5"> <input type="submit" value="Send message" value="Click" class="submit-btn" name="Submit"> </div> </div> Now the views.py email function which I want to call: def email(request): fname = request.GET.get('FirstName', None) lname = request.GET.get('LastName', None) email = request.GET.get('YourEmail', None) phone_no = request.GET.get('PhoneNumber', None) message = request.GET.get('Message', None) name = fname + " " + lname body = message + "\nContact No. " + phone_no # Send Email send_mail( 'Subject - Thanks for contacting', 'Hello ' + name + ',\n' + message + "\n" + phone_no, EMAIL_HOST_USER, [ email, ] ) return redirect('index') -
Django showing percentage of task completed/total task
I'm trying to make a simple django app which is like a todo app, I want to add the percentage of task completed. Here's my model.py from django.db import models from django.urls import reverse class Task(models.Model): title = models.CharField(max_length=200) create_time = models.DateTimeField(auto_now_add=True) complete_time = models.DateTimeField(blank=True, null=True) status = models.BooleanField(default=False) def __str__(self): return self.title and here's the template file <form method="POST" action="/"> {% csrf_token %} {{form}} <input class="btn submit" type="submit" name="save"> </form> {% for task in tasks %} {% if task.status == True %} <strike>{{task}}, {{task.complete_time}}</strike> {% else %} {% endif %} {% endfor %} and this is views.py file def list(request): queryset = Task.objects.order_by('complete_time','complete_time') if request.method =='POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = { 'tasks':queryset, 'form':form, } return render(request, 'tasklist.html', context) -
How to start django-project using postgresql?
There was a need to work with geodata in my project, namely to bind a geodata field to my models. To do this, need to work with postgresQL. I followed the instructions from the documentation, set everything up, but the following error appeared (this happens when I either try to start the server, or perform migrations): django.db.utils.OperationalError File "C:\Users\Пользователь\django\PycharmProjects\usadba\venv\lib\site-packages\django\db\backends\postgresql\base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\Пользователь\django\PycharmProjects\usadba\venv\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) So: # ALLOWED_HOSTS = ['mysite.com', 'localhost', '127.0.0.1', '192.168.1.220', '127.0.0.1:5432'] ALLOWED_HOSTS = ['*'] DATABASES = { 'default': { # 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '***', 'USER': '***', 'PASSWORD': '***', 'HOST': 'localhost', 'PORT': '5432' } } The construct in the file located along the path C:\Windows\System32\drivers\etc\hosts looks like this 127.0.0.1 localhost. OS windows 10. All required libraries are installed checked through the console. -
user profile image duplicating according to number of users in django
Blockquote Heading class profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True,blank=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics',null=True,blank=True) -
Twitter API 2 stream working locally but not on Heroku - Django
I am trying to deploy a live Twitter streaming on my Django web app on Heroku but I am facing an error. It works locally but returns an error page on live. https://twitter--sentiment.herokuapp.com/ I've added the twitter BEARER_TOKEN using heroku config set: Here is my Heroku deployment page. I've also added the directory in my settings.py file BEARER_TOKEN = os.environ['BEARER_TOKEN'] This is my first time deploying an web app! Any help would be appreciated. -
Passing values from our models to ModelForm in Django
I have a payment page were i want the amount for a particular commodity a user picks, to be displayed at default(amount) when the page loads. with that been said, i've def get_total_everything(), were the amount is been calculated. this is the calculated amount i will like to send to the Modelform initial #Form class PaymentForm(forms.ModelForm): def __init__(self,amount, *args, **kwargs): super(PaymentForm, self).__init__(*args, **kwargs) self.amount = amount self.fields["amount"].initial = amount.get_total_everything_payment() class Meta: model = Payment fields = ['firstname', 'lastname', 'email', 'amount'] class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ManyToManyField(OrderItem) def __str__(self): return self.user.username def get_total_everything(self): total = 0 for order_item in self.item.all(): total += order_item.get_final_price() return total class Payment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) firstname = models.CharField(max_length=250) lastname = models.CharField(max_length=250) email = models.EmailField() # amount = models.FloatField() amount = models.ManyToManyField(Order) def __str__(self): return self.user.username -
How to pass Rating implemented in HTML to Views in Django
I'm implementing a Movie rating website for my College mini-project using Django and I'm just a beginner so I need some help on this topic. So for movie rating, I created stars using HTML and CSS. But to store them in Model, I don't know how to pass the rating to View which user has chosen from the webpage. Here is my HTML template where I implemented Rating: <div class="rating1"> <span class="fa fa-star checked" onmouseover="starmark(this)" onclick=""starmark(this) id="1one" style="font-size:40px;cursor:pointer;" ></span> <span class="fa fa-star checked" onmouseover="starmark(this)" onclick=""starmark(this) id="2one" style="font-size:40px;cursor:pointer;" ></span> <span class="fa fa-star checked" onmouseover="starmark(this)" onclick=""starmark(this) id="3one" style="font-size:40px;cursor:pointer;" ></span> <span class="fa fa-star checked" onmouseover="starmark(this)" onclick=""starmark(this) id="4one" style="font-size:40px;cursor:pointer;" ></span> <span class="fa fa-star checked" onmouseover="starmark(this)" onclick=""starmark(this) id="5one" style="font-size:40px;cursor:pointer;" ></span> <br><br> <button style="margin-top:10px;margin-left:5px;" onclick="showRating()" class="btn btn-lg btn-success">Submit</button> </div> I'm invoking rating given by user in JS function as follows: <script type="text/javascript"> var rating=""; function starmark(item){ var count=item.id[0]; rating=count; var subid=item.id.substring(1); for(var i=0;i<5;i++){ if(i<count){ document.getElementById((i+1)+subid).style.color="orange"; } else{ document.getElementById((i+1)+subid).style.color="black"; } } } function showRating(){ alert(rating); } </script> I tried to implement form but I don't know what should I pass to View on form submission. So, for now my View is: def detail(request, tconst): movie = get_object_or_404(Movie, tconst=tconst) #for rating return render(request, 'web/detail.html', {'movie':movie}) At for rating …