Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'QuerySet' object has no attribute 'product'
Hi I'm building a Webshop. Now I'm trying to add and delete their quantity and calculate the total price of them but I don't know how I could get the product.name or the product.quantity without getting an error as shown below. this is my views.py : def add_cart(request): memid = request.session.get( "memid" ) pnum = request.GET.get("pnum") product = Product.objects.get(pnum=pnum) try: cart = Order.objects.get(order_id_id = memid, prod_num_id = pnum) if cart: if cart.product.pname == product.pname: cart.quantity += 1 cart.save() except Order.DoesNotExist: user = Sign.objects.get(pk=request.user.pk) cart = Order( user=user, product=product, quantity=1, ) cart.save() return redirect('cart') def minus_cart_item(request): pnum = request.GET.get("pnum") cart_item = Order.objects.get(prod_num_id = pnum) product = Product.objects.get(pnum=pnum) try: for item in cart_item: if item.product.pname == product.pname: if item.quantity > 1: item.quantity -= 1 item.save() return redirect('cart') else: return redirect('cart') except Order.DoesNotExist: raise Http404 Now I'm trying to get pnum and quan from Query set but the error describes that AttributeError at /order/add_cart 'Order' object has no attribute 'product' models.py class Order( models.Model) : onum = models.AutoField(null=False, unique=True, primary_key=True) prod_num = models.ForeignKey(Product, on_delete=models.CASCADE) order_id = models.ForeignKey(Sign, on_delete=models.CASCADE) quan = models.PositiveSmallIntegerField(null=True, default=1, validators=[MinValueValidator(1), MaxValueValidator(100)]) this my html : {% for i in j %} <tr> <td>{{i.prod_num.pnum}}</td> <td><img src={{i.prod_num.image.url}} width="100" height="100"></td> <td>{{i.prod_num.pname}}</td> <td>{{i.prod_num.price}}원</td> <td>{{i.quan}} … -
@login_required does not take effect across apps in project
I want to use the decorator @login_required on all apps in my Django project. Following this thread, which shows how to write a middleware for that, here is my middleware: loginmiddleware.py from django.conf import settings from django.utils.deprecation import MiddlewareMixin from re import compile from django.shortcuts import redirect EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS] class LoginRequiredMiddleware(MiddlewareMixin): def process_request(self, request): assert hasattr(request, 'user') if not request.user.is_authenticated: path = request.path_info.lstrip('/') if not any(m.match(path) for m in EXEMPT_URLS): return redirect(settings.LOGIN_URL) And in my settings.py LOGIN_URL = '/account/login' LOGIN_EXEMPT_URLS = (r'/account/login/',) MIDDLEWARE = [ ... 'account.middleware.loginmiddleware.LoginRequiredMiddleware', ] Here is the folder structure in my project: \projec_root account\ middleware\ loginmiddleware.py models.py views.py ... boards\ models.py views.py ... dashboard\ settings.py urls.py ... In the app boards, this is the view I would like to apple the decorator on: boards\views.py: from django.shortcuts import render from django.contrib.auth.decorators import login_required @login_required() def home_board(request): return render(request, 'homeboard/home_board.html', {}) boards\urls.py from django.urls import path from . import views app_name = 'boards' urlpatterns = [ path('', views.home_board, name='home_board'), ] However, I can still access the template home_board.html without being logged in. What's missing here? -
Cannot assign "'Single Bedded'": "Patients.room_type" must be a "Accomodation" instance
I am new to Django and I have to make a project, with a scenario of a website for a Hospital. I have an Accomodations model which has data regarding what kind of beds are available and have a Patients model which has data regarding the Patient. room_type is a foreign key from Patients model to Accomodations model. Now the trouble I am having is when a new Patient has to register. I have a field which is a dropdown list with the options as the various types of beds available. I need to save the option selected from this dropdown to the DB. I used a custom form, and implemented using crispy fields. The error I am getting is Cannot assign "'Single Bedded'": "Patients.room_type" must be a "Accomodation" instance. I don't know how correct I am but I think that the problem occurs when I am passing 'Single Bedded' instead of Single Bedded (without quotes) to the DB. I am attaching my codes below: forms.py room_types = (('Single Bedded', 'Single Bedded'), ('Double Bedded', 'Double Bedded'), ('General Ward', 'General Ward'), ('Emergency Ward', 'Emergency Ward'), ('ICU', 'ICU')) class NewUserForm(forms.ModelForm): def __init__(self, *args, **kwargs): user = kwargs.pop('user', '') super(NewUserForm, self).__init__(*args, **kwargs) self.helper … -
Running django-simple-buefy in django 3.2.4
When I am trying to compile a Django 3.2 application with django-simple-buefy package, I am getting the following error: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load raise InvalidTemplateLibrary( django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'django_simple_buefy.templatetags.django_simple_buefy': No module named 'django.contrib.staticfiles.templatetags' I know that django.contrib.staticfiles.templatetags was removed in Django version 3.0. What can be done to include buefy in my project? -
Django channels with react native resulting this error "Expected HTTP 101 response but was '200 OK'"
Django channels endpoint is working well with WebSocket client(WebSocket king client) and the react-native gives no error when tested with test WebSocket endpoint(wss://echo.websocket.org). But things getting failed with the following error when using Django channels endpoint with react native. Error on error block LOG Expected HTTP 101 response but was '200 OK' Django channels code from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync from .models import CustomUser from django.core import serializers import json class EchoConsumer(WebsocketConsumer): def connect(self): self.team_name = self.scope["url_route"]["kwargs"]["teamCode"] self.team_group_name = self.team_name print(self.team_group_name) async_to_sync(self.channel_layer.group_add)( self.team_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.team_group_name, self.channel_name ) def receive(self, text_data): async_to_sync(self.channel_layer.group_send)( self.team_group_name, { "type": "get_location", "payload": text_data, }, ) . . Get location function react-native code useEffect(() => { var ws = new WebSocket( 'ENDPOINT__URL ', ); ws.onopen = () => { console.log('connected'); ws.send( 'some data', ); }; ws.onmessage = e => { // a message was received console.log('on message block'); console.log(e.data); }; ws.onerror = e => { // an error occurred console.log('on error block'); console.log(e.message); }; ws.onclose = e => { // connection closed console.log('Connection closed'); console.log(e.code, e.reason); }; }, []); Thanks in advance. -
How to fill response model in Django REST Swagger?
In Django 1.11, I want to fill in this section: Now it's empty and seems like it's not parsed out of comments. I don't see in the docs how to add it for this version of Django. -
python path, can't use Django
i tried to install django, the installation was succeeded but i couldn't create new project. so i uninstalled and try to install again and this message showed up(didn't see it the first time): WARNING: The script django-admin.exe is installed in 'C:\Users\ASUS\AppData\Roaming\Python\Python39\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. so i look up online and people said used sys.path.append to fix but when i used it: sys.path.append('C:\Users\ASUS\AppData\Roaming\Python\Python39\Scripts') SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape. please help, i'm still new to Python and Django. -
SQL or NoSQL database for a building company website? [Django, PSQL]
I am developing a buiding company website using django on BE. I have several apps at the moment - Shop, Photo gallery, Blog. All of these apps have their own models (entities). Anyway, tables between these django-apps have no relation (i.e. Photo and Tag in photo gallery and Product, Category in shop). Even Service and Product table within one app are not related. It is not okay to have such structure in relational database, isn't it? If so, should i use a NoSQL for this project (MongoDb in priority)? Is it better to migrate to Flask to use NoSQL or there are no problems to use it in Django? -
AttributeError at /accounts/register/ 'str' object has no attribute '_meta' (Django)
I'm getting AttributeError at /accounts/register/ 'str' object has no attribute '_meta' I could have a spelling mistake in some of my files. urls.py (In project) """QuestionTime URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import include, path from django_registration.backends.one_step.views import RegistrationView from users.forms import CustomUserForm # https://django-registration.readthedocs.io/en/3.1.2/activation-workflow.html urlpatterns = [ path('admin/', admin.site.urls), path("accounts/register/", RegistrationView.as_view( form_class="CustomUserForm", success_url="/", ), name="django_registration_register"), path("accounts/", include("django_registration.backends.one_step.urls")), path("accounts/", include("django.contrib.auth.urls")), path("api-auth/", include("rest_framework.urls")), path("api/rest-auth/", include("rest_auth.urls")), path("api/rest-auth/registration/", include("rest_auth.registration.urls")), ] forms.py (in app) from django_registration.forms import RegistrationForm from users.models import CustomUser class CustomUserForm(RegistrationForm): class Meta(RegistrationForm.Meta): model = CustomUser django_registration.forms and django_registration.backends.one_step.views gets highlighted yellow in VSCODE -
Login page error - dictionary update sequence element #0 has length 0; 2 is required
I am getting an error on the login page when I log out. ValueError at /accounts/login/ dictionary update sequence element #0 has length 0; 2 is required I do not know why I get this error because I've never had such an error before. What does this error mean and how can I solve it? traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/?next=/ Django Version: 3.1.4 Python Version: 3.8.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'register', 'customer', 'financial_analysis', 'ocr', 'core', 'approvals', 'crispy_forms', 'ckeditor', 'rest_framework', 'requests', 'ckeditor_uploader', 'django_filters', 'activity_log', 'djmoney', 'djmoney.contrib.exchange', 'mathfilters', 'bootstrap3', 'phone_field'] Installed 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'] Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\handlers\base.py", line 202, in _get_response response = response.render() File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\response.py", line 83, in rendered_content return template.render(context, self._request) File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\base.py", line 168, in render with context.bind_template(self): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2800.0_x64__qbz5n2kfra8p0\lib\contextlib.py", line 113, in __enter__ return next(self.gen) File "C:\Users\USER\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\template\context.py", line 244, in bind_template updates.update(processor(self.request)) Exception Type: ValueError at /accounts/login/ Exception Value: dictionary update sequence element #0 has length 0; 2 is required register/urls.py from django.conf.urls import … -
Django - Media Sharing/Streaming
I'm making an application that shares locally hosted files on my server. They're all a standard format that won't need transcoding done for the web clients I'm expecting to be used, so theoretically I should just be able to serve the data through my site. The issue is, there's a lot of data. I don't really want it all public-facing at once. I want a system where a user goes to the page for the media, and it then makes the data public. As it stands all the file locations will be stored in a model, so my idea would be some sort of hard-link solution that could temporarily put it in a public-facing location. Is there a more elegant way to do something like this? Are there other frameworks that might be better suited for this use-case? -
In django python i want to get the users name as well as only the active users in the dropdown
I am having two html forms where i fill the forms and submit and show the forms right now I want two fields to be worked simultaneously I have two fields This is what I am fetching the value of database and showing in html form as dropdown <select name="assignee" required id="assignee" class="form-control"> <option hidden value="">Select Assignee</option> {% for r in b %} <option>{{r.firstname}} {{r.lastname}}</option> {% endfor %} </select> This is my status dropdown to select the assignees are active or inactive now from the above html snippet I want to do something that it only fetches the active users right now I am fetching the all users but I want to fetch only the active users and show it in the dropdown and not the inactive how can I do this if anyone knows please help. <select required name="status" id="status" class="form-control"> <option hidden value="">Select Status</option> <option value = "Active">Active</option> <option value="Inactive">Inactive</option> </select> -
why do I solve this connection refuse error in postgres database
what to do to solve this operational error issue? hi,sir i have deployed my django website and i have some issues with db connection my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'avc', 'USER': 'postgres', 'PASSWORD': '****', 'HOST': 'localhost', 'PORT':'5432' } } i am using postgres 10 this is the error database refused the client request, error -
SQL instr equivalent in Django
I want to check if given text contains in a sub string present in db, ex:- string to search - "my name is john" string in db- "john". SQL query select * from `demo` where instr('my name is john','column_name') > 0 What is the Django Equivalent of above query? -
How to add dynamic mega menu in Django app with generic views
My project need dynamic mega menu links in all pages. In function view I have to query the model for each views. Can I reduce the line of code using django generic views and inherit form one class view. -
How to put all the db data in redis while making POST call? The below code just stores the data which was posted but not all
The code is attached as an image. Need to store whole data from db to redis after post but my code only POSTs the current data -
Data are not being retrieved form database ..Django Todol List app
class TodoModel(models.Model): enter code herecontent = models.TextField(max_length=500) enter code herecontent_date = models.DateTimeField() enter code hereuser = models.ForeignKey(User, enter code hereon_delete=models.CASCADE) `enter code hereobjects = models.Manager() `enter code todolist = CustomManager() import datetime from django.db import models class CustomManager(models.Manager): enter code heredef get_today_list(self): enter code herecurrent_date = datetime.datetime.today() enter code herereturn super().get_queryset().filter(content_date=current_date) enter code here enter code here def get_next_day_list(self): enter code herenext_day_date = datetime.datetime.today()+ enter code heredatetime.timedelta(days=1) enter code herereturn super().get_queryset().filter(content_date=next_day_date) def schedule(request): hereif request.user.is_authenticated: enter code hereif request.method == 'POST': enter code herefm = enter code hereTodoForm(request.POST,instance=request.user) enter code hereif fm.is_valid(): enter code herecon = fm.cleaned_data['content'] enter code herecon_date = fm.cleaned_data['content_date'] enter code herescd = TodoModel(content=con, enter code herecontent_date=con_date, enter code hereuser=request.user) enter code herescd.save() enter code herefm = TodoForm() enter code hereelse: enter code here`fm = TodoForm() `enter code here`my_day = TodoModel.todolist.get_today_list() `enter code here`my_next_Day = `enter code here`TodoModel.todolist.get_next_day_list() `enter code here`current_date = `enter code here`datetime.datetime.today().strftime("%B %d, %Y") `enter code here`nex_day_date = datetime.datetime.today() + `enter code here`datetime.timedelta(days=1) context = { 'form': fm, 'myday': my_day, 'my_next_day': my_next_Day, 'current_date': current_date, 'next_day_date': nex_day_date, } return render(request, 'ultratodo/profile.html', context) else: return HttpResponseRedirect('/userlogin/') #and this is what I have written in html file <tr> {% for day in myday %} <td>{{day.content}}</td> {% endfor … -
Bootstrap elements not showing in a row (class="row")
what it looks like what it's supposed to look like I'm trying to get them to fit in one row <form method="POST" class="row"> {% csrf_token %} <label class="col-lg-4">Your tasks for today?</label> <input type="text" class="form-control col-lg-6" name="task" id="exampleFormControlInput1" placeholder="New Task?"> <button type="submit" class="btn btn-primary col-lg-2">Add task</button> </form> "col-lg-6" on the input is not working , the size doesn't change even if I give a different number. -
how to return json response from html fragment stored in a dictionary key
courseware_context['fragment'] = self.section.render(self.view, section_context) the above written line is returning an html fragment in courseware_context['fragment'].here section is a variable defined in class. can anybody please help me out how to return json response from this line of code. -
Queryset on Django
I want to retrieve data from 10 data from largest to smallest, I use a queryset like this and it runs smoothly. similarity_scores = Similarity.objects.all().order_by('-similarity_score')[:10] but when i want to fetch data first_movie with word "Innocence (2014)" and sort it from data 10 from largest to smallest, i use queryset just add .filter() like this and get error similarity_scores = Similarity.objects.all().filter(first_movie ="Innocence (2014)").order_by('-similarity_score')[:10] Error invalid literal for int() with base 10: 'Innocence (2014)' did I make mistake? I really appreciate all the answers even if they are explanations, because I've read the docs from Django I can't understand them yet. Thank you -
Why the users are automatically added to likes field in many to many relation
enter image description here enter image description here -
how do i get the sum of my marks in django
@require_http_methods(["POST"]) @login_required def edit_question_parts(request): req = json.loads(request.body) question_id=req["question_id"] part_id= req["part_id"] part_desc = req["part_desc"] part_total_marks = req["part_total_marks"] total_mark = sum([part_total_marks]) #this is wrong models.Questions.objects.filter(pk=question_id).update( qn_total_mark=total_mark, updated_by=request.user.username, ) models.QuestionsPart.objects.filter(part_id=part_id).update( part_desc=part_desc, part_total_marks=part_total_marks ) return success({"res": True}) in my code above what i am trying to get the sum of all the part total marks and update it into questions table above however i am not sure how to get the sum of all the part total marks as i keep getting TypeError: unsupported operand type(s) for +: 'int' and 'str' -
Django - Certain Static Files not loading?
Repo: https://github.com/CmOliveros/encore-v1 Hi all, I may just be too tired to think right now, but in my _Base.html file in my root templates folder, I can load my index.css file, but I can't load my style.css file. They're in the same folder, and I've confirmed that all my static files are collected, but only the index.css file in my "djangoReact1/static/css/style.css" will load. Am I completely missing something here? -
when i am add post then add but not show in dashboard it is show only home page . Post is not add for current user what can i do
when i am add post then add but not show in dashboard it is show only home page . Post is not add for current user . how to add post for current user Post class in Models.py class Post(models.Model): title = models.CharField(max_length=100) decs = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def get_absolute_url(self): return reverse('author-detail', kwargs={'pk': self.pk}) def __str__(self): return self.title + '|' + str(self.user) DASHBOARD code in viwes def dashboard(request): if request.user.is_authenticated: current_user = request.user posts = Post.objects.filter(user=current_user) else: redirect('/login/') return render( request, "dashboard.html", {'posts':posts} ) dashboard HTML Code <h3 class="my-5">Dashboard </h3> <a href="{% url 'addpost' %}" class="btn btn-success">Add Post</a> <h4 class="text-center alert alert-info mt-3">Show Post Information</h4> {% if posts %} <table class="table table-hover bg white"> <thead> <tr class="text-center"> <th scope="col" style="width: 2%;">ID</th> <th scope="col" style="width: 25%;">Title</th> <th scope="col" style="width: 55%;">Description</th> <th scope="col" style="width: 25%;">Action</th> </tr> </thead> <tbody> {% for post in posts %} {% if post.user == request.user%} <tr> <td scope="row">{{post.id}}</td> <td>{{post.title}}</td> <td>{{post.decs}}</td> <td class="text-center"> <a href="{% url 'updatepost' post.id %}" class="btn btn-warning btn-sm">Edit</a> <form action="{% url 'deletepost' post.id %}" method="post" class="d-inline"> {% csrf_token %} <input type="submit" class = "btn btn-danger btn-sm" value="Delete"> </form> </td> </tr> {% endif %} {% endfor %} </tbody> </table> {% else %} <h4 … -
trying to upload a file to django server with post request from spring webClient
I am trying to upload a file to django server with post request from spring webClient. But I noticed that django receives the file and body separately from the request. Like this request.FILES['file'] How do I send a file from Spring then? current webclient code MultipartBodyBuilder builder = new MultipartBodyBuilder(); builder.part("file", file); return webClient.post() .uri("...") .body(BodyInserters.fromMultipartData(builder.build())) .retrieve() .bodyToMono(String.class);