Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run makemigrations for dockerized django app
I have been trying to setup a django app using this guide: https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/ And it was a great resource to get everything up and running. However i have problem now when it comes to migrations. Say i add a model, add data into my db, and later i change the model. Now i can run makemigrations using the exec method on the container, but when i shut down my migrations are not stored in my local files i save to my git project, instead they are lost as i spin down the container. Does anyone know how to solve this, how do you makemigrations is such a setup where you run two dockerized django/postgres dev/prod environments? -
(Django - Python) Hidden Input Request to views.py
I have to create a site with auctions and I have an homepage which shows all the auctions active... I want to redirect users to auctions details clicking on relative button but I have some problems with the hidden input request because it doesn't report the hidden value to my function ( def bid (request, auction) ) but I see it on the url bar after the csrfmiddlewaretoken (id=1), can you help me? (I have tried also with POST request...) These are my codes: views.py def home(request): auctions = Auction.objects.filter(status=True) form = detailForm(request.GET or None) if request.method == "GET": id = request.GET.get("id") if form.is_valid(): [bid(request,auction) for auction in auctions if auction.id==id] else: form = detailForm() return render(request, "index.html", {"auctions":auctions, "form":form}) forms.py class detailForm(forms.ModelForm): class Meta: model = Auction fields = ("id",) index.html {% for auction in auctions %} <--! I put all the informations about auctions --> <form method="GET"> {% csrf_token %} <input type="hidden" name="id" value={{auction.id}}> <input type="submit"> {% endfor %} </form> Thanks to everyone! -
how it is not getting request object in django serializer after getting it(printing it)
I'm sending request from views.py in context to serializers.py As you can see in ServiceCatagorySerializer() Views.py @api_view(['GET']) def mainPageData(request): if request.method=='GET': data = {} data['ServiceCatagories']=ServicesCatagorySerializer(ServicesCatagory.objects.all(), many=True, context={'request':request}).data data['Plans']=PlansSerializer(Plans.objects.filter(Open=True), many=True).data data['FrontPageFeedback']=FrontPageFeedbackSerializer(FrontPageFeedback.objects.filter(Type='Good'), many=True).data return Response(data) and in serializers.py class ServicesCatagorySerializer(serializers.ModelSerializer): Image = serializers.SerializerMethodField() class Meta: model = ServicesCatagory fields = ('id','Name','Image','Description','get_absolute_url') def get_Image(self, ServicesCatagory): request = self.context.get('request') image_url = ServicesCatagory.Image.url print() print() print() print(dir(request)) print() print() print() return request.build_absolute_uri(image_url) after that in cosole i'm getting the output of print(dir(request)) output in console but after getting data got an error of NonType i got that also in console. -
ForeignKey with where cluase in django model
I am a newer person in Django. I face a challenge with Foreign key in Django model. I have 3 models like this: class A(models.Model): emp=models.CharField(max_length=20) class B(models.Model): type = models.OneToOneField(A, on_delete=models.CASCADE) class C(models.Model): emp_type=models.ForeignKey(B, on_delete=models.CASCADE) in Admin panel when I want to chose a data for inserting in database a DropdownBox shows all the B model but I'd like to show only specific data on B model in C model not all the data. How could I solve this problem? -
Why am I getting MultiValueDictKeyError: on 'date' even my form suppose to have 'date'
I am making a very simple web application where users encounter a form in which they can select a origin,destination (both are airports) and a date for their travel. I only have one form in forms.py: from django.forms import ModelForm,DateField,ChoiceField from .models import Flight from django.forms.widgets import SelectDateWidget,TextInput from datetime import datetime from .skyscanner import list_airports airports = list_airports() class FlightForm(ModelForm): origin = ChoiceField(required=True, choices = airports) destination = ChoiceField(required=True, choices = airports) class Meta: model = Flight fields = ['origin', 'destination', 'date'] widgets = { 'date': SelectDateWidget(years=[2021,2022]), } Where I declaratively define 'origin' and 'destination' while 'date' is coming from Flight model but represented as SelectDateWidget. Here is my models.py : from decimal import Decimal from django.contrib.auth.models import AbstractUser from django.db import models from . import fields class User(AbstractUser): pass class Airport(models.Model): code = models.CharField(max_length=3) city = models.CharField(max_length=64) def __str__(self): return f"{self.city} ({self.code})" class Flight(models.Model): origin = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="departures") destination = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="arrivals") price = fields.DecimalRangeField(min_value=Decimal( '0.00'), decimal_places=2, max_digits=10) date = models.DateTimeField() def __str__(self): return f'From {self.origin} to {self.destination} at {self.date}' And the index view: def index(request): if request.method == 'POST': origin=Airport.objects.get(code=request.POST['origin']) destination=Airport.objects.get(code=request.POST['destination']) form = FlightForm(initial={'origin': origin, 'destination': destination, 'date': request.POST['date']}) if form.is_valid(): flight={} flight['origin'] = form.cleaned_data['origin'] … -
How to implement date range filter in Django Admin using nonexistent field?
I would like to implement date range filtering on a model in Django Admin by a value which does not actually exist in the model as a field. I want to use the date range picker like DateRangeFilter from the django-admin-rangefilter package. Assume, the model has the date field and we would like to display objects, for which date - 7 lies between the specified range (just an artificial example). I have created a custom field class. class CustomDateFilter(DateRangeFilter): title = "custom_date" def queryset(self, request, queryset): queryset = super(request, queryset) queryset = queryset.annotate(custom_date=F("date") - 7) return queryset But it's usage leads to either the FieldDoesNotExist ... error if used so: @admin.register(SomeModel) class SomeModelAdmin(admin.ModelAdmin): list_filter = [("custom_date", CustomDateFilter)] or SystemCheckError: System check identified some issues: ERRORS: <class '...SomeModelAdmin'>: (admin.E114) The value of 'list_filter[0]' must not inherit from 'FieldListFilter'. if used so: @admin.register(SomeModel) class SomeModelAdmin(admin.ModelAdmin): list_filter = [CustomDateFilter] How can I achieve the thing I want to do? -
How build AJAX in follow user functionality
I have big challange with AJAX. I made 'Follow User' functionality and don't know how implement AJAX for this... This is my code: In models.py i have: class UserFollowing(models.Model): following_from = models.ForeignKey("Profile", related_name="following_from", on_delete=models.CASCADE) follow_to = models.ForeignKey("Profile", related_name="follow_to", on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: db_table = 'users_userfollowing' constraints = [models.UniqueConstraint(fields=["following_from", "follow_to"], name="unique_followers")] ordering = ("-created",) def __str__(self): return f"FROM:{self.following_from} TO:{self.follow_to}" class Profile(AbstractUser, HitCountMixin): slug = models.SlugField(null=False, unique=True) following = models.ManyToManyField("self", through=UserFollowing, related_name="followers", symmetrical=False) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.username) return super().save(*args, **kwargs) In view.py I made function to follow user: def follow_user(request): user = request.user if request.method == 'POST': user_id = request.POST.get('user_id') user_obj = Profile.objects.get(id=user_id) if user not in user_obj.followers.all(): UserFollowing.objects.get_or_create(following_from=user, follow_to=user_obj) else: UserFollowing.objects.filter(following_from=user, follow_to=user_obj).delete() return redirect('profile', slug=user_obj.slug) And in urls.py urlpatterns = [ path("followers/", follow_user, name="follow_user"), ] At least my html template: {% with total_followers=profile.followers.count %} ({{ total_followers }} Follower) <br> {% endwith %} <form action="{% url 'users:follow_user' %}" method="POST" class="follow-form" id="{{ profile.id }}"> {% csrf_token %} <input type="hidden" name="user_id" value="{{ profile.id }}"> <button type="submit" class="follow-btn{{ profile.id }}"> {% if request.user not in profile.followers.all %} Follow {% else %} Unfollow {% endif %} </button> This works very good. I can follow anad unfollw user … -
How can I access my sqlite3 database through the html template using Django?
I have a Django application where most of my backend code is in views.py. In the frontend, I'm using an html template, but currently I have hardcoded options that the user can choose from a drop down menu. Those hardcoded options are all available in the sqlite3 database which is used extensively in views.py. Is there a way that I read those fields of database from the html file directly instead of hardcoding them? -
How to add a dynamic value in settings.py Django
I want to maintain a variable TOKEN in my settings.py of my django project, and it changed with time. The token saved at db like: class FbBmToken(models.Model): manager_name = models.CharField(max_length=64) token = models.CharField(max_length=255, blank=True, null=True) effective = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'fb_bm_token' And I want use it in my django project anywhere by from django.conf import settings token = settings.TOKEN How can I make this happen? Greate thanks -
PostGIS on WSL2 - extension "postgis" has no installation script nor update path for version
I am trying to add PostGIS extension to a postgresql database on my WSL2 (with Ubuntu 20.04) for a django project. I have already installed postgresql, postgis and all dependencies with the following: sudo apt -y install postgresql-12 postgresql-client-12 sudo apt install postgis postgresql-12-postgis-3 sudo apt-get install postgresql-12-postgis-3-scripts And everything worked fine. In postgresql, I have already created my db and connected to it: sudo -u postgres psql -p 5432 -h 127.0.0.1 postgres=# CREATE DATABASE dbname; postgres=# \c dbname; But then, when I try to add the postGIS extension with: postgres=# CREATE EXTENSION postgis; I get the following error: ERROR: extension "postgis" has no installation script nor update path for version "3.0.0" And despite searching for similar questions on stackoverflow, I couldn't find any satisfactory solution for my case. Any idea what it could be wrong and how I can solve it? thank you! -
django configure apache to serve media and static files
So I have apache and mod-wsgi installed on windows. Now I need to configure apache to serve django's media files. urls.py from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('api/', include('api_backend.urls')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) apache httpd.conf LoadModule wsgi_module "c:/users/iyapp/pycharmprojects/cloud_server/venv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win32.pyd" ... # custom httpd configuration WSGIPythonPath "c:/users/iyapp/pycharmprojects/cloud_server" WSGIPythonHome "c:/users/iyapp/pycharmprojects/cloud_server/venv" <VirtualHost *:80> ServerName localhost WSGIScriptAlias / "c:/users/iyapp/pycharmprojects/cloud_server/rebox_django/wsgi.py" Alias /media/ "c:/users/iyapp/pycharmprojects/cloud_server/media/" Alias /static/ "c:/users/iyapp/pycharmprojects/cloud_server/static/" <Directory "c:/users/iyapp/pycharmprojects/cloud_server/static"> Require all granted </Directory> <Directory "c:/users/iyapp/pycharmprojects/cloud_server/media"> Require all granted </Directory> <Directory "c:/users/iyapp/pycharmprojects/cloud_server/rebox_django"> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> This is what I have so far. However, when I try to access a media file that the server has, I get a 404 not found error. Why is that? Can someone please help me? I am using Apache24 (32 bits with python) and the mod-wsgi python module. settings.py ROOT_URLCONF = 'rebox_django.urls' WSGI_APPLICATION = 'rebox_django.wsgi.application' STATIC_URL = '/static/' STATICFILES_DIRS = [] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') STATIC_ROOT = os.path.join(BASE_DIR, "static/") -
Python Django arrangement of posts within a category?
I wanted some help from you, if it is possible, I am working in Django, I was trying to arrange the posts in the template, but without success, so far I have displayed the posts in the template. order_by ('-data_e_postimit') the same I want to function in posts Within a category. class LajmetListView(ListView): model = Kategori model = Lajmet template_name = 'main/lajme-home.html' # <app>/<model>_<viewtype>.html context_object_name = 'lajmet' def get_context_data(self, **kwargs): context = super(LajmetListView, self).get_context_data(**kwargs) context['lajmet'] = Lajmet.objects.order_by('-data_e_postimit') context['trilajmet'] = Kategori.objects.get(pk=1) context['katego'] = Kategori.objects.all() return context <div class="slick_slider"> {% for lajmet in trilajmet.lajmet_set.all %} {% if forloop.counter < 5 %} <div class="single_iteam"> <a href="{% url 'lajme-detail' lajmet.slug %}"> <img src="media/{{lajmet.fotografit}}" alt=""></a> <div class="slider_article"> <h2><a class="slider_tittle" href="{% url 'lajme-detail' lajmet.slug %}">{{lajmet.titulli}}</a></h2> <p>{{lajmet.detajet|safe}}</p> <p>{{lajmet.data_e_postimit|date:"F d, Y H:i"}}</p> </div> </div> {% endif %} {% endfor %} -
Reverse for 'post_like_dislike' with arguments '('',)' not found. 1 pattern(s) tried: ['post_like_dislike/(?P<post_id>[0-9]+)/$']
I am building a Blogapp and Adding like , unlike buttons into it. BUT when i trying to open page, i keep getting this error. Reverse for 'post_like_dislike' with arguments '('',)' not found. 1 pattern(s) tried: ['post_like_dislike/(?P<post_id>[0-9]+)/$'] views.py def post_like_dislike(request, post_id): post = get_object_or_404(Post, pk=post_id) # Like if request.GET.get('submit') == 'like': if request.user in post.dislikes.all(): post.dislikes.remove(request.user) post.likes.add(request.user) return JsonResponse({'action': 'undislike_and_like'}) elif request.user in post.likes.all(): post.likes.remove(request.user) return JsonResponse({'action': 'unlike'}) else: post.likes.add(request.user) return JsonResponse({'action': 'like_only'}) # Dislike elif request.GET.get('submit') == 'dislike': if request.user in post.likes.all(): post.likes.remove(request.user) post.dislikes.add(request.user) return JsonResponse({'action': 'unlike_and_dislike'}) elif request.user in post.dislikes.all(): post.dislikes.remove(request.user) return JsonResponse({'action': 'undislike'}) else: post.dislikes.add(request.user) return JsonResponse({'action': 'dislike_only'}) else: messages.error(request, 'Something went wrong') return redirect('mains:posts') urls.py path('post_like_dislike/<int:post_id>/',views.post_like_dislike, name='post_like_dislike'), show_more.html <div class="card-footer"> <form method="GET" class="likeForm d-inline" action="{% url 'mains:post_like_dislike' post.id %}" data-pk="{{post.id}}"> <button type="submit" class="btn"><i class="far fa-thumbs-up"></i> <span id="id_likes{{post.id}}"> {% if user in post.likes.all %} <p style="color:#065FD4;display: inline">{{post.likes.count}}</p> {% else %} <p style="color:black;display: inline">{{post.likes.count}}</p> {% endif %} </span> Like</button> </form> <form action="{% url 'mains:post_like_dislike' post.id %}" method="GET" class="d-inline dislikeForm" data-pk="{{ post.id }}"> <button type="submit" class="btn"><i class="far fa-thumbs-down"></i> <span id="id_dislikes{{post.id}}"> {% if user in post.dislikes.all %} <p style="color:#065FD4; display: inline;">{{post.dislikes.count}}</p> {% else %} <p style="color:black; display: inline;">{{post.dislikes.count}}</p> {% endif %} </span> Dislike </button> </form> </div> I don't what am … -
django redirect under post statement doesn't work
This is the exmaple code that works, or any other if statements def login_page(request): if request.user.is_authenticated: return redirect('home') return render(request, 'Page-2.html') def home(request): return render(request, 'Page-1.html') But when I change the redirect under a request.method =='POST' statement, it doesn't redirect the page, but the print works def login_page(request): if request.user.is_authenticated: return redirect('home') if request.method == 'POST': print('test') return redirect('home') return render(request, 'Page-2.html') def home(request): return render(request, 'Page-1.html') urls of the project from django.contrib import admin from django.urls import path from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('', include('login.urls')), ] urls of the app from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('login/', views.login_page, name='login'), path('home/', views.home, name='home') ] The original code was just for login and redirect the page, did I miss something to set up? thanks! -
Unable to view database on frontend in Django via Shell
Hello wonderful people. I am currently learning Django and trying to display the database which is created via form on inventiory_view.html I am unable to do so via shell scripting. I am able to display the objects via shell terminal but whenever I use the same command which is Form1.objects.all I am unable to display it on my desired html page. I would really appreciate your help in this matter. Thanks in advance This is the form1.html where I am getting the data from the user. {% extends 'base.html' %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> {% block title %} Title of Form1 {% endblock %} </head> {% block body %} <div class="container"> <h1>Form1</h1> <form method="POST" action=" /form1/"> {% csrf_token %} <div class="form-group"> <label for="exampleFormControlInput1">Item name</label> <input type="text" class="form-control" id="exampleFormControlInput1" name= "item" placeholder="laptop"> </div> <!-- <div class="form-group"> <label for="exampleFormControlInput1">Quantity </label> <input type="number" class="form-control" id="exampleFormControlInput1" name= "quantity" placeholder="1,2,3"> </div> --> <div class="form-group"> <label for="exampleFormControlSelect1">Quantity</label> <select class="form-control" input type="number" id="exampleFormControlSelect1" name= "quantity"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> </div> <div class="form-group"> <label for="exampleFormControlInput1">Vendor name</label> <input type="text" class="form-control" id="exampleFormControlInput1" name= "vendor" placeholder="Nokia"> </div> … -
Python qrcode does not work inside docker
My django application generates a qrcode in the models everytime a new item is added through the form. It works perfectly fine when I run it using the python manage.py runserver command but when I dockerize the application, it shows the following error: qr_codes_img = qrcode.make(self.bag_asset_id) AttributeError: module 'qrcode' has no attribute 'make' This only happens when I build and run the docker file, otherwise it works fine. I do not have any other file or function by the name 'qrcode' and the requirements.txt file is updated perfectly. My Dockerfile looks like this: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN apt-get update RUN apt-get install -y gconf-service libasound2 libatk1.0-0 libcairo2 libcups2 libfontconfig1 libgdk-pixbuf2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libxss1 fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils WORKDIR /app ADD . /app COPY ./requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app -
How to create model with 2 columns unique together and autoincrement?
I have two columns in my Invoice model in Django: class Invoice(models.Model): use_in_migrations = True year = models.CharField(max_length=16, default='') index = models.IntegerField(default=0) with which I want to achieve in the database this sequence: ... 2020, 134 2020, 135 2021, 1 2021, 2 ... First I tried to add class Meta: unique_together = [['prefix', 'index']] so I will be sure that I get always unique row values in columns. The issue is that with PostgreSQL, this creates this sequence: ... 2020, 134 2020, 135 2021, 136 2021, 137 ... Any solution how to solve this in Django? I am using Django 2.2... -
How to call a function in django admin to refresh data available?
I want to refresh all data under all source fields in django admin. Below is my ModelAdmin class SourceAdmin(admin.ModelAdmin): list_display= ('id','source_name','missing_data','modified_date_missing','refresh_data','email_refresh_days','modified_date_refresh','search_appearance','modified_date_search','date_added','date_modified','email_count','refresh','stop') search_fields = ['id','source_name','email_refresh_days'] ordering = ['-date_modified'] list_editable = ['missing_data','refresh_data','search_appearance','email_refresh_days'] list_filter = [SourceidFilter, SourcenameFilter] def refresh(self, obj): return mark_safe('<input type="button" value="start">') def stop(self, obj): return mark_safe('<input type="button" value="stop">') def set_refresh(self, request): self.model.objects.all().update(refresh_data=True) self.message_user(request, "All data are now refreshed") return HttpResponseRedirect("../") def set_stop(self, request): self.model.objects.all().update(refresh_data=False) self.message_user(request, "All data are now stopped") return HttpResponseRedirect("../") def save_model(self, request, obj, form, change): if 'missing_data' in form.changed_data: obj.modified_date_missing = timezone.now() if 'refresh_data' in form.changed_data: obj.modified_date_refresh = timezone.now() if 'search_appearance' in form.changed_data: obj.modified_date_search = timezone.now() obj.modified_by = request.user obj.save() I want to call set_refresh and set_stop function using below functions when i will click start and stop which i mentioned in list_display. It should refresh data available in refresh_data one by one. def refresh(self, obj): return mark_safe('<input type="button" value="start">') def stop(self, obj): return mark_safe('<input type="button" value="stop">') Start and Stop Button -
Django POST form with 2 submit buttons, "enter" behavior
I have a form with 2 submit buttons that look like this: <select class="form-select" name="modelsz" id="modelsz"> <option selected>{{found_model}}</option> {% for i_model in searched_model %} <option>{{i_model}}</option> {% endfor %} </select> <button type="submit" name="chooseModel" class="btn btn-outline-success" value="Confirm">Confirm</button> ... <input type="text" class="form-control" placeholder="Symbol" name="symbolsz" id="symbolsz" value={{found_symbol}}> <button type="submit" name="searchProduct" class="btn btn-outline-success" value="Search">Search</button> There is no problem in handling both of them in one form but I can't figure out how to change default button when using "enter" key on my keyboard. Every time I press "enter" it chooses first button -
Implementing django-rest-passwordreset to React Native
I'm trying to add change password functionality to a Django / React app. I'm using django-rest-passwordreset library for creating Reset or Forgot Password API using Django Rest Framework. After I type the email that registered, I've managed get the token from the console But I'm struggling to find a way to send an email to their email address with the link to reset their password along the given token. I've tried the SMTP Method or SendGrid. Was trying this way and this way Can someone show me the correct way to make this work? Thanks a lot. -
i am using bootstrap 5 modal, nothing is happening when i try to trigger it
this is cart.html , i am using modal html on top of the page, but is still not working <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> {% extends 'base.html' %} {% block content %} {% load cart %} {% load custom %} <div class="container"> <div class="border rounded m-4 p-4" > <p class="display-4 ">Your Cart</p> <hr> <table class="table"> <thead> <tr> <th>Sno.</th> <th>image</th> <th>Product</th> <th>Price</th> <th>Quantity</th> <th>Total</th> </tr> </thead> <tbody> {% for product in products %} <tr> <td>{{ forloop.counter }}</td> <td><img style=" height:80px" src="{{ product.image.url }}" class="rounded-circle" alt="product image"></td> <td>{{product.name}}</td> <td>{{product.price |currency }}</td> <td>{{product|cart_count:request.session.cart}}</td> <td> {{product|price_total:request.session.cart|currency}}</td> </tr> {% endfor %} </tbody> <tfoot> <tr> <th colspan="4"></th> <th class="" colspan="">Subtotal</th> <th> {{ products|subtotal:request.session.cart|currency }}</th> </tr> <tr> <th colspan="5"></th> </tr> </tfoot> </table> <hr> <div class="m-3 p-3"> <a href="#" data-toggle="modal" data-target="#exampleModal" class="btn btn-outline-info border rounded col-lg-3 float-right">Check out</a> </div> </div> </div> <!-- Button trigger modal --> <!-- Modal --> {% endblock %} base.html which is inherited by cart.html , am i correctly using script ? … -
User model is not finding current user?
I used the default User model. Inside my models.py: from django.contrib.auth.models import User from django.contrib.auth import get_user_model class TweetModel(models.Model): text = models.TextField(max_length=150, blank=False) created_at = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) I have tried both get_user_model and User, but they are not working. When I try to write it is saying owner field is required. But Token was provided in the request. -
What VSCode language config setting allows HTML to add extra line in a tag on enter?
What causes the extra linebreak on pressing enter between an HTML tag within VS Code (like below)? And how can you set it up in another language without using HTML as the language's formatter (like Django-HTML for instance)? -
ValueError: invalid literal for int() with base 10: 'favicon.ico' in Terminal
I am building blog app. AND i am using Django Version :- 3.8.1. AND i am stuck on an Error. views.py def detail_view(request,id): id = int(id) data = get_object_or_404(Post,id=id) comments = data.comments.order_by('-created_at') new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): comment_form.instance.post_by = data comment_form.instance.commented_by = request.user comment_form.instance.active = True new_comment = comment_form.save() return redirect('mains:detail_view',id=id) else: comment_form = CommentForm() context = {'data':data,'comments':comments,'new_comment':new_comment,'comment_form':comment_form} return render(request, 'show_more.html', context ) urls.py path('<id>',views.detail_view,name='detail_view'), Error When i start server. Everything is working Fine. Every page is opening fine, BUT when i see the terminal then It is showing ValueError: invalid literal for int() with base 10: 'favicon.ico' in terminal at every page i Click in Browser. Any help would be Appreciated . Thank You in Advance. -
When i run my Django project i am getting this error
When i run my project i am getting this errro Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\ProgramData\Anaconda3\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\base.py", line 382, in run_checks return checks.run_checks(**kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\ProgramData\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\ProgramData\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\ProgramData\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "C:\ProgramData\Anaconda3\lib\importlib_init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 967, in _find_and_load_unlocked File "", line 677, in _load_unlocked File "", line 728, in exec_module File "", line 219, in call_with_frames_removed File "C:\Users\mehra\Downloads\Covid19Chatbot-master\BLL\urls.py", line 21, in path('', include('UI.urls')), File "C:\ProgramData\Anaconda3\lib\site-packages\django\urls\conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "C:\ProgramData\Anaconda3\lib\importlib_init.py", …