Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter using gte of a attribute of corresponding model object in django
bar_1 = models.IntegerField() bar_2 = models.IntegerField() Filter all values where bar_1<=bar_2 -
How can I get the authorized user on vaild?
How can I get the authorized user on vaild? It all happens in the forms.py file. I need to verify an authorized user with his mail. self.request.user - not working. I get this error: object has no attribute 'request' def clean_email(self): email = self.cleaned_data["email"] try: User.objects.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError("error") -
Form is not saving
Hello I have form and I can fill it but when I submit it nothing happens, I can add or edit the form in the admin panel but on the normal page as I said nothing happens. Can you please help me. this is my template where you at the bottom see my form. {% extends "base.html" %} {%block content%} {% load crispy_forms_tags %} <div class="container"> {% for i in distribution%} <div class='img1'> <img name="pic" src="{{ i.distribution.url }}"> <p style="text-align:center;">{{i.lecture}} | {{i.semester}}</p> </div> {% endfor %} </div> <div class="container"> <table class="table table-hover results"> <thead> <tr> <th >Kullanıcı</th> <th >Yorum</th> </tr> </thead> <tbody> {% for j in commentmodel_list%} <tr> <th>{{j.author}}</th> <th>{{j.comment}}</th> </tr> {% endfor %} </tbody> </table> </div> <div class="container"> <button style="margin-bottom:10px;float:right;"type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo">Yorum Ekle</button> </div> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Yorum</h5> </div> <div class="modal-body"> <form method="post" style="margin-top: 1.3em;"> {% csrf_token %} {{ form|crispy }} <div class="modal-footer"> <button type="submit" class="btn btn-primary">Submit</button> <button type="submit" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </form> </div> </div> </div> </div> this is my view class LecturerDistribution(FormMixin, generic.DetailView): model = Lecturer template_name = 'lecturer.html' context_object_name = 'post' form_class = CommentForm def get_context_data(self, **kwargs): context = … -
How can I install Ubuntu production server in Godaddy hosting server
So I tried my best to create a full-stack app with Django & React and I built it. And I did want to learn how to deploy the application to Linux/Ubuntu server and wanted to fallow this article. Godaddy provides a Cpanel, not a Ubuntu server. So I was wondering how can I install the Ubuntu production server in Godaddy hosting server. I don't have any experience with Linux or Cpanel or any hosting service (it is my first time buying the domain and hosting server) it would be nice to have a detailed answer. I am open to any kind of advice. Thank you for reading. -
How to write a funtion that will check for the empty room in hotel in django
I am building a Hotel management system and I have writing a check_availability function that will check if a room is not empty depending of the category required by the client but it turns out that the database is ignore by the function cause it just care about the existing one not the added one. here is the code: from django.db import models from django.contrib.auth.models import User class RoomCategory(models.Model): name = models.CharField(max_length=59) price = models.IntegerField() beds = models.PositiveIntegerField() capacity = models.PositiveIntegerField() size = models.CharField(max_length=59) def __str__(self): return self.name class Room(models.Model): room_number = models.CharField(max_length=60) room_category = models.ForeignKey(RoomCategory, on_delete=models.CASCADE) def __str__(self): return f"The room {self.room_number} {self.room_category} has a maximum of {self.room_category.capacity} person and cost {self.room_category.price}/night " class Booking(models.Model): customer = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) check_in = models.DateTimeField() check_out = models.DateTimeField() def __str__(self): return f"{self.customer} has booked for a {self.room} room from {self.check_in} to {self.check_out}" from django.shortcuts import render from .forms import BookingForm from .models import Booking, RoomCategory, Room from django.views.generic import FormView from Hotel.Availabililty.Available import check_availability from django.http import HttpResponse # Create your views here. class BookingFormview(FormView): form_class = BookingForm template_name = 'Hotel/bookingformview.html' def form_valid(self, form): data = form.cleaned_data roomlist = Room.objects.filter(room_category__name=data['room']) for room in roomlist: booked_room = Booking.objects.filter(room__room_number=room.room_number) available_rooms … -
Define variable on django project startup
I am trying to make one variables.py (reusbale module that can be used by other py files in the app) in my django project which should be set only once when the runserver command is executed. ex. reading a csv file using pd.read_csv once at the startup of the project so that every time an API call is made, variable should not load csv file instead it should already have the dataframe value already in the variable. How can this be achieved? Python version - 3.6 Django - 2.1 -
How do I see the value of a field belonging to my model with the method I defined in restapi?
I can access the foreground in my model with "Advertising.frontal.get". But how can I see this in restapi. The value of the frontal area in restapi appears numerical. Because of the way I describe this area. This is normal. But I know the method I should use when viewing (this method: Advertise.frontal.get). How do I view it in restapi with this method. ## Serializer.py ## class AdvertiseMainSerializer(ModelSerializer): class Meta: model = Advertise fields = '__all__' ## views.py## class advertise(ListAPIView): serializer_class = AdvertiseMainSerializer queryset = Advertise.objects.all() ## model.py## class Advertise(models.Model): owner = models.ForeignKey(to="user.User", on_delete=models.CASCADE, null=True) title = models.CharField(max_length=100, verbose_name="ilan başlığı") frontal = models.ManyToManyField(to="advertise.Frontal") -
How to integrate a typeform like experience for CRUD website
I'm building a web app and I want to have a typeform like flow to create and edit entities on my website. As far as I know, I can't use typeform itself, as they don't allow for edits. Is there a tool/snippet/package to create good looking forms, without refresh between pages, include animations, skip logic etc.? I'm using django for my website. Thanks! -
Can't delete post Django delete_post() missing 1 required positional argument: 'post_slug'
When i hit on my Delete button i get delete_post() missing 1 required positional argument: 'post_slug' I made a DeleteForm too, but im really not understanding how to delete things, i was trying to make the same that i did to edit_post. views.py: def edit_post(request, post_slug): """Edit an existing entry.""" post = get_object_or_404(Post, slug=post_slug) context = {} form = EditPostForm(request.POST or None, instance=post) if form.is_valid(): form.save() return HttpResponseRedirect(post.get_absolute_url()) context["form"] = form return render(request, 'blog/post/edit_post.html', context) def delete_post(request, post_slug): post = get_object_or_404(Post, slug=post_slug) if request.method == 'POST': post.delete() context = {'post': post} return render(request, 'blog/post/delete_post.html', context) urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.post_list, name='post_list'), path('tag/<slug:tag_slug>/', views.post_list, name='post_list_by_tag'), path('new_post/', views.new_post, name='new_post'), path('<slug:post_slug>/', views.post_detail, name='post_detail'), path('<slug:post_slug>/share/', views.post_share, name='post_share'), path('edit_post/<slug:post_slug>/', views.edit_post, name='edit_post'), path('delete_post/<slug:post_slug/', views.delete_post, name='delete_post'), ] delete_post.html {% extends 'blog/base.html' %} {% block title %}{{ post.title }}{% endblock %} {% block content %} <div class="main"> <!-- Create a Form --> <form method="POST" action="{% url 'blog:delete_post' post.slug %}" class="form"> {% csrf_token %} Are you want to delete this item ? <input type="submit" value="Yes" /> <a href="/">Cancel </a> </form> </div> {% endblock content %} forms.py from django import forms from .models import Comment, Post class EmailPostForm(forms.Form): … -
Django rest-auth PUT method returning JSON Unexpected token
I've been trying to try to do this for a couple of days for now. I am trying to update the user's data through put method in Django using rest framework. However, I've been receiving this error message in the console. This is the fetch function that is used to send the data to the backend. As it's shown, I'm even trying to compare it to other fetch methods and I think nothing is wrong with the body of the fetch. Below are my codes used to update the data. views.py serializers.py urls.py -
Storing the data into SQLiteStudio database when any data is entered in front end
How to store data into database using Django framework and python. -
How to use Django to make a dependent dropdown list from a database I would like to write to as well
I have seen many tutorials of how to pull information using a foreignKey in the models for a dropdown list, but I'd like to keep everything on the same table if possible. First I use AddAreaForm to add the Area, then AddMachineForm, using the Area(in a dropdown) and Machine being typed in. As detailed below this gets me to the point where I have Area and Machine drop downs in the AddTasksForm, but I'd like to make the Machine dropbox dependent on the Area using the SOME VARIABLE(Line 5 in Forms Codeblock and it is defined as area_id on line 4 in Views Codeblock). MODEL class Tasks(models.Model): area = models.CharField(max_length=500) machine = models.CharField(max_length=500, null=True, blank=True) task = models.CharField(max_length=500, null=True, blank=True) interval = models.IntegerField(null=True, blank=True) def _str_(self): return self.area FORMS #Call's the area and machine from the database, lists all unique choices as i'll be adding only to existing data-points AREA_CHOICES_UNSORTED = list(Tasks.objects.values_list('area', flat=True)) AREA_CHOICES = list(dict.fromkeys(zip(AREA_CHOICES_UNSORTED[0::1], AREA_CHOICES_UNSORTED[0::1]))) MACHINE_CHOICES_UNSORTED = list(Tasks.objects.values_list('machine', flat=True).filter(area='%s'% '**SOME VARIABLE**')) MACHINE_CHOICES = list(dict.fromkeys(zip(MACHINE_CHOICES_UNSORTED[0::1], MACHINE_CHOICES_UNSORTED[0::1]))) class AddAreaForm(forms.ModelForm): class Meta: model = Tasks fields =( 'area', ) class AddMachineForm(forms.ModelForm): area = forms.CharField(widget=forms.Select(choices=AREA_CHOICES)) class Meta: model = Tasks fields =( 'area', 'machine', ) class AddTasksForm(forms.ModelForm): area = forms.CharField(widget=forms.Select(choices=AREA_CHOICES)) machine = … -
How can I prepopulate a form in class based views with url variable <str:>
As the question says,I'm trying to prepopulate a form with a url varible, by this I mean that the form fills with the variable that is in the url. I was trying to use the get initial function, but it's not working, so I will share my code so you can see what's going on and what mistakes I'm doing views.py class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'app1/createpost.html' def get_initial(self, **kwargs): #Returns the initial data to use for forms on this view. initial = super().get_initial() initial['stock'] = self.kwargs.get('sym') return initial def form_valid(self, form, sym): form.instance.author = self.request.user return super().form_valid(form) models.py class StockNames(models.Model): name = models.CharField(max_length=255) symbol = models.CharField(max_length=255) def __str__(self): return self.symbol class Post(models.Model): title = models.CharField(max_length= 255) header_image = models.ImageField(null = True, blank = True, upload_to = 'images/') author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank = True, null = True) #body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default='coding') snippet = models.CharField(max_length=255) likes = models.ManyToManyField(User, related_name = 'blog_posts') stock = models.ForeignKey(StockNames, null=True, on_delete = models.CASCADE) def total_likes(self): return self.likes.count() def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('app1:article-detail', args=(self.id,)) forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = … -
Can we use django as a front end?
I Have Confusion for Django as it is mostly use for back end support but can we use it as front end also? I have to go for something else for front end or only html and CSS is fine. -
Should extra fields be an extension of User or Profile in Django?
I am beginner in Django and currently practising by building a calorie counter website where users can register. When they register, I want to ask them for some mandatory fields such as their goal weight, activity level, current weight, current height, etc. Do I add them to a class called Profile(models.Model) such as : class Profile(models.Model): user = models.OneToOne(User, on_delete=models.CASCADE) bio = models.CharField(max_length=500) image = models.ImageField(default="", upload_to="profile_pics") weight = models.FloatField(min_value=1.0) #metric tbd height_metric = models.FloatField(min_value=1.0) #in cm goal_weight = models.FloatField(min_value=1.0) or should I create a custom User model that extends the default User model provided by Django? (or a third option) Thanks -
How to add an extra parameter to a Django object when creating it?
I have a Django model that has many parameters, amongst which is one called 'system' which is a reference to an object of type 'System'. class Format(models.Model): system = models.ForeignKey(System, on_delete=models.SET_NULL, null=True) petition_date = models.DateField(auto_now=True) resolution_date = models.DateField(null=True, default=None) ... other fields ... The system may be null, but I'd want this field to be the same as the user that creates the Format object. My user object is like this: class CustomUser(AbstractUser): current_system = models.ForeignKey(System, on_delete=models.SET_NULL, null=True, default=None) department = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, default=None) I have a form which successfully creates the Format objects. However, I'd like to know a way to do something like this in my CreateView: class FormatCreateView(LoginRequiredMixin, CreateView): """ -----------------------Vista de crear nuevos articulos-------------------------- """ template_name = 'format_form.html' model = Format success_url = reverse_lazy("formats:formats") form_class = FormatUpdateForm def post(self, request, *args, **kwargs): form = FormatUpdateForm(request.POST) if form.is_valid(): user = User.objects.get(id=self.request.user.id) format = self.object # I'm pretty sure this is wrong and doesn't get the Format object that was just created format.system = user.current_system format.save(update_fields=['system']) return HttpResponseRedirect(reverse('formats:formats')) This, however, doesn't work. Any suggestions would be appreciated. -
How to sort models into categories django
I have an article model and I want to make that so when the user clicks he has drop-down menu so he chooses a category and then it registers it in this category in the database. -
Foreign key values do not appear in related rendered table using accessor (django-tables2)
I am trying to display a table with a Tool model as well as a publication DOI model that has the tool as a foreign key. Django (django-tables2) is just not having it and displays - instead of actual values. There are no shortages of examples (Django-tables2: How to use accessor to bring in foreign columns?, Django Tables 2 Field Accessor backward relationship, Accessing related models with django-tables2) and it seems simple, but I cannot get it to work. Here is a bit of code... models.py class DOI(models.Model): """Model representing a doi model.""" doi = models.URLField(verbose_name='DOI', max_length=300, default='', blank=True) tool = models.ForeignKey('Tool', on_delete=models.SET_NULL, null=True) ... class Tool(models.Model): tool_name = models.CharField(verbose_name='Package Name', max_length=200) release_date = models.DateField(verbose_name='Release Date', null=True, blank=False) ... tables.py class ToolTable(tables.Table): tool_name = tables.Column(linkify=True) doi = tables.Column(accessor='doi.doi', linkify=True) id = tables.Column(linkify=True, orderable=False) ... Any assistance is greatly appreciated. -
Django save image locally as well as s3
An image file is being uploaded from a POST REST API call and I want to do the following save the file locally also save it in an s3 bucket after saving the file, get the URL of the saved object How can I do this in Django? -
Form on Base.html
I have a navbar on my project in base.html and I want to add a form to the navbar. When you click on 'add' a window prompts and you should able to see and fill the form and then submit it. But I think I cannot connect my view with my templates, I am also unsure how to make a url path because it should be everywhere. I created a view under the project/views, and my template is under the project/templates. Here is my code which is relative easy but as I said I need to connect my form and template. Thank you very much. view.py from django.views import generic from account.models import Distribution from account.forms import DistributionForm class Distribution(generic.CreateView): template_name="base.html" model=Distribution fields=['distribution','semester'] base.html <!DOCTYPE html> {% load static %} {% load crispy_forms_tags %} <html lang="en" dir="ltr"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> <meta charset="utf-8"> <title></title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top"> <a class="navbar-brand" href="{% url 'distribution:home'%}">Ana Sayfa</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarText"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'account:register' %}">Kayıt … -
Alter Django Form
How can i adjust my code so that a user cannot choose another user for a new post. I want to make it so that the logged in user is automatically added as the author. I have tried setting the fields part in the views.py to just the content field, however it doesn't work models.py class post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.CharField(max_length=140) views.py class CreatePostView(CreateView): model = post fields = '__all__' template_name = 'users/create.html' Myform.html <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Login"> </form> -
Django Web App: problem with “OperationalError: (psycopg2.OperationalError) server closed the connection unexpectedly”
Application My application based on kubernetes cluster with backend (django), frontend and other related pods. Also it has some services and one of them is postgresql database. I have two instances of my application (dev and prod - they exist in different namespaces) and problem that will be discussed bellow exists in both. About problem Sometimes I have troubles on my cite when performing operations related to accessing database (trying to login for example). In kubernetes backend pod logs I see error messages ended with: ... django.db.utils.OperationalError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. This usually happens within 10-30 minutes and then goes away by itself. I have no idea how to reproduce or temporary solve this problem so I just can watch for it and some of my observation I will try to describe in this post. Django database configurations DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('POSTGRES_DBNAME'), 'USER': os.environ.get('POSTGRES_NAME'), 'HOST': os.environ.get('POSTGRES_HOST'), 'PASSWORD': os.environ.get('POSTGRES_PASS'), 'PORT': os.environ.get('POSTGRES_PORT'), 'CONN_MAX_AGE': None, } Researching the problem In moments when problem exists I found out the following: I can access server with database via ssh. Also I can exec -it docker container … -
Pycharm cannot run debug Django Web App ,What is something wrong?
I cannot run debug for the Django project in Pycharm I got stuck on how to debug Django Python Project in Pycharm. I don't know how I configure something in Pycharm incorrectly despite no problem in the other python project. Is there anything for additional setting in Pycharm Or further code in Django project file such as settings.py In figure below, I do the following step. Set Breakpoint in here 2.Click Debug in view.py debug stop at init.py raise ImproperlyConfigured( "Requested %s, but settings are not configured. " "You must either define the environment variable %s " "or call settings.configure() before accessing settings." % (desc, ENVIRONMENT_VARIABLE)) Debugger never reaches my breakpoint at all. click to see picture debuger in pycharm Thank you -
getting the COUNT of unique values on django queryset with for loop
newbie here on django and django-rest-framework. May I ask if it is possible to get the COUNT of the unique values on a for loop? I have encountered this use case where I need to get the the COUNT of all unique values on a for loop querysets. The implementation was to loop within the querysets and put on the list all the unique objects and return the len() of it. The problem with this implementation was it causes multiple queries on the DB base on django-debug-toolbar. Please see code below for reference. Is there another way to implement this? Thank you in advance. activity_list = [] classes = Class.objects.all() for class in classes: student_activities = class.studentactivity_set.all() for activity in student_activities: if activity not in activity_list: activity_list.append(activity) return len(activity_list) -
Django with vue.js frontend - Static Files Path
I am attempting to serve a django app with a vue frontend and need some help configuring the static files. Django serves the built index.html from vue, however it can not find the static files (scripts/css) that are autoinjected from the build process due to the path being "absolute". I have modified the vue.config.js to not autoinject the scripts (since they will need {% static %} during the build, and the template index.html to add them in appropriately. My directory structure is as follows: - Root - app - migrations - templates - app (outputDir) - index.html (Built from vue) - base.html - templateFolder1 - templateFolder2 - various .py files - assets (assetsDir) - css - static files - js - static files - frontend - public - index.html (Template for build for vue) - src - assets - components - App.vue - main.js The build is run from the frontend directory, with --no-clean to not delete my django templates folder on build. Here is my workaround for adding {% static %} tags to the built index.html. I realize I am breaking the convention vue has that assetsDir is a subdirectory of outputDir, and I am not opposed to adding …