Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django, how do I write a query that filters a date column by a specific day of the week?
I'm using Python 3.9, Django 3.1, and PostGres 10. I have the following query to give me the articles created in a particular date range ... qset = Article.objects.filter( created_day__gte=start_date, created_day__lte=end_date ) What I would like to add is a clause to specify the number of articles created in a date range that were also created on a specific day of the week (e.g. Monday), where the days of the week are represented by integers (0 = Monday, 1 = Tuesday, ... 6 = Sunday). How do I add a clause that would also filter by the day of the week? -
Django requirements.txt file conditional to distinguish between development and production
The headline pretty summary it. We can create settings.py files for different environments.(development/production). But Is it possible to do the same with the requirements file ? I have the same Django project running on heroku for production, and on docker-compose container on my localhost. I read PEP-508 and the same questions about systems. Is there a way to achieve conditions in the requirements file to distinguish between heroku to docker ? -
Is there a way to check if a value is equal to another value directly on a django template
I have this {% for position in delegates %} {{ position.department }} # This is here to check the value of position.department, Returns Information Technology {% if position.department == department %} <h1>Got It</h1> {% else %} <h1>NUUUUH </h1> {{ departmemt }} # This is here to see the value of department, Returns Information Technology {% endif %} The values are the same but it executes the else statement. Any help? -
Django: included login form reloading when there are errors
I'm building a Django app where I show a landing page if there's no user logged in, and I display the login form within that page. I've followed these setup steps to get going, and then I added a context processor so I could display the login form within my landing page view, and I added it to the context_processors list in settings.py. All of that is working great! I can successfully log someone in, or if I give a wrong password I get the message that the credentials aren't right. The problem: in the case where I give a wrong password and fail authentication, the website reloads the login form on its own with the message to the user (so the user's going to another page). How I can display the error message from within that same landing page where the form is originally displayed? (Note: I'm using the default Django authentication and haven't done anything yet to define any special behavior) landing.html: {% block content %} Some welcome message! {% include "registration/login.html"%} Some other contents {% endblock content %} context_processors.py: def include_login_form(request): from django.contrib.auth.forms import AuthenticationForm form = AuthenticationForm() return {'form': form} Login.html: {% extends 'familytree/base.html' %} {% … -
shared_task not getting registered in Celery, Redis, Django, on windows 10
Django = 3.2 Celery = 4.3.0 (rhubarb) Redis = 3.5.3 windows 10 proj/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'kunai.settings') celery_app = Celery('kunai') celery_app.config_from_object('django.conf.settings', namespace='CELERY') celery_app.autodiscover_tasks() @celery_app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') @celery_app.task(bind=True) def greet_task(self): print('hello World') proj/init.py from __future__ import absolute_import, unicode_literals from .celery import celery_app __all__ = ('celery_app',) app/task.py from celery import shared_task from celery import app from .track import track celery = Celery('task', broker='redis://127.0.0.1:6379') #! @shared_task(name="update_product_task") def update_product_task(): track() return True @app.task(bind=True) def product_task(): track() return True proj/settings.py CELERY_RESULT_BACKEND = 'django-db' CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' celery output screen (venv) PS E:\DjangoProjects\kunai> celery -A kunai worker -l info -P gevent -------------- celery@DESKTOP-6F61B0H v4.3.0 (rhubarb) ---- **** ----- --- * *** * -- Windows-10-10.0.19041-SP0 2021-05-09 00:03:02 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: kunai:0x2cbc1802490 - ** ---------- .> transport: redis://127.0.0.1:6379// - ** ---------- .> results: - *** --- * --- .> concurrency: 4 (gevent) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . kunai.celery.debug_task . kunai.celery.greet_task [2021-05-09 00:03:02,857: INFO/MainProcess] … -
Related Field got invalid lookup
I have a Django3 project (my first) with a model named Product that has a m2m relationship with Location (ProductLocation). ProductLocations have a m2m relationship with Category through ProductLocationCategory). I am looking to pull all products that have ProductLocation.active = True and ProductLocation.active_last_run = False. To do so, I use the following code: new_products = Product.objects.filter(locations__active=True, locations__active_last_run=False) which I borrowed from the Django help docs. The Product, ProductLocation, and ProductLocationCategory are as follows: class Product(models.Model): name = models.CharField(max_length=100, null=True, blank=True) description = models.CharField(max_length=500, null=True, blank=True) image = models.CharField(max_length=500, null=True, blank=True) locations = models.ManyToManyField('Location', null=True, through='ProductLocation') active = models.BooleanField(default=True, blank=True) class ProductLocation(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE) location = models.ForeignKey('Location', on_delete=models.CASCADE) categories = models.ManyToManyField('Category', null=True, through='ProductLocationCategory') active = models.BooleanField(default=True, blank=True) active_last_run = models.BooleanField(default=False, blank=True) class ProductLocationCategory(models.Model): product_location = models.ForeignKey('ProductLocation', on_delete=models.CASCADE) category = models.ForeignKey('Category', on_delete=models.CASCADE) active = models.BooleanField(default=True, blank=True) active_last_run = models.BooleanField(default=False, blank=True) The full(er) error I receive is as follows: File "/home/user/projects/myproject/app/product/views.py", line 24, in location_detail ... new_products = Product.objects.filter(locations__active=True, locations__active_last_run=False) ... django.core.exceptions.FieldError: Related Field got invalid lookup: active_last_run I have verified all the migrations have run, the fields are in the database, I have created multiple migrations adding and removing the field. If I only run: new_products = Product.objects.filter(locations__active=True) then the … -
How to manage cpu and memory with django channels
Is there a way to better manage cpu and memory usage with django channels? I am trying to stream data very quickly over websockets, which works well until my ubuntu server cpu hits 100% and memory hits 90%, then daphne crashes. I am using NGINX and Daphne as server/proxy. Is there a better way to setup redis? or potentially a method to 'clear cache' or something similar? my setup is: settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], "capacity": 5000, "expiry": 5, }, }, } asgi.py application = ProtocolTypeRouter({ # Django's ASGI application to handle traditional HTTP requests "http": django_asgi_app, # WebSocket chat handler "websocket": AuthMiddlewareStack( URLRouter([ url(r"^stream/(?P<device_id>[\d\-]+)/$", StreamConsumer.as_asgi()), url(r"^status/(?P<device_id>[\d\-]+)/$", StatusConsumer.as_asgi()) ]) ), }) consumer.py class StreamConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['device_id'] self.room_group_name = 'stream_%s' % self.room_name self.token_passed = self.scope['query_string'].decode() #token passed in with ws://url/?token self.token_actual = await self.get_token(self.room_name) #go get actual token for this monitor # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) #check to ensure tokens match, if they do, allow connection if self.token_passed == self.token_actual: await self.accept() print('True') else: print(self.token_passed) print(self.token_actual) await self.close() async def disconnect(self, close_code): # Leave room group print(close_code) print("closing") await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) @database_sync_to_async def … -
Error while Installing Packages from requirements.txt in python 3.9
when i run pip install -r requirements.txt i get ERROR: Could not find a version that satisfies the requirement cffi==1.14.0 (from versions: 0.1, 0.2, 0.2.1, 0.3, 0.4, 0.4.1, 0.4.2, 0.5, 0.6, 0.7, 0.7.1, 0.7.2, 0.8, 0.8.1, 0.8.2, 0.8.3, 0.8.4, 0.8.5, 0.8.6, 0.9.0, 0.9.1, 0.9.2, 1.0.0, 1.0.1, 1.0.2.post2, 1.0.3, 1.1.0, 1.1.1, 1.1.2, 1.2.0.post1, 1.2.1, 1.3.0, 1.3.1, 1.4.0, 1.4.1, 1.4.2, 1.5.0, 1.5.1, 1.5.2, 1.6.0, 1.7.0, 1.8.2, 1.8.3, 1.9.0, 1.9.1, 1.10.0, 1.11.0, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.12.0, 1.12.1, 1.12.2, 1.12.3, 1.13.0, 1.13.1, 1.13.2, 1.14.0, 1.14.1, 1.14.2, 1.14.3, 1.14.4, 1.14.5) ERROR: No matching distribution found for cffi==1.14.0 by the way my requirements.txt file contains absl-py==0.9.0 asgiref==3.2.7 astor==0.8.0 astunparse==1.6.3 attrs==19.3.0 backcall==0.1.0 backoff==1.10.0 beautifulsoup4==4.9.1 bleach==3.1.4 blinker==1.4 bs4==0.0.1 cachetools==3.1.1 certifi==2020.4.5.1 cffi==1.14.0 chardet==3.0.4 click==7.1.2 cryptography==2.9.2 decorator==4.4.2 defusedxml==0.6.0 dill==0.3.1.1 Django==3.0.6 entrypoints==0.3 future==0.18.2 gast==0.3.3 geocoder==1.38.1 grpcio==1.27.2 h5py==2.10.0 idna==2.9 importlib-metadata==1.5.0 notebook==6.0.3 numpy==1.18.1 pickleshare==0.7.5 pyOpenSSL==19.1.0 pyrsistent==0.16.0 PySocks==1.7.1 python-dateutil==2.8.1 pytz==2020.1 pyzmq==18.1.1 qtconsole==4.7.4 QtPy==1.9.0 ratelim==0.1.6 requests==2.23.0 requests-oauthlib==1.3.0 testpath==0.4.4 tornado==6.0.4 tqdm==4.46.0 traitlets==4.3.3 twilio==6.40.0 urllib3==1.25.8 widgetsnbextension==3.5.1 wrapt==1.12.1 zipp==3.1.0 bcrypt argon2-cffi django-allauth pywhatkit -
How can I go about creating a web app for people to reserve a duration of time(1hr) in a day for a gym related website
So I have been studying python for a good amount of time and am learning django. I have also learned basics of html/css/javascirpt. Here is my idea: I want to create a web application for a local gym where subscribers are able to login, and because of covid, people are required to reserve the time they want to workout at, so how can I go about doing the following things: How can I make the logic for people to be able to reserve a duration of time and of course there should be a limit of people that can workout during the same time, say 30 people in a given hour, so the website should disable allowing other users to reserve that time. I am not sure how to implement the logic of RESERVATION if anyone has any idea, so should there be a model containing all the days of the year or what. This part is a big confusion of mine How can i make it possible to make that users are given a username and password to login as there shouldn't be a sign up page, because only paid subscribers should be able to login and reserve, so … -
Is it possible to only specify the name of the "base.html" file in the {%extends%}, instead of "app/base.html"?
I'm learning Django and I stumble upon a question: Is it possible to make the path to the base.html file in the {% extends "app/base.html" %} link from the helloworld.html file as short as possible? So I would only have to write {% extends "base.html" %} to make it work. Right now, if I try to do this, python will throw an exception at the def helloworld(request): function in views.py. So my app file structure is: ├── app │ ├── migrations │ ├── static │ ├── templates │ ├── app │ ├── base.html │ ├── helloworld.html │ ├── views.py │ └── models.py ├── DjangoProject │ ├── __init__.py │ ├── urls.py │ ├── settings.py │ ├── templates ├── manage.py helloworld.html: {% extends "app/base.html" %} {% block head_title %} hello {% endblock %} {% block content %} <p> hello world </p> {% endblock %} views.py: from django.shortcuts import render from django.http import HttpRequest def helloworld(request): hello_title = 'Test' assert isinstance(request, HttpRequest) return render( request, 'app/helloworld.html', { 'title_test':hello_title } ) settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = [ 'app',] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates'),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I … -
Wagtail Filter ForeignKey By Current User
I am trying to build a progress tracker for an educational training app in Wagtail. I use a PageModel to represent a "Lesson": # courses/models.py class SectionLessonPage(Page): lesson_video = models.ForeignKey('wagtailvideos.Video', related_name='+', null=True, on_delete=models.SET_NULL) content_panels = Page.content_panels + [ VideoChooserPanel('lesson_video'), ] def serve(self, request): if request.user.is_authenticated: lesson_viewed_signal.send(self.__class__, instance=self, request=request) return super().serve(request) And I have a separate 'progress' app, which receives a signal from the serve function to record a page visit by a specific user. # progress/models.py class UserLessonView(models.Model): lesson = models.ForeignKey( 'courses.SectionLessonPage', null=True, blank=True, on_delete=models.CASCADE, related_name="views" ) user = models.ForeignKey(User, on_delete=models.CASCADE) viewed_on = models.DateTimeField(auto_now_add=True) This establishes a one-to-many relationship between the two models. However, the current logged in user is not taken into account when in the template I try to obtain the SectionLessonPage's 'views' for the logged in user. Since the current user is not a field of SectionLessonPage, there is no model relationship to use. Instead possibly this needs to be handled in the get_context() or serve() method of SectionLessonPage. The problem is that the when I call {{ self.views }} on the SectionLessPage template, it returns all views for all users. I need it to return the views only for the current user. How can I pass … -
Django Error on terminal "ValueError: source code string cannot contain null bytes"
Django project was working fine. Now it gives me this ValueError when I'm attempting to run the server. Been searching for a solution for the past 3 days, but I'm stuck. Many solutions say I must just convert the files to UTF-8. But how do I do that? Which file do I have to convert? I'm using the Atom Editor, which saves all files in UTF-8. This is from my terminal: Terminal -
Image/Files not Being Posted Django
I have been trying to Post Images in Django and I don't know why they are not being posted. I use image = form.cleaned_data.get("image") and It is not being save. whenever I save the image won't get saved but the text or the content gets saved, now I'm perplexed. Please Help Me... Models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Post(models.Model): title = models.CharField(max_length = 200) content = models.TextField() image = models.ImageField(upload_to = "post_img", null = True, blank = True) pub_date = models.DateTimeField(default = timezone.now) author = models.ForeignKey(User, on_delete = models.CASCADE) def __str__(self): return f"{self.title} // {self.author}" forms.py from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ["title", "content", "image"] Views.py from django.shortcuts import render,redirect from django.http import HttpResponse from .models import Post from .forms import PostForm # Create your views here. def index(request): posts=Post.objects.order_by("-pub_date") context ={ "posts":posts } return render(request, "index.html",context) def post_view(request): form = PostForm(request.POST,request.FILES or None) if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] image = form.cleaned_data.get("image") activeUser = request.user post = Post.objects.create(title = title, content = content, image = image, author = activeUser) post.save() return redirect("posts:home") else: … -
Does Django differentiate btw jpg and png files when processing static files?
Does Django differentiate between jpg and png files when processing static files? Specifically, when a jpg file is in the static directory (vs. in the static/media directory)? In my case: the jpg image doesn't load in <img src="{% static 'weather.jpg' %}" alt="">, but the png image does in the same url: <img src="{% static 'doggie.png' %}" alt="">. But both the png and jpg images load if they are in the static/media directory--which led me to wonder whether jpg files must be in a media folder: <img src="{% static 'media/doggie3.png' %}" alt=""> and <img src="{% static 'media/weather.jpg' %}" alt=""> Here's how 'static' is setup in settings.py file (ok: I admit The code is cobbled together, but at least one type of static file is loading): STATIC_URL = '/static/' STATIC_ROOT = Path.joinpath(BASE_DIR, 'static') MEDIA_URL ='/media/' MEDIA_ROOT = Path.joinpath(BASE_DIR, 'media') And in urls.py: urlpatterns = [ ... ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += [ path('accounts/', include('django.contrib.auth.urls')), ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Django for tag doesn't work without a model
I want to use a for bucle in Django but with my own list (not using de model): This works great: {% for book in book_list %} {{ book.title }} {% endfor %} But this doesn't work: {% for book in ['Lord of the rings', 'Django for Beginners', 'Harry Potter'] %} {{ book }} {% endfor %} -
Checking if the filter-form is empty in django
I have a problem with filtering in Django. I have a database which I want to filter and return the result on the screen but when I submit empty filed it shows all the database. I would like to have an empty page when the user submit an empty filed and does not filter at all. I already used if not queryset but no difference. I appreciate your help. the View : def advanceFilter2(request): books = Setup2.objects.all() # filter setting form = ManipulationForm() filtering = Setup2Filter(request.GET, queryset=books) if not filtering: return render(request,'AdvanceFilter2.html') books = filtering.qs sprache = Setup2.sprache # if filtering: # return render(request, 'Test.html') context = {"filtering": filtering, 'books': books, 'form': form, 'sprache': sprache} if request.method == 'GET' and sprache != '&' : context.update({'post_output': request.GET.get('books','')}) return render(request, 'AdvanceFilter2.html', context) HTML file : {%load static%} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{%static 'testApp\Buecher.css'%}" type="text/css"> </head> <form method="get"> {{filtering.form}} <input type="submit" name="submit" value="Submit" /> </form> {% if request.GET.submit and filtering%} {%for i in books%} {{ i.sprache }} {%endfor%} {% endif %} ``` filter.py: `` import django_filters from .models import * class Setup2Filter(django_filters.FilterSet): class Meta: model = Setup2 fields = ['sprache'] forms.py: from .models import * from django.forms import ModelForm … -
Graphene-django api responds methos OPTIONS not allowed when POST is dent from React
I am following this tutorial to create a graphene-django endpoint, and everything seems fine (I can test the endpoint with graphene tool): from django.contrib import admin from django.urls import path from django.views.decorators.csrf import csrf_exempt from graphene_django.views import GraphQLView urlpatterns = [ path('admin/', admin.site.urls), path("graphql", csrf_exempt(GraphQLView.as_view(graphiql=True))), ] The problem comes when I try to send a POST from a React app: export const fetchApplicationComposite = async () => { const requestString = graphql_api_url; const form = { query: '{hello}', variables: null } try { const Response = await axios.post(requestString, form); return { data: Response.data, message: null }; } catch (Error) { return Error.message; } } This POST returns the following error: Request URL: http://localhost:8000/graphql Request Method: OPTIONS Status Code: 405 Method Not Allowed Remote Address: 127.0.0.1:8000 Referrer Policy: strict-origin-when-cross-origin I can't find a solution to this problem. -
I keep getting server error 500 and on debug = True, the actual error is "TemplateDoesNotExist at /createaccount/ Bootstrap4/uni_form.html"
I deployed my django app to heroku but I keep getting server error 500 and on debug = True, the actual error is that "TemplateDoesNotExist at /createaccount/ Bootstrap4/uni_form.html" when trying to open the 'login'and 'register' pages. TemplateDoesNotExist However, other pages are working that have specified links the url.py file. Here's my url.py file. from django.contrib import admin from django.urls import path , include from createaccount import views as c from myBlog import views as m from django.contrib.auth import views as auth_views urlpatterns = [ path ( 'admin/' , admin.site.urls ) , path ( '' , m.IndexView.as_view () , name='home' ) , path ( 'createaccount/' , c.createaccount , name='create' ) , path ( '' , include ( 'django.contrib.auth.urls' ) ) , path ( 'reset_password/' , auth_views.PasswordResetView.as_view ( template_name='myBlog/password_reset.html' ) , name='reset_password' ) , path ( 'reset_password_sent/' , auth_views.PasswordResetDoneView.as_view ( template_name='myBlog/password_reset_sent.html' ) , name='password_reset_done' ) , path ( 'reset/<uidb64>/<token>/' , auth_views.PasswordResetConfirmView.as_view ( template_name='myBlog/password_update.html' ) , name='password_reset_confirm' ) , path ( 'reset_password_complete/' , auth_views.PasswordResetCompleteView.as_view ( template_name='myBlog/password_reset_done.html' ) , name='password_reset_complete' ) , path ( '<slug:slug>/' , m.post_detail, name='post_detail' ) , ] Here's the files tree. -
Django application is not recognized when running
I am new to Django and I am following this tutorial: https://www.youtube.com/watch?v=1aJ49vtM3nQ&list=PLMyNvIPi_kYF8oUnMiyTk_M92gJz9WvZt&index=30 I added a new application called firstapp, but it seems like it is not recognized and i don't know why. I added it to the INSTALLED_APPS: 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'firstapp', ] but when trying to import it only works if i add the main project in front of it: in which case i get an error when trying to run the server. in which case i get a "not found" error. I mention that I activated a virtual environment using Anaconda Prompt based on the tutorial, but I am not sure how to check if that is the problem. -
Pass Swagger-UI url in drf-spectacular settings
I have a project written in Django 2.x. I want to add automatic documentation to it using drf-spectacular. I'm using drf-spectacular=0.15.1 at the moment. I'm running my project in Docker, and the build context for my api container is set as the root folder of the api project. When I run the command to generate the schema, ./manage.py spectacular --file schema.yml, the script creates a schema.yml file in the root of my api project, but my Django settings.py are found one level below, in a folder called my_website. The structure of the project is like this: main-project \api \_my_website __init__.py apps.py settings.py urls.py schema.yml \client docker-compose.yml So in settings.py I added specific settings to tell Swagger-UI where from to take the schema, as specified in the drf-spectacular documentation: SPECTACULAR_SETTINGS = { 'SWAGGER_UI_SETTINGS': { 'url': 'schema.yml' }, } Once I try to access the swagger-ui url in my project to check that the schema is loaded there, I get the error: **Fetch error** Not Found schema.yml. I tried passing the schema url in various ways, for example through relative url ../schema.yml but that didn't work either. Maybe somebody can give me an idea of what I'm doing wrong. Thanks! -
How to design Models for Product and its Feature (Options) in Django for online store in right way?
I`m trying to create online store by myself (just a training project). There are models Product, Feature and ProductFeature. Product may have different features (every new product may have from zero to infinity specifications) with different values (so I need some flexiable solution). Features names could be same for different Product (for ex. color or size). In short: User choose existing option or add new option, then sets value for this feature. Profit) My Feature model stores only only names for options. I created ProductFeature to connect Product with Features and to set values. At first it looks ok. But in admin panel user has access to all objects (name-value) in ProductFeature. It looks a bit confusing. Are there any variants to hide existing options for new Product in admin panel (keep only add new databes record to ProductFeature)? Or maybe there are any other variants to design models and connections? class Product(models.Model): name = models.CharField(max_length=300, verbose_name='Название товара') description = models.TextField(verbose_name='Описание товара', blank=True) main_category = TreeForeignKey( Category, on_delete=models.CASCADE, related_name='main_products', verbose_name='Основная категория' ) main_image = models.ImageField(verbose_name='Изображение', null=True, blank=True) features = models.ManyToManyField( 'ProductFeature', related_name='product', verbose_name='Характеристики', blank=True ) created = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания') updated = models.DateTimeField(auto_now=True, verbose_name='Дата изменения') class Feature(models.Model): name = models.CharField(max_length=300, … -
ValueError when loading the page with objects without image
I receive this error after creating a Bb object without image: "The 'image' attribute has no file associated with it." When I restart the debug server I get the same error until I provide Bb object with an image using django admin panel. Possible solution I came up with: add default static image: <img default="default.jpg"> But I want to know why there's an error even when null=True and blank=True are passed in models.py models.py: class Bb(models.Model): title = models.CharField(max_length=50, verbose_name='Product', error_messages={'blank' : 'Wrong product name'}) content = models.TextField(null=True, blank=True, verbose_name='Description') price = models.FloatField(null=True, blank=True, verbose_name='Current price') published = models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='Published in') # Image image = models.ImageField(verbose_name='Image', null=True, blank=True) views.py: from django.shortcuts import render, redirect from django.http import HttpResponse from django.template import loader from django.urls import reverse_lazy, reverse from django.template.response import TemplateResponse from django.core.paginator import Paginator from .forms import BbForm, ImgForm, ImgNonМodelForm from .models import Bb, Rubric, Img def index(request): bbs = Bb.objects.all() # Paginator paginator = Paginator(bbs, 4) if 'page' in request.GET: page_num = request.GET['page'] else: page_num = 1 page = paginator.get_page(page_num) context = {'bbs' : page.object_list, 'page' : page} return TemplateResponse(request, 'bboard/index.html', context=context) def create_bb(request): if request.method == 'POST': form_bb = BbForm(request.POST, request.FILES) form_images = ImgNonМodelForm(request.POST, request.FILES) if … -
How do I get the form field name from a queryset list in django
I am trying to create a application which will have a list of tasks against which float values have to be entered, (something like a excel sheet). I am unable to map the name of the form field to the desired value. Here is the code which I have written so far. Models.py class SubTask(models.Model): subtask_id = models.IntegerField(default=0, blank=True, null=True) subtask_name = models.CharField(max_length=120, null=False) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) def __str__(self): return self.subtask_name class Attendance(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) subtask = models.ForeignKey(SubTask, on_delete=models.CASCADE) value = models.FloatField(default=0.0) non_billable_hours = models.FloatField(default=0, blank=True, null=True) billable_hours = models.FloatField(default=0, blank=True, null=True) total_hour = models.FloatField(default=0, blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse("attendance", kwargs=None) Forms.py from django import forms from .models import Attendance, SubTask class AttendanceForm(forms.ModelForm): class Meta: model = Attendance fields = ['subtask'] #'non_billable_hours', 'billable_hours', 'total_hour',] def __init__(self, *args, **kwargs): user = kwargs.pop('user', '') super(AttendanceForm, self).__init__(*args, **kwargs) self.fields['subtask']=forms.ModelChoiceField(queryset=SubTask.objects.all()) self.fields['value']=forms.FloatField() Views.py from django.shortcuts import render from .forms import AttendanceForm from .models import SubTask, Attendance def attendanceView(request): form = AttendanceForm(request.POST or None) subtask_list = SubTask.objects.all() context = { 'form': form, #'subtask_list': subtask_list, } if form.is_valid(): attendance = form.save(commit=False) attendance.user = Attendance.objects.get(user=request.user) attendance.save() return render(request, "attendance/attendance.html", context) I want the app to look … -
Not Found: /post/12/responses/
What i am trying to do is i want to access perticular posts all comments in Responses Url. This is my view which i want pass to url class CommentDetailView(DetailView): model = Comments template_name = 'CovidHelp/comment_response.html' context_object_name = 'comments' paginate_by = 10 def get_queryset(self): post = get_object_or_404(Post, id=self.kwargs.get('pk')) return Comments.objects.filter(post=post).order_by('-date') Url is path('post/<int:pk>/responses/', CommentDetailView.as_view(), name='responses') comment models is class Comments(models.Model): post = models.ForeignKey(Post,related_name='comments',on_delete=models.CASCADE) name = models.CharField(max_length=50) date = models.DateTimeField(default=timezone.now) content = models.TextField() def get_absolute_url(self): return reverse('Home') post model is class Post(models.Model): title = models.CharField(max_length = 100) content = models.TextField() date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) Althought i am getting post_id from url which i can see in error Not Found: /post/12/responses/ But My comments Models not able to show it Need Help.. -
Django route with multi string parameters
I have two separate route re_path( r"something/(?P<slug>name_one|name_two)/$", views.SomeView.as_view(template_name='some_template.html'), name='something' ), re_path( r"something/(?P<slug>name_one|name_two)/(?P<params>p_one|p_two)/$", views.SomeView.as_view(template_name='some_template.html'), name='something_extera' ), I want these route accepts specific string as far as you can see in route above. for example something/name_one something/name_two something/name_one/p_one something/name_one/p_two ... but i get error django.urls.exceptions.NoReverseMatch: Reverse for 'something' with arguments '('',)' not found. 1 pattern(s) tried: ['something/(?P<slug>name_one|name_two)$']