Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: FOREIGN KEY constraint failed
I have two models. What I tried doing was creating an instance of School and assigning a user to the created school at the time of creating a superuser. Below are the models. It returns an error part of which is shown below. Please someone help me out on what best to do. OR Is there any other way other than what I'm trying to do here that can help?? class School(models.Model): name = models.CharField(max_length=100,null=True,blank=True,unique=True) subscribed = models.BooleanField(default=True) invoice_date = models.DateField(null=True, blank=True) installed = models.BooleanField(default=False) def __str__(self): return str(self.name) def create_school(self): self.school.id = 1 self.school.name = "default" self.school.subscribed = True self.school.installed = False return self.school class CustomUser(AbstractUser): school = models.ForeignKey(School, on_delete=models.CASCADE, null=True, blank=True, default=1) is_librarian = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) phone = models.IntegerField(null=True,blank=True) def __str__(self): return self.username The error return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\FR GULIK\AppData\Roaming\Python\Python310\site-packages\django\db\backends\utils.py", line 75, in _execut e_with_wrappers return executor(sql, params, many, context) File "C:\Users\FR GULIK\AppData\Roaming\Python\Python310\site-packages\django\db\backends\utils.py", line 79, in _execut e with self.db.wrap_database_errors: File "C:\Users\FR GULIK\AppData\Roaming\Python\Python310\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\FR GULIK\AppData\Roaming\Python\Python310\site-packages\django\db\backends\utils.py", line 84, in _execut e return self.cursor.execute(sql, params) File "C:\Users\FR GULIK\AppData\Roaming\Python\Python310\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: FOREIGN KEY constraint failed -
request django token msg: 'set' object has no attribute 'items'
I'm trying to get a token from the Django authentication. But I'm getting following error: Exception type: <class 'AttributeError'> msg: 'set' object has no attribute 'items' My test code snippet looks like this: import os import requests import json from dotenv import load_dotenv load_dotenv() BASE_DEV_URL = "http://127.0.0.1:4000" def login(url=(BASE_DEV_URL + "/api/user/token")): headers = { 'accept: application/json', 'accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Content-Type:' 'application/x-www-form-urlencoded', } try: payload = {"email": os.getenv('TEST_USER_NAME'), "password": os.getenv('TEST_USER_PASSWORD')} print(payload) res = requests.post(url, data=json.dumps(payload), headers=headers) print(f'####### {type(res)}') except Exception as e: return f'Exception type: {type(e)} msg: {e}' return res response = login() print(response) However, when I test it with swagger with curl command it works fine curl looks like this curl -X 'POST' \ 'http://127.0.0.1:4000/api/user/token/' \ -H 'accept: application/json' \ -H 'Content-Type: application/x-www-form-urlencoded' \ -H 'X-CSRFTOKEN: T7wW385wMiYDERJU2yWvqGorrbKjtb9zhWqlAkAlE30QKgP7DoQMbc7MnQT3UAti' \ -d 'email=test%40example.com&password=123XVW174' Any idea how to make it work. I'm not sure, but it may because by serialized. I worked with request library a lot and never encountered such error. Will be grateful for any advice which could solve it. -
how to make primay or unique three field in django models?
I have the four models in my Django models.py ( User, Exam, Questions, Answers ) the Answer model has four fields ( user, exam, question, answer) after creating an exam and creating questions for that, the users come to take an exam I want to store the user's answers in the Answer model, therefore, I specify which user is taking which exam and answering which question, at the end I save the user's answers in the last field ( the 'answer' field in Answer modle ) but I want this user only once can answer this question in this exam, so I want to make these fields ( user, exam, question ) primary in the Answer model that my Answer model: class Answer(models.Model): exam = models.ForeignKey(Exam, on_delete=models.CASCADE, default=None) user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.CharField(max_length=8) I don't know how to do this action to primary three field actually, there is no matter whether the two or one fields of these three fields are similar, I just want to prevent storing records that user, exam, and question fields are already stored for example, I have this record in my database: user:1, exam:52, question:38, answer: "option_a" when I … -
Django model reference when using AbstractBaseUser model
I 'm following a tutorial of how to use AbstractBaseUser model in Django project. Now I would like to go one step further by creating other models for example address_book and product. When using defaulter user model, we put like this: class User(models.Model): .... class AddressBook(models.Model): .... class Product(models.Model): .... Now when I use like class MyUser(AbstractBaseUser): Which reference should I use in the AddressBook and Product class? (The user in the Address book is a foreign key from Class MyUser). class AddressBook(AbstractBaseUser) and class Product(AbstractBaseUser) or class AddressBook(models.Model) and class Product (models.model)? Thanks for your help in advance! -
How to do a search in Django correctly?
I'm quite new to Django. And I have a problem with the search implementation. I looked through quite a lot of material and tried many options, but nothing came out. I want to implement a search so that it searches for the product model. Can you help me with this problem? views.py from django.shortcuts import render from .filters import * from .models import index from .forms import * # Create your views here. def indexViews(request): search = request.GET['search'] indexAll = index.objects.all if search == None: posts = index.objects.filter(model__in=search) else: posts = index.objects.all() index_filter = IndexFilter(request.GET, queryset=all) context = { 'index_filters': index_filter, 'all': indexAll } return render(request, 'index.html', context) models.py from django.db import models # Create your models here. class index(models.Model): BRAND = [ ('apple', 'apple'), ('samsung', 'samsung'), ('huawei', 'huawei'), ] brand = models.CharField(max_length=20, choices=BRAND) model = models.CharField(max_length=50, default='None') price = models.FloatField(max_length=10, default=0.0) image = models.URLField() class Meta: verbose_name = 'Продукт' verbose_name_plural = 'Продукты' def __str__(self): return self.model urls.py from django.urls import path from .views import * urlpatterns = [ path('', indexViews, name='index') ] index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="get" action="{% url 'index' %}"> {{ index_filters.form }} <input type="search" placeholder="Поиск" … -
Google Cloud AppEngine and Django: how should I set the domain name for have it work?
I've deployed a Django project on Google Cloud standard AppEngine, My Domain Name is registered in Google Domains which confirms that it already points to my project when I try to customize my domains. On the Web, I've access my project under its project name: https://mooveup-9645.oa.r.appspot.com However when I try https://my-domain.fr the web site cannot be accessed. My Question is: Where should I add my domain name ? if APPENGINE_URL: # Ensure a scheme is present in the URL before it's processed. if not urlparse(APPENGINE_URL).scheme: APPENGINE_URL = f"https://{APPENGINE_URL}" ALLOWED_HOSTS = [urlparse(APPENGINE_URL).netloc, "www.my-domain.fr", "my-domain.fr"] Is this the appropriate solution in Django settings or is there another configuration step with GCP? -
having ImportError that i did not import
Please someone should help me out. I did not import ugettext_lazy from anywhere in my project am using django 4.2.1. i just install django-messages from then i cannot proceed with my project. this error keep showing an am stock in one place. I check all my import to see where the ugettext_lazy is comming from but i could not trace it. i even downgrade django 4 to django 3 but i was still having some import error in django 3. i upgrade it again to django 4. please help me out. thanks this is my views.py imports # from http.client import HTTPResponse # from django.contrib.auth import login from django.shortcuts import redirect, render from .forms import CustomUserCreationForm, PostForm, CommentForm, NovenaCommentForm from . models import About_us, My_blog, Like, Comment, Slider, Prayers, Description, Novena, NovenaComment from django.urls import reverse from django.http import HttpResponseRedirect from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from . like import new_likes, authmessage from django.contrib import messages from django.http import HttpResponse from django.urls import reverse_lazy from django.contrib.auth.models import User, auth from django.contrib.auth import authenticate # from django.contrib import messages from django.views.generic import ListView, DetailView, DeleteView from django.contrib.auth.decorators import login_required, user_passes_test, permission_required from authentications.message import infor this is admin imports from django.contrib … -
convert Queryset to array
Have been trying to work on this for some sometime maybe my mind is rusty so i am seeking another mind for help. below is a query set is get from the Database for equipment [0] that are used per month1. 0 01 1 () Name: 0, dtype: object 0 02 1 () Name: 1, dtype: object 0 03 1 () Name: 2, dtype: object 0 04 1 () Name: 3, dtype: object 0 05 1 ({'id': 1, 'qty': 1}, {'id': 2, 'qty': 2}) Name: 4, dtype: object 0 06 1 () Name: 5, dtype: object 0 07 1 () Name: 6, dtype: object 0 08 1 () Name: 7, dtype: object 0 09 1 ({'id': 2, 'qty': 1}) Name: 8, dtype: object 0 10 1 () Name: 9, dtype: object 0 11 1 ({'id': 1, 'qty': 1}) Name: 10, dtype: object 0 12 1 () Name: 11, dtype: object I would want to convert this Queryset to a PD dataframe to look like the below table where the table is filled with the qty coming from the query set with the equipment ID in each month: Dataframe required would appreciate your input! -
How to get a logged in user profile in context_processors.py Django?
I have a context_processors.py to display extra info at base.html. I need to get a request.user to get his profile and show all his user's posts in news.html. When I do profile = Profile.objects.filter(user=request.user.id) Django shows that no user matches to a given profile. How do I fix it ? context_processors.py from users.models import Profile def notification_to_base(request): counter = 0 profile = Profile.objects.filter().first() # I'm getting Admin_profile, but I need to get a logged in user profile subscribing = profile.subscribing.filter() # TestUser, TestUser_two for following in subscribing: posts = following.post_set.filter(is_checked=False) # post № 1, post № 2 for post in posts: counter += 1 return {'answers': answers, 'counter': counter} -
Join two models and group with SUM in Django but some fields are not display
I have two model name ProductDetails and InventorySummary. I want to join this two model and wants to group with product name and SUM product quantity. The quantity should be multiplication with product price. My models are given bellow: class ProductDetails(models.Model): id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=100, unique=True) purchase_price = models.DecimalField(max_digits=7, decimal_places=2) dealer_price = models.DecimalField(max_digits=7, decimal_places=2) retail_price = models.DecimalField(max_digits=7, decimal_places=2) remarks = models.CharField(max_length=255, blank=True) def __str__(self): return self.product_name class InventorySummary(models.Model): id = models.AutoField(primary_key=True) date = models.DateField(default=date.today) product_name = models.ForeignKey(ProductDetails, on_delete=models.CASCADE) quantity = models.IntegerField() def __str__(self): return str(self.product_name) My views are given bellow which are working good: def stockPrice(request): stock = ( InventorySummary.objects.annotate(total_amount=Sum(F("product_name__purchase_price") * F("quantity")))) return render(request, 'inventory_price.html', {'stock': stock}) But when I group then not working. Only total_amount working. product_name, purchase_price, and quantity not display def stockPrice(request): stock = ( InventorySummary.objects.values("product_name__product_name") .order_by("product_name__product_name") .annotate(total_amount=Sum(F("product_name__purchase_price") * F("quantity")))) return render(request, 'inventory_price.html', {'stock': stock}) -
DRF / POST view for two tables connected by foreign keys
How to write POST view for two tables that are mapped by foreignkey? here are my models.. class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE,null=True, blank=True, editable=False) title = models.CharField(max_length=255, null=False) description = models.TextField(null=True, blank=True) created_date = models.DateTimeField(auto_now=True) enable = models.BooleanField(default=True) class PostImages(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) images = models.ImageField(null=True, blank=True) serializer: class UserPostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['author','title','description'] I made view but it doesn't do anything with PostImages table.. I want it to create post with images.. @api_view(['POST']) @permission_classes([IsAuthenticated]) def PostUpload(request): data = request.data user = request.user if request.method == 'POST': serializer = UserPostSerializer(data=data, many=False) if serializer.is_valid(): serializer.save(author=user) return Response(serializer.data) return Response(serializer.errors) -
How to add new plugins like HtmlEmbed in django-ckeditor-5?
I am using django-ckeditor-5 https://github.com/hvlads/django-ckeditor-5 for my project. But I am not able to add new plugins like HtmlEmbed. Can anyone please help me how can we add new plugins in django-ckeditor-5? -
Create dropdown menu for login account
I would like to create a dropdown menu from the logged-in user account. currently, the top-right button in the navigation bar is either "Login" or "Logout" based on if user is logged in. I would hope to create a dropdown menu when user is logged in, which contains options such as account and logout. The desired examples look like below: The login dropdown menu can contain two options (Account and Logout). how to achieve this, without using boostrap external stylesheet? Current HTML <div class="nav"> <div class="login-container"> {% if user.is_authenticated %} <form class="navbar-form navbar-right" action="{% url 'logout' %}" method="get"> <span>Welcome, {{ user }}.&nbsp;&nbsp;</span> <button type="submit">logout</button> {% else %} <form class="navbar-form navbar-right" action="{% url 'login' %}" method="get"> <span>Welcome, {{ user }}.&nbsp;&nbsp;</span> <button type="submit">login</button> {% endif %} </form> </div> </div> -
Images 'static' crash on redeploying - django app to heroku
When redeploying django app with heroku, and refresh the [age to see the changes, all the images crashed, are you familiar with this situation ? -
Hi everyone, I'm new to python and Django I'm trying to run a cloned repository on github when I run the commands: python manage.py migrate
Traceback (most recent call last): File "/home/cand/Python_Project/Data Science Github/gitando/django-simples/manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/cand/Python_Project/Data Science Github/gitando/django-simples/manage.py", line 21, in main() File "/home/cand/Python_Project/Data Science Github/gitando/django-simples/manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
How to fix Django logger Permission denied in Docker container?
I'm trying to run my Django project on docker I'm using logger to write in a .txt file but I'm getting an error related to permissions Django can't write in AdminFileDebug.txt This is the settings.py code LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'adminsDebug': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'log/AdminFileDebug.txt', 'formatter': 'verbose' # 'filename': '/path/to/django/debug.log', }, }, 'loggers': { 'AdminsDebug': { 'handlers': ['adminsDebug', 'console'], 'level': 'DEBUG', 'propagate': True, }, }, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {asctime} {message}', 'style': '{', }, }, } This is the docker compose file for my configuration: version: '3.9' services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=test - POSTGRES_USER=postgres - POSTGRES_PASSWORD=test app: build: context: . command: sh -c "python manage.py runserver 0.0.0.0:8000" volumes: - .:/app ports: - 8000:8000 environment: - DJANGO_DEBUG=1 - POSTGRES_NAME=test - POSTGRES_USER=postgres - POSTGRES_PASSWORD=test depends_on: - db when i run docker compose up i get this error PermissionError: [Errno 13] Permission denied: '/app/log/AdminFileDebug.txt' Any solutions? -
Is there any Django code for detecting plagiarism of a text file [closed]
I am making a website for detecting the plagiarism of a text file with Django. I need some codes that can compare two text file, and can detect that which part of the file1 is copied in file2 -
Pass data between views and response data using second view -> Django/DRF
I'm trying to implement APIView where I can pass data (category and number of flashcards that I want to see in response) from below view: def start_view(request): """ View where user is choosing the category he/she wants to learn flashcards from and number of flashcards. After submit the form view will upload chosen number of flashcards from chosen category. """ if request.method == "POST": form = LearningForm(request.POST) if form.is_valid(): category_to_learn = form.cleaned_data["category"] number_of_flashcards_to_learn = form.cleaned_data["number_of_flashcards"] queryset = Flashcard.objects.filter( # type: ignore category=category_to_learn )[:number_of_flashcards_to_learn] return render(request, "flashcard_challenge.html", {"queryset": queryset}) else: form = LearningForm() return render(request, "start_page.html", {"form": form}) In above view I have list in response (I want json using other endpoint.) I got stuck few days ago and I don't know what to do.. All I want is: Choose category (from those I have in a db) and write number of flashcards in start_view and than I want to be redirect to view where flashcards (from chosen category) will be displayed in json format. I'd be thankful for any advice. -
Don't understand how to logout of FusionAuth from Django Application
I am writing a Django app that uses a 3rd-Party Authentication Service implemented with FusionAuth. I can successfully register and login (using the authorization code flow). However, logging out is not working. I can logout from the local Django app, but when I try to login after that FusionAuth recognizes that my access_token is still valid and just goes directly to the redirect page (the page you usually goto after successfully logging into FusionAuth). Clearly I don't understand something about FusionAuth. I have tried both the python client and the restful API and I don't really understand what it does. According to the documentation it "...is intended to be used to remove the refresh token and access token cookies if they exist on the client and revoke the refresh token". Why then is the access_token still valid? -
CHECK IF A USER HAS ALREADY ADDED AN ELEMENT IN THE DATABASE
I need help💔😥 !!! please someone help me. I designed a site like a directory, where school administrators can log in and add their schools, it works perfectly. but in the life in the picture, the user creates an account and he is directed to the login page, if he logs in, he is directed to the add school page directly, after adding he is direct towards its no reception. All works perfectly. but my problem is that I want to check if the user has already added a school, he skips the step of adding a school, and that he goes directly to his home page. PLEASE I NEED HELP, I HAVE TO DELIVER THIS TOMORROW AND I AM DESPERATE! PLEASSSSSSSE😪 URLS from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from . import views, visit_views, Hot_views, user_login urlpatterns = [ path('admin/', admin.site.urls), path('base', views.BASE, name='base'), path('', views.HOME, name='home'), path('ecole', views.ECOLE_SECONDAIRE, name='ecole_secondaire'), path('contact', views.CONTACT_US, name='contact_us'), path('about', views.ABOUT_US, name='about_us'), path('View-school/<str:id>', views.VIEW_SCHOOL, name='view_school'), path('accounts/register', user_login.REGISTER, name='register'), path('accounts/', include('django.contrib.auth.urls')), path('doLogin', user_login.DOLOGIN, name='doLogin'), path('doLogout', user_login.doLogout, name='logout'), path('Hothome', Hot_views.HOME, name='hothome'), path('Add-school', Hot_views.ADD_SCHOOL, name='add_school'), path('View-school', Hot_views.VIEW_SCHOOL, name='hote_view_school'), path('Update-school', Hot_views.UPDATE_SCHOOL, name='update_school'), path('Delete-school', Hot_views.DELETE_SCHOOL, name='delete_school'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) … -
Django: How to update choice field in DJango?
I have a model with a tuple, that i use in a fields for choices, it looks like this TRANSFER_STATUS = ( ("Failed", "Failed"), ("completed", "Completed"), ("pending", "Pending"), ("processing", "processing"), ("none", "None"), ) class ModelName: status = models.CharField(choices=TRANSFER_STATUS, max_length=100, default="none") when a condition is met, i want to change the default which is processing to completed, i have tried doing it from views.py but it does not seem to work. @login_required def TransferProcess(request, account_number, transaction_id): transfer_transaction = Transaction.objects.get(transaction_id=transaction_id) if request.method == "POST": pin_number = request.POST.get("pin-number") if pin_number == request.user.account.pin_number: transfer_transaction.status = 'completed' transfer_transaction.transaction_type = 'transfer' transfer_transaction.save() # sender_account = int(sender_account.account_balance) - int(transfer_transaction.amount) sender_account.account_balance -= transfer_transaction.amount sender_account.save() account.account_balance += transfer_transaction.amount account.save() messages.success(request, "Transfer Successful.") return redirect("core:transfer-successful", account.account_number, transfer_transaction.transaction_id) else: messages.warning(request, "Pin not correct, try again") return redirect("core:transfer-confirmation", account.account_number ,transaction_id) -
How to put object datefield in html input value
I have a class "client" with an attribute datefield called "birth_date". I want to give the possibility for update this field. How can i put the default value in the form, in the input type date? Because the format in "client.birth_date" is different. If i try with, for example: The input value is setting true, but the format is different from the one i get -
Django template error in basic html file?
I have coded the navbar in basic.html which is extended with all other pages. In the navbar, I added a social link button and their links were added by admin from the admin panel and I fetched in views function and render it to basic.html. But problem is that these social buttons not working on all other pages that are extended with basic.html . one solution is that if I get these links from database in all functions then it works. But In this case code repeats and repeats. I have around 30 functions, so I need a common solution. -
When you insert a text value that contains quotation marks or an apostrophe, it is truncated
When pasting a text value containing quotes or an apostrophe using jQuery into a value field, it is truncated at that character. I know about single and double quotes. The text can be anything. It is saved in the database normally, everything is in order in the variable, but when outputting to html - confusion. How to avoid this error? One of the options: $('<div>', { class: 'menu-block', html: `<div class="menu-button"> <button onclick="return itemField(this)" type="button" class="btn btn-warning"> <i class="bi bi-pencil"></i> </button> <button onclick="return deleteField(this)" type="button" class="btn btn-danger""> <i class="bi bi-trash"></i> </button> </div> <div class="row"> <div class="col"> <input type="text" class="form-control" data="label" value='${label}' disabled /> </div> <div class="col"> <input type="text" class="form-control" data="datal" value='${datal}' disabled /> </div> </div>` }).appendTo('#div-extra'); -
Django change secret-key in settings from previous developer
I want to change my SECRET_KEY for deploying in production, and I found this tool for using - https://pypi.org/project/django-generate-secret-key/ but, it seams that this tool is not working, because it's not changing the existing key... what I'm doing wrong? P.S tried with --replace flag, but seams no result... Can anyone help me with it?