Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku & Django: Debug = False returns server error, I tried couple of solutions but nothing works
So I am trying to put my website into production applying variables to secretkey and debug value, after passing heroku config: set Secret_Key="(My key)" and heroku config: set Debug_value=False . My website returns server error 500. Every page of it returns same error. I've done adding my site URL in allowed host and done with collectstatic both on local and server. But still the error continues. Please help I am trying this for last 3days. Here is my settings.py """ Django settings for Calculator project. Generated by 'django-admin startproject' using Django 3.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import django_heroku import mimetypes import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = (os.environ.get("DEBUG_VALUE") == "True") #DEBUG = True ALLOWED_HOSTS = [ 'mathtools.herokuapp.com','127.0.0.1/','localhost' ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', 'Calculator_base' ] … -
How to implement two different types of users with extended attributes in Django?
I am using python 3.8.3 and Django 3.0.8 I am building a project that allows students and teachers to login to it. Hence I have two different kinds of users. Also these two users have extended attributes and methods apart from the one that Django provides implicitly to its user model, like department, organisation, etc. How can I implement them? Most of the articles I come across are either very old and for outdated versions of Django and python or they don't combine my required functionality? How can I extend my user model to have more attributes and how do I implement two different kinds of users? And how do I separately enforce authentication for these two different kinds of users? -
Don't know how to convert the Django field recipes.Recipe.image (<class 'cloudinary.models.CloudinaryField'>)
I basically started working on a graphene-django website that uses cloudinary to hose images model: from django.db import models from cloudinary.models import CloudinaryField from tinymce.models import HTMLField class Origin(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name DIFFICULTY_CHOICES = [ ('Easy', 'Easy'), ('Moderate', 'Moderate'), ('Experienced', 'Experienced'), ('Hard', 'Hard') ] class Recipe(models.Model): name = models.CharField(max_length=150) image = CloudinaryField('image') origin = models.ForeignKey(Origin, related_name="recipes", on_delete=models.CASCADE) category = models.ForeignKey( Category, related_name="recipes", on_delete=models.CASCADE ) serves = models.IntegerField(blank=True, null=True) difficulty = models.CharField(max_length=11, choices=DIFFICULTY_CHOICES, default="Moderate") kcal = models.FloatField(max_length=6) fat = models.FloatField(max_length=6) saturates = models.FloatField(max_length=6) carbs = models.FloatField(max_length=6) sugars = models.FloatField(max_length=6) fibre = models.FloatField(max_length=6) protein = models.FloatField(max_length=6) salt = models.FloatField(max_length=6) instructions = HTMLField() def __str__(self): return self.name and the problem seems like that graphene is not sure how to convert the cloudinary field, and I'm not sure how to deal with that? I saw these questions that were close but still didn't quite get it. One Two -
How to translate numbers in django translation?
My head could not click how to translate numbers in django translation. It is not possible to translate by string id. I could print 2020 like: {% translate '2' %}{% translate '0' %}{% translate '2' %}{% translate '0' %} Obvioulsy, It is not the way. So, I am missing something. I would want something like: {% translate "2020"|number %} # may be It should be that, translation from 0 to 9. -
How to queryset the field with foreign key's ID in form in Django?
I have 2 models, Class and Attendance. Inside Attendance model I have 2 fields, student(ManytoManyField) and course(ForeignKey). Inside AttendanceForm I want to queryset student field with course's id. How can I do it? # models.py class Class(models.Model): student = models.ManyToManyField("account.Student") class Attendance(models.Model): student = models.ManyToManyField("account.Student") course = models.ForeignKey(Class, on_delete=models.CASCADE) # forms.py class AttendanceForm(forms.ModelForm): class Meta: model = Attendance fields = ['student', ] widgets = {'student': forms.CheckboxSelectMultiple()} def __init__(self, class_pk, *args, **kwargs): super(AttendanceForm, self).__init__(*args, **kwargs) current_class = Class.objects.get(id=class_pk) <- # try to get class's id here self.fields['student'].queryset = current_class.student # view.py class AttendanceFormUpdate(UpdateView): model = Attendance form_class = AttendanceForm def get_form_kwargs(self): kwargs = super(AttendanceFormUpdate, self).get_form_kwargs() if self.request.user.is_teacher: kwargs['class_pk'] = self.kwargs.get('pk') <-- # try to pass class's pk to form return kwargs As you can see what i'm doing inside get_form_kwargs is passing the id of the model not the id of course field. How can pass the course field id to the form? -
what are the steps to check before uploading a django project to github to secure the project
When I uploaded my project to GitHub it sends me an email saying that my secret key is exposed to the project. So what are the things to check before uploading a Django project to GitHub -
I don't understand that keyerror occurs in my code in django
I am using the django rest framework modelviewset to re-turn the entire post when I request get. But after writing the code, I sent the get request and the following error appears. Traceback (most recent call last): File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\viewsets.py", line 114, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_except ion raise exc File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "D:\school\대회 및 프로젝트\CoCo\feed\views.py", line 23, in list 'email': serializer.data['author_email'], KeyError: 'author_email' I have clearly stated this in the serializer, but I don't understand why a keyerror appears. Can you tell me what the problem is in my code? Here's my code. Thank in advance. views.py class CreateReadPostView (ModelViewSet) : serializer_class = PostSerializer permission_classes = [IsAuthenticated] queryset = Post.objects.all() def perform_create (self, serializer) : serializer.save(author=self.request.user) def list (self, request) : serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) data = { 'author': … -
chnage url paramaters parameters in request by id
i wanna make urls with GET url pattern example.com/blog/?id=1 my current code views.py def home(request,blog_uuid): blogs = Blog.objects.get(pk=blog_uuid) return render(request,'home.html',{'blogs':blogs}) url pattern path('blog/<blog_uuid>/',views.home,name='Blog'), my current url now like this example.com/blog/1 -
open(file.read(), 'rb') raises UnicodeDecodeError
I'm creating a project with Django that involves user uploading images. To test for an image and how it's stored in Django's default storage, I'm using the combination of SimpleUploadedFile, io.BytesIO(), and the Pillow Image class. When I test for the successful creation of a model instance (Photo) a UnicodeDecodeError is raised. ERROR: setUpClass (photos.tests.test_models.TestPhotoModel) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\..\..\..\..\..\venv\lib\site-packages\django\test\testcases.py", line 1137, in setUpClass cls.setUpTestData() File "C:\..\..\..\..\..\photos\tests\test_models.py", line 23, in setUpTestData content=open(file.read(), 'rb') UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte I cannot figure out why this error is being raised. How can this be addressed so the test can run properly? from io import BytesIO from unittest.mock import Mock, patch from django.test import TestCase from django.db.models import ImageField from django.core.files.uploadedfile import SimpleUploadedFile from PIL import Image from ..models import Photo class TestPhotoModel(TestCase): @classmethod def setUpTestData(cls): file = BytesIO() image = Image.new("RGB", (50, 50), 'red') image.save(file, "png") file.seek(0) data = { 'title': "Title", 'image': SimpleUploadedFile( 'test_image.png', content=open(file.read(), 'rb') ) } cls.new_photo = Photo.objects.create(**data) def test_photo_instance_created(self): total_photos = Photo.objects.count() self.assertEqual(total_photos, 1) -
Multi Language DjangoCMS
I want use multi language in my project . I had install cms app core . But this app only English language. But I want multi language when I choose option . So I have to create anorther app or create new template or anything ? . I don't know how to do it . Let me know the solution -
Django: How to compare two different data table for datafield and get match exactly correct data?
Models.py class Newspaper (models.Model): newspaper = models.CharField(max_length=50) language = models.CharField(max_length=50, choices=Language) wh_price = models.DecimalField(max_digits=6,decimal_places=2) sa_price = models.DecimalField(max_digits=6,decimal_places=2) description = models.CharField(max_length=50) company = models.CharField(max_length=50) publication = models.CharField(max_length=50, choices=Publication) class Daily_Cart(models.Model): ac_no = models.CharField(max_length=32) newspaper = models.CharField(max_length=32) added_date = models.DateTimeField(max_length=32,auto_now_add=True) daily_update.py def bill(): current_time = datetime.datetime.now().day if current_time == 27: news = Newspaper.objects.all() daily = Daily_Cart.objects.all() for x in news: if x.publication=='Weekdays': for xc in daily: print(xc.newspaper, x) Daily_cart table have to compere with newspaper table. If data exits have to print newspaper AND ac_no. This result i expect to. Here you can see models /Newspaper/Daily_cart print(xc.newspaper, x) monnews monnews if use print(set(xc.newspaper)& set(x)) i got error Traceback (most recent call last): File "C:\Users\user\Documents\Project--Django\Pro_Venv\lib\site-packages\apscheduler\executors\base.py", line 125, in run_job retval = job.func(*job.args, **job.kwargs) File "C:\Users\user\Documents\Project--Django\Pro_Venv\NewspaperAPI\invoice.py", line 18, in bill print(set(xc.newspaper)& set(x)) TypeError: 'Newspaper' object is not iterable -
How can I customize the response value of the {'get': 'list'} request in django?
I am making an API that gives the entire post when requested by get. After writing the code, the value was printed as follows when the request was sent. { "pk": int, "author_username": "", "author_email": "", "author_profile": "profile_url", "title": "", "text": "", "like": liker.count, "liker": [ pk ], "image": [ image_url , ] "view": 1 }, I would like to customize this to the following form. { "pk": int, "author: { "author_username": "", "author_email": "", "author_profile": "profile_url" } "title": "", "text": "", "like": liker.count, "liker": [ pk ], "image": [ image_url , ] "view": 1 }, How can I change the shape of json like this? Attach the code on views.py. Thanks in advance. class CreateReadPostView (ModelViewSet) : serializer_class = PostSerializer permission_classes = [IsAuthenticated] queryset = Post.objects.all() def perform_create (self, serializer) : serializer.save(author=self.request.user) -
Update using record with no pk in body using UpdateAPIView
I am trying to develop an update (PUT) endpoint that would not require adding pk to the url or body. The code below requires the currentbal_autorecharge entered as an id and it works. But i will like to update records without adding the pk to the body of request. I would prefer to use the token to get the current user and then use that to complete the update. i can successfully get the current user and current user id using the view below. How can i utilize this pk without entering it in the body? class CurrentBalance(models.Model, Main): currentbal_autorecharge = models.OneToOneField(User, on_delete=models.CASCADE, related_name='currentbal_autorecharge') currentbal_update = models.DecimalField(decimal_places=2, max_digits=10000, null=True) def __str__(self): return self.currentbal_autorecharge.phone class CurrentBalanceSerializer(serializers.ModelSerializer): class Meta: model = CurrentBalance fields = ( 'currentbal_autorecharge', 'currentbal_update' ) class CurrentBalanceUpdate(UpdateAPIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) # queryset = CurrentBalance.objects.all() serializer_class = CurrentBalanceSerializer def update(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) print(serializer) serializer.is_valid(raise_exception=True) serializer.save() return JsonResponse({"status": "success"}) -
Expected view to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly
I am customizing the value given when sending get: list request from django modelviewset. In the meantime, the following error occurs and questions are asked. Traceback (most recent call last): File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\viewsets.py", line 114, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "D:\school\대회 및 프로젝트\CoCo\feed\views.py", line 20, in list instance = self.get_object() File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\generics.py", line 88, in get_object assert lookup_url_kwarg in self.kwargs, ( AssertionError: Expected view CreateReadPostView to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. I sent a list request, but I don't know why I got into trouble at looked_up field and pk. Can you determine why this problem occurred? Here's my code. Thank in advance. views.py class CreateReadPostView (ModelViewSet) : … -
'Authentication Unsuccessful' When Trying To Send Email Through Django
I've been trying to send emails using my Outlook email through Django but have been getting a variety of error messages, including (535, b'5.7.3 Authentication unsuccessful [SYBPR01CA0102.ausprd01.prod.outlook.com]') Apparently I need to allow SMTP AUTH, but cannot find how to do this as I am using Outlook in my browser and don't have it downloaded (it keeps requesting I pay for it, but I'd prefer not to as I really don't see the need for this small project, unless I need to). I did however pay for the email. I've also read that Outlook doesn't support smpt: Outlook 365 OAuth 535 5.7.3 Authentication unsuccessful My settings in Django are: DEFAULT_FROM_EMAIL = '###@###.###' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp-mail.outlook.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '###@###.###' EMAIL_HOST_PASSWORD = '########' My question is can I send Outlook emails through Django? If so, what am I doing wrong? Thank you. -
How can I define the color of my Navbar from Materialize CSS codes that I've used
newbie here, the navbar default color is materialize red I want to change it to light blue: <nav> <div class="nav-wrapper"> <a href="/" class="brand-logo">LARAYAN ONLine BookStore</a> <ul id="nav-mobile" class="right hide-on-med-and-down"> <li><a href="/">Home</a></li> <li><a href="/register">Register</a></li> <li><a href="/login">Login</a></li> </ul> </div> -
Django Image Shows As A Error How TO Fix?
I have an image called paris and I am trying to display it on my website it just shows the image url thing but does not display the image image <head> <style> img { border: 1px solid #ddd; border-radius: 4px; padding: 5px; width: 150px; } </style> </head> <body> <h2>Thumbnail Images</h2> <p>Use the border property to create thumbnail images:</p> <img src="paris.jpg" alt="One Piece" style="width:150px"> </body> my full home code: <!-- base.html --> <!DOCTYPE html> {% extends 'main/base.html' %} {% block title%} home {% endblock %} {% block content %} <html> <head> <style type="text/css"> body { background-color: #212F3C; } .sidenav2 h1 { margin-top: 196px; margin-bottom: 100px; margin-right: 150px; margin-left: 350px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } .sidenav3 h1 { margin-top: -125px; margin-bottom: 100px; margin-right: 150px; margin-left: 400px; padding-left: 290px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } .sidenav4 h1 { margin-top: -128px; margin-bottom: 100px; margin-right: 150px; margin-left: 800px; padding-left: 290px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } .sidenav6 h1 { margin-top: 250px; margin-bottom: 100px; margin-right: 150px; margin-left: 600px; padding-left: 290px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } .sidenav7 h1 { margin-top: -130px; margin-bottom: 100px; margin-right: 150px; margin-left: 50px; padding-left: 240px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } .sidenav8 h1 { margin-top: 370px; … -
I deployed my Django server via Heroku, the build was successful, but keep getting 'Application Error' on the deployed URL
I deployed my Django server via Heroku, the build was successful. Whenever I go to the deployed URL, I get an application error without no specific error. It just says for me to check my logs. Here is my log. Is there something Im missing? still new to deploying with Heroku. -----> Python app detected -----> No change in requirements detected, installing from cache -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 -----> Installing SQLite3 -----> Installing requirements with pip -----> $ python manage.py collectstatic --noinput /app/.heroku/python/lib/python3.6/site-packages/environ/environ.py:630: UserWarning: /tmp/build_b0b32caa_/portfolio_project/.env doesn't exist - if you're not configuring your environment separately, create one. "environment separately, create one." % env_file) 330 static files copied to '/tmp/build_b0b32caa_/staticfiles'. -----> Discovering process types Procfile declares types -> (none) -----> Compressing... Done: 71M -----> Launching... Released v19 https://coreys-portfolio-server.herokuapp.com/ deployed to Heroku -
(Django) How to create a verification mixin that references two models?
I have two classes Organisation, and Staff in addition to the User class. I want to create a mixin called "UserIsAdminMixin" that checks whether the user logged in has the role "admin" in a specific Organisation. The classes (simplified) class Organisation(models.Model): name = models.CharField(max_length=50) class Staff(models.Model): class Role(models.TextChoices): ADMIN = 'ADMIN', "Admin" STAFF = 'STAFF', "Staff" user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, db_index=True, related_name="staff_profiles", on_delete=models.SET_NULL) organisation = models.ForeignKey('organisations.Organisation', db_index=True, related_name="staff", on_delete=models.CASCADE) role = models.CharField(max_length=10, choices=Role.choices, default=Role.STAFF) I then currently have this for my UserIsAdmin mixin: class UserIsAdminMixin: def dispatch(self, request, *args, **kwargs): if self.request.user.staff_profiles.filter(organisation=self.get_object(), role=Staff.Role.ADMIN): return super().dispatch(request, *args, **kwargs) else: raise PermissionDenied This works great for this view: organisations.views.py (URL: organisation/<int:pk>) class OrganisationDetail(LoginRequiredMixin, UserIsAdminMixin, generic.DetailView): model = Organisation template_name= "organisations/detail.html" login_url = "login" But I'd also like it to work for this view as well, which it obviously doesn't as self.get_object() returns a Staff object in this case when it's expecting an Organisation object: staff.views.py (URL: organisation/<int:pk_alt>/staff/<int:pk>) class StaffDetail(LoginRequiredMixin, UserIsAdminMixin, generic.DetailView): model = Staff template_name="staff/detail.html" login_url = "login" I was able to make changes to the mixin to get it to work in the second scenario but not the first: class UserIsAdminMixin: def dispatch(self, request, *args, **kwargs): if self.request.user.staff_profiles.filter(organisation__pk=self.kwargs['pk_alt']), role=Staff.Role.ADMIN): return … -
Why we need django-session?
I have writen a function that has two functionality: take a request object and render a template with Product view, It adds product-id to django session corresponding to the product that the user clicked "add to cart" def catalog(request): if 'cart' not in request.session: request.session['cart'] = [] cart = request.session['cart'] request.session.set_expiry(0) store_items = Product.objects.all() ctx = { 'store_items': Product.objects.all(), 'cart_items': len(cart) } if request.method == "POST": cart.append(int(request.POST['obj_id'])) return redirect('catalog') return render(request, 'catalog.html', ctx) What is a django session? Why and when should we use it? And the most important question, does django session store data on the server-side or client-side using cookie? -
How do i group all expenses of the same category in django?
I am new to Django and trying to group and retrieve all expenses of the same category together and retrieve them in one "link like" table raw which when clicked can then display all the expenses in that category in another form. I have these Models: class Category(models.Model): name = models.CharField(max_length=50) class Meta: verbose_name_plural = 'Categories' unique_together = ("name",) def __str__(self): return self.name class Expense(models.Model): amount = models.FloatField() date = models.DateField(default=now, ) description = models.TextField() owner = models.ForeignKey(to=User, on_delete=models.CASCADE) category = models.CharField(max_length=50) def __str__(self): return self.category class Meta: ordering = ['-date', '-pk'] homeView: def home(request): categories = Category.objects.all() expenses = Expense.objects.filter(owner=request.user) paginator = Paginator(expenses, 5) page_number = request.GET.get('page') page_obj = Paginator.get_page(paginator, page_number) currency = UserPreference.objects.filter(user=request.user) # .currency query = Expense.objects.values('category').annotate(total=Sum( 'amount')).order_by('category') context = { 'expenses': expenses, 'page_obj': page_obj, 'currency': currency, 'query': query } return render(request, 'expenses/home.html', context) mytemplate: <div class="app-table"> <table class="table table-stripped table-hover"> <thead> <tr> <th>Amount</th> <th>Category</th> <th>Description</th> <th>Date</th> <th></th> </tr> </thead> <tbody> {% for myquery in query %} <tr class="clickable-row" data-href="https://www.mavtechplanet.com/"> <td>{{myquery.category }}</td> </tr> {% endfor %} </tbody> </table> </div> I am trying to figure out things but are not coming out clearly. Any help is highly appreciated. -
django text form view error 'User' referenced before assignment
i have this view that has 3 forms a form for the signin and one for the signup and the other one is for posting a text as a post where this text is saved to the database here is my views.py file from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout as django_logout from django.contrib import messages from django.urls import reverse from .models import * from .forms import * def home(request): user = request.user # for rendering texts text_form = TextForm() signin_form = SigninForm() signup_form = SignupForm() if request.method == "POST": if 'text_form' in request.POST: text_form = TextForm(request.POST) if text_form.is_valid() and request.user.is_authenticated: user = request.user obj = text_form.save(commit=False) author = User.objects.filter(email=user.email).first() obj.author = author text_form.save() if 'signin_form' in request.POST: signin_form = SigninForm(request.POST) if signin_form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user: login(request, user) elif user is None: messages.error(request, 'ُEmail or password is incorrect') if 'signup_form' in request.POST: signup_form = SignupForm(request.POST) if signup_form.is_valid(): User = signup_form.save() full_name = signup_form.cleaned_data.get('full_name') email = signup_form.cleaned_data.get('email') raw_password = signup_form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) texts = Text.objects.all().order_by('-id') context = {'signin_form': signin_form,'signup_form': signup_form,'text_form': text_form,'texts': texts} return render(request, 'main/home.html', context) in my models.py #the text model class Text(models.Model): … -
Class Style not working on Django Template
I'm trying to color the background of readonly input text in my Django templates. I'm being brief in code because the only thing is not working is the color background. I'm using the field 'rua' as the example. Maybe the problem is with the link of 'my own css' inside the base.html. My forms.py: 'rua': forms.TextInput(attrs={'readonly': 'readonly', 'id': 'rua', 'class': 'readonly'}), My template: {% extends "base.html" %} {% load static %} {% block content %} <script src="https://cdn.rawgit.com/igorescobar/jQuery-Mask-Plugin/master/src/jquery.mask.js"></script> <!-- customer login start --> <div class="customer_login"> <div class="container"> <div class="row"> <!--register area start--> <div class="col-lg-6 col-md-6 mx-auto"> <div class="account_form register"> {% if register_edit == 'register' %} <p>{{ msg }}</p> <h2>Não tem conta? Registre-se!</h2> <form method="post" action="{% url 'account:register' %}"> {% else %} <h2>Altere os dados da sua conta</h2> <form method="post" action="{% url 'account:edit' %}"> {% endif %} {% csrf_token %} <div>{{ user_form.as_p }}</div> <div>{{ profile_form.as_p }}</div> <p><button type="submit">Enviar</button></p> </form> </div> </div> <!--register area end--> </div> </div> </div> <!-- customer login end --> <script src="{% static 'js/cadastro.js' %}" type="text/javascript"></script> {% endblock %} My base.html {% load static %} <!doctype html> <html class="no-js" lang="pt-br"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>Denise Andrade - Store</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Favicon --> … -
linking class to another automatically
i have this class class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=200) def __str__(self): return self.name i want the User class to be linked to customer.user automatically once a User is created is there a way to do that? -
AttributeError at /cart/ 'NoneType' object has no attribute 'price'
I'm working on a e-commerce site, I wanted to change the products that I previously had. I went into the admin site and uploaded the new products you see in the photo. Once I saw everything was working I decided to delete 6 old products through the admin page. I then went to my cart and got this error, I'm confused why I'm getting this error with new products and not my original products site with new products error yellow page def cart(request): # check authenticated user data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items': items, 'order': order, 'cartItems': cartItems} return render(request, 'store/cart.html', context)