Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: ModelForm save() method for multiple objects for a span of dates
I need to make a form to save multiple instances of a Model for a span of dates provided by a user. I have created a ModelForm with a change - exclude date (a model attribute) and added 2 fields: date_from and date_to (for a starting and ending date). I would like the form to save as many records as needed based on the dates span. The code below doesn't work. models.py class Tour(models.Model): company = models.ForeignKey('Company', on_delete=models.PROTECT) employee = models.ForeignKey('Employee', on_delete=models.PROTECT) date = models.DateField() forms.py class TourForm(forms.ModelForm): DATE_INPUT_FORMATS = ['%d-%m-%Y'] date_from = forms.DateField(widget=AdminDateWidget) date_to = forms.DateField(widget=AdminDateWidget) class Meta: model = Tour fields = ['company', 'employee', 'date_from', 'date_to'] def save(self, *args, **kwargs): start_date = self.cleaned_data['date_from'] end_date = self.cleaned_data['date_to'] delta = datetime.timedelta(days=1) count = end_date - start_date while start_date <= end_date: data = { 'company': self.cleaned_data['company'], 'employee': self.cleaned_data['employee'], 'date': start_date, } single_tour = SingleTourForm(data) single_tour.save() start_date += delta class SingleTourForm(forms.ModelForm): DATE_INPUT_FORMATS = ['%d-%m-%Y'] class Meta: model = Tour fields = '__all__' The custom save() method above doesn't work. I get an error 'NoneType' object has no attribute 'save' What should I do to make it work? I am tryign to make it work using Django Admin Panel. -
Django: fetch multiple models
This is my first project with Django, I want to recreate my static HTML/CSS/js site to a dynamic site with an admin panel. However, I have a hard time understanding the views/urls.On my index, I have main news, events, mini news - 3 categories. I can render mainnews, however, I'm not sure what to use as 'return' for the other 2(all 3 are on the belongs to index page) Currently, I have 'index' but doesn't show the events/news. pages>view.py from django.shortcuts import render, redirect, get_object_or_404 from mainnews.models import Mainnews from events.models import Event from mininews.models import Mini # Create your views here. def home_view(request): main_news = Mainnews.objects.order_by('-publish_date').filter(is_published = True)[:1] context = { 'main_news' : main_news } return render(request, 'index.html', context) def event_view(request): events = Event.objects.order_by('-publish_date').filter(is_published = True)[:3] context = { 'events' : events } return render(request, 'index.html', context) def mini_view(request): mini_news = Mini.objects.order_by('-publish_date').filter(is_published = True)[:4] context = { 'mini_news' : mini_news } return render(request, 'index.html', context) main>urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from pages.views import home_view, event_view, mini_view urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name = 'home'), path('', event_view, name = 'home'), path('', mini_view, name = 'home'), … -
Django - How to filter database using HTML select tag?
I am trying to create an E-Commerce Website. So, I am trying to add filters like Price: Low - to High and vice versa. I know how to filter the price but I don't know how to apply the filter on select value getting changed. Here is HTML Code <div class="d-flex flex-row-reverse" style="margin-right: 20px; margin-bottom: 20px;"> <label> <select class="bg-dark" name="price" id="priceFilter"> <option value="normal">Sort by Price</option> <option value="low">Low-to-High</option> <option value="high">High-to-Low</option> </select> </label> </div> Django Code def index(request): fil = request.GET('price') if fil == "low": products = Product.objects.all().order_by('productDiscountedPrice') elif fil == "high": products = Product.objects.all().order_by('-productDiscountedPrice') else: products = Product.objects.all() context = { 'products': products } return render(request, "Amazon/index.html", context) So, How to sort products when select tag value gets changed? -
How to implement element ordering accross two different models in Django?
I've got these Car and Bike models I can't modify. They may need to be linked to a Ferry model which I can modify. I want to implement ordering of these elements of two different models in the database and I want to avoid using Generic Foreign Keys. So far this is what I've come up with: class Car(models.Model): pass class Bike(models.Model): pass class Ferry(models.Model): pass class Lot(models.Model): position = SmallInteger() car = models.ForeignKey(to=Car, null=True, related_name="ferries") bike = models.ForeignKey(to=Bike, null=True, related_name="ferries") ferry = models.ForeignKey(to=Ferry, null=False, related_name="load") Now my goal is to be able to access directly all the elements of a particular ferry –be they cars or bikes– ordered by position, and all the ferries (in the context of ferry travel bookings there may be several) of a particular car or bike: some_ferry.load.all().order_by("position") some_car.ferries.all() How do I create these relations, including a sort of combination of (car + bike)? -
Django models - Model relations misunderstandings
I want to create a table that only adds some information about another table. Here is what I have: I have 2 tables Exchange and ExchangeConnection: class Exchange(models.Model): slug = models.CharField(max_length=200, primary_key=True, blank=False, null=False) name = models.CharField(max_length=200, blank=False, null=False) class ExchangeConnection(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) exchange = models.OneToOneField(Exchange, on_delete=models.CASCADE) There are multiple exchanges which are defined by me and won't be modified throughout the app usage. It's only useful stored data to make my app works. I see it more like a type of ExchangeConnection. Then, I have ExchangeConnection. This table will be modified throughout the app usages because it represents information that belongs to a user, and it will be able to create some: When the user create an ExchangeConnection, he select which only one Exchange he is using. In my code you can see I'm using OneToOneField which isn't good because It implies an Exchange can be "linked" only once for every ExchangeConnection. I don't want to use ForeignKeyField in Exchange because I don't want ExchangeConnections to be part of an Exchange. I certainly misunderstood the logic of relations so I may bot be clear... -
Context must be a dict rather than list rendering template
I´m making a queryset with django. Now I have a little issue rendering the template. It retuned this error "context must be a dict rather than list". I know that context should be return as a dict, I´m suspecting in the context['cursos'] line. Anyone can confirm my suspect or give me some solution? thanks in advance class ListCursos( TemplateView): model1 = User model2 = Course template_name = 'plantillas/miscursos.html' def get_context_data(self, *args, **kwargs): context = super(ListCursos, self).get_context_data(**kwargs) rels = CourseRelUser.objects.filter(user_id=1) courses_id=[] for rel in rels: courses_id.append(rel.c_id) return courses_id context['cursos'] = Course.objects.filter(id__in=courses_id) return context -
How to add a button that redirects you to html page django admin page
In my case, I was creating a template for a PDF that I wanted to be preview-able directly from the admin page where the template was created, so people could see what the result would be of the object they’d just created. I really just needed a single link with a view that would show a PDF for me, but even something that basic is not immediately obvious in Django admin. I have a TransactionModel registered in the admin page as below : @ admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): search_fields = ['chp_reference', 'familymember__name'] inlines = [FamilyGroupInline, FamilyMemberInline] def report(self, obj): return mark_safe(json2html.convert(json=obj.report, table_attributes="class=\"results\" style=\"overflow-x:auto;\"")) fieldsets = ( ('Transaction Details', { 'fields': ('chp_reference', 'income_period', 'property_market_rent', 'rent_effective_date', 'number_of_family_group',), }), ('Report', { 'classes': ('collapse',), 'fields': ('report',), }), ) readonly_fields = ['report', 'complete', 'last_rent'] i want the Report object from the fieldsets to be a clickable link that redirect user to a html file, I dont know if that is possible.. and if its, what is the best approach to do so, Thank you! -
Why cannot iterate over Model.objects.all()?
In Django shell I don't have any problems in looping over Airport.objects.all() but in a .py I cannot iterate over my model's QuerySet. Here is my code: from django.forms import ModelForm,DateField,ChoiceField from flights.models import Flight,Airport from django.forms.widgets import SelectDateWidget,TextInput from datetime import datetime # pylint: disable=no-member queries=Airport.objects.all() airports = [tuple(x) for x in queries] I got TypeError: 'Airport' object is not iterable. Why? -
Reverse for 'posts' with keyword arguments '{'id': 106}' not found. 1 pattern(s) tried: ['posts/$']
I am building a BlogApp AND Everything is working fine BUT when i return redirect('mains:posts',id=post_id). It is showing me :- Reverse for 'posts' with keyword arguments '{'id': 106}' not found. 1 pattern(s) tried: ['posts/$'] views.py def post_like_dislike(request, post_id): post = get_object_or_404(Post, pk=post_id) # Like if request.GET.get('submit') == 'like': if request.user in post.dislikes.all(): post.dislikes.remove(request.user) post.likes.add(request.user) return JsonResponse() elif request.user in post.likes.all(): post.likes.remove(request.user) return redirect('mains:posts',id=post_id) else: post.likes.add(request.user) return JsonResponse({'action': 'like_only'}) # Dislike elif request.GET.get('submit') == 'dislike': if request.user in post.likes.all(): post.likes.remove(request.user) post.dislikes.add(request.user) return JsonResponse({'action': 'unlike_and_dislike'}) elif request.user in post.dislikes.all(): post.dislikes.remove(request.user) return JsonResponse({'action': 'undislike'}) else: post.dislikes.add(request.user) return JsonResponse({'action': 'dislike_only'}) else: messages.error(request, 'Something went wrong') return redirect('mains:posts',id=post_id) The Error is is at this Line -----------------^ detail.html <form method="GET" class="likeForm d-inline" action="{% url 'mains:post_like_dislike' data.id %}" data-pk="{{ data.id }}"> <button type="submit" class="btn"><i class="far fa-thumbs-up"></i> <span id="id_likes{{data.id}}"> {% if user in data.likes.all %} {{data.likes.count}}</p> {% else %} {{data.likes.count}}</p> {% endif %} </span><form><button name='submit' type='submit' value="like"> Like </button></form> </button> </form> ERROR When i click on Like button, it is showing Reverse for 'posts' with keyword arguments '{'id': 106}' not found. 1 pattern(s) tried: ['posts/$']. Any help would be Appreciated. Thank You in Advance -
How to run django views.function() on everyday midnight 00:00 using scheduler or schedu
## below created scd.py import schedule import time from .views import * # Create your tests here. def job(): views.attendancetemplate() #a= urllib.request.urlopen(url='http://172.16.1.100:8000/tmp', ) ## this is working but still `enter code here` print("I'm working...") schedule.every().day.at("20:23").do(job) while True: schedule.run_pending() time.sleep(1) #--------------------------------------------------------------------------------------- # THIS IS Views.py #-------------------------------------------------------------------------- from django.contrib.auth.backends import UserModel from django.contrib.auth.models import User from django.contrib.auth.signals import user_logged_in, user_login_failed from django.shortcuts import render , redirect from django.http import HttpResponse from django.contrib import messages from schedule import every from . import views from .models import * from django.contrib.auth import authenticate, get_user, login ,get_user_model, update_session_auth_hash from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.forms import UserCreationForm from datetime import date from django.contrib.auth.forms import PasswordChangeForm from datetime import timedelta import csv from django.contrib.auth.decorators import permission_required import schedule import time enter image description here ######################################################################################################### ## ****************!IMPORTANT ********************** USER TEMPLATE ######################################################################################################### def attendancetemplate(request): today = datetime.date.today() x=datetime.datetime.now() ldate= Attendance.objects.order_by('id').last() ldate1=ldate.date yesterday = today - timedelta(days = 1) prev = today - timedelta(days = 2) # if ldate1 == yesterday: User1 = get_user_model() users = User1.objects.all() for i in users: uname = i.username iname = i.first_name ausr =Attendance(User_Name = uname,date =today,Name=iname) ausr.save() if i is None: break print("I'm working...") [1]: https://i.stack.imgur.com/ciyLW.png -
I can not display Django form
I am trying to make a contact form but it's html template does not see {{ form }} template. What am I doing wrong? Where is an error. My code is attached above. models.py class Contact(models.Model): listing = models.CharField(max_length=200) listing_id = models.IntegerField() name = models.CharField(max_length=200) email = models.EmailField() phone = models.CharField(max_length=100) message = models.TextField(blank=True) file = models.FileField(upload_to='files/%Y/%m/%d/', blank=True) contact_date = models.DateTimeField(default=datetime.now, blank=True) user_id = models.IntegerField(blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('listings', kwargs={'pk': self.pk}) In views.py file class ContactCreate(CreateView): model = Contact fields = ['name','email','phone','file'] form_class = ContactForm redirect_field_name = '/' class ContactUpdate(UpdateView): model = ContactForm fields = ['name','email','phone'] urls.py from django.urls import path from . import views urlpatterns = [ path('listings/<int:pk>/', views.ContactCreate.as_view(), name='contact-create') ] html <form action="{% url 'contact-create' pk=listing.pk %}" method="post"> {{ form }} {% csrf_token %} <input type="submit" value="Send" class="btn btn-block btn-secondary"> </form> Could you help me out, please -
Getting Error: MultiValueDictKeyError at /__debug__/render_panel/ 'store_id'
I'm trying to access debug_toolbar and this error shown up MultiValueDictKeyError at /debug/render_panel/ 'store_id' -
Django: Adding Context From View Throws Module Not Found Error
I am trying to add context to a Django template by calling a function from another module. The code in the other module works, but when called from the get_context_data function inside the view class, it throws a module not found error - not finding the module of one of the function's dependencies. I have getplex.py that works fine when run in Python Console: from plexapi.myplex import MyPlexAccount # [PLEX CREDENTIALS] servername = 'xxxxxxx' username = 'plex@xxxx.com' password = 'xxx-yyy-yyy' baseurl = 'http://111.0.1.1:32400' try: account = MyPlexAccount(username, password) plex = account.resource(servername).connect() print('Plex connected') login_status = True except: print('Could not reach plex') login_status = False def new_tv(): shows_list = [] new_tv = plex.library.section('TV Shows').recentlyAdded() shows = [show for show in new_tv] for show in shows: summary_item = show.grandparentTitle + ' - ' + show.parentTitle shows_list.append(summary_item) new_seasons = [] for i in shows_list: if i not in new_seasons: new_seasons.append(i) if len(new_seasons) == 5: break return new_seasons I have views.py where I am trying to add the output of new_tv() to the context: from django.views.generic import TemplateView import plexigram.getplex from plexigram.getplex import new_tv class HomePageView(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): tv_shows = new_tv() context = dict() context['new_tv'] = tv_shows return context I … -
How to make django forms change as user enters information
I'm trying to make a django form that allows users to make some selections and then, depending on what selections they make, shows them the rest of the options that make sense. Here's an example of the logic I'm thinking: 1. Users selects their gender (radio button) [magic happens] 2(a). Male users select their clothing options - trousers, shorts, shirt, jacket 2(b). Female users select their clothing options - skirt, trousers, shorts, dress, shirt, jacket So my big question here is how do I make the magic happen so 2(a) or 2(b) only shows after the selection in (1) has been made? P.S. I have some code, but it doesn't really interact with the [magic] - should I include it or not? -
Is Django ORM Supports Snowflake and How
I want to connect snowflake db with Django and Use the Django ORM, I couldnt find database settings for the snowflake -
Is it possible to do a redirect on class based views
Is it possible to do a redirect on class based views. Like i have other contexts to return but if assuming I have blocked the user, i want to redirect to home page and make it such that they cannot view the detail page. Sorry! am new to class based views class DetailBlogPostView(BlogPostMixin,DetailView): template_name = 'HomeFeed/detail_blog.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) blog_post=self.get_object() blog_post.save() context['blog_post'] = blog_post account = Account.objects.all() context['account'] = account if blog_post.author in self.request.user.blocked_users.all(): return redirect('HomeFeed:main') return context -
How to change hairstyle in user photo(just like in snapchat) to show various style in a salon app?
I am working on a salon app in Django3.1 and I want to add a feature in it. I want to take input a photo from the user and according to the style chosen I want to change the hairstyle in the photo. But I don't know how to do it, do I need to do it in Django-REST? -
only staff user should post a product in django
hi everyone i am working with an ecommerce app where everone who login can post their product but i want only staff user to post the product when the staff user is true: my models.py is: class User(AbstractBaseUser): email = models.EmailField(max_length=255 ,unique=True) full_name = models.CharField(max_length=255, blank=True, null=True) active = models.BooleanField(default=True) #can login staff = models.BooleanField(default=False) #staff user non super user admin = models.BooleanField(default=False) #superuser time_stamp = models.DateTimeField(auto_now_add=True) #USERNAME_FIELD and password are required by default USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] object = UserManager() def __str__(self): return self.email def get_full_name(self): if self.full_name: return self.full_name return self.email def get_short_name(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self , app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active and my views.py for creating product is: class ProductCreateView(LoginRequiredMixin,CreateView): model = Product template_name = 'product-form.html' fields = ['title', 'price' , 'status' , 'size' , 'color', 'image' , 'description'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) and also i want that if staff is true then navbar show create product for user. rightnow if user is authenticated navbar show him to post the product {% if request.user.is_authenticated %} <li class="nav-item {% if request.path == … -
Django app share cookies with a chrome extension
I want to be able to set cookie on the client side with the Django app. So I can use as authentication for my API to be use for chrome extension. But I've been problems in finding most updated answer for using them and how to access them. -
How to get the related objects from a queryset?
models class Question(DateTimeEntity): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_questions') question = models.CharField(max_length=300) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='questions') class Answer(DateTimeEntity): question = models.ForeignKey(Question,on_delete=models.CASCADE, related_name='ques_answers') answer = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='answers') Here in the product detail view I am passing the questions context like this. product = Product.objects.get(pk=1) questions = product.product_questions.all().order_by('-created_at') answers = ... # I want to get the related answers of each question object from questions I can show the answers in the template from question like this {% for question in questions %} {% for ans in question.ques_answers.all %} {{ans}} {% endfor %} ... But with some reason I have to send answers of every question from view as a context. How can I achieve this from view ? -
Set default serializer for user in django
I created a rest-framework API in django for signup and its serializer is like this: class SignupSerializer(ModelSerializer): class Meta: model = User fields = ('email', 'password', 'first_name', 'last_name') read_only_fields = () def create(self, validated_data): with transaction.atomic(): new_user = User.objects.create_user(....) return new_user Now its working perfectly fine, but problem is that it also returns password hash in response object. Or if i include user in any other serializer and set depth=1 it still returns every field including password How can I set default serializer for user? so that it only returns those fields which I set by myself? -
How do I get the designation of a model field?
How can I put a designation (such as label in forms) in the model so that later it can be obtained, as here, for example: models: class characterist_0001_pkModel(models.Model): a1 = models.CharField('Процессор. Процессор', label = 'Процессор', max_length= 40, null= True) view: # хочу получить: Процессор characterist_0001_pkModel.a1.label -
Get objects that are not in manytomany relationship of a different model?
Lets say I have two models and a form: class Person(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) class Car(models.Model): plate = models.CharField(max_length=255) persons = models.ManyToManyField(Person) class CarAddForm(forms.ModelForm): plate = forms.CharField() persons = forms.ModelMultipleChoiceField(queryset=Person.objects.all()) class Meta: model = Car fields = [ 'plate', 'persons' ] Is there a way to get ModelMultipleChoiceField queryset of people that are NOT associated with any car? In case of editing Car model object, the queryset should contain people that are NOT associated with any car PLUS people that are associated with the car being edited PS: maybe there is a better way to achieve this? -
Django: objects are not showing at index page
This is my first project with Django and I got a problem. In the backend I created news, but I have an issue displaying the news on the frontpage. Models should be fine since I can create news into the admin panel. But I can't figure out where is my mistake. I have app 'pages'>views.py from django.shortcuts import render, redirect, get_object_or_404 from mainnews.models import Mainnews # Create your views here. def home_view(request): main = Mainnews.objects.all() context = { 'main' : main } return render(request, 'index.html', context) root>urls.py from pages.views import home_view urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name = 'home'), ] and app mainnews>views.py from django.shortcuts import render, get_object_or_404 from .models import Mainnews # Create your views here. def index(request): main = Mainnews.objects.all() context = { 'main' : main } return render(request, 'index.html', context) and the template mainnewsandevents.html that extends to index {% block content %} <!-- Section 2 News and Events --> <div id="news-container"> <div class="jumbo-news"> <img id = 'jumboImgUrl' class='jumbo-img' src="{{ main.image.url }}"> <h2 id = 'jumboTitle' class='jumbo-title'>{{ main.title }}</h2> <h4 id = 'jumboDescription' class='jumbo-parag'>{{ main.description }}</h4> </div> {% endblock %} -
No such application (or application not configured) A2 hosting django [closed]
** I have create that app already but it still show it while i restart the app **