Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Displaying different data on page depending on the date?
Is there a way to display different data on a page depending on the date? For example, I am building a macro tracker, and I would to show the data just for the day that the user inputted. So their meals that they added for 08-28-2021 would only display on the page for that day. Heres my Meal model. class Meal(models.Model): name = models.CharField( max_length=1, choices=TYPES, default=TYPES[0][0] ) date = models.DateField() foods = models.ManyToManyField(Food) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('meal_details', kwargs={'meal_id': self.id}) URL path('meal/<int:meal_id>/', views.meal_details, name='meal_details') and view @login_required def meal_details(request, meal_id): meal = Meal.objects.get(id=meal_id) unadded_foods = Food.objects.exclude(id__in = meal.foods.all().values_list('id')) return render(request, 'meals/meal_details.html', {'meal': meal, 'foods': unadded_foods}) -
unable to get the username if the data is entered from the front end in django
I am creating an invoice app, I want once the data is entered the app should automatically pick the user. if I am entering the data from admin panel it works fine.. but when I enter the data using forms in front end it takes the user name as 'none' only. -
ValueError at / save_data/
Cannot assign "'Electronic'": "Product.category" must be a "Category" instance. File/models.py: from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=150, db_index=True) def __str__(self): return self.name class SubCategory(models.Model): name = models.CharField(max_length=150, db_index=True) category = models.ForeignKey(Category, related_name='souscatégories', on_delete=models.CASCADE) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=100, db_index=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) subcategory = models.ForeignKey(SubCategory, on_delete=models.CASCADE) def __str__(self): return self. and business logic code is there.... File/views.py # from django.urls import reverse_lazy # from django.views.generic import ListView, CreateView from django.shortcuts import render from .models import Product, Category, SubCategory # Create your views here. def home(request): if request.method == "POST": name = request.POST['name'] subcategory = request.POST['subcategory'] category = request.POST['category'] ins = Product(name=name, subcategory=subcategory, category=category) ins.save() data = Product.objects.all() return render(request, 'mysiteapp/index.html', {'data': data}) and templates is there.... <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Hello, world!</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="/">Product List </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" … -
Managing static files Separately For Media Uploads and Separate for React Build
I have a little problem with my current Static Files Config. Current Settings.py #... GOOGLE_APPLICATION_CREDENTIALS = BASE_DIR / 'Cloud_Storage_Secrets/model-calling-323507-96957393f399.json' STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ BASE_DIR / 'static', BASE_DIR / 'build/static' #React Frontend Files ] MEDIA_ROOT = BASE_DIR / 'static/images' STATIC_ROOT = BASE_DIR / 'staticfiles' GS_BUCKET_NAME = 'GS_BUCKET_NAME' STATICFILES_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_CREDENTIALS = service_account.Credentials.from_service_account_file( GOOGLE_APPLICATION_CREDENTIALS ) #... Now the problem is that React frontend Build is also considered as static files when Django serves these files. Locally it works fine after creating a build from the npm run build command manually. But when I push this in production with two separate engines One Node.js for React and the other is Python for Django app on Heroku, then Django tries to get Build files from GS_BUCKET as configured for Media files and static files. So frontend build files are not picked by Django. So I'm trying to make two configurations. Google Cloud Storage for just media files but Static Files should work as default bypassing Google Cloud Storage. So How to make it possible. Please suggest to me any method to make them separate. Or how to Bypass Google Cloud Storage Config for just Media Files. Thanks! If … -
Cloud Identity Aware Proxy Cors Problem | React, Django
I deployed two different services on Google App engine. I want to use IAP for security. Service A is a Django Rest backend, second service is React Client. I have Cors issue i can't resolve. In React i use react-google-login to get Authorization Berer token to make request to my backend. When i try to make request from client to backend i have cors issue like on picture below: If i copy this request as curl and put it into postman and send it, i get 200 and expected response from backend. If i disable IAP, there is no cors problem, frontend app gets 200 from backend. My django settings accept all cors origins. What am I missing guys? I guess it must be something very simple. I tried different axios/fetch options like withCredentials, refererPolicy, headers etc. Also when i run chrome without web security app works fine. In django setting i have CORS_ORIGIN_ALLOW_ALL= True, CORS_ALLOW_ALL_ORIGINS = True ALLOWED_HOSTS = ['*'] i don't think this is backend problem. -
Link existing file in django ImageField
I'm trying to initialize an image file, which is already present on my system, using the shell. But this creates a copy of that file and store it at the specified location. What I want is that the file that is present that should be used and its copy should not be created. Here are my model and shell commands. My Model: class Manupulate(models.Model): image = models.ImageField(upload_to='media',blank=True) Shell Command: from django.core.files import File from {my app name}.models import Manupulation item = Manupulation() item.image.save("<filename>", File(open("<File path>", "rb"))) # "rb" mode for python 3 This will create a file in my media directory(copy of that image which I don't want). Please someone help me with this. -
''TypeError at /user expected string or bytes-like object'' on submitting the for in django?
When I submitting the form in django it is giving error ''TypeError at /user expected string or bytes-like object''. This is my staff models class staff(models.Model): id = models.AutoField name = models.CharField(max_length=250) role = models.CharField(max_length=250) salary = models.CharField(max_length=250) address = models.CharField(max_length=250) number = models.CharField(max_length=250) date = models.DateField() This is my user views. def user(request): if request.method == "POST" : name = request.POST['name'] role = request.POST['role'] salary = request.POST['salary'] address = request.POST['address'] number = request.POST['number'] date = DateTimeField() ins = staff(name=name, role=role, salary=salary, address=address, date=date, number=number) ins.save() staffs = staff.objects.all() return render(request, "salary/user.html", {'staff': staffs}) and this is form of template user.html <form class="forms-sample" action="/user" method="post"> {% csrf_token %} <div class="form-group row"> <label for="exampleInputUsername2" class="col-sm-3 col-form-label">Name:</label> <div class="col-sm-9"> <input type="text" name="name" id="name" class="form-control" id="exampleInputUsername2" placeholder="Username"> </div> </div> <div class="form-group row"> <label for="exampleInputUsername2" class="col-sm-3 col-form-label">Role:</label> <div class="col-sm-9"> <input type="text" name="role" id="role" class="form-control" id="exampleInputUsername2" placeholder="Role"> </div> </div> <div class="form-group row"> <label for="exampleInputUsername2" class="col-sm-3 col-form-label">Salary:</label> <div class="col-sm-9"> <input type="text" name="salary" id="salary" class="form-control" id="exampleInputUsername2" placeholder="Salary"> </div> </div> <div class="form-group row"> <label for="exampleInputUsername2" class="col-sm-3 col-form-label">Address:</label> <div class="col-sm-9"> <input type="text" name="address" id="address" class="form-control" id="exampleInputUsername2" placeholder="Address"> </div> </div> <div class="form-group row"> <label for="exampleInputUsername2" class="col-sm-3 col-form-label">Mobile no.:</label> <div class="col-sm-9"> <input type="text" name="number" id="number" class="form-control" id="exampleInputUsername2" placeholder="Mobile no."> </div> </div> … -
How to structure django + react project for deployment?
I'm building a django + django-rest-framework project with react as frontend. I've look around for the best way to structure and deploy it and it seems there are several aproaches. One is to build the react frontend as static files and have django serve them, another one is to have 2 diffeernt servers and let both projects comunicate over http. Which is the better option? What are the pros and cons of each aproach? It seems the latter one would be more expensive since we have to pay for both servers. Notes: The project is realatively small but can end up evolving into a larger one. We are using a MySQL database We want the option to use the django admin webpage -
Django ajax return a html page
i am trying to decrypt encrypted text and return the plain text through ajax call, instead of getting the message response i get an html page back as response. i have tried returning the response as json but still getting the same html response. ''' function loadMessage() { fetch("{% url 'chat:history' chatgroup.id %}") .then( response => response.json() ) .then( data => { for (let msg of data) { var message=msg.message; $.ajax({ type: 'GET', url: '', data: { message: message}, success: function(response){ broadcastMessage(response.message, msg.username, msg.date_created) } }) } }) } ''' view.py ''' def get(request): message = request.GET.get('message') key = b'\xa8|Bc\xf8\xba\xac\xca\xdc/5U0\xe3\xd6f' cipher = AES.new(key, AES.MODE_CTR) nounce = b64encode(cipher.nonce).decode('utf-8') if request.is_ajax(): nounce_ = self.nounce msg_ = self.message key = self.key nounce = b64decode(nounce_) ct = b64decode(msg_) cipher = AES.new(key, AES.MODE_CTR, nounce=nounce) msg_ = cipher.decrypt(ct) mwssage = msg_.decode() return JsonResponse({'message': message}) return render(request, 'chat/room.html') ''' -
How to display two separate lists of two different models declared in ListView in one HTML template in Django?
I have coded a ListView for search engine. I wanted to extract data from fields of two different models. First, I declared separate lists for each model. Then I combined them into one list as shown below. view.py class SearchView(ListView): template_name = 'articles/search_view.html' def get_queryset(self): query = self.request.GET.get('q') object_list = Article.objects.filter(Q(title__icontains=query) | Q(description__icontains=query)| Q(body__icontains=query) | Q(stocks_etfs_or_bonds__ticker__icontains=query) | Q(stocks_etfs_or_bonds__description__icontains=query) | Q(stocks_etfs_or_bonds__name__icontains=query) | Q(tags__name__icontains=query)) securities_list = StockETFBond.objects.filter(Q(name__icontains=query)) search_result = list(chain(object_list, securities_list)) return search_result In this case, the template will display one list of two models. search_view.html template now {% for object in object_list %} {{ object }} {% endfor %} But I would like to be able to display two separate lists of two different models in the template as shown below. search_view.html {% for object in object_list %} {{ object }} {% endfor %} {% for object in securities_list %} {{ object }} {% endfor %} How can I do it? -
How to accommodate simple serializer into Model Serializer Or combine 2 separate apps (Model Serializer) in Django rest API View
I am using Django and Django rest framework (latest version) for my Department - Employee rest API. Created 2 apps in my project DepartmentApp - which has Model : Department (Id, Department name , Location) , Department --> ModelSerializer and finally DepartmentApi using Class API (views.py) EmployeeApp - which has Model : Employee (Id, Employee name , Job title, Salary , Department ID) , Employee --> ModelSerializer and finally EmployeeApi using Class API (views.py) Now under EmployeeApp --> views.py , I am calling DepartmentApi under def get method .The purpose it to get department name and location for a give employee object.departmentID and use those attributes as part of employeeSerializer response.. I am not sure how to achieve this. below code snippet from views.py from EmpployeeApp def get(self, request, EmployeeId = None): if EmployeeId: employee=Employees.objects.get(EmployeeId=EmployeeId) print (employee.Department) # This prints DepartmentID from employee Model e_response = requests.get('http://127.0.0.1:8000/department/1') # calling DepartmentAPI deptData = e_response.json() print (f"{deptData['DepartmentName']} and {deptData['Location']}") employees_serializer = EmployeeDeptSerializer(employee) return Response(employees_serializer.data) Above code will only contain Employee object . But my ask is to add Department name and Location in my Response while calling EmployeeApi(for a given Employee ID or for all objects). Please help me out as I … -
ModuleNotFoundError at /auth/users/me/ No module named 'accounts'
I am using djoser and django-rest-framework JWT for user authentication . According to doc.for djaoser . I have /user/ end point for creating a user and /user/me/ for getting details. The first endponts works fine but in the second /user/me/ , it give me the error ModuleNotFoundError at /auth/users/me/ No module named 'accounts' I don't know where the problem lies. I am testing it on postman. here is my settings.py: """ Django settings for backend project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from django.conf import settings from datetime import timedelta from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-jyhhr)v0kyrb+^ifdlio=p3mo&l=$(^an7xb&fow--z^rxd7^r' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework_simplejwt', 'rest_framework_simplejwt.token_blacklist', 'djoser', 'base.apps.BaseConfig', 'corsheaders', 'social_django' ] MIDDLEWARE = [ 'social_django.middleware.SocialAuthExceptionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', … -
I was created method in Django media Folder to add watermark to images , but when i import the method to views .py it shows
in myApp->views.py from ..media.main import addwatermark ImportError: attempted relative import beyond top-level package -
Django Rest Framework Custom error format
Hi I have the following dict to be serialised { "field_name":"myrole", "description":"it has access", "status":"active", "role":"admin", "modules":[ { "module_id":"newid", "create":true, "read":true, "update":true, "delete":true } ] } Serializer I'm having now is class ModulerSerializer(serializers.Serializer): module_id = serializers.BooleanField(required=True, allow_null=True) delete = serializers.BooleanField(required=True) read = serializers.IntegerField(required=True) create = serializers.BooleanField(required=True) update = serializers.BooleanField(required=True) class RoleValidateSerializer(serializers.Serializer): field_name = serializers.BooleanField(required=True) description = serializers.CharField(required=True, max_length=128) role = serializers.CharField(required=True, max_length=128) status = serializers.CharField(required=True, max_length=128) modules = serializers.ListField(child=ModulerSerializer()) it is producing the error message like below {'field_name': [ErrorDetail(string='Must be a valid boolean.', code='invalid')], 'modules': { 0: {'module_id': [ErrorDetail(string='Must be a valid boolean.', code='invalid')], 'read': [ErrorDetail(string='A valid integer is required.', code='invalid')]}}} What I'm expecting is to append all error message values in to a single array like below or extracting error message from all nested child object [field_name Must be a valid boolean,module_id Must be a valid boolean, read A valid integer is required. ] -
Django doesn't show ValidationError in my web-site
guys, I am beginner at Django. I watch lessons on youtube and get different results. I use Django==2.0.7 and Python==3.6.5. I try to get error on my page, if I write not correct name of title, but I don't get it. Look at func - **def clean_title(self, *args, kwargs), I hope, you understand, what I mean. There I have "raise forms.ValidationError("Error")", but it doesn't work anymore. forms.py from django import forms from .models import Product class ProductForm(forms.ModelForm): title = forms.CharField(label='', widget=forms.TextInput(attrs={"placeholder": "title"})) Description = forms.CharField( required=False, widget=forms.Textarea( attrs={ "placeholder": "Your description", "class": "new-class-name two", "id": "new-class-name two", "rows": 20, 'cols':120 } ) ) Price = forms.DecimalField(initial=199.99) class Meta: model = Product fields = [ 'title', 'Description', 'Price' ] def clean_title(self, *args, **kwargs): title = self.cleaned_data.get('title') if "Ruslan" in title: return title else: raise forms.ValidationError("Error") In forms.py I created class ProductForm and declared the fields. In my page I see it. Also I defined clean_title. I wanted to get error if I filled in wrong name of title. views.py from django.shortcuts import render from .models import Product from .forms import ProductForm as CreateForm, PureDjangoForm def create_form(request): form = CreateForm(request.POST or None) if form.is_valid(): form.save() form = CreateForm() context = { 'form': … -
Django S3bucket uploaded images visible only when i upload but after certain time it is not visible
When i upload an image with django admin, i can see the image for a few minutes, but after few minutes, i cant see the image anymore, it show me error But i can that image another way and when i remove the url parameter of image, the the image always visable. Like when image urls look like this https://example.s3.amazonaws.com/media/images/2021/08/27/0A96395C-EB5B-4DC4-B0F7-43C322A4E6CC.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIA4KGTUZ6KPWNI3KGE%2F20210828%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20210828T164251Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=805bee29302409a99d27fe26c237b664f5b92a5cd9d4341cc1c990d5ba64 It works only for few minutes, then it fires me error <Message>Error parsing the X-Amz-Credential parameter; the region 'us-east-1' is wrong; expecting 'us-east-2'</Message> and when i remove the parameter and make it look like this. https://example.s3.amazonaws.com/media/images/2021/08/27/0A96395C-EB5B-4DC4-B0F7-43C322A4E6CC.jpg It works very well, what is the reaons? This is my django settings AWS_S3_CUSTOM_DOMAIN = ' AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"} AWS_DEFAULT_ACL = os.getenv("AWS_DEFAULT_ACL", "public-read") AWS_AUTO_CREATE_BUCKET = os.getenv("AWS_AUTO_CREATE_BUCKET", True) AWS_S3_SIGNATURE_VERSION = 's3v4' Can anyone tell me what is the issue? -
Sending a List with Dictionary type data
I am working on a quiz app. I have Quiz, Question, Answer models. I save the Quizzes made in the 'TakingQuiz' model, and the answers are in the 'TakingQuizAnswer' model. While talking to my friend, he mentioned that what I have to do is as follows: "When we send an Update request to the TakingQuiz API from Frontend, you need to send responses like answers : [{answer1object}, {answer2object}] and register them on the Backend." How can I get and save data like this in the Serializer of the TakingQuiz model? I have no idea how to send data as a list in the request. Related models class Quiz(AbstractQuizBaseModel): ENABLED_CHOICES = ( (True, _("Active")), (False, _("Not Active")), ) book = models.ForeignKey("book.Book", on_delete= models.CASCADE, related_name="book_quiz") title = models.CharField(max_length=150) enabled = models.BooleanField(choices=ENABLED_CHOICES, default=False) class Question(AbstractQuizBaseModel): quiz = models.ForeignKey("quiz.Quiz", on_delete=models.DO_NOTHING, related_name="question_quiz") question = models.CharField(max_length=500) topic = models.CharField(max_length=500) class Answer(AbstractQuizBaseModel): IS_CORRECT_CHOICES = ( (True, _("Correct")), (False, _("Wrong")) ) question = models.ForeignKey("quiz.Question", on_delete=models.CASCADE, related_name = "question_answer") answer = models.CharField(max_length=500) is_correct = models.BooleanField(choices=IS_CORRECT_CHOICES, default=False) class TakingQuiz(AbstractQuizBaseModel): quiz = models.ForeignKey("quiz.Quiz", on_delete=models.DO_NOTHING, related_name="quiz_taking_quiz") child = models.ForeignKey("account.ChildProfile", on_delete=models.CASCADE, related_name = "child_taking_quiz") title = models.CharField(max_length=150, editable=False, default="-") total_point = models.PositiveIntegerField(default=0, editable=False) class TakingQuizAnswer(AbstractQuizBaseModel): taking_quiz = models.ForeignKey("quiz.TakingQuiz", on_delete=models.CASCADE, related_name="taking_quizes") question = models.ForeignKey("quiz.Question", … -
Can I host Django Web Application which uses Wand API in its code?
I have made small project which uses Wand API in its code for some parts of project. Wand uses Imagemagick , those it needs to be installed in Computer. I have already installed it . Now, I want to Host my Web Application. is it possible to host this type of Web Application ?if Yes, then how ? If you Answer this it will help me a lot . Thankyou. -
why my django-simple captcha form is not showin up django
I am tryin to use captcha form to authenticate a real person but my form is not showing in template this is my views.py def codhandler(request): if request.method == "POST": form = CaptchaForm(request.POST) if form.is_valid(): form.save() return redirect('orders:successcod') else: form = CaptchaForm() return render(request, 'cashondeliversummary.html', {'form': form}) my html <form action="{% url 'orders:codhandler' %}" method='POST'> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-outline-primary" style="border:2px solid #025;">Place Order</button> <button class='js-captcha-refresh'></button> </form> i did install django-simple-captcha in my virtualenv my forms from django import forms from captcha.fields import CaptchaField class CaptchaForm(forms.Form): captcha = CaptchaField() any idea what i am doing wrong here -
django static files when hosting in heroku
I have excel files in my static folder that I read from to get some data but the files arent there when I deploy my project these are my settings for configuring static files STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_DIRS = [ BASE_DIR / 'static' ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' this is how I call them in my views from django.conf import settings from django.templatetags.static import static from django.contrib.staticfiles.storage import staticfiles_storage from django.contrib.staticfiles.finders import find def get_static(path): if settings.DEBUG: return find(path) else: return static(path) def sport_news(request): path = 'excel\sport_update.xlsx' excel_data = excel(get_static(path)) return render(request, 'news/news.html', {"excel_data":excel_data, 'type':'Sport News'}) -
Upgrading django from 3.0.4 to 3.2.6 results in missing content_type objects while testing
I'm trying to migrate a project from Django 3.0.4 to 3.2.6. I'm running into the following issue while running my testsuite django.db.utils.IntegrityError: insert or update on table "auth_permission" violates foreign key constraint "auth_permission_content_type_id_2f476e4b_fk_django_co" DETAIL: Key (content_type_id)=(1) is not present in table "django_content_type". self = <QuerySet []>, defaults = {'name': 'Can export log entry (adminactions)'} kwargs = {'codename': 'adminactions_export_logentry', 'content_type': <ContentType: admin | log entry>} params = {'codename': 'adminactions_export_logentry', 'content_type': <ContentType: admin | log entry>, 'name': 'Can export log entry (adminactions)'} def get_or_create(self, defaults=None, **kwargs): """ Look up an object with the given kwargs, creating one if necessary. Return a tuple of (object, created), where created is a boolean specifying whether an object was created. """ # The get() needs to be targeted at the write database in order # to avoid potential transaction consistency problems. self._for_write = True try: > return self.get(**kwargs), False /usr/local/lib/python3.9/site-packages/django/db/models/query.py:581: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <QuerySet []>, args = () kwargs = {'codename': 'adminactions_export_logentry', 'content_type': <ContentType: admin | log … -
debug setting is ignored when I move my django project to docker compose
we have a Django application. Right now we run it using Ubuntu 18.04 on Vagrant. Everything works fine. Now we have decided to move to docker compose. We have set everything and all is great and running. The only problem is that we have a very weird bug with the debug value. So, we have DEBUG=True in our settings file. We pass that value to the configuration template to use come includes in html. To do that, we have the following settings: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. os.path.join(PROJECT_DIR, 'templates'), ], 'OPTIONS': { 'debug': DEBUG, 'loaders': [ # List of callables that know how to import templates from various sources. 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ], 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.request', 'leads.context_processors.leads', ] } }, ] As you can see, we declare the option debug with the value of DEBUG. I have set a breakpoint on both environments there, I can see DEBUG=True. Now comes the fun part, if I set a breakpoint on a django template, for instance, this one: {% if not debug %} <link rel="stylesheet" href="somlink" /> {% … -
Django. CSRF token missing or incorrect
I have just recently started learning Django. I have a problem with the password change page 403 Reason given for failure: CSRF token missing or incorrect. My users/urls.py urlpatterns = [ path( 'logout/', LogoutView.as_view(template_name='users/logged_out.html'), name='logout' ), path( 'login/', LoginView.as_view(template_name='users/login.html'), name='login' ), path( 'password_change/', PasswordChangeView.as_view(template_name='users/password_change_form.html'), name='password_change_form' ), path( 'password_change/done/', PasswordChangeDoneView.as_view(template_name='users/password_change_done.html'), name='password_change_done' ), ..., ] And My Form in Template starts <form method="post" {% if action_url %} action="{% url action_url %}" {% endif %} > {% csrf_token %} <input type="hidden" name="csrfmiddlewaretoken" value=""> With this form, I get the error 403 and "CSRF token missing or incorrect." Without this string everythink works <input type="hidden" name="csrfmiddlewaretoken" value=""> everythink works. 1)Could you please explain me why? And what is it? What is the best way to use csrf? 2) I also used to write like <form method="post" action="{% url 'users:password_change_form' %}"> But founded this example using action_url. What is action_url? What way is better? -
How do you do logic on Post request sent from react in django?
When making a website (django and react) with its own currency. How can one use the data from the post method from react to do some logic on it and then return back the user info? Example: User has 20 coins, tries to buy something for 15 coins If user has more than 15 coins: User coins = User coins - 15 Return user info Else: Return "user does not have sufficient funds" -
after add postgresql get programming error in django
I'm creating a blog app with django and also it works fine with django default database called dbsqllite so. I decided to add postgresql database for my blog application after adding postgresql database it gives me a error like this django.db.utils.ProgrammingError: relation "blog_category" does not exist LINE 1: ...log_category"."name", "blog_category"."name" FROM "blog_cate.. . by the way I have already tired so many things like python manage.py makemigrations python manage.py migrate python manage.py migrate --run-syncdb python manage.py migrate --fake python manage.py migrate {app name} zero but any of this can't solve. I coudn't find any answer for this anyway here is model if you need for any reference. models.py of category model from django.db import models from django.contrib.auth.models import User from django_summernote.fields import SummernoteTextField from django.urls import reverse from django.template.defaultfilters import slugify STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = SummernoteTextField(blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) image = models.ImageField(upload_to='images',null=True, blank=True) category = models.CharField(max_length=50, default='uncatagories') class Meta: ordering = ['-created_on'] # this is used to order blog posts using time def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) …