Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error Messages for Django Login are not appearing?
I am building a web application that Django with a custom login field, and I want to include error messages if the user does not exist or uses the wrong password. I've tried a bunch of different approaches and looked at other SO questions, but no matter what, the error messages are not appearing on my page, and I am not sure what else to try. For reference: Login View: def log_in(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): email = request.POST.get('email') password = request.POST.get('password') username = User.objects.get(email = email.lower()).username user = authenticate(username=username, password=password) if user is not None : login(request, user) return render(request, 'accounts/profile.html') else: messages.error(request, "Invalid email or password.") return render(request, 'registration/login.html', context = {'form': form}) else: messages.error(request, "Invalid email or password.") return render(request, 'registration/login.html', context = {'form': form}) form = LoginForm() return render(request, 'registration/login.html', {'form' : form}) login.html: {% if messages %} <ul class="messages" style="position: fixed; top: 40%; left: 78%; z-index: 100;"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} -
CBV with 2 Mixins that define the same methods - How can I have each Mixin execute its own code?
My view has 2 Mixins: class FooView(LoginRequiredMixin, EmailVerifiedMixin, View): ... EmailVerifiedMixin is a Mixin I wrote: class EmailVerifiedMixin(UserPassesTestMixin): def test_func(self): return self.request.user.email_verified def handle_no_permission(self): return redirect(reverse("confirm_account")) The problem is that when an Anonymous user goes to this view, they get redirected to confirm_account, rather than my login_url from LoginRequiredMixin's handle_no_permission(). See the MRO of this view: >>> pprint(FooView.__mro__) (<class 'foo_app.views.FooView'>, <class 'django.contrib.auth.mixins.LoginRequiredMixin'>, <class 'foo_app.views.EmailVerifiedMixin'>, <class 'django.contrib.auth.mixins.UserPassesTestMixin'>, <class 'django.contrib.auth.mixins.AccessMixin'>, <class 'django.views.generic.base.View'>, <class 'object'>) >>> FooView.handle_no_permission <function EmailVerifiedMixin.handle_no_permission at 0x7fbc46d8f1f0> I think the EmailVerifiedMixin is just overwriting the LoginRequiredMixin's handle_no_permission()? How can I use both of these Mixins? Just for clarity: The desired behavior is if the user is not logged in, redirect to login_url. If they are logged in, have them go through the EmailVerifiedMixin. -
Running unit tests inside Docker Container Django
What is the right way of running the unit test cases for django as part of build process ? We use Jenkins pipeline for building the docker image and container will be started by using a startup script. Do i need to call the manage.py test before the nginx container was started ? or Do i need to add a post build task in the Jenkins build pipeline to run the tests after the container was started ? So basically looking for best practice to run tests.. Do we need to run unit tests before the server has started or after the server has started ? I know that it makes more sense to run unit tests before we start the nginx, but won't it create an increased time with more n more test cases being added in future? -
Why does Django search my common static files in a sub path?
I have a bunch of static files that are used commonly for all the pages of my site. They are located in BASE_DIR/static/ For some reason, only my main page (index.html) finds them. I have this in my settings.py : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ... STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] This is in my url.py file : urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('stats/', views.stats, name='stats') ] # Adding login urls urlpatterns += [ path('accounts/', include('django.contrib.auth.urls')), ] On my home page, it finds the static files, however on the stats/ page, it does not find it. It searches in stats/static/... instead of static/... as stated by the error in the console : Not Found: /stats/static/js/main.js. The page is diplayed but with no css at all. I thought that putting a variable STATICFILES_DIRS would solve that but it does not. Can someone help me? I'm sure it is a rookie mistake... Thanks -
Django - Form from Model is_valid() == False and no errors
My code. Model: class Bid(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name='bid') created_at = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='bids') value = models.DecimalField(max_digits=19, decimal_places=2) View: class BidForm(forms.ModelForm): class Meta: model = Bid fields = ['value'] def __init__(self, min_value=0, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['value'].label = '' self.fields['value'].widget.attrs.update({ 'placeholder': 'Bid', 'class': 'form-group form-control', 'min': min_value, }) def make_bid(request): if request.method == 'POST': bid_form = BidForm(request.POST) if bid_form.is_valid(): # do something HTML: <form class="px-4 py-3" action="{% url 'make_bid' %}" method="post"> {% csrf_token %} {{ bid_form }} <input class="btn btn-primary" type="submit" value="Make bid"> </form> The problem is: when send post request with data the form will not be valid in def make_bid. bid_form.errors is empty. Data from field available via request.POST['value']. print(form) returns <tr><th></th><td><input type="number" name="value" step="0.01" placeholder="Bid" class="form-group form-control" min="&lt;QueryDict: {&#x27;csrfmiddlewaretoken&#x27;: [&#x27;2UB4RwofBmTQagDrp9ImFDJZ4OIIWzhawgp5x7tgje6ySVKzjrmNRQpI5QTUGLMr&#x27;], &#x27;value&#x27;: [&#x27;123123&#x27;]}&gt;" required id="id_value"></td></tr> The question is: why form is not valid? -
Evaluating boolean expressions and annotating the result
Let's say I have a model: class Measurement(models.Model): measurements = JSONField( null=True, blank=True, help_text="Key value pairs for measurements." ) timestamp = models.DateTimeField(auto_now_add=True) class Meta: get_latest_by = "timestamp" The values within the measurements can one to three key value pairs with boolean values but the values could also be null. For example: { "a": true, "b": false, // optional "c": null // optional } I need to be able to AND those together. For example: result_expression = F("measurements__a") & F("measurements__b") & F("measurements__c") Obviously, this doesn't work. Also, how would I be able to annotate the results of that? Measurement.objects.annotate(result=result_expression).values("result") Where the result here should be False because of the null and False values. How would I go about doing this? I'm aware that I can do this purely with Python. I'd rather not do that. If there's a Postgres or Django way to do it, I'd rather do that. -
My .exe for Django project doesn't run the server
I'm trying to generate a .exe for my Django Project. But after I execute the following command pyinstaller --name=teste manage.py and execute my runserver command using dist/teste/teste.exe runserver nothing happens, neither an error message. And, this is the .spec that was automatically generated: # -*- mode: python ; coding: utf-8 -*- block_cipher = None a = Analysis(['manage.py'], pathex=['C:\\Users\\felipe\\Desktop\\my-project\\my-api-django'], binaries=[], datas=[], hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name='teste', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, console=True ) coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=True, upx_exclude=[], name='teste') Could anyone help me? Thanks!! -
Django client.get response has no 'data' attribute
TL;DR I can't figure out why a response object has a content attribute but not a data attribute. I'm learning about Django REST Framework using this tutorial and referencing the testing approaches here. I'm trying to unit test a REST API response using Django REST Framework. The test is simply trying to assert that the response data length matches the number of objects created in the test, like so: from django.urls import reverse from rest_framework.test import APITestCase from project.models import SomeObject class ObjectAPITest(APITestCase): def test_get_list_returns_list_of_objects(self): SomeObject.objects.create() SomeObject.objects.create() response = self.client.get(reverse('object-list')) self.assertEqual(len(response.data), 2) Right now, for the sake of testing, I have a model that only has a uuid: import uuid from django.db import models class SomeObject(models.Model): some_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) And then a simple serializer class: from rest_framework import serializers from project.models import SomeObject class SomeSerializer(serializers.ModelSerializer): class Meta: model = SomeObject fields = ['some_id'] And of course all of this is wired up in a very simple view: from django.http import JsonResponse from project.models import SomeObject from project.serializers import SomeSerializer def some_list(request): some_objects = SomeObject.objects.all() serializer = SomeSerializer(some_objects, many=True) return JsonResponse(serializer.data, safe=False) When I run the test, I get this error: AttributeError: 'JsonResponse' object has no attribute 'data' But … -
Django session not passing through views
I was creating an application in django that requires some pages to only be accessible through the previous page, that is, given page A -> B -> C, only A can be accessed by the user initially, with B accessible from A and C accessible from B. To achieve this, I pass a flag through the use of sessions in django when navigating through pages, for example, when going from A to B, I set request.session["fromA"] = True, and check in page B's view that request.session.get("fromA", False) ==True to ensure that it comes from A. However, when doing so, for some reason the session object does not work as expected, and loses all information in it when navigating from a previous page to the new page (New page/view does not get any session data), and as such the user would get redirected back to the first page as from this the view determines that it is not from the previous page. I am running my django 3.0.8 app using gunicorn, behind an apache2 reverse proxy. (I do not think both of these causes any issue, and I've checked the conf just in case, but feel free to enlighten me). My … -
How can I include images in Django
I'm new to web development. Currently, I'm working on an e-commerce app project using Django framework.Now the from the media directory these are my settings MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py {(under app directory) from django.urls import path from . import views from django.conf.urls.static import static from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns=[ path('', views.baseTemplate, name="dashboard"), path('products_page', views.productsPage, name="products_page"), path('customers_page', views.customersPage, name="customers_page"), path('customer_details/<str:pk_test>/', views.customerDetails, name="customer_details"), path('delete_customer/<str:pk_test>/', views.deleteCustomer, name="delete_customer"), path('notloggedin',views.notLoggedPage, name= "notloggedin"), path('manage',views.managePage, name= "manage"), ] urls.py {(under project directory) from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('dailydeals.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models .py from django.db import models from django.contrib.auth.models import User # Create your models here. class Customer(models.Model): name = models.CharField(max_length=200, null = True) phone = models.CharField(max_length=200, null = True) email = models.CharField(max_length=200, null = True) date_created = models.DateTimeField(auto_now_add=True, null = True) def __str__(self): return self.name class Product(models.Model): product_pic = models.ImageField(null=True, blank=True) I can upload an image from admin and it's uploading to my preferred directory. When I'm entering image URL it opens that image on browser, but when i use the method below, the image doesn't show up and the console is showing … -
do django version 2.2 and above support get_by_id method for model managers
class ProductManager(models.Manager): def get_queryset(self): return ProductQuerySet(self.model, using=self._db) def get_by_id(self): qs = self.get_queryset().filter(id=id) if qs.count() == 1: return qs.first() return None -
Passing query but still getting None while printing kwargs.get(query_field)
URL: http://localhost:8000/policy-portal2020/super-mentor/dashboard/team?id=12 view @csrf_exempt def team(request, *args, **kwargs): print(kwargs) if kwargs.get('id'): return JsonResponse({"name": "params"}) elif request.user.is_super_mentor: return JsonResponse({"name": "not-param"}) return JsonResponse({"msg": "error"}) output screenshoot console output I am getting an empty dictionary {} Why is it giving an empty dictionary though i have passed parameter to the url ? -
GET data from html forms
def scan(request): scan = Stock.objects.all() type = 'Hammer' filter = {} if request.GET.get('filter'): type = request.GET['filter'] filter[type] = 100 hammer = Stock.objects.filter(**filter) belthold = Stock.objects.filter(Belthold=100) context = {'All': scan, 'Belthold': belthold, 'Hammer': hammer This is my views.py file and the following is html for a dropdown menu I am making: <form method="get"> <select onchange="this.form.submit()"> <label for="filter">Filter</label> <select name="filter" id="filter"> <option value="Hammer">Hammer</option> <option value="Belthold">Belthold</option> </select> </select> </form> Oddly enough, i get this on my html page: Any idea where things could have gone wrong? Thanks! -
Will it be a problem if i install django using pip before setting up the virtual environment?
my venv folder and django project- firstsite both are in the same folder. Although as i have mentioned . I installed django before virtual environment and now I am confused if it will work finely. ps: I am new into this field and thus this whole thing is messier for me -
while saving data to a database some of html parts are being lost
Here is my model: class Page(models.Model): title = models.CharField(max_length=70) slug = models.SlugField() priority = models.IntegerField() body = RichTextUploadingField() author = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published' The problem is when I save the record, some of the HTML elements are lost. For example,<I class="icofont-check-circled"></i> is lost. Could you help me -
Heroku build django app doesn't create STATIC_ROOT dir if DEBUG=False. Why, what goes up in there?
Dajango (+channels/postgres/redis) app on heroku with DEBUG=True works well, no errors, no abnormalities. If DEBUG=False then it actually doesn't work at all, error500. Some clue how DEBUG flag can be involved in a way like that? Thank you. Heroku Log Example, DEBUG=True (works OK): GET path="/" "GET / HTTP/1.1" 302 "GET /accounts/login/?next=/ HTTP/1.1" 200 2020-07-23T16:14:24.496575+00:00 heroku[router]: at=info method=GET path="/" host=immense-escarpment-72885.herokuapp.com request_id=78bccd24-e86e-481f-995e-0aa31b2e440d fwd="68.14.159.220" dyno=web.1 connect=1ms service=117ms status=302 bytes=240 protocol=https 2020-07-23T16:14:24.495692+00:00 app[web.1]: 68.14.159.220:0 - "GET / HTTP/1.1" 302 2020-07-23T16:14:24.705467+00:00 app[web.1]: 68.14.159.220:0 - "GET /accounts/login/?next=/ HTTP/1.1" 200 login page is displayed, OK. Now the problem: only difference is DEBUG=False: GET path="/" UserWarning: No directory at: /app/pickupteaming/staticfiles/ "GET / HTTP/1.1" 302 "GET /accounts/login/?next=/ HTTP/1.1" 500 Heroku Log Example detailed below: 2020-07-23T16:17:32.649059+00:00 heroku[router]: at=info method=GET path="/" host=immense-escarpment-72885.herokuapp.com request_id=22b8a783-04e8-4fda-a185-f0f39c69125e fwd="68.14.159.220" dyno=web.1 connect=0ms service=125ms status=302 bytes=240 protocol=https 2020-07-23T16:17:32.527579+00:00 app[web.1]: /app/.heroku/python/lib/python3.7/site-packages/whitenoise/base.py:116: UserWarning: No directory at: /app/pickupteaming/staticfiles/ 2020-07-23T16:17:32.527606+00:00 app[web.1]: warnings.warn(u"No directory at: {}".format(root)) 2020-07-23T16:17:32.643881+00:00 app[web.1]: 68.14.159.220:0 - "GET / HTTP/1.1" 302 2020-07-23T16:17:32.733941+00:00 app[web.1]: 68.14.159.220:0 - "GET /accounts/login/?next=/ HTTP/1.1" 500 2020-07-23T16:17:32.739475+00:00 heroku[router]: at=info method=GET path="/accounts/login/?next=/" host=immense-escarpment-72885.herokuapp.com request_id=991497fb-57f9-42f6-ae6b-c4a85dcdc79c fwd="68.14.159.220" dyno=web.1 connect=0ms service=60ms status=500 bytes=353 protocol=https -
Django regex validation not working as expected
Tried to use custom validation on django model based form via regex validation on password | ReType password using clean method form is working perfectly fine but clean isn't working out as expected can anyone please point out the mistake or shed some light on this topic as i'm stuck with it django.org ain't working out well for me, for your reference ALSO if i've provided wrong password it easily stored it in database without raising the error from django import forms from .models import Person from django.contrib.auth.password_validation import validate_password from django.core.validators import ValidationError, RegexValidator import re class FormClass(forms.ModelForm): Password = forms.CharField(widget=forms.PasswordInput, required=True, validators=[RegexValidator(regex=r'[A-Za-z0-9@#$%^&+=]{8,}', message="Password should contain Upper, lower, digit and Special Character.")]) ReType_Password = forms.CharField(widget=forms.PasswordInput, required=True, validators=[RegexValidator(regex=r'[A-Za-z0-9@#$%^&+=]{8,}', message="Password should contain Upper, lower, digit and Special Character.")]) def clean_password(self): super(FormClass, self).clean() a = self.cleaned_data['Password'] b = self.cleaned_data['ReType_Password'] if a != b: raise ValidationError("Password not Matched") return self.cleaned_data class Meta: model = Person fields = '__all__' -
How to use Django __str__() method for Django Tables2
I would like my django_tables2 table to show the __str__() formatted version of a record. Here' what I'm working with: #models.py class people(models.Model): namelast = models.CharField(max_length=100, verbose_name='Last Name') namefirst = models.CharField(max_length=100, verbose_name='First Name') # more fields... def __str__(self): return "%s %s" % (self.namefirst, self.namelast) #tables.py import django_tables2 as tables from .models import people class PersonTable(tables.Table): person = tables.Column() def render_person(self, value, record): return record #Also tried record.lastname, record.__str__() class Meta: model = people fields = ('person',) All variations of that has just returned a table with a column named "Person" and blank lines (i.e. "_"). How can I get a column that's formatted as namefirst namelast? -
Posting data to DjangoRestFramework api from ajax errors with 400 bad request
I have created a post api with DjangoRestFramework but sending a post request to the API from ajax errors out with 400 bad request. here is my ajax code: var imgsrc = canvas.toDataURL("image/png"); var dataURL = canvas.toDataURL(); var fd = new FormData(); fd.append('screenshot', dataURL); fd.append('fight_card', '{{fight_card.id}}'); $.ajax({ type: "POST", dataType: "json", contentType: "application/json", processData: false, enctype: 'multipart/form-data', url: "/api/save_screenshots/", data: fd, }).done(function(o) { console.log('saved'); alert('image saved'); }); -
I'm not getting redirected to current todos
Im doing a udemy course named django 3-full stack websites with python web development by nick walter. im getting error in view and update todos(lecture no. 70). When ever im updating my todos it is not re directing me to currentodos ive copying his code form github but it didnt help. Plz help me im stuck. here is my views.py: from django.shortcuts import render,redirect, get_object_or_404 from django.contrib.auth.forms import UserCreationForm,AuthenticationForm from django.contrib.auth.models import User from django.db import IntegrityError from django.contrib.auth import login,logout,authenticate from .forms import TodoForm from .models import Todo def home(request): return render(request,'todo/home.html') def signupuser(request): if request.method=='GET': return render(request,'todo/signupuser.html', {'form':UserCreationForm()}) else: if request.POST['password1']==request.POST['password2']: try: user=User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() login(request,user) return redirect("currenttodos") except IntegrityError: return render(request,'todo/signupuser.html', {'error':'User name has been taken'}) else: return render(request,'todo/signupuser.html', {'error':'Passwords do not match'}) def loginuser(request): if request.method=='GET': return render(request,'todo/loginuser.html', {'form':AuthenticationForm()}) else: user= authenticate(request, username=request.POST['username'], password=request.POST['password']) if user is None: return render(request,'todo/loginuser.html', {'form':AuthenticationForm(), 'error':'Check username or password'}) else: login(request,user) return redirect("currenttodos") def logoutuser(request): if request.method =='POST': logout(request) return redirect('home') def createtodo(request): if request.method =='GET': return render(request, 'todo/createtodo.html',{'form':TodoForm()}) else: try: form = TodoForm(request.POST) newtodo = form.save(commit=False) newtodo.user = request.user newtodo.save() return redirect("currenttodos") except ValueError: return render(request,'todo/createtodo.html',{'form':TodoForm(),'error':'Bad data passed in. Try again'}) def currenttodos(request): todos= Todo.objects.filter(user=request.user, datecompleted__isnull=True) return render(request,'todo/currenttodos.html',{'todos':todos}) def … -
How to use user credentials to authorize with oauth2
I am currently developing a django rest api and for authentication I decided to go with OAuth2(django-oauth-toolkit). However I can't use the oauth system, from my understanding while user logging in we take user credentials and validate them, afterwards we need to create a token for the user and use it to authorize him/her. But I don't know how to create a token for logged in users, so there is my code: views.py class UserLoginAPIView(generics.CreateAPIView): permission_classes = (AllowAny,) serializer_class = UserLoginSerializer queryset = CustomUser.objects.all() serializers.py class UserLoginSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('username', 'password') extra_kwargs = { 'password': {'write_only': True} } -
Is there a way to restrict a model class from having a certain combination of permissions on it?
I have the following user model extension called UserProfile class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... def __str__(self): return str(self.user.username) class Meta: permissions = ( ("tier_3_oversight", "Tier 3 Oversight"), ("tier_2_oversight", "Tier 2 Oversight"), ("tier_1_oversight", "Tier 1 Oversight"), ) Over here , im using the custom permissions : tier_x_oversight to restrict the listing and retrieving of query sets . Everything is working fine , however , i wish to be able to restrict the adminstrative users from assigning more than 1 custom tier permission. For example , i wish to stop them from assigning tier_3_oversight and tier_2_oversight to the same user group as that would break my application's filtering logic. Is there an easy way to put such a validation , where is the Permissions saving method called at? -
'function' object has no attribute 'get' in django
I am trying to make a user not able to ask a Question only when he is logged in. This is the error I'm getting in my terminal window: Internal Server Error: /ask_question/ Traceback (most recent call last): File "/home/rayan/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/rayan/.local/lib/python3.8/site-packages/django/utils/deprecation.py", line 96, in __call__ response = self.process_response(request, response) File "/home/rayan/.local/lib/python3.8/site-packages/django/middleware/clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'function' object has no attribute 'get' [23/Jul/2020 17:19:16] "GET /ask_question/ HTTP/1.1" 500 62327 I am using a decorator, this is the code in my decorators.py: def usersOnly(view_func): def func(request, *args, **kwargs): if request.user.is_authenticated: return view_func else: return redirect('login') return func And this is the code in my views.py: @usersOnly def ask_question(request): form = AskQuestion() if request.method == "POST": asker = request.user form = AskQuestion(request.POST) if form.is_valid(): form.save() id = form.cleaned_data.get('id') return redirect(f'/question/{id}/') dic = { "form":form, } return render(request, 'blogs/ask_question.html', dic) And this is the code from my models.py: class Question(models.Model): title = models.CharField(max_length=250) asker = models.ForeignKey(User,on_delete=models.CASCADE) text = models.TextField() pub_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title I am trying to allow only the logged in users to ask a question, if the user isn't logged in, he will be redirected … -
Django - query the records in all tables that have the foreign key equal to the selected record in the main table
In Django I want to query the records in all tables that have the foreign key project = ProjectMain's chosen pk. So if I choose a record in ProjectMain and it's pk=2 I also want the records from the other three tables where the foreign key product=2. Here are the tables: class ProjectMain(models.Model): username = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.CharField(max_length=60) product = models.ForeignKey(ProductType, on_delete=models.CASCADE) filler = models.CharField(max_length=100) class Methods(models.Model): method_name = models.CharField(max_length=10) method_test = models.CharField(max_length=50, null=False) project = models.ForeignKey(ProjectInformation, on_delete=models.CASCADE) class Things(models.Model): thing1 = models.CharField(max_length=10) thing2 = models.CharField(max_length=50, null=False) project = models.ForeignKey(ProjectInformation, on_delete=models.CASCADE) class MoreStuff(models.Model): stuff1 = models.CharField(max_length=10) stuff2 = models.CharField(max_length=50, null=False) project = models.ForeignKey(ProjectInformation, on_delete=models.CASCADE) I've been trying Django querysets and am getting nowhere. Please help. -
How to delete product in users cart if i deleted it in django admin
How do i delete the product without causing any errors on the users side.Am getting an error saying nonetype object has no attribute price