Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add a link in fcm-django notification?
I am working on a project where I am using fcm-django for sending push notifications to a devices. I want to include a link in the notification that opens a specific page in the web app when clicked. How can I add a link to the notification using fcm-django? Here is my code from firebase_admin.messaging import Message from firebase_admin.messaging import Notification from fcm_django.models import FCMDevice fcm_devices_of_this_user = FCMDevice.objects.filter(user=user_obj, active=True) if fcm_devices_of_this_user: fcm_devices_of_this_user.send_message( MESSAGE( notification=NOTIFICATION(title=notification_for, body=message) ) ) Any help would be appreciated. -
Why can't the inherited class get updated value?
The parent: class TemplateViewEnhance(TemplateView): cur_page_number = -1 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["field_names"] = School.get_fields_name() cur_page_number = int(self.kwargs["page_number"]) print("update page _number to {}".format(cur_page_number) ) child: class EditSchool(TemplateViewEnhance): template_name = "editschool.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) print(super().cur_page_number) result: update page _number to 1 -1 I think context = super().get_context_data(**kwargs) will update the cur_page_number value and then super().cur_page_number will get the updated value. But it's not. Also, do I hvae to give initial value to cur_page_number? Thanks. -
Only render part of django template if objects.all is not empty
I only want to render part of a django template if objects.all is not empty. Normally this is done like: <ul> {% for thing in things.all %} <li>{{ thing.name }}</li> {% empty %} <li>Sorry, nothing to list here</li> {% endfor %} </ul> But what if I want to have a heading or something that only shows if there's something to put in the list? I don't want the heading to be repeated each time the for loop runs. Is there something like {% not empty %} I could use, e.g.: {% if things.all not empty %} <h1>Here's the list of things</h1> <ul> {% for thing in things.all %} <li>{{ thing.name }}</li> {% endfor %} </ul> The above, however, throws a TemplateSyntaxError for django Not expecting 'not' as infix operator in if tag. How can we check if something is empty before running the loop? -
Render Submit Button in Same Row as Form Field in Django Crispy Forms
I'm using Django Crispy Forms, and rather than have the Submit button render below the rest of the fields, I want to move it to the same row as another field. My current Form code follows: class SetForm(forms.ModelForm): class Meta: model = Set fields = ['exercise', 'actual_weight', 'actual_reps', 'actual_difficulty'] helper = FormHelper() helper.form_method = 'POST' helper.layout = Layout( Row( Column('exercise', css_class='form-group col-md-12 mb-0'), css_class='form-row' ), Row( Column('actual_weight', css_class='form-group col-6 mb-0'), Column('actual_reps', css_class='form-group col-6 mb-0'), ), Row( Column('actual_difficulty', css_class='form-group col-6 mb-0'), Column(helper.add_input(Submit('submit', 'Submit', css_class='form-group btn-primary col-6 mb-0'))), ) ) This doesn't work though, the Submit button is still on its own row below the form, though the col-6 class does appear to be applied. I tried looking at this question, but it neither has answers nor uses Django Crispy Forms, as well as this one, but that one is focused on prepended text and it's not straightforward to modify the answers for this use case. Help please! -
301 redirect with query parameter "?page=" in urls.py
Have some problem with duplicate pages in Django 1.10. When the file had the following code: urlpatterns = [ ... url(r'^(?P<slug>[-\w]+)$', views.category, name='cat'), ... ] Pages site.com/category?page=5 and site.com/category/?page=5 displayed the same content. Then I added next redirect: urlpatterns = [ ... url(r'^(?P<slug>[-\w]+)$', views.category, name='cat'), url(r'^(?P<slug>[-\w]+)/$', RedirectView.as_view(pattern_name='cat', permanent=True)), ... ] And now i have redirect from site.com/category/?page=5 to site.com/category (without query parameter), but not to site.com/category?page=5 Please tell me where to fix it -
Collectstatic Code Line Changed my CSS code in Django
So I build a RESPONSIVE website on Django, and deployed it on Heroku. Here is a link https://three-d-production.herokuapp.com/ On a the full HD resolution design looks good, but when entered website on my phone, some parts of website were moved. I think that the problem in the settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') But I have no idea how to fix it. Here is a GITHUB code: https://github.com/PHILLyaHI/ThreeDProduction PLEASE HELP ME CHROME DEV TOOLS POV IPHONE 12 POV -
Can I create an instance of AbstractUser in my model class in the model.py in django?
I am new to django and from a tutorial video, in the model.py file for the profile app, he created an instance of the User model in a one-to-one relationship with the profile model class like so: ` from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, blank=True, null=True) I understand that he created a one-to-one relationship with the profile model and the User model by creating an instance of the User model in the class. I am trying to achieve this with AbstractUser as well. I tried to do the same thing like so: from django.contrib.auth.models import AbstractUser class Blogger(models.Model): user = models.OneToOneField(AbstractUser, blank=True, null=True) In the settings.py, I have connected the PostGresSql database like so: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'bookandreviews', 'USER': 'postgres', 'HOST': 'localhost', 'PASSWORD': '2030', 'PORT': '5432' } } I ran py manage.py runserver and I got this error: django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: users.Bloggers.user: (fields.E300) Field defines a relation with model 'AbstractUser', which is either not installed, or is abstract. users.Bloggers.user: (fields.E307) The field users.Bloggers.user was declared with a lazy reference to 'auth.abstractuser', but app 'auth' doesn't provide model 'abstractuser'. I don't understand it. So I tried to add … -
if form.is_valid() return errors when using get_or_create
class Books(models.Model): book_file = models.FileField( upload_to="books", validators=[validate_book_extension], verbose_name="book", ) title = models.CharField(max_length=255, default=None) author = models.ForeignKey(Author, on_delete=models.CASCADE, default="") coauthors = models.ManyToManyField(CoAuthor, blank=True) publisher = models.ForeignKey( Publisher, on_delete=models.SET_DEFAULT, default=None, related_name="books_published", ) genres = models.ManyToManyField(Genre) edition = models.IntegerField(default=None) description = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) i am having trouble with form validation when uploading a book to a database. The model has fields for authors and coauthors with ForeignKey and ManyToManyField relationships, and you're using the get_or_create method in the view function that handles the submission of fields with ForeignKey and ManyToManyField relationship. However, the if form.is_valid() statement returns errors and if i don't check if the form is valid the form submits. Below is the error that pops up. views.py @login_required def addbook(request): if not request.user.is_superuser: return redirect(notfound) else: books = Books.objects.all() genres = Genre.objects.all() authors = Author.objects.all() coauthors = CoAuthor.objects.all() publishers = Publisher.objects.all() form = BookForm() if request.method == "POST": form = BookForm(request.POST, request.FILES) if form.is_valid(): book = request.FILES.get("book_file") title = request.POST.get("title") genres_name = request.POST.getlist("genres") author_name = request.POST.get("author") co_authors = request.POST.getlist("coauthors") publisher_name = request.POST.get("publisher") author, created = Author.objects.get_or_create( name=author_name.title()) publisher, created = Publisher.objects.get_or_create( name=publisher_name.title() ) book = Books.objects.create( title=title.title(), publisher=publisher, edition=request.POST.get("edition"), author=author, book_file=book, ) for genre in genres_name: … -
Pythonanywhere Template is not rendering on the django
I'm trying to deploy my webapp on pythonanywhere, but my template is not rendering at all, however the same code is showing just fine on my local visual studio. i'm receiving the below error. my views is as follows: from django.shortcuts import render # Create your views here. def Home(request): return render(request, 'Home.html') my settings is 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', ], }, }, ] Please help, what am i missing? -
Forbidden (CSRF cookie not set.) - Django 4.1 and React
General Information: I'm facing the following error Forbidden (CSRF cookie not set.) while posting in my React app. I've been through many of the similar posts, but they doesn't seem to solve my issue. I believe my issue is on my React app, and not on my Django side, since I do get a 200 response on a GET request, but when posting, my React app doesn't get a grip on my CSRF token. Noted, but unexplainable: I do not see my CSRF set when I check in Applications in my chrome inspector on http://localhost:3000/ Terminal Response: Django System check identified 1 issue (0 silenced). April 01, 2023 - 22:02:51 Django version 4.1.7, using settings 'core.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [01/Apr/2023 22:05:05] "GET /accounts/csrf-cookie HTTP/1.1" 200 29 Forbidden (CSRF cookie not set.): /accounts/register/ [01/Apr/2023 22:05:14] "POST /accounts/register/ HTTP/1.1" 403 2870 React Note that the development build is not optimized. To create a production build, use npm run build. assets by status 1.33 MiB [cached] 17 assets assets by status 16.9 MiB [emitted] assets by chunk 16.9 MiB (name: main) asset static/js/bundle.js 16.9 MiB [emitted] (name: main) 1 related asset asset main.41b1aa5256b383579099.hot-update.js 4.01 KiB [emitted] … -
I want to deploy django to gae and display images
I have an app created with django and deployed with google app engine. Images stored in the static folder are not displayed in the template. But the css file works fine. I don't understand why the image is not loaded even though the css file is loaded. Is there any solution? ▼version Django 4.1.1 ▼Error GET https://<myapp>.an.r.appspot.com/static/img/example.png/ 404 ▼app.yaml runtime: python39 instance_class: F1 env: standard service: default entrypoint: gunicorn -b :$PORT config.wsgi:application includes: - secrets/secret.yaml handlers: - url: /static static_dir: staticfiles/ - url: .* secure: always script: auto ▼part of settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent if os.getenv('GAE_APPLICATION', None): # production DEBUG = False ALLOWED_HOSTS = ['myapp.an.r.appspot.com'] else: # develop DEBUG = True ALLOWED_HOSTS = ['*'] import yaml with open(os.path.join(BASE_DIR,'secrets','secret_dev.yaml'), encoding="utf-8") as file: objs = yaml.safe_load(file) for obj in objs: os.environ[obj] = objs[obj] INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', "myapp", 'django_cleanup.apps.CleanupConfig', 'django_feather', 'widget_tweaks', ] 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", 'myapp.middleware.middleware.AdminProtect', ] ROOT_URLCONF = "config.urls" 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", 'myapp.context_processor.notice_content', ], }, }, ] WSGI_APPLICATION = "config.wsgi.application" # Database … -
Search a part of a word using django-elasticsearch-dsl-drf
I am building a Django application that contains search engine using elastic search by django_elasticsearch_dsl_drf library. I want to allow user to search for only letters or a part of a word and elastic search returns all words that contain these letters. For example if the user submitted 'legal' word the result will be all articles containing 'legal, legally, illegal, illegally'. I have used nGram tokenizer to make this but it doesn't work as when I submit the word no results are shown to me. here is the most important part which is in documents.py: from django_elasticsearch_dsl import Document, fields, Index from django_elasticsearch_dsl.registries import registry from django.conf import settings from .models import * from elasticsearch_dsl import analyzer, tokenizer autocomplete_analyzer = analyzer('autocomplete_analyzer', tokenizer=tokenizer('trigram', 'nGram', min_gram=1, max_gram=20), filter=['lowercase'] ) entry_index=Index('entries') @registry.register_document class EntryDocument(Document): title = fields.TextField( attr='title', fields={ 'raw': fields.TextField(required=True,analyzer=autocomplete_analyzer), 'suggest': fields.CompletionField(), } ) body = fields.TextField( attr='body', fields={ 'raw': fields.TextField(required=True,analyzer=autocomplete_analyzer), # 'suggest': fields.CompletionField() } ) class Index: name = 'entries' settings = { "number_of_shards": 1, "number_of_replicas": 0, 'max_ngram_diff': 20 } class Django: model = entry fields= [] for more details: models.py: class entry(models.Model): title = models.CharField(max_length=600) body = models.TextField() Serializers.py: class EntryDocumentSerializer(DocumentSerializer): class Meta: document = EntryDocument fields = ( 'title', … -
This django app asks a mutiple-choice question from the user
The app checks the user answer and shows the result and then checks if the user answered the question or not. if the user answered the question the options will disable and **checks **the option that user selected but i got that error: TemplateSyntaxError at /questions/ Could not parse the remainder: '[question.id]' from 'answers[question.id]' html: ` {% for question in questions %} <div class="question"> <p>{{ question.text }}</p> <form method="post" action="{% url 'submit_answer' question.id %}"> {% csrf_token %} <input type="hidden" name="question" value="{{ question.id }}"> <input type="radio" id="option_1_{{ question.id }}" name="answer" value="1" {% if 1 in answers[{{question.id}}] %}checked{% endif %} {% if answers[question.id] is not None %}disabled{% endif %}> <label for="option_1_{{ question.id }}">{{ question.option_1 }}</label> <br> <input type="radio" id="option_1_{{ question.id }}" name="answer" value="2" {% if 2 in answers[question.id] %}checked{% endif %} {% if answers[question.id] is not None %}disabled{% endif %}> <label for="option_2_{{ question.id }}">{{ question.option_2 }}</label> <br> <input type="radio" id="option_1_{{ question.id }}" name="answer" value="3" {% if 3 in answers[question.id] %}checked{% endif %} {% if answers[question.id] is not None %}disabled{% endif %}> <label for="option_3_{{ question.id }}">{{ question.option_3 }}</label> <br> {% if not request.session.question_answers.get(str(question.id)) %} <button type="submit">Submit Answer</button> {% else %} <p>Your answer has been submitted.</p> {% endif %} </form> </div> {% endfor %} … -
django filter by related
my models: class Person(models.Model): name = models.CharField(max_length=255) class BankAccount(models.Model): iban = models.CharField(max_length=28) owners = models.ManyToManyField(Person, through='BankAccountPerson') class BankAccountPerson(models.Model): bank_account = models.ForeignKey(BankAccount, on_delete=models.RESTRICT, related_name = 'ownership') person = models.ForeignKey(Person, on_delete=models.RESTRICT, related_name = 'ownership') is_owner = models.BooleanField(null=True, blank=True) class Meta: unique_together= [['bank_account','person']] let's assume, that account no 1 has two owners: person:1 and person:2 And now if I filter like this: person=Person.objects.get(pk=1) collection = BankAccount.objects.filter(owners=person) will get only one row - with person1. But I'd like to get two rows: - with both people. Because I want to get accounts with owners, where one of owners is person I can do it with SQL: SELECT * FROM structure_bankaccount INNER JOIN "structure_bankaccountperson" ON ("structure_bankaccount"."id" = "structure_bankaccountperson"."bank_account_id") WHERE structure_bankaccount.id in (SELECT bank_account_id FROM "structure_bankaccountperson" WHERE "structure_bankaccountperson"."person_id" = 1) I can do it with two steps: owned_accounts = BankAccountPerson.objects.filter(person=person).values_list('bank_account_id') collection = BankAccount.objects.filter(id__in=owned_accounts) But I wonder if I can do it with some Q, F or other function in one django filter... -
Django and Postgres "does not exist" when add new relation
Hi I'm havin some problems with Django and Postgres. Here's the model I'm working on: class UserMessage(models.Model): ... replied_by = models.ManyToManyField("users.User", related_name="replied_by_users", default=None, blank=True) When I add the field replied_by and perform the new migrations, all works but when I try to access to the model instances from database, it raised the following error: ProgrammingError at /admin/moments/usermoment/ relation "app_usermessage_replied_by" does not exist LINE 1: ...t"."event_id", "app_usermessage"."end_at" FROM "... And that's because there were already some instances before adding the replied_by field, but since I set the new field to None as default, it needs to ignore them. Here's a snippet of migration file: migrations.AddField( model_name='usermoessage', name='replied_by', field=models.ManyToManyField(blank=True, default=None, related_name='replied_by_users', to=settings.AUTH_USER_MODEL), ), How can I solve this problem without losing database data? Of course I'm in development mode, are there any good practice that I'm missing to handle database when you add a new relation. Thank you -
Can somebody help to fix this problem? im realy tired of trying
enter image description here class EmailVerificationView(TitleMixin, TemplateView): title = 'Store - Подтверждение электронной почты' template_name = 'users/email_verification.html' def get(self, request, *args, **kwargs): code = kwargs['code'] user = User.objects.filter(email=kwargs['email']) email_verifications = EmailVerification.objects.filter(user=user, code=code) if email_verifications.exists() and not email_verifications.first().is_expired(): user.is_verified_email = True user.save() return super(EmailVerificationView, self).get(request, args, **kwargs) else: return HttpResponseRedirect(reverse('index')) I already changed get to filter. Before i had get in user there was issue "get() returned more than one user -- it returned" Im trying to send email to verify acc. -
Django cannot find template, app is in installed_apps and backend DjangoTemplates is enabled
Inside of a page in my templates folder, I tried using an include statement in a for loop, like so: {% for model_othermodel in model.othermodels.all%} {% include othermodels.html with othermodel=model_othermodel %} {%endfor%} At first, I had the issue that it complained there was no key/value being sent to the other template, which was that othermodel=model_othermodel looked like other_model = model_othermodel. However, after that, I had the issue that it could not find the included html file (the file name is correct), for which the error problem would show me the base.html file that each page extends. (I will be using django_app to refer to the app folder) I got the error message: In template path\root\django_app\templates\base.html, error at line 0 No template names provided My base.html file is just a file for bootstrap that every other html file extends. My project structure looks like this: root/django_app root/django_project root/django_app/templates I tried adding the template path directly to 'DIRS' in TEMPLATES, such as so: DIRS = [os.path.join(BASE_DIR, django_app/templates/)] with variations such as django_app/templates, /templates/, /templates, etc. After that, I heard a suggestion to reorder my INSTALLED_APPS list, which is currently: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'django_app', ] to … -
Pythonanywhere deployment failure on the wsgi according to error log
I'm trying to deploy to Pythonanywhere and i believe i have followed all of the right steps. The latest error on the error log is: Error running WSGI application ModuleNotFoundError: No module named 'Project' File "/var/www/sizwe93_pythonanywhere_com_wsgi.py", line 17, in <module> application = get_wsgi_application() File "/home/sizwe93/.virtualenvs/mysite-virtualenv/lib/python3.10/site- packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) My WSGI file is on the Dashboard: from this # +++++++++++ DJANGO +++++++++++ # To use your own Django app use code like this: import os import sys # assuming your Django settings file is at '/home/myusername/mysite/mysite/settings.py' path = '/home/sizwe93/Project' if path not in sys.path: sys.path.insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'Project.settings' ## Uncomment the lines below depending on your Django version ###### then, for Django >=1.5: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() ###### or, for older Django <=1.4 #import django.core.handlers.wsgi #application = django.core.handlers.wsgi.WSGIHandler() I'm trying to deploy from my project on Github... I'm not sure what i'm missing, please help... -
print form value into the HttpResponseRedirect(HTML), Django
I'm filling in a reference number automatically when the form is loaded, now, i want to print this reference number to the HTML after the form is successfully submitted. !! views.py forms.py models.py HTML BTW, everything is working fine but the reference number never appeared !! please help -
How to use field variable of the model related with ForeignKey
I'm trying to create an Album model and a Song model which are both having a genre field. I want Song model's genre field is same with the Album model's by default. class Album(models.Model): genre = models.TextField() class Song(models.Model):` album = models.ForeignKey(Album, on_delete=models.CASCADE) genre = models.TextField() #The field I want to be same with its related model -
'ascii' codec can't decode byte 0xc3 in position 7: ordinal not in range(128)
Unicode error hint The string that could not be encoded/decoded was: Ubicación Getting error this spanish word in django standard translation. -
Django Web App Deployment on Render.com, Import Errors
I am currently trying to deploy my Django Web App to https://render.com/, but I got several problems, I am following this tutorial: https://www.youtube.com/watch?v=AgTr5mw4zdI, at 19:00 I have to import dj_database_url I have imported the Package in my Virtual Environment! This is what pip list says Here is my folder stucture: I think the problem is possibly because of the folder structure. Here is the Import -
Django form design
How can I make my form looks better? A few questions: How can I make the checkbox and buttons beside Favourite, Photo and Audio. And how can I change the design of the "Choose File" button to the same design as the "Save" and "Cancel" buttons? Can I show the image and audio after uploading it? BTW, I am using crispy form and Bootstrap 4. The html {% extends "base.html" %} {% block content %} <form method="POST" enctype="multipart/form-data"> <div class="mx-auto mt-4" style="width: 600px;"> {% csrf_token %} {{ form.as_p }} <div class="text-center"> <input type="submit" value="Save" class="btn btn-outline-info"> </div> </div> </form> {% if journal %} <div class="text-center"> <a href="{% url 'journal_detail' journal.id %}"><button type="button" class="btn btn-outline-info">Cancel</button></a> </div> {% else %} <div class="text-center"> <a href="{% url 'journal_list' %}"><button type="button" class="btn btn-outline-info">Cancel</button></a> </div> {% endif %} {% endblock %} -
Why does the form validation fail in this django formset?
I have been trying to make a django formset for giving feedback for assignments in a rubric style, where a form is generated for each criteria in an assignment, with the submissionID being automatically assigned, and the user selects what level the student has met a criteria to, and gives a comment about the criteria. Example: The problem I'm facing is that submitting the form does not do anything and just seems to refresh the current page, and I've tried everything I can think of to solve the problem, but the only thing I've managed to find out is where it is going wrong, which is at the line if form.is_valid(), which is returning false as it seems to be getting no forms passed to it for some reason. The expected result of the code is that when a post request is sent, it loops through the submitted forms, sets the submissionID, and saves the forms. So far I have tried doing some debugging by printing variables at different points of the code but mainly the line before it fails. Prints tried: formset: `(Hidden field TOTAL_FORMS) This field is required.(Hidden field INITIAL_FORMS) This field is required. ` Number of forms … -
Combine multiple django forms into one
I'm working with a django(4) project, Where I have two forms and want to combine them into one to display in my template with custom html not by sing {{form}} syntax. Here's my forms.py: class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email'] # Create a ProfileUpdateForm to update image. class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] How can I combine both of these forms into single one to display all the filed in HTML and submit as a single form?