Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change a boolean value after a click on a button in Django does not work
I need some help regarding button clicks and boolean value changes in django. My model: class Topic(models.Model): subject = models.CharField(max_length=255) category = models.CharField(max_length=255) last_updated = models.DateTimeField(auto_now_add=True) starter = models.ForeignKey(User, on_delete=models.CASCADE, related_name='topics') slug = models.SlugField(unique=True) isReported = models.BooleanField(default=False) startPrice = models.IntegerField(validators=[RegexValidator(r'^\d{1,10}$')]) I want to change the state of the field "isReported" from the default value "False" to "True" after a click on a button: <button type="submit" class="btn btn-primary btn-block">Report</button> How can I change the boolean value in my database after a single button click? It is not neccessary to change the value back on this button. I somehome tried to adapt the code of the link: views.py: def ajax_change_status(request): isReported = request.GET.get('isReported', False) pk = request.GET.get('pk', False) # first you get your Job model job = Topic.objects.get(pk=pk) try: job.isReported = isReported job.save() return JsonResponse({"success": True}) except Exception as e: return JsonResponse({"success": False}) return JsonResponse(data) xxx.html: <form method="post" novalidate> {% csrf_token %} <button type="submit" class="btn btn-danger btn-sm" id="change" role="button">Report</button> </form> <script> $("#change").on('click', function () { var pk = '{{ topic.pk }}' var isReported = 'True' $.ajax({ url: '/ajax/change_status/', data: { 'isReported': isReported 'pk': pk }, dataType: 'json', success: function (data) { if (data.success) { alert("ajax call success."); // here you update the … -
Django Integrity Error: Unique Constraint Failed [closed]
strong textHere is the input. And the output is giving me the error. -
django unittest to use "real" database
I am currently writing test cases for views, Which eventually uses database also. By default a test database is being created and removed after test are run. As the database itself is development database, I don't want my test to create a separate db but use exciting only. Also I will like to bring to your notice, that in my environment, database are created and provided and django can't run migration or create database. How can I create unittest which uses real database ? -
How to make an IAM Role for a Django Application?
I want to make an IAM Role for my Django app. How can I do this both from AWS side and Django side? Also, I have heard that this is best practice, but don't really understand why it is important. Could someone explain? Thanks! -
Django error for image upload to S3 bucket using Rest Post Request
I am learning and trying how to upload file in Django using Post method, and here I encountered two errors for the same code Postman uploading via Post->form-data error is {'bookName': [ErrorDetail(string='This field is required.', code='required')], 'bookCover': [ErrorDetail(string='No file was submitted.', code='required')]} Uploading via web-based Django Framework : { "bookCover": [ "The submitted data was not a file. Check the encoding type on the form." ] } Serializer.py class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ['bookName', 'bookCover'] # '__all__' for all View.py @api_view(['GET', 'POST']) def book_list(request): elif request.method == 'POST': # user = request.user # if not user: # return Response(status=status.HTTP_403_FORBIDDEN) serializer = BookSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) print(serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Url.py path('books/', book_list) I am using the same URL for post and get request. books/ and books/?name=Book1 get request books/ for post I am trying to upload books image to s3 using post request. If I remove the image field then its working fine for web-based API it's creating the book object but for the postman, it just gives error even if I try the raw data instead of form-data. for web-based Post request: { "bookName": "Book8", "bookCover": null // here should I use … -
i have to transfer cust data to book. any possible method ? let me know please
from.models import Book,Cust Cust.objects.get(acc, no1) Book.objects.create(ac="acc",no="no1") -
How to reduce latency in a web application that uses Django in the backend?
What is the most suitable tech stack for a web application, keeping the priority to low latency? I have knowledge in Django but Python isn't really the solution for latency. Di need to start coding the entire backend in c++ or just a part and make it work with the Django server? If You happen to know any solution, please attach links for reference. I am a beginner. -
DevTools failed to load SourceMap: Could not load content http://localhost:8000/static/assets/plugins/bootstrap/css/bootstrap.min.css.map
Could you please tell me why I am getting this error when I tried to run a project in local django server(localhost:8000),the application is loaded with this error in console... DevTools failed to load SourceMap: Could not load content for http://localhost:8000/static/assets/plugins/bootstrap/css/bootstrap.min.css.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE Thanks in advance, Parvathy -
can i show data with Pagination in two different html pages from views using Django?
hello i want show data with pagination in two different html pages i mean i have model called PCgames and i want pass data to ( two different html page ) i have added this in views.py : def pc_games(request): app = PCgames.objects.all() page = request.GET.get('pc-games-page', 1) # the_home_page is the name of pages when user go to page 2 etc paginator = Paginator(app, 6) # 6 that's mean it will show 6 apps in page try: pc_Games_one = paginator.page(page) except PageNotAnInteger: pc_Games_one = paginator.page(1) except EmptyPage: pc_Games_one = paginator.page(paginator.num_pages) return render(request,'html_file/pc_games.html', { 'pc_Games_one': pc_Games_one }) this code is render to pc_games.html and i want pass same data to home.html how i can do that ? -
ERROR 1045 - A big problem with the access to my mysql db
I was trying to execute "python manage.py migrate" in my project directory made in django. The output was: django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)") So, I thought that I was having a problem with the db password of root user, I saw toturials to change the password, then, I try to enter with "mysql -u root -p" and it tried to enter but it did not accept, it said it was invalid. I tried "sudo" and if it worked, I changed the password and everything was fine. but when I try to migrate data I still have same dilemma. django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)") I assumed that I had to see that I could only do it with "sudo", the question is that I needed to use the data for my project to make use of them auth': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'api_db_project', 'USER': 'root', 'PASSWORD': 'PASSWORDRANDOM', 'HOST': 'localhost', 'PORT': 3306 }, I thought that I had not solved the problem so I look for more guides and I find:https: //stackoverflow.com/questions/39281594/error-1698-28000-access-denied-for-user-rootlocalhost $ sudo mysql -u root # I had to use "sudo" since is new installation mysql> USE mysql; mysql> UPDATE … -
How to call python OpenCV on the browser in a WSGI application
I am building a face detection web app. I have a WSGI client & server. The client is supposed to capture the frames and pass it to Redis datastore. The server is supposed to process the images and send it back. The problem I am facing is that the WSGI client is calling the python OpenCV library on the browser which isn't being loaded. Is there anyway I can use the python OpenCV library on the browser using Django maybe? I'm quite new to Django/WSGI so any help would be much appreciated! Thanks. -
Can't access errors when rendering a field individually
In views.py: if form.is_valid(): # ...process form... return HttpResponseRedirect(reverse('auctions:index')) else: return HttpResponseRedirect(reverse('auctions:create')) In the template, doing {{ form.fieldname }} renders the form field correctly. However, if I submit a value for this field that passes html validation but doesn't pass is_valid(), the error message doesn't render in the template even though I put {{ form.fieldname.errors }}. What am I doing wrong? -
Django: Values list for a many to many relation
I'd like to know why I cannot get the item names in the same order as they are presented in the QuerySet when using values_list. print(self.prd_obj.basket.values_list()) <QuerySet [(2, 27, Decimal('20.00')), (1, 23, Decimal('12.50')), (3, 28, Decimal('15.00'))]> (above is understood as id 2 item on a ManyToMany list, this item in turn refers to id 27 on a global items list. On the global item list, id 27 is Honda that costs 20, id 28 is Mazda that costs 15 and id 23 is Ford that costs 12.50) The same order re-appear when I ask for price, as below. print(self.prd_obj.basket.values_list('price')) <QuerySet [(Decimal('20.00'),), (Decimal('12.50'),), (Decimal('15.00'),)]> However, when asking for brand (through the items field) the order is not the same. Later when re-assembly the values, Honda now costs 15, Mazda 12.50, and Ford 20.00 print(self.prd_obj.basket.values_list('items__brand')) <QuerySet [('Ford',), ('Mazda',), ('Honda',)]> This is the Model for the basket, I refer to this as a ManyToMany field as I needed a model to connect Item with a price. class ShoppingBasketItem(models.Model): items = models.ForeignKey(Item, on_delete=models.SET_NULL, blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=5, blank=True, null=True) Why is it happening and is there a better way to refer to item and its price within a "shopping basket"? -
Check which model is the current user an instance of in Django
The Employee model in my Django project has a OneToOneField relationship with the built-in Django User model. I have then further inherited this Employee model into two different Manager and Associate models. Now, when a user logs in, I want to check if this user is a Manager or an Associate in my HTML template so that I can display different options, depending on whether they are a Manager or an Associate. What is the best way to that? Models.py- GENDER = [('male','Male'),('female','Female')] class Employee(models.Model): user_def = models.OneToOneField(User,on_delete=models.CASCADE,null=True) name = models.CharField(max_length = 50) age = models.IntegerField() gender = models.CharField(max_length = 10,choices = GENDER) def __str__(self): return self.name class Manager(Employee): dept = models.CharField(max_length = 50) def __str__(self): return super().__str__() class Associate(Employee): reports_to = models.ForeignKey(Manager,on_delete=models.CASCADE) def __str__(self): return super().__str__() -
I am trying to display added items to my cart page. But when I render my cart page I get attribute error at /cart/
This is a portion of my cart.js file function updateUserOrder(productId, action){ console.log('User is logged in, sending data..') var url = '/update_item/' fetch(url, { method: 'Post', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId': productId, 'action':action}) }) .then((response)=>{ return response.json() }) .then((data)=>{ console.log('data:', data) }) } This is a function in my 'views.py' file. def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() else: items = [] order = {'get_cart_total':0, 'get_cart_items':0} context={'items': items, 'order':order} return render(request, 'store/cart.html', context) I am getting this error. I would appreciate it if someone could help me out here. File "C:\Users\PC\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 225, in inner return func(self._wrapped, *args) AttributeError: 'User' object has no attribute 'customer' [07/Sep/2020 09:15:43] "GET /cart/ HTTP/1.1" 500 70674 I don't think I even have a "User" object. I don't know where this error came from. -
My Django app passes authentication on localhost, but not on heroku
So I created a simple "social media website" where by using API I GET data from a database and I can also POST to create a social media post after I register and log in. On my localhost it all works well. I can register, login, then write a social media post and it displays on the screen. However, when I use Heroku, GET API works fine, but after I log in (and I am sure I am logged in as I can log in on admin), I cannot write anything on my website. In my IDE I get: Forbidden: /api/posts/action/ In the network page I can see this: Request URL: http://localhost:8000/api/posts/action/ Request Method: POST Status Code: 403 Forbidden Remote Address: 127.0.0.1:8000 Referrer Policy: no-referrer-when-downgrade Any idea where should I look for an error? If there is any code I should send, let me know. Thank you! -
CSRF token is null in debug mode - Django 1.6
Note: this is for Django 1.6 I'm trying to figure out why CSRF tokens don't generate in on our site when the Django DEBUG setting is set to true. Some background: the way CSRF tokens are not done the way as suggested on the Django documentation (however, I have tried that as well). They are done as follows, inside of the init function of the form: from django.middleware import csrf self.fields['csrfmiddlewaretoken'].initial = csrf.get_token(self.request) After stepping through the order of execution, I have found that When DEBUG is True: this initialisation happens before the csrf middleware runs. In this scenario, when the above code runs, csrf.get_token(self.request) returns None. when DEBUG is False: this initialisation happens after the csrf middleware runs. In this scenario, when the above code runs, csrf.get_token(self.request) returns the correct CSRF token. I have also tried removing the above way of adding in the csrf token, and instead doing it the way Django requests, i.e. by adding {% csrf_token %} into the form, however this does not either. What could be the issue here? What determines the order in which the middleware runs compared to the initialisation of the application itself? Feel free to ask for more info. -
how to fix django Model instance
error messages ValueError: Cannot assign "<User: user0@example.com>": "Diagnoses.owner" must be a "Patient" instance i get the above error when i try to create either a new card or diagnoses. Models.py class Patient(models.Model): name = models.CharField(max_length=255, null=True) country = models.CharField(max_length=255, null=True) state = models.CharField(max_length=255, null=True) phone = models.CharField(max_length=255, null=True) email = models.CharField(max_length=255, null=True) owner = models.ForeignKey(to=User, null=True, on_delete=models.CASCADE) def __str__(self): return self.name class Card(models.Model): name = models.CharField(max_length=255, null=True) card_number = models.CharField(max_length=255, null=True) owner = models.OneToOneField(Patient, null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return (self.patient.name)+"'s card" class Diagnoses(models.Model): sickness = models.CharField(max_length=255, null=True) note = models.TextField(max_length=255, null=True) owner = models.ForeignKey(Patient, null=True, on_delete=models.SET_NULL) def __str__(self): return (self.patient.name)+"'s diagnoses" -
ValueError at /add_coupon/ Cannot assign "<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/checkout/">"
i want to add coupon but when i enter wrong code it shows that error don't throw the expect part ValueError at /add_coupon/ Cannot assign "<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/checkout/">": "Order.coupon" must be a "Coupon" instance. views def get_coupon(request, code): try: coupon = Coupon.objects.get(code=code) return coupon except ObjectDoesNotExist: messages.info(request, "This coupon does not exist") return redirect("core:checkout") class AddCouponView(View): def post(self, *args, **kwargs): form = CouponForm(self.request.POST or None) if form.is_valid(): try: code = form.cleaned_data.get('code') order = Order.objects.get( user=self.request.user, ordered=False) order.coupon = get_coupon(self.request, code) order.save() messages.success(self.request, "Successfully added coupon") return redirect("core:checkout") except ObjectDoesNotExist: messages.info(self.request, "You do not have an active order") return redirect("core:checkout") models class Coupon(models.Model): code = models.CharField(max_length=15) amount = models.FloatField() def __str__(self): return self.code -
Django - ValueError when trying to update a model object
I am working on a Django program for a class. I know the error has to do with foreign key assignment but I cannot understand where my flaw in logic is. Here are the two pertinent models: class listing(models.Model): title = models.CharField(max_length=100) description = models.TextField() url = models.URLField(default="", null=True, max_length=100) category = models.CharField(default="", max_length=50) user_name = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) min_bid = models.DecimalField(max_digits=8, decimal_places=2) class watchlist(models.Model): item_id = models.IntegerField(null=False) user_id = models.IntegerField(null=False) #item_id = models.ForeignKey("auctions.listing", on_delete=models.CASCADE, related_name="item_watchlist") #user_id = models.ForeignKey("auctions.User", on_delete=models.CASCADE, related_name="user_watchlist") The last two lines in the watchlist class were commented out, allowing the code to work. However, I would like to understand how to make this work as I originally intended. Which is as follows: (the below code fails at the object create section, with a ValueError, cannot assign : item_id must be an instance of listings.) @login_required def item_listing(request, id): itemID = id # GET call coming in from clicking a title link if request.method == "GET": item = listing.objects.filter(id=id) # Check if the item is on the user's watchlist if watchlist.objects.filter(item_id=id, user_id=request.user.id).exists(): watch = True else: watch = False return render(request, "auctions/ItemPage.html", { "item": item, "name": item[0].title, "url": item[0].url, "description": item[0].description, "user_name": item[0].user_name, … -
Trouble raising ValidationError when using Form.add_error()
As a form is passed data, I'm testing for a ValidationError when the Form.clean() method is invoked. The clean() method evaluates a conditional to see if two fields have the same value. If evaluated to true, I want to invoke Form.add_error() and add a Validation Error to one of the fields. As it stands now, the test does not pass and I'm getting this error: AssertionError: ValidationError not raised I'm not clear on what needs to be refactored in order for the test to pass and a Validation Error to be raised? forms.py from django import forms from django.core.exceptions import ValidationError from .validators import validate_name class NewUserForm(forms.Form): email = forms.EmailField() password = forms.CharField(min_length=6) last_name = forms.CharField( max_length=20, error_messages={'required': "You must provide your last name"}, validators=[validate_name] ) first_name = forms.CharField( max_length=20, error_messages={'required': "You must provide your first name"}, validators=[validate_name] ) reminders = forms.BooleanField(required=True) def clean(self): cleaned_data = super().clean() email = cleaned_data.get("email", None) password = cleaned_data.get('password', None) if email == password: msg = "The password provided cannot be the same as your email" self.add_error('password', ValidationError(msg)) test_forms.py from django.test import TestCase from django.core.exceptions import ValidationError from ..forms import NewUserForm class TestNewUserPassword(TestCase): @classmethod def setUpTestData(cls): user_data = { "email": "user@email.com", "password": "user@email.com", "first_name": "firstName", … -
Django best practices - ensuring atomicity while executing business logic
I am refactoring some legacy code on a Python/Django application and I'm looking for a styling/best practices recommendation about performing actions on a SQL Database. Right now I am trying to rework the following code: def fun(): try: with transaction.atomic(): # query DB # do business logic # update DB entries with new values except: # handle exception The thing is, there is a fair amount of business logic between my query and my update. However I feel like it doesn't make sense to throw additional code under another indentation/i.e defining as part of a DB transaction. Ideally I'd like to clean this up and only perform certain things as atomic. I suppose it wouldn't actually cut down on my lines of code, but I'm curious what transaction.atomic() is actually accomplishing? From my understanding of atomicity, reads don't actually affect the state of a datastore, so I'm not entirely sure the initial read belongs under the atomic() anyway. thanks in advance. -
Porgress bar/loading icon while running python scrip for Django project
I have a django project where I am running a python script to process some data and then present the result. That part is not an issue and work perfectly. However, I am wondering how I can show a progress bar or something like that while the script runs. I can most likely render an intermediate page with that bar but even still how will I continuously update the progress? Just looking for information about the concept. Do I have to have an intermediate page or do I have to use a responsive front end such as Vue? -
Changed from 3 different settings files (base, dev, prod) to 1 settings.py file, and now templates are not recognized?
Trying to use django-dotenv, I went from 3 different files for settings to 1: settings.py. However, server runs but templates are not recognized, why? settings.py: """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import dotenv import sys import os from decouple import config dotenv.read_dotenv() PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(PROJECT_DIR) #SECRET_KEY = config('SECRET_KEY') SECRET_KEY = os.getenv('SECRET_KEY') DEBUG = os.getenv('DEBUG') from dj_database_url import parse as dburl default_dburl = 'sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3') DATABASES = { 'default': config('DATABASE_URL', default=default_dburl, cast=dburl), } # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # Application definition INSTALLED_APPS = [ 'home', 'search', 'flex', 'streams', 'menus', 'site_settings', 'subscribers', 'blog', 'doctrina', 'storages', 'registration', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.contrib.settings', 'wagtail.contrib.modeladmin', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'modelcluster', 'taggit', 'django_extensions', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'debug_toolbar', 'crispy_forms' ] SITE_ID = 1 #django-allauth setting MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', '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', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(PROJECT_DIR, 'templates'), … -
Can't set up virtual environment or see if Anaconda is installed, can't access bash folder, 'command not found'
I'm just starting out learning web programming and am trying to set up a virtual environment in atom. I am on a mac. the terminal window doesn't seem to be able to access my bin or bash folder anymore, I'm not sure. In the terminal window I am typing 'conda --version' to determine which version of Anaconda I have installed but I get the message "-bash: conda: command not found" - Also when I am in Atom, and am using the python text editor and I'm trying to create a virtual environment, I type 'sudo conda create --name myDjangoEnv django' and I get the same message, 'sudo: conda: command not found'. I used sudo because otherwise it would not let me set up a virtual environment. I thought I had to enter a password to set up a virtual environment on a mac, and it worked yesterday. I think I edited the bash profile when I set up the virtual environment. I was able to do all of this yesterday, when I typed 'conda --version' in my terminal I got the version of anaconda I installed, and I was able to update the version of anaconda. And in the python …