Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to join serializer in django without foreignkey relationship and perform crud operation?
Models.py class MunicipalCouncil(models.Model): designation_id = models.PositiveIntegerField() address_id = models.PositiveIntegerField() council_name = models.CharField(max_length=255) email = models.EmailField(max_length=255, blank=True, null=True) country_code = models.CharField(max_length=5, blank=True, null=True) phone_number = models.CharField(max_length=15, blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) def __str__(self): """Return string representation of our models""" return self.email`enter code here` class Designation(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) def __str__(self): """Return string representation of our models""" return self.name class Address(models.Model): address_line1 = models.CharField(max_length=250, blank=True, null=True) address_line2 = models.CharField(max_length=250, blank=True, null=True) postcode = models.CharField(max_length=20, blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) def __str__(self): """Return string representation of our models""" return str(self.id) + ' ' + self.address_line1 Serializer.py class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = ('address_line1','address_line2','postcode') class MunicipalCouncilSerializer(serializers.ModelSerializer): class Meta: model = MunicipalCouncil fields = ('id','designation_id','council_name','email','country_code','phone_number') class DesignationSerializer(serializers.ModelSerializer): class Meta: model = Designation fields = ('name',) views.py Here In views.py what is the logic to join all three models and perform crud Operation, I will pass the data in postman, Note i will write only single api, that api should perform crud operation in all three models, No child and parent relationship, For more convenient i will pass the data in postman like this Council_name … -
Django urldispatcher: directing the request to special view
Django=3.0.8 urls.py urlpatterns += [ path('<slug:categories>/', include('categories.urls', namespace="categories")), ] categories/urls.py urlpatterns = [ path('', CategoryGeneralView.as_view(), name='general'), re_path(r'^(?P<type>novosti|tema)$/',CategorySpecialView.as_view(), name="type"), path('draft/<slug:slug>/', PostDetailView.as_view(), name="draft_post_detail"), path('<slug:slug>/', PostDetailView.as_view(), name="post_detail"), ] Proelem When I input either of http://localhost:8000/windows/tema/ http://localhost:8000/windows/novosti/ the request goes to PostDetailView. But I want it to go to CategorySpecialView. Could you help me here? -
How to get attributes of the current instance of the class in Django CBV
I'm building a tagging system for my blog using django-taggit module. I would like to get a list of all tags that the current post has when I open this post with a DetailView. Seems easy, but I just can't figure it out. I thought I would override the default get_queryset method in the DetailView class like this: def get_queryset(self): post_tags_ids = Post.tags.values_list('id', flat=True) but if later I: print(post_tags_ids) I get: <QuerySet [1, 2, 3, 4, 5, 6]> which is a queryset for all tags I have so far for all posts. I thought Django was smart enough to know to reference the current instance and I'm sure it is, so how do I get the attributes of the current instance of the class in Django -
The Django project that has been debugged locally is deployed to the centos7 server
The Django project that has been debugged locally is deployed to the centos7 server, and it is found that the static file images and CSS cannot be found, but there is no problem in the local debugging process before. How to deploy the static files in the server. I have searched a lot of questions on the Internet, but I have not solved this problem. Thanks -
Connecting Foreign key models with Django signal
I'm trying to build a Django signal whose sender is a Model (called Bacteria) and whose receiver is a model (called Bumblebee). These models have a foreign key relationship through the following: class Bumblebee(models.Model): name = models.CharField(max_length=50) class Bacteria(models.Model): bumblebee = models.ForeignKey(Bumblebee, on_delete=models.CASCADE) When I'm building this post_save signal to listen for a Bacteria being created, how do I then call fields of Bumblebee? This is what I have but it's not working. @receiver(post_save, sender=Bacteria) def my_handler(sender, **kwargs): bumblebee = Bacteria.bumblebee print(bumblebee.name) -
django-allauth multiple user type: adding users through admin portal
I'm new to Django and django-allauth, and would appreciate your help! I'm building out a custom User (email authentication with no username) with multiple user proxy models and associated user profiles (Student, Teacher, etc.), each with their own unique fields and unique sign-in form. Current Challenges: Normal login and signup work. Unfortunately, new user creation with a superuser account on the admin portal fails with no trace; only displays "Please correct the error below." This might be an easier fix... When I create a new superuser, its base_type is set to STUDENT. Is there a quick way to save superusers with type ADMIN rather than STUDENT? Disclaimer: The jumble of code below was put together from a variety of tutorials. If there's ways to improve beyond solving 1 and 2, would be happy to hear your input. Cheers! # models.py class CustomUserManager(BaseUserManager): """User manager with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) extra_fields.setdefault('is_active', True) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) … -
Django QuerySets - how to annotate off one field but return a different field?
Looking at the example given in the docs: https://docs.djangoproject.com/en/3.0/topics/db/aggregation/ Relevant Code to my question (from docs): from django.db import models class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() class Publisher(models.Model): name = models.CharField(max_length=300) class Book(models.Model): name = models.CharField(max_length=300) pages = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) rating = models.FloatField() authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) pubdate = models.DateField() class Store(models.Model): name = models.CharField(max_length=300) books = models.ManyToManyField(Book) The examples show how I could get the max price of a book at the store: >>> from django.db.models import Max, Min >>> Store.objects.annotate(max_price=Max('books__price')) However, what I want in my situation is the NAME of the max price book. How can I go about this? I recognize there could me multiple books with max price, but for my use case the tie breaking criteria doesn't matter. In my use case I will also be passing the QuerySet to a template so I would prefer to use the annotation framework. -
Passing an argument from views to Form Validation
Is there a way I can get the product gotten from product = Product.objects.get(id=id) and use it in my form validation? In my template, I have listed all my products and each has the AddSaleForm. When the user fills the form and submits it sends them to the make_sale view. Now I need to check that the quantity entered from the form does not exceed the quantity each product has (as shown in my commented code in my FORMS.PY.) Is there a way I can get the product? MY FORMS.PY class AddSaleForm(forms.ModelForm): class Meta: model = Sale fields = ['quantity', 'selling_price'] widgets = { 'quantity': NumberInput(attrs={'class': 'form-control', 'placeholder': 'items number'}), 'selling_price': NumberInput(attrs={'class': 'form-control', 'placeholder': '1000.00'}), } def clean_quantity(self, *args, **kwargs): sale_quantity = self.cleaned_data.get('quantity') if sale_quantity == 0: raise forms.ValidationError('The sale quantity cannot be zero (0)') # elif sale_quantity > product_quantity: # <----rom the product accessed from make_sale view # raise forms.ValidationError('The sale quantity cannot exceed the available quantity. ' # 'The availabe quantity for this product is ' + str(product_quantity)) return sale_quantity MY VIEWS.PY def make_sale(request, id): product = Product.objects.get(id=id) # To be accessed in the form for validation if request.method == 'POST': form = AddSaleForm(request.POST) if form.is_valid(): quantity = … -
How to create Class Based Views for Nested Crud in Django?
I was able to refactor half of my code to Class Based Views, but I am having a hard time with the nested crud portion of it. Here are my code. I am trying to refactor all the reviews to Class Views. [ enter image description here -
NeoVim Cannot Detect Django HTML FileType neither load snippets (htmldjango)
Using nvim 0.5.0, coc.nvim 0.0.78 and Nord for GNOME terminal. I'm editing Django template html files but the html doesn't open djangohtml snippets: call plug#begin('~/.config/nvim/autoload/plugged') " Better Syntax Support Plug 'sheerun/vim-polyglot' " Auto pairs for '(' '[' '{' Plug 'jiangmiao/auto-pairs' " Auto close tags <> Plug 'alvan/vim-closetag' " Theme Plug 'arcticicestudio/nord-vim' " Air theme Plug 'vim-airline/vim-airline' " Cool Icons Plug 'ryanoasis/vim-devicons' " Stable version of coc && snippets Plug 'neoclide/coc.nvim', {'branch': 'release'} Plug 'honza/vim-snippets' " Complements Plug 'tpope/vim-commentary' " Repeat stuff Plug 'tpope/vim-repeat' " Surround Plug 'tpope/vim-surround' " Fast within-file word replacement. Plug 'wincent/scalpel' " FZF and rooter Plug 'junegunn/fzf', { 'do': { -> fzf#install() } } Plug 'junegunn/fzf.vim' Plug 'airblade/vim-rooter' " For show the #color in a css file Plug 'ap/vim-css-color' " For git integration Plug 'mhinz/vim-signify' Plug 'tpope/vim-fugitive' Plug 'tpope/vim-rhubarb' " Vim whichkeys Plug 'liuchengxu/vim-which-key' " Distraction free writing by removing UI elements and centering everything. Plug 'junegunn/goyo.vim' " For nice & tabular tables. (works in md too) Plug 'godlygeek/tabular' " VimWiki Plug 'vimwiki/vimwiki' " Vim-Startify Plug 'mhinz/vim-startify' call plug#end() comment and uninstalled Plug 'sheerun/vim-polyglot' was not the issue then in my coc.vim file I try to fix the issue editing g:coc_filetype_map " Tell djangohtml to filetype map … -
Django CreateView ignoring get_success_url
I have the following view that works except that it is ignoring get_success_url(). It sends the user back to the same url for the form. The user is created. The view class is just an extended createview that I use in many other places without an issue. class SignUpView(BSModalCreateView): model = User form_class = SignUpForm success_message = 'Please check your email to complete the registration' template_name = 'form_modal.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['heading'] = 'Create ID' return context def form_valid(self, form): user = form.save(commit=False) user.is_active = False user.save() # current_site = get_current_site(request) current_site = '127.0.0.1:8000' mail_subject = 'Activate your account.' message = render_to_string('registration/confirm_email.html', { 'user': user, # 'domain': current_site.domain, 'domain': '127.0.0.1:8000', 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('dashboard') I have tried a bunch of different things t no avail but hope someone else can help. -
Add more than one item in Dynamic form django
I'm new in Web programming, i am trying to create a form in which it is possible to aggregate many IP addresses and ports, When i click summit with only one IP and port it works and my model is updated, but when i try to add more than one it does not work. I realized that index isn't updating, but i dont know how fix it #Views from django.shortcuts import render, redirect from django.http import HttpResponse from django.forms import modelformset_factory from BrainCH.forms import formulario_crear_serv,formulario_members from django.contrib import messages from django.db import transaction,IntegrityError from F5APP.models import CrearServicio,members def Home(request): diccionario_home = {} return render(request,"home.html",diccionario_home) #return HttpResponse("Home") def NuevoServicio(request): diccionario_crearservicio={} Membersformset=modelformset_factory(members, form=formulario_members) form =formulario_crear_serv(request.POST or None) formset=Membersformset(request.POST or None, queryset=members.objects.none(), prefix="members") if request.method== "POST": if form.is_valid() and formset.is_valid(): try: with transaction.atomic(): crearServicio = form.save(commit=False) crearServicio.save() for member in formset: data=member.save(commit=False) data.crearServicio = crearServicio data.save() #print("paso 7") except IntegrityError: print("Error") return redirect("list") diccionario_crearservicio["formset"] = formset diccionario_crearservicio["form"] = form return render(request,"CrearServicio.html",diccionario_crearservicio) def list(request): datas= CrearServicio.objects.all() return render(request,"list.html",{"datas":datas}) #MOdels from django.db import models class persistencias(models.Model): tipo=models.CharField(max_length=15) def __str__(self): return(self.tipo) class serviciosite(models.Model): #act-act o act-bkp tipo=models.CharField(max_length=15) def __str__(self): return(self.tipo) class areas(models.Model): tipo=models.CharField(max_length=30) def __str__(self): return(self.tipo) class ambientes(models.Model): tipo=models.CharField(max_length=15) def __str__(self): return(self.tipo) class estadositecdlv(models.Model): tipo=models.CharField(max_length=10) def … -
Django/Pandas: Trying to add new column to Excel but getting Error
I've created a Django powered solutions to process Excel sheets with Pandas. Trying to code a process to create a missing mandatory column if not existed in Excel. With Pandas its piece of cake but with structured laid for supporting to make this happen within Django I have an error I can't get rid off. Models With Save Func: from datetime import datetime today = datetime.today().strftime('%Y-%m-%d') class Sheet(models.Model): UNKNOWN_PERIOD_END = 'unknonw_period_end' UNKNOW_PERIOD_END_DEFAULT = today name = file = header_row = num_sheets = template_sheet = extracted_headers = num_headers = header_mappings = has_all_required_mappings = def __str__(self): return self.name .... .... def get_required_columns(self): """ Returns a dict of where the keys are the names of the db field names that are required and its values are the mapped header file column names. """ mapped_headers = json.loads(self.header_mappings) required_columns = {key: val for key, val in mapped_headers.items() if key in settings.REQUIRED_COLUMNS} if required_columns["Reporting_Period_End_Date"] == self.UNKNOWN_PERIOD_END: del required_columns["Reporting_Period_End_Date"] return required_columns def has_unknown_period_end(self): header_mappings = json.loads(self.header_mappings) return header_mappings['Reporting_Period_End_Date'] == self.UNKNOWN_PERIOD_END class MainSheet(models.Models): ..... ..... template = models.ForeignKey excel_file = models.ForeignKey is_matching_all_templates = ..... ..... @property def classified(self): return self.excel_file.file def get_errors_list(self): if self.errors: return json.loads(self.errors) return None @property def filename(self): if self.original_filename: return self.original_filename return os.path.basename(self.classified.name) def … -
django listview filter & get value templates
I made a list of events registered today in the inventory template, and I would like to show the total rating of the events(registered today). I called it from the template by making the sum of the scores a function, but it is not visible. Does anyone know? views.py class CalendarView(generic.ListView): model = Event template_name = 'cal/calendar.html' def get_queryset(self, **kwargs): return Event.objects.all().filter(start_time__date=date.today()) def get_context_data(self, **kwargs): queryset = super(CalendarView, self).get_context_data(**kwargs) queryset['some_data'] = 'this is data' return queryset def filter_event_rating_sum(self): filtered_event = Event.objects.all().filter(start_time__date=date.today()) sum_rating = 0 for each_event in filtered_event: sum_rating += each_event.rating return sum_rating templates.html <p class="today">Today</p> {% for list in object_list %} <div class="today_list_item"> <span>{{ list.title }}</span> <span class="each_rating">{{ list.rating }}</span> </div> {% endfor %} <p class="total">TOTAL</p> {{ sum_rating }} </div> models.py class Event(models.Model): title = models.CharField(max_length=200) start_time = models.DateTimeField(default = timezone.now, blank = True) # default = timezone.now, profile=models.ForeignKey(Profile, related_name='event',on_delete=models.CASCADE) rating = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)], blank=True, default='enter your value') def __str__(self): return '{}/ {}/ {}'.format(self.id, self.title, self.start_time, self.rating) -
How do I associate multiple python-social-auth social accounts with an existing user via REST api?
I'm using python-social-auth to allow my users to register via Apple and Google. I'm trying to figure out how via REST I can associate social accounts to an existing user with a different email than the social account (project req is that users are manually created in the backend and then can associate a social login for ease-of-access). This is a React Native app so the usual automatic way of active sessions won't work. I'm using https://github.com/st4lk/django-rest-social-auth to create easy endpoints. Thanks in advance y'all. -
django rest framework simple jwt "detail": "No active account found with the given credentials"
I implemented membership using custom registration serializer. And after signing up as a member, I am going to get access token and refresh token.But the following error is disturbing me. "detail": "No active account found with the given credentials" The incomprehensible part is that the admin account created using the createupuser command proceeds normally, but the member account does not generate a token. Can you give me a tip on this? Here is my code models.py class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, email, profile, userName, password): user = self.model( email=self.normalize_email(email), password=password, userName=userName, profile=profile, ) user.set_password(password) user.save() return user def create_superuser(self, email, password, userName, profile): user = self.create_user( email=self.normalize_email(email), password=password, userName=userName, profile=profile, ) user.is_staff = True user.is_superuser = True user.set_password(password) user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) userName = models.CharField(max_length=10) profile = models.ImageField(default='default_image.jpeg') is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['userName', 'profile'] serializers.py class customRegisterSerializer(serializers.Serializer): email = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED) password = serializers.CharField(write_only=True) user_Name = serializers.CharField(required=True) profile = serializers.ImageField(use_url=True) def validate_email(self, email): email = get_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( _("A user is already registered with this e-mail address.")) return email def validate_password(self, password): return get_adapter().clean_password(password) def get_cleaned_data(self): return { 'email': … -
Wagtail: View page log entries from PageLogEntry
From the docs it says that changes are automatically logged at the model level. I am in a situation where I need to check said logs but I am unable to import the PageLogEntry model. From the docs above I tried from wagtail.core.models import PageLogEntry but it's not importable. Looking at Wagtail's source code, I can see the specified module. I tried to also check my database for the table itself but nothing there either. Is it that this functionality isn't in fact enabled automatically or is there something special that needs to be done to access the logs. TIA -
url cant reverse match in django
I have encountered quite an interesting problem while specifying urls in django.I know there are lots of SO questions on it,but mine seems to be different than every other one.here is the problem: I have a list of 3 layers,that was created in views.py and passed to templates by context.the list seems to look like this pattern: my_list = [ [[x,y] , [z,a]] , [.....] , [.....] ,...] in Jinja i tried to reach the inner 'x' labelled content. so, i tried like this.. {% for item in my_list: %} {{item.0.0.category}} .....code .....code and it worked successfully.It really reached the 'x' label content and printed out its category name. but as soon as i put a url like this <a href = "{% url 'category' item.0.0.category %}"> abcd </a> It says no reverse match for 'category' found.I am attaching all my codes for a better understanding. in my urls.py: from django.contrib import admin from django.urls import path from store.views import ( home_view, ) urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name = 'home'), path('category/<str:category_name>/', category_view, name = 'category'), ] some focus of my views.py: def home_view(request): ...... ...... context = { 'my_list' : my_list, } return render(request , 'xyz.html', context) … -
how can i use react redux in antd?
i have this code on my Form inside reactjs , i whanna know in ANT Design wich way is currect to send data from form into jason and then send to backend import React from "react"; import axios from "axios"; import { Form, Input, Button, Select, Switch, DatePicker, InputNumber, } from "antd"; const FormItem = Form.Item; const { Option } = Select; // const onFinish = values => { // console.log(values); // }; class ExtrashiftForm extends React.Component { handleFormSubmit = (values, requestType, ExtrashiftID) => { const title = values.title; const manager = values.manager; const datetime = values.datetime; const gender = values.gender; const Lable = values.Lable; const quantity = values.quantity; console.log(title, manager, datetime, gender, Lable, quantity); switch (requestType) { case "post": return axios .post("url://127.0.0.1:8000/api/", { title: title, manager: manager, datetime: datetime, gender: gender, Lable: Lable, quantity: quantity, }) .then((res) => console.log(res)) .catch((err) => console.err(err)); case "put": return axios .put(`http://127.0.0.1:8000/api/${ExtrashiftID}/`, { title: title, manager: manager, datetime: datetime, gender: gender, Lable: Lable, quantity: quantity, }) .then((res) => console.log(res)) .catch((err) => console.err(err)); } }; render() { return ( <div> <Form onFinish={(values) => this.handleFormSubmit(values, this.props.values) } > <FormItem name="title" label="Title"> <Input placeholder="title here" /> </FormItem> <Form.Item name="manager" label="Manager" hasFeedback rules={[{ required: true, message: "Please select … -
Custom error from Django Rest Framework is not working
I trying to return a JSON response from Django exceptions, I have implemented the following function def custom_exception_handler(exc): response = exception_handler(exc) if response.status_code == 404: return Response({'foo':'bar'}, template_name=None, content_type='application/json', status=status.HTTP_404_NOT_FOUND) else: return Response({'foo':'bar'}, template_name=None, content_type='application/json', status=status.HTTP_201_CREATED) And I have added these in my settings.py file REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'views.custom_exception_handler' } But I am still getting a HTML file rather than a JSON resonse. -
How to access other model fields through foreign key in Django Views
I want to query from OrderItem Model like total_orders = OrderItem.objects.filter(product.user == request.user.id).count() but i am getting error ** NameError at /home name 'product' is not defined ** MY MODELS: Product Model: class Product(models.Model): title = models.CharField(max_length=150) user = models.ForeignKey( User, blank=True, null=True, on_delete=models.SET_DEFAULT, default=None) description = models.TextField() price = models.FloatField() quantity = models.IntegerField(default=False, null=True, blank=False) minorder = models.CharField( max_length=150, help_text='Minum Products that want to sell on per order', null=True, default=None, blank=True) image = models.ImageField() category = models.ForeignKey( Categories, default=1, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) def __str__(self): return self.title Order Item Model class OrderItem(models.Model): product = models.ForeignKey( Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey( Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.FloatField(default=0, null=True, blank=True) date_orderd = models.DateTimeField(auto_now_add=True) user = models.ForeignKey( User, on_delete=models.SET_NULL, blank=True, null=True) price = models.FloatField(blank=True, null=True) def __str__(self): return str(self.product) My View: def home(request): total_orders = OrderItem.objects.filter( product.user == request.user.id).count() return render(request, "sellerprofile/home.html", {'total_orders': total_orders}) -
Django Listview filter & show in templates
I am trying to register events in the calendar and show events registered today together at the bottom of the template.there are errors in writing a filter query that shows the events registered today in the view that goes to the page that shows the calendar. My goal: filter events (start_time = today) at bottom of the template. My model: class Event(models.Model): title = models.CharField(max_length=200) start_time = models.DateTimeField(default = timezone.now, blank = True) # default = timezone.now, profile=models.ForeignKey(Profile, related_name='event',on_delete=models.CASCADE) rating = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)], blank=True, default='enter your value') def __str__(self): return '{}/ {}/ {}'.format(self.id, self.title, self.start_time, self.rating) Forms.py from django.forms import ModelForm, DateInput from cal.models import Event from .widgets import RateitjsWidget class EventForm(ModelForm): class Meta: model = Event # datetime-local is a HTML5 input type, format to make date time show on fields widgets = { 'rating': RateitjsWidget, 'start_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), } fields = ['title','start_time','rating'] # , 'profile' def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) # input_formats parses HTML5 datetime-local input to datetime field self.fields['start_time'].input_formats = ('%Y-%m-%dT%H:%M',) My view: class CalendarView(generic.ListView): model = Event template_name = 'cal/calendar.html' # event_queryset = Event.objects.filter(start_time__startswith=datetime.date.today) def get_queryset(self, **kwargs): event_queryset = Event.objects.filter(start_time__day=datetime.today()) context = { 'data': self.event_queryset } return self.render_to_response(context) templates/calender.html: {% extends 'cal/base.html' %} … -
I deleted sqlite3 and after Migration I keep receiving: OperationalError at / no such table: core_item
I wanted to clean my database and start over so I deleted sqlite3 and after deleting it I ran python manage.py makemigrations and python manage.py migrate but I keep receiving an error OperationalError at / no such table: core_item I am not sure why is this happening so I am copying the traceback call: Traceback (most recent call last): File "C:\Users\User\Desktop\Projectz 4.3\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\User\Desktop\Projectz 4.3\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\User\Desktop\Projectz 4.3\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\Desktop\Projectz 4.3\venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\User\Desktop\Projectz 4.3\venv\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "C:\Users\User\Desktop\Projectz 4.3\venv\lib\site-packages\django\views\generic\list.py", line 157, in get context = self.get_context_data() File "C:\Users\User\Desktop\Projectz 4.3\core\views.py", line 82, in get_context_data context = super(HomeView, self).get_context_data(**kwargs) File "C:\Users\User\Desktop\Projectz 4.3\venv\lib\site-packages\django\views\generic\list.py", line 119, in get_context_data paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size) File "C:\Users\User\Desktop\Projectz 4.3\venv\lib\site-packages\django\views\generic\list.py", line 69, in paginate_queryset page = paginator.page(page_number) File "C:\Users\User\Desktop\Projectz 4.3\venv\lib\site-packages\django\core\paginator.py", line 70, in page number = self.validate_number(number) File "C:\Users\User\Desktop\Projectz 4.3\venv\lib\site-packages\django\core\paginator.py", line 48, in validate_number if number > self.num_pages: File "C:\Users\User\Desktop\Projectz 4.3\venv\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\User\Desktop\Projectz 4.3\venv\lib\site-packages\django\core\paginator.py", line 97, in num_pages if … -
Django & Python: AttributeError: module 'blog.views' has no attribute 'detail'
File url.py from django.urls import path from . import views urlpatterns = [ path('', views.allblogs, name='allblogs'), path('<int:blog_id>/', views.detail, name='detail'), ] File views.py from django.shortcuts import render, get_object_or_404 from .models import Blog def allblogs(request): blogs = Blog.objects return render(request, 'blog/allblogs.html', {'blogs':blogs}) def detail(request, blog_id): detailblog = get_object_or_404(Blog, pk=blog_id) return render(request, 'blog/detail.html', {'blog':detailblog}) I got AttributeError: module 'blog.views' has no attribute 'detail'. The error was in "portfolio-project\blog\urls.py", line 7, in path('int:blog_id/', views.detail, name='detail'), -
How to access a list's length in a template's code block for Django?
In a template, I have a variable of type list called "participants". I want to check if the length of the list is equal to 2, for example. I tried the following: {{ participants | json_script:"participants"}} {% if participants|length==2 %} ..... {% endif %} However, this does not work. The error I get is: TemplateSyntaxError at /chat/lobby/ Could not parse the remainder: '==2' from 'participants.count==2' Can someone point out a way to access a list's length in a template's code block? thank you for your time and consideration!