Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django remove unwanted user fields in models using AbstractUser
I'm a beginner in django and I'm working on user authentication. I'm using Abstractuser and default User model to create the users. However, there a lot of unnecessary information being gathered that is of no use to my project. This is my models.py: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass These are the fields that are generated: ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), ('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')), ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), The … -
can I get a backend developer job without knowing front-end
-I'm a second year software engineering student, I work with django and I master python and other programming languages, but when it comes to front-end I struggle with it I don't master css. so can I get my first job without knwoing front-end. -
How can I add an element to a profile in django without getting 'Page not found at /post'?
I'm trying to add a 'favorite' anime to my profile in django but when I post my form it says 'Page not found at /post'. The code does get the anime's id but then it doesn't add it to my profile and instead takes me to /post. How can I fix this? This is my view of the 'anime': @login_required def anime(request): if request.method == "POST": anime_id = request.POST.get("anime_id") anime = Anime.objects.get(id = anime_id) request.user.profile.animes.add(anime) messages.success(request,(f'{anime} added to wishlist.')) return redirect ('search:anime') animes = Anime.objects.all() return render(request = request, template_name="search.html") This is the part of html related to this: {% if animes %} {% for anime in animes %} <form action="post"> <section> <div class="col-md-4 col-sm-6 col-lg-3"> <div class="card"> <div class="card-body text-center"> <p class="card-title"> <b>{{anime.Title}}</b></p> <hr> <p class="card-text">Episodes: <b>{{anime.Episodes}}</b></p> <img src = {{anime.Image}} /> </div> </section> <input type="hidden" value="{{anime.Id}}" name="anime_id"> <button type="submit" class="btn btn-outline-primary" style="font-size:18px; border-radius: 50%">★</button> </form> {% endfor %} {% endif %} This is the url it goes to after I post the form: /post?anime_id=18507 It should just add it to the profile and redirects me to the search page but it doesn't. -
Django model order by model method or calculation on model fields
I have a Django Model, OrderItem class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_line') quantity = models.PositiveIntegerField(default=1) title = models.CharField(max_length=100) order_number = models.CharField(max_length=25, null=True, blank=True, verbose_name='Order Number') order_date = models.DateField(auto_now_add=True) dispatch_date = models.DateField(auto_now_add=True) cancel_date = models.DateField(auto_now_add=True) I have a model function that calculates the days between today and the OrderItem order_date or dispatch_date and order_date def get_aging(self): today = datetime.today().date() if self.dispatch_date is not None: aging = self.dispatch_date - self.order_date return aging.days elif self.cancel_date is not None: return 0 else: aging = today - self.order_date return aging.days I want to order the OrderItems by the same calc. I have tried to use the python sort but I can't apply the django FilterSet on the list created by the python sorted method. This is the code in my view, I am using a custom template as I allow for inline editing of the data. order_qs = OrderItem.objects.all() sorted_qs sorted(order_qs, key= lambda a: a.get_aging()) user_filter_orders = OrderItemsFilter(request.GET, queryset=order_qs) The error because of the sorted method returning a list: 'list' object has no attribute 'model' Any suggestions, please? -
Integrating django-cms into an existing project - Error: Reverse for 'pages-root' not found. 'pages-root' is not a valid view function or pattern name
I am trying to add news functionality to an existing django project. I decided to use django-cms to provide the functionality. The documentation is lacking and what little there is, is next to useless, in terms of integrating django-cms into an existing project. I have looked at this question and this one but the offered answers only take me so far. What I want to do is to be able to have pages with static data, and use django-cms to allow users with the right permissions to create new pages and/or update existing pages. At the moment, when I run python manage.py runserver and I navigate to http://127.0.0.1:8000/news/1/, I get the following error message: NoReverseMatch at /news/1/ Reverse for 'pages-root' not found. 'pages-root' is not a valid view function or pattern name. Here is the relevant versioning information for my software components: Django 3.2.2 django-classy-tags 2.0.0 django-cms 3.8.0 django-formtools 2.3 django-sekizai 2.0.0 django-treebeard 4.5.1 djangocms-admin-style 2.0.2 settings.py (relevant section) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'cms', 'menus', 'treebeard', 'sekizai', 'news', ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.locale.LocaleMiddleware', 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', 'cms.middleware.language.LanguageCookieMiddleware', ] LANGUAGES = [ ('en', 'English'), ] … -
how to redirect in django through select option in forms.py
I need help. I am makig a sign up page in django In my forms.py I have two select optins. option 1) free trial & option 2)monthly subscription I want user to go to login page if he selects option1 and to checkout page if he selects option2. here is my code. forms.py class RegisterForm(UserCreationForm): email = forms.EmailField() CHOICES = (('Option 1', 'Free 30 days trial'),('Option 2', '$9.99 Monthly subscription')) plan = forms.ChoiceField(choices=CHOICES) class Meta: model = User fields = ['username', 'email', "plan", "password1", "password2" views.py def signupUser(request): if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): if plan == 'Free 30 days trial': form.save() return redirect("/main/login/") else: form.save() return redirect("/main/checkout/") else: form = RegisterForm() return render(request, 'signup.html', {"form":form}) but this gives error: plan is not defined Need help please. -
Django REST Framework field serializer validation is not being called
After some hours of research, I still can't find the answer to the issue I am facing. I am trying to add some simple validation to a field in one of my models. In serializers.py: class BrandSerializer(serializers.ModelSerializer): class Meta: model = Brand fields = '__all__' def validate_name(self, value): """ Check that the brand name has at least 20 characters """ if len(value) < 20: raise serializers.ValidationError( "The name of the brand should be longer than 20 characters") return value I am using function based views: @api_view(['POST']) def brandCreate(request): data = request.data try: brand = Brand.objects.create( name=data['name'], ) serializer = BrandSerializer(brand, many=False) return Response(serializer.data) except: message = {'detail': 'Brand is not created'} return Response(message, status=status.HTTP_400_BAD_REQUEST) And this is my model: class Brand(models.Model): name = models.CharField(max_length=80) logo = models.ImageField(null=True, blank=True) def __str__(self): return str(self.name) After sending a POST request with postman, the record is successfully created, even though the name is shorter than 20 characters! Any hints on what I am missing here? Thank you! -
Bootstrap exception thrown when overriding PasswordResetConfirmView in Django
I am getting a bootstrap exception when trying to override the PasswordResetConfirmView in Django. Parameter "form" should contain a valid Django Form. Request Method: GET Request URL: http://127.0.0.1:8000/SL_webapp/reset/MQ/amcfbe-81074d0d92c35e3b6c9eeb50bc141582/ Django Version: 3.1.7 Exception Type: BootstrapError Exception Value: Parameter "form" should contain a valid Django Form. Exception Location: /Users/arnasastapkavicius/opt/anaconda3/envs/TM470/lib/python3.9/site-packages/bootstrap5/renderers.py, line 144, in __init__ Python Executable: /Users/arnasastapkavicius/opt/anaconda3/envs/TM470/bin/python Python Version: 3.9.1 My code is as follows: my URL patterns in urls.py urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('reset_password/', auth_views.PasswordResetView.as_view(template_name="password_reset.html"), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="password_reset_sent.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="password_reset_form.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="password_reset_done.html"), name="password_reset_complete"), ] my password_reset_form.html file: {% extends "base.html" %} {% load bootstrap5 %} {% block content %} <div class="container"> <div class="col-lg-6 p-5"> <h1>Enter new password.</h1> <p>Please enter your new password twice so we can verify you typed it in correctly.</p> <form method="POST"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" class="btn btn-warning btn-lg" value="Update password"> </form> </div> </div> {% endblock %} I cannot understand why this is happening, as another form using bootstrap that I have overriding PasswordResetView with password_reset.html renders correctly. Any ideas? Thank you in advance. -
Send data from Jquery to Django html template
how can I get a list of data from JQuery (Ajax) into the the Django HTML templates, forexample in my file : transitions.js, I have this : window.addEventListener("load", function() { (function ($) { 'use strict'; const transition_id = $(".trans_id").get(0).id; cooperationPartnerTransitions(transition_id) function cooperationPartnerTransitions(id) { $.ajax({ url: `/api/v1/accounts/cp_transitions/${id}`, type:'get', dataType: 'json', headers: {}, success: function (data) { console.log("--->", data) } }); } })(django.jQuery); }); then, in my plan.html I have this : {% extends 'admin/custominlines/change_form.html' %} {% load static %} {%block extrahead %} <script src='{% static "admin/js/transitions.js" %}'></script> {% endblock %} {% load i18n %} {% block submit_buttons_bottom %} {{ block.super }} {% if request.GET.edit %} <div class="submit-row"> <div class="trans_id" id="{{ original.pk }}"></div> <input type="submit" value="custom" name="_transition-states"> </div> {% endif %} {% endblock %} I want to access the data from Jquery so that I can loop the button, how can I do this -
how to migrate django database after model change?
I have model M1. it had a field F1 of type IntegerField. I created a number of items and filled their F1 with numbers. Then I created new model M2 and changed F1 to be ForeignKey to M2. makemigrations worked fine. But migrate doesn't work - since it can't find M2 items corresponding to old F1 int values. Moreover I can't delete M1 items through shell - attempt to get Objects.all() result in same error. How can I delete "problematic" items of M1 without flushing database? -
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 %}