Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django querysets using __lte
Can I do something like this in django/python without hardcoding it? def get_rating_average(self, type): return list(super().aggregate(Avg(type)).values())[0] def filter_rating_average_under(self, type): return super().filter(type__lte=self.get_rating_average(type=type)) # FILTER WHERE rating_type is smaller than average type keyword# #In my views.py I call something like this: context['item8'] = Stock.aggregators.filter_rating_average_under(type='mykeyword') I dont want to hardcode a keyword into a field so is there a way to format this code? So that {type}__lte works and I can run this query with different keywords instead of only one? -
Model constraint on checking existing relationship between two fields
I'm writing a Django app and I want Users to be able to review Courses. The Users have to select the Professor they are reviewing when creating a Review, because multiple Professor can teach that single Course. I created a Taught table that keeps the relations between Professors and Courses. How do I enforce that when I'm adding a review, I will only be shown in the dropdown of professors, the professors which have an existing relationship with that course (only the professors which have taught the course). class Professor(models.Model): name = models.CharField() class Course(models.Model): name = models.CharField(max_length=200) professor = models.ManyToManyField(Professor, through="Teaches", related_name='taughtBy') class Teaches(models.Model): course = models.ForeignKey(Course,on_delete=models.CASCADE,related_name="reviews_course") professor=models.ForeignKey(Professor,on_delete=models.CASCADE,related_name="reviews_professor") class Review(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE,related_name="is_author") course = models.ForeignKey(Course,on_delete=models.CASCADE,related_name="reviews_course") professor = <<<<How do I enforce that professor and course have to have an existing relationship in Teaches?>>>> -
Setting css class to field in form depending of it's type
I want to manually render login and signup forms in Django. Here is my code: {% load widget_tweaks %} {% for field in form.visible_fields %} <div class="field"> <label class="label">{{ field.label_tag }}</label> <div class="control"> {% if form.is_bound %} {% if field.errors %} {% render_field field class="nice-looking-field"%} {% for error in field.errors %} {{ error }} {% endfor %} {% else %} {% render_field field %} {% endif %} {% else %} {% render_field field %} {% endif %} {% if field.help_text %} <p>{{ field.help_text }}</p> {% endif %} </div> </div> {% endfor %} {% if form.non_field_errors %} <div class="box"> {% for error in form.non_field_errors %} {{ error }} {% endfor %} </div> {% endif %} My question: is it possible to check in a loop what type the field has and depending on the field, assign a specific css class? For example: Field_1 has type text, so we apply css-class-1 to it Field_2 has a checkbox type, so we apply css-class-2 to it -
permission_required for user who only users who are part of a group ,in view based class
Based on a tutorial,i have a view with a restriction on the display of data, based on a permission of the form "book.can_view" in class BookDetailView This works, but the probleme are every user not have access to the view I'd like to do the same thing but using the group name. . I would like only users who are part of a group named "premium" to have access to this page my views.py from django.shortcuts import render from django.contrib.auth.mixins import PermissionRequiredMixin from django.http import HttpResponse from catalog.models import Book, Author, BookInstance, Genre from accounts.models import CustomUser from django.views.generic import ListView, DetailView class BookListView(ListView): model = Book paginate_by = 10 #permission_required = 'catalog.view_book' def index(request): # Generate counts of some of the main objects num_books = Book.objects.all().count() num_instances = BookInstance.objects.all().count() # Available books (status = 'a') num_instances_available = BookInstance.objects.filter( status__exact='a').count() # The 'all()' is implied by default. num_authors = Author.objects.count() context = { 'num_books': num_books, 'num_instances': num_instances, 'num_instances_available': num_instances_available, 'num_authors': num_authors, } # Render the HTML template index.html with the data in the context variable return render(request, 'index.html', context=context) class BookDetailView(PermissionRequiredMixin, DetailView): """Generic class-based detail view for a book.""" model = Book template_name = "catalog/permission_required.html" permission_required = 'book.can_view'# change this … -
Wagtail API not exposing custom field
I am enabling wagtail api v2 in my wagtail project. After adding the api.v2 I am getting this json response { "id": 32, "meta": { "type": "blog.AddStory", "detail_url": "http://localhost/api/v2/pages/32/", "html_url": "http://localhost/blog/1st-story/", "slug": "1st-story", "first_published_at": "2022-07-19T18:06:50.205210Z" }, "title": "1st story" } I want to add my content field after title field. I added this in my models.py file from wagtail.api import APIField from rest_framework import serializers #Exposing Custom Page Fields/content api_fileds = [ APIField('content'), APIField('custom_title'), APIField('blog_image'), ] Here is my api.py file from wagtail.api.v2.views import PagesAPIViewSet from wagtail.api.v2.router import WagtailAPIRouter from wagtail.images.api.v2.views import ImagesAPIViewSet from wagtail.documents.api.v2.views import DocumentsAPIViewSet api_router = WagtailAPIRouter('wagtailapi') api_router.register_endpoint('pages', PagesAPIViewSet) api_router.register_endpoint('images', ImagesAPIViewSet) api_router.register_endpoint('documents', DocumentsAPIViewSet) Why it's not exposing custom fields? Here is my full models.py file """Blog listing and blog detail pages.""" from django.db import models from modelcluster.fields import ParentalManyToManyField from django import forms from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel, MultiFieldPanel,InlinePanel from wagtail.core.fields import StreamField #Api Section import from wagtail.api import APIField from rest_framework import serializers from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.core.models import Page from wagtail.snippets.models import register_snippet from . import blocks from .blocks import InlineVideoBlock from modelcluster.fields import ParentalKey from modelcluster.contrib.taggit import ClusterTaggableManager from taggit.models import TaggedItemBase @register_snippet class BlogCategory(models.Model): """Blog category for a snippet.""" name = models.CharField(max_length=255) … -
amadeus Ajax airport search autocomplete not working python
trying this code available here https://developers.amadeus.com/blog/django-jquery-ajax-airport-search-autocomplete to add autocomplete functionality in my django app, but nothing happening, view.py def origin_airport_search(request): if request.is_ajax(): try: data = AMADEUS.reference_data.locations.get(keyword=request.GET.get('term', None), subType=Location.ANY).data except ResponseError as error: messages.add_message(request, messages.ERROR, error) return HttpResponse(get_city_airport_list(data), 'application/json') html <body> {% include "nav.html" %} <script type='text/javascript'> $(document).ready(function () { $("#iata").autocomplete({ source: "{% url 'airport_search'%}", minLength: 1, delay: 200, }); }); </script> <form class="form" name="Query" method="post" > {% csrf_token %} <div class="form-row"> <div class="form-group col-md-4"> {{ form.origin|as_crispy_field }} </div> <div class="form-group col-md-4"> {{ form.destination|as_crispy_field }} </div> </div> <div class="d-flex align-items-center form-group col-md-6"> <button type="submit" class="btn btn-primary">NotifyMe</button> </div> </form> urls: urlpatterns = [ path('', home, name='home'), path('airport_search/', origin_airport_search, name='airport_search'), ] forms.py origin = forms.CharField(max_length=30, label='Origin', required=True, widget=forms.TextInput( attrs={'type': 'text', 'id': 'iata', 'name': 'origin'})) destination = forms.CharField(max_length=30, required=True, widget=forms.TextInput( attrs={'type': 'text', 'id': 'iata', 'name': 'destination', 'placeholder': 'destination code'})) followed as mentioned in documentation but it's not working out. -
Django sitemap i18n repeats default language, doesn't include urls for non-default languages
Using Django 4.0.6, I have sitemaps working fine for a single default language - English. After adding i18n, the sitemap isn't showing the URLs for other languages, but instead repeats the English URL, whilst labeling it as a URL for the other language. I've read the documentation but can't see my mistake. from datetime import datetime from django.contrib.sitemaps import Sitemap from django.urls import reverse_lazy class LettergunSitemap(Sitemap): i18n = True languages = ["en", "nl"] alternates = True x_default = True changefreq = "daily" priority = 0.5 lastmod = datetime.strptime(LAST_MOD, "%Y-%m-%d") class Home(LettergunSitemap): location = reverse_lazy("base:home") def items(self): return ["item"] class Contact(LettergunSitemap): location = reverse_lazy("base:contact") def items(self): return ["item"] class DemoRequest(LettergunSitemap): location = reverse_lazy("base:demo") def items(self): return ["item"] ... long sitemap extract: <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"> <url> <loc>http://lettergun.com/en/</loc> <lastmod>2022-07-04</lastmod> <changefreq>daily</changefreq> <priority>0.5</priority> <xhtml:link rel="alternate" hreflang="en" href="http://lettergun.com/en/" /> <xhtml:link rel="alternate" hreflang="nl" href="http://lettergun.com/en/" /> <xhtml:link rel="alternate" hreflang="x-default" href="http://lettergun.com/" /> </url> <url> <loc>http://lettergun.com/en/</loc> <lastmod>2022-07-04</lastmod> <changefreq>daily</changefreq> <priority>0.5</priority> <xhtml:link rel="alternate" hreflang="en" href="http://lettergun.com/en/" /> <xhtml:link rel="alternate" hreflang="nl" href="http://lettergun.com/en/" /> <xhtml:link rel="alternate" hreflang="x-default" href="http://lettergun.com/" /> </url> <url> <loc>http://lettergun.com/en/say-hello</loc> <lastmod>2022-07-04</lastmod> <changefreq>daily</changefreq> <priority>0.5</priority> <xhtml:link rel="alternate" hreflang="en" href="http://lettergun.com/en/say-hello" /> <xhtml:link rel="alternate" hreflang="nl" href="http://lettergun.com/en/say-hello" /> <xhtml:link rel="alternate" hreflang="x-default" href="http://lettergun.com/say-hello" /> </url> <url> <loc>http://lettergun.com/en/say-hello</loc> <lastmod>2022-07-04</lastmod> <changefreq>daily</changefreq> <priority>0.5</priority> <xhtml:link rel="alternate" hreflang="en" href="http://lettergun.com/en/say-hello" /> <xhtml:link rel="alternate" hreflang="nl" href="http://lettergun.com/en/say-hello" … -
How to render ValidationError in Django Template?
I am new in Django, and I ask community help. Now I I'm working on user registration and I want to do password validation: if passwords are not repeated, a message appears below the bottom field. As far as I understand, {{ form.errors }} must be used to render the error text specified in ValidationError , but when this error occurs, its text is not displayed on the page. Please tell me how to solve this problem. Perhaps I did not quite understand how Django forms work. I tried the solutions suggested in other answers, but unfortunately nothing worked so far. Thank you. forms.py: from .models import CustomUser class RegisterUserForm(forms.ModelForm): email = forms.EmailField(required=True, label="Адрес электронной почты", widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder':'email'})) password = forms.CharField(label='Пароль', widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder':'password'}) ) confirm_password = forms.CharField(label='Пароль(повторно)', widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder':'confirm password'})) def clean(self): super().clean() password = self.cleaned_data['password'] confirm_password = self.cleaned_data['confirm_password'] if password != confirm_password: raise ValidationError({'confirm_password': 'пароли не совпадают'}) views.py: def sign_up(request): if request.method=="POST": form = RegisterUserForm(request.POST) if form.is_valid(): form.save() return redirect('pages:index') form = RegisterUserForm() return render(request=request, template_name="users/sign_up.html", context={'form': form}) template: </head> <link rel="stylesheet" type="text/css" href="{% static 'users/css/style.css' %}"> <head> <div class="text-center log-in-bg rounded"> <img class="mb-4" src="{% static "users/images/logo_sign_in.png" %}" alt="" width="72" height="72"> <h1 class="h3 mb-3 font-weight-normal text-dark">РЕГИСТРАЦИЯ</h1> … -
Django, why this is not working(reply of comment function)
I want to make reply of comment function. so I added parent option in Answer model. answer_create() working well. but, when i submit reply of comment, url is different with url i setting. i think i should be http://127.0.0.1:8000/debateboard/305/ but return http://127.0.0.1:8000/debateboard/answer/reply/31/ help me plz models.py class Question(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author_question') subject = models.CharField(max_length=200) content = models.TextField() create_date = models.DateTimeField() modify_date = models.DateTimeField(null=True, blank=True) voter = models.ManyToManyField(User, related_name='voter_question') def __str__(self): return self.subject class Answer(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author_answer') question = models.ForeignKey(Question, on_delete=models.CASCADE) content = models.TextField() create_date = models.DateTimeField() modify_date = models.DateTimeField(null=True, blank=True) voter = models.ManyToManyField(User, related_name='voter_answer') ######### i added this parent to make reply of comment parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='+') def __str__(self): return self.content @property def children(self): return Answer.objects.filter(parent=self).order_by('-create_date').all() @property def if_parent(self): if self.parent is None: return True return False urls.py urlpatterns = [ path('', base_views.index, name = 'index'), path('<int:question_id>/', base_views.detail, name = 'detail'), path('answer/create/<int:question_id>/', answer_views.answer_create, name = 'answer_create'), path('answer/reply/<int:answer_id>/', answer_views.reply_comment_create , name='reply_comment_create'), view def detail(request, question_id): # question = Question.objects.get(id = question_id) question = get_object_or_404(Question, pk = question_id) context = {'question' : question} return render(request, 'debateboard/detail.html', context) @login_required(login_url='common:login') def reply_comment_create(request, answer_id): answer = get_object_or_404(Answer, pk=answer_id) # question = get_object_or_404(Question, pk = answer.question.id) if … -
Django ManyToMany table output
i'm having a bit of trouble trying to return the actual value of a seperate model, i would like to return simple 'in progress' or 'open' or whichever states i add. Instead it's showing <queryset and this is only viewable when i add the .all on the end, otherwise it states None (or is blank). the status does bring back the correct data, however i just need it to say the result OPEN or IN progress and get rid of the queryset- a workflow can go through multiple status's throughout its lifecycle Views.py def workflows(request): return render(request, 'workflows/workflows.html', { 'workflows': Workflow.objects.all() }) models.py class Workflow(models.Model): id = models.AutoField(primary_key=True, editable=False) name = models.CharField(max_length=50) description = models.TextField(null=True, blank=True, max_length=30) status = models.ManyToManyField('Status', blank=True, related_name='workflows') created = models.DateTimeField(auto_now_add=True) # tags = models.ManyToManyField('Tag', blank=True) modified = models.DateTimeField(auto_now_add=True) # created_by = # requester_id retired = models.BooleanField(default=False) def __str__(self): return self.name #foreign key 1 to many relationship class Review(models.Model): #owner = workflow = models.ForeignKey(Workflow, on_delete=models.CASCADE) body = models.TextField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.AutoField(primary_key=True, editable=False) def __str__(self): return f'workflow: {self.workflow} {self.created}' #many to many relationship # Tag to be easily identifiable. class Tag(models.Model): name = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) id = models.AutoField(primary_key=True, editable=False) def __str__(self): … -
Django: How to take a data by Foreighkey for some date?
Model: class Electricitymeter(models.Model): name = models.CharField(max_length=100) serialnumber = models.CharField(unique=True, max_length=30, primary_key=True, null=False, blank=False,) ratio_transform = models.PositiveSmallIntegerField(null=False, blank=False, default=1) class Lessor(models.Model): name = models.CharField(unique=True, max_length=100) class Rentaroom(models.Model): room = models.OneToOneField(Room, on_delete=models.CASCADE) renter = models.ForeignKey(Renter, on_delete=models.CASCADE) electricitymeter = models.OneToOneField(Electricitymeter, on_delete=models.CASCADE) tarifofelectricity = models.FloatField(blank=False, null=False, default=11.8) class Electricitydate(models.Model): serialnumber = models.ForeignKey(Electricitymeter, blank=True, null=True, on_delete=models.CASCADE) datedata = models.DateField(null=False, blank=False) consumption = models.PositiveIntegerField(blank=False) View def outputmetersdata(request): form = MyForm() if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): form = form.cleaned_data startdataperiod = form['startdataperiod'] enddataperiod = form['enddataperiod'] pk = form['lessor'] obj = Rentaroom.objects.all().filter(lessor_id=pk.id) startdate = startdataperiod - timedelta(days=3) enddate = startdataperiod + timedelta(days=3) startconsumption = Electricitydate.objects.filter(datedata__range=[startdate, enddate]) context = { 'obj': obj, 'startdataperiod': startdataperiod, 'enddataperiod': enddataperiod, 'pk': pk, } return render(request, 'roomsmeters/outputmetersdata.htm', context) else: form = MyForm() return render(request, 'roomsmeters/outputmetersdata.htm', {'form': form}) Template: {% for obj in obj %} <h1> Period {{ startdataperiod }} - {{ enddataperiod }} </h1> <tr> <td>{{ obj.spotelectr }}</td> <td>{{ obj.renter }}</td> <td>{{ obj.room }}</td> <td>{{ obj.electricitymeter }}</td> <td>{{ obj.electricitymeter.ratio_transform }}</td> <td>{{ obj.electricitymeter.serialnumber }}</td> <td>{{ pk }}</td> </tr> How to take a consumption for some datedata? And how to take a valid consumption for some date if the date is between two datadates? In what file can I make calculations: (consumption_for_second_date … -
Proper implementation of a FileInput and Upload function in Django using JavaScript
I'm working on a functionality which allows a user to preview images before uploading them and I'm using JavaScript in Django. When the images are selected from the FileInput, I create a Url for them with JavaScript which turns them to blob images and allows their preview. Whilst previewing, the User can delete images he doesn't want in the preview before deciding to upload. Now when the user deletes some images, out of the selected FileInput or add. I'm using the values of the previewed images the user has selected to filter out the FileList for the images the user has deleted and to keep the images the user wants uploaded. After that is complete, I want to send the FileList as JSON to Djangos view and then input them as the images to be saved in the Database. Is this a right implementation of the functionality? OR when the user selects the images I should send it to the DB and then get it from the DB for preview by the User who can then choose to delete, how ever I'm looking at the amount of loads and effect the round trip might have on the DB, please advice. -
While Deploying my django application to ubantu server facing this problem
On local machine my code running fine but while running on server its showing this error -
Django queryset monkeypatching to add a new attribute to returned models in QuerySet object
I am using Django 3.2 I have a model like this: class MyModel(models.Model): last_valid_field_values = models.TextField(help_text='JSON field of fieldnames and values') # ... I want to be able to monkeypatch my queries, so that when fetching MyModel instances, I can added an attribute last_values_dict - which is just the loaded JSON of the last_valid_field_values So I would have something like this (pseudocode): def callback_func(instance): instance.last_values_dict = json.loads(instance.last_valid_field_values) MyModel.objects.all().apply_some_function_to_monkey_patch(callback_func) How can I do this? I also think that possibly, this could be done via a generator iterating over the QuerySet? -
stripping down unnecessary apps from Django project
I want to remove all the unnecessary apps that come as default while creating a project in Django. My Project uses Auth0 for authentication and Firestore for database. I don't want the default database app, the admin app and the auth app. By following answers to this question, I have removed the admin app but now I want to remove the auth and the database app. Is there any way to do so? Any suggestion about something else that I can remove from my project will be helpful. Thank you. -
Django gunicorn docker nginx progect 502 Bad Gateway nginx/1.21.6
I was deploying my Django project on Ubuntu server 20.04.in Docker. I used nginx and gunicorn. In the localhost work all right. On the server takes a long time to load pages. страницы. And sometimes there is an error: 502 Bad Gateway nginx/1.21.6. In logs: 1 [CRITICAL] WORKER TIMEOUT (pid:9) [error] 21#21: *17 upstream prematurely closed connection while reading response header from upstream, client: 188.170.174.36, server: , request: 1 [WARNING] Worker with pid 9 was terminated due to signal 9 . I used FROM python:3.10-alpine и FROM nginx:1.21 it is good practice? -
Kubernetes liveness probe fails when the logs show a 200 response
I am using https://pypi.org/project/django-health-check/ for my health checks in a Django app run through kubernetes_wsgi with the following YAML: livenessProbe: httpGet: path: /ht/ port: 8020 httpHeaders: - name: Host value: pdt-staging.nagyv.com initialDelaySeconds: 5 periodSeconds: 10 successThreshold: 1 failureThreshold: 10 readinessProbe: httpGet: path: /ht/ port: 8020 httpHeaders: - name: Host value: pdt-staging.nagyv.com initialDelaySeconds: 20 timeoutSeconds: 5 The pod logs claim that the probe was successful: INFO:twisted:"-" - - [22/Jul/2022:22:11:07 +0000] "GET /ht/ HTTP/1.1" 200 1411 "-" "kube-probe/1.22" At the same time, the pod events deny this: Liveness probe failed: Get "http://10.2.1.43:8020/ht/": context deadline exceeded (Client.Timeout exceeded while awaiting headers) ... and after a while, the pod regularly restarts. The pod seems to be fully functional. I can reach the /ht/ endpoint as well. Everything seems to work, except for the liveness probes. I read about slow responses causing the issue, but this is pretty fast. Any idea what the issue might be? -
How can I allow large file uploads on Django
I have a website www.theraplounge.co that allows users to upload videos. The problem is our limit on file sizes are to small. How can I increase the file size users are able to upload through my forms.py FileField? By the way I’m currently using Amazon S3. -
Django error handling - "exception" is not accessed - Pylance
I have the following views.py to handle 400, 403 and 404 error requests def handler400(request, exception): return render(request, "400.html", status=400) def handler403(request, exception): return render(request, "403.html", status=403) def handler404(request, exception): return render(request, "404.html", status=404) In my Project's urls.py file I have: handler400 = 'tasks.views.handler400' handler403 = 'tasks.views.handler403' handler404 = 'tasks.views.handler404' handler500 = 'tasks.views.handler500' The app that the views are in is named tasks. DEBUG = False is in my settings.py file. When I purposefully create an error, the error handler does not work. As mentioned, in my views.py file the "exception is not accessed - Pylance." Any help would be greatly appreciated. -
Python Django To save the old request post value and use it later
I want to save the request post value and use it later Do you know how to save the request value in Python and use it later? my_code(error) def send_form(request): if request.method == 'POST': selected_target = request.POST['target'] selected_template = request.POST['template'] -
Reverse for 'updatecategory' with arguments '({'category': <category: category object (1)>},)'
Can anyone help me with this, I try to fix out what is error?. I try to build the CRUD and I am in update now, I try to point the idea of the table and this happen please help I'm new to this I am watching youtube and try to do it Views.py update_category.html urls.py category.html -
DJANGO: NOT NULL constraint failed: courses_comment.lesson_id
I try create comments form add and take error. But I'm not shure that I correctly use lesson = at view.py at def post function. Can You help me? models.py: class Comment(models.Model): text = models.TextField('Comment text') user = models.ForeignKey(User, on_delete=models.CASCADE) lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE) view.py: class LessonDetailPage(DetailView): .... def post(self, request, *args, **kwargs): lesson = Lesson.objects.filter(slug=self.kwargs['lesson_slug']).first() post = request.POST.copy() post['user'] = request.user post['lesson'] = lesson request.POST = post form = CommentForms(request.POST) if form.is_valid(): form.save() part of urls.py path('course/<slug>/<lesson_slug>', views.LessonDetailPage.as_view(), name='lesson-detail'), forms.py: class CommentForms(forms.ModelForm): text = forms.CharField( label='Text', required=True, widget=forms.Textarea(attrs={'class': 'form-control'}) ) user = forms.CharField( widget=forms.HiddenInput() ) lesson = forms.CharField( widget=forms.HiddenInput() ) class Meta: model = Comment fields = ['text'] comment.html <div class="form-section"> <form method="post"> {% csrf_token %} {{ form }} <button type="submit">ОК</button> </div> And my Error IntegrityError at /course/linux/set-on-linux NOT NULL constraint failed: courses_comment.lesson_id Request Method: POST Request URL: http://127.0.0.1:8000/course/linux/set-on-linux Django Version: 4.0.6 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: courses_comment.lesson_id -
How do I resolve "Host key verification" django error on Heroku deployment?
I deployed to heroku with django, but I get an error. How can this be resolved? 2022-07-23T06:42:33.623380+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked 2022-07-23T06:42:33.623381+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 671, in _load_unlocked 2022-07-23T06:42:33.623381+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 848, in exec_module 2022-07-23T06:42:33.623381+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2022-07-23T06:42:33.623381+00:00 app[web.1]: File "/app/MovieReview/wsgi.py", line 16, in <module> 2022-07-23T06:42:33.623382+00:00 app[web.1]: application = get_wsgi_application() 2022-07-23T06:42:33.623382+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2022-07-23T06:42:33.623382+00:00 app[web.1]: django.setup(set_prefix=False) 2022-07-23T06:42:33.623383+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/__init__.py", line 19, in setup 2022-07-23T06:42:33.623383+00:00 app[web.1]: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2022-07-23T06:42:33.623383+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 87, in __getattr__ 2022-07-23T06:42:33.623383+00:00 app[web.1]: self._setup(name) 2022-07-23T06:42:33.623384+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 74, in _setup 2022-07-23T06:42:33.623384+00:00 app[web.1]: self._wrapped = Settings(settings_module) 2022-07-23T06:42:33.623384+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 183, in __init__ 2022-07-23T06:42:33.623384+00:00 app[web.1]: mod = importlib.import_module(self.SETTINGS_MODULE) 2022-07-23T06:42:33.623385+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module 2022-07-23T06:42:33.623385+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-07-23T06:42:33.623385+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2022-07-23T06:42:33.623385+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2022-07-23T06:42:33.623386+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked 2022-07-23T06:42:33.623386+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 671, in _load_unlocked 2022-07-23T06:42:33.623386+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 848, in exec_module 2022-07-23T06:42:33.623386+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2022-07-23T06:42:33.623386+00:00 app[web.1]: File "/app/MovieReview/settings.py", line 23, in … -
CustomUser has no field named 'username' django-allauth
I create a custom user model in django to remove username and use email as identifier for authentication purposes using this tutorial https://testdriven.io/blog/django-custom-user-model/ Then I want to use Google as my Authentication for my web-app. After following this tutorial. https://learndjango.com/tutorials/django-allauth-tutorial. When I try to login using my email it's give me an error CustomUser has no field named 'username' Then as I was searching for clues on how to fix this I found this post FieldDoesNotExist at /accounts/signup/, User has no field named 'username'. ACCOUNT_FORMS = {'signup': 'users.forms.UserChangeForm'} but this is for google signup I want users to login with their existing emails stored in my django-admin. this is my home.html {% load socialaccount %} <h1>My Google Login Project</h1> <a href="{% provider_login_url 'google'%}?next=/">Login with Google</a> I'll gladly add the rest of the code if needed. -
How to add comment without refreshing the page itself in django
I was making a blog website, I am new to django and I don't know how to add comment without refreshing the page itself. I was trying to do with the help of tutorial but they are not helping anymore here is my html file <div class="row"> <div class="comment-section col-8"> {% for i in data %} <li>{{i}}</li><br> {% endfor %} </div> <div class="col-4"> <h4 class="m-3">{{comments.count}} Comments...</h4> {% for j in comments %} <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">{{j.title}}</h5> <h6 class="card-subtitle mb-2 text-muted">{{j.visitor.name}}</h6> <p class="card-text">{{j.description}}</p> </div> </div> {% endfor %} <hr> <h3>Comment here</h3> <form method="post" id="comment-form"> {% csrf_token %} <input type="hidden" id="contentId" name = 'contentId' value="{{ result.id }}"> <div class="form-group"> <input type="hidden" id="name" name="name" class="form-control" value="{{request.session.user.name}}" readonly> </div> <div class="form-group"> <label for="title">Title</label> <input type="text" id="title" name="title" class="form-control"> </div> <div class="form-group"> <label for="description">Description</label> <textarea name="description" id="description" cols="30" rows="5" class="form-control"></textarea> </div> <button type="submit" class="btn btn-secondary">Submit</button> </form> </div> here is my views.py file def addComment(request): if request.method == 'POST': post_id = request.POST['contentId'] title = request.POST['title'] description = request.POST['description'] user = request.session['user']['id'] con = Comment( post_id=post_id, title=title, description=description, visitor_id=user, ) con.save() print() return HttpResponseRedirect(request.META.get('HTTP_REFERER'))