Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to parse and show info in template with requests_cache
I have several general questions about requests_cache and how is it working and how can i use that How can i get json from 3rd party and parse that in my template? I have some information from api that i dont need to write in model in db and i want just to parse that but need just to show that in parsed info in template views.py def customer_view(request): session = requests_cache.CachedSession('project_budget_cache') session.get('http://someurl.com/api') return render(request, 'customer/customer_home.html', {'context': session}) I can get request with that but i actually dont know how to show my json in template {{ context }} cant help there Another question: How can i synch request every 5 min? Last question: How can i avoide problems with 3rd party api? Like if api is closed or they have problems and i cant get json how can i use previous request that was working? I mean if they have problems and cant accept requests rn i need to use request that was made 5 mins ago -
Change the current structure of Django rest api to a structure that has 2 parent element
i will want create a form app that which users enter their information i want change my api structure. my api structure look like this { "questions": [ { "id": 1, "answers": [ { "id": 2, "answer_title": "I study", "answer_weight": "1.0000", "created_at": "2023-03-16T11:22:48.871716Z", "updated_at": "2023-03-16T12:11:27.525798Z", "answer_type": "2A" }, { "id": 3, "answer_title": "I am working", "answer_weight": "2.0000", "created_at": "2023-03-16T11:22:48.872752Z", "updated_at": "2023-03-16T12:11:27.526798Z", "answer_type": "2A" }, { "id": 4, "answer_title": "Unemployed", "answer_weight": "1.0000", "created_at": "2023-03-16T11:22:48.873752Z", "updated_at": "2023-03-16T12:11:27.527832Z", "answer_type": "2B" } ], "question_title": "Your current occupation:" }, { "id": 2, "answers": [ { "id": 5, "answer_title": "middle", "answer_weight": "1.0000", "created_at": "2023-03-16T12:12:55.097428Z", "updated_at": "2023-03-16T12:12:55.097428Z", "answer_type": null }, { "id": 6, "answer_title": "high school", "answer_weight": "2.0000", "created_at": "2023-03-16T12:12:55.098198Z", "updated_at": "2023-03-16T12:12:55.098198Z", "answer_type": null } ], "question_title": "what is your education?" } ] } but I want to change this structure look like this [ "questions": [ { "id": 1, "answers": { "2A":[ { "id": 2, "answer_title": "I study", "answer_weight": "1.0000", "created_at": "2023-03-16T11:22:48.871716Z", "updated_at": "2023-03-16T12:11:27.525798Z", }, { "id": 3, "answer_title": "I am working", "answer_weight": "2.0000", "created_at": "2023-03-16T11:22:48.872752Z", "updated_at": "2023-03-16T12:11:27.526798Z", } ], "2B":[ { "id": 4, "answer_title": "Unemployed", "answer_weight": "1.0000", "created_at": "2023-03-16T11:22:48.873752Z", "updated_at": "2023-03-16T12:11:27.527832Z", } ] }, "question_title": "Your current occupation:" }, { "id": 2, "answers": [ { … -
The products are not deleting from the shopping cart after ordering in python-django
I am trying to make an e-commerce website. There is 1 problem which has been very hard to fix. The problem: After ordering, products are supposed to be deleted from the shopping cart. But it is not working. There are no syntaxis errors but there is still products remaining after ordering. Here is the part my views.py for it: if not request.user.is_authenticated: session = request.session cart = session.get(settings.CART_SESSION_ID) if cart is not None: del session[settings.CART_SESSION_ID] else: customer = request.user.customer order, created = Order.objects.get_or_create( customer=customer, complete=False) order_products = OrderProduct.objects.filter(order=order) if order_products: order_product = order_products[0] else: order_product = OrderProduct.objects.create(order=order) order.save() messages.success(request, 'Заказ успешно оформлен. Проверьте свою электронную почту!!!') session = request.session cart = session.get(settings.CART_SESSION_ID) if cart is not None: del session[settings.CART_SESSION_ID] session.modified = True return redirect('product_list') I really hope someone can help me, please. -
How to extend authentication for a C#/.NET web app to Django project?
I have a C#/.NET web site with SAML authentication implemented on it. In a page of this web site, I put a link for another web site, made in Python-Django, and I need to implement the same authentication system. So, it's like I want to extend the same authentication to Django website (same IAM). How can I implement it for the Python-Django web site? -
How to optimize SQL in tree-like comment structure django?
I have posts with tree comments in it. Comments have likes as well. I've managed to optimize SQL queries that usual comments, related to the post itself, don't create new queries, but answers to the other comments still create 3-4 new requests to the data base. Can I somehow reduce number of queries? I've been using prefetch_related for this purpose. My Post model: class Post(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE ) title = models.CharField( max_length=200, null=True, blank=True ) header_image = models.ImageField( null=True, blank=True, upload_to="posts/headers", help_text='Post will start from this image' ) body = CharField( max_length=500 ) post_date = models.DateTimeField( auto_now_add=True ) likes = models.ManyToManyField( User, through='UserPostRel', related_name='likes', help_text='Likes connected to the post', ) def total_likes(self): return self.likes.count() Comment model class Comment(models.Model): user = models.ForeignKey(User, related_name='comment_author', on_delete=models.CASCADE) post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) body = models.TextField(max_length=255) comment_to_reply = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name='replies') likes = models.ManyToManyField(User, through='CommentLikeRelation', related_name='comment_likes') created_at = models.DateTimeField(auto_now_add=True) def replies_count(self): return self.replies.count() def total_likes(self): return self.likes.count() def is_a_leaf(self): return self.replies.exists() def is_a_reply(self): return self.comment_to_reply is not None class CommentLikeRelation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.ForeignKey(Comment, on_delete=models.CASCADE) View that process data def get(self, request, *args, **kwargs): current_user = request.user user_profile = User.objects.get(slug=kwargs.get('slug')) is_author = True if current_user == user_profile … -
how to use values_list in Django to show one column from the table
I have three models user, usecase, and user_assign I have list of users in the database assigned to specific usecase in the user_assign table. I'm trying to show the user names not the emails assigned to specific usecase. Result I'm trying to get: SELECT user_email FROM usecase_assign WHERE usecase_id LIKE 'NN245'; my models: class UsecaseAssign(models.Model): usecase_assign_date = models.DateTimeField(primary_key=True) usecase = models.ForeignKey(Usecase, models.DO_NOTHING) user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email') class Usecase(models.Model): usecase_id = models.CharField(primary_key=True, max_length=20) usecase_name = models.CharField(max_length=256) user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email') usecase_type = models.ForeignKey('UsecaseType', models.DO_NOTHING) kpi = models.ForeignKey(Kpi, models.DO_NOTHING) class User(models.Model): user_email = models.CharField(primary_key=True, max_length=100) user_role_id = models.CharField(max_length=20) user_password = models.CharField(max_length=20) user_name = models.CharField(max_length=100) my views.py: @user_login_required def view_usecase_details(request,ucid): usecase_details = Usecase.objects.filter(usecase_id=ucid).all() if request.method == "GET": usecase_assigned = UsecaseAssign.objects.values_list('user_email').filter(usecase_id=ucid).values() context = {'usecase_details': usecase_details, "users": User.objects.all(), 'usecase_assigned':usecase_assigned} return render(request, 'UsecaseDetails.html', context) my template: <div class="card card-body shadow-sm mb-4 mb-lg-0"> <form action="/usecase-details/{{usecase_details.usecase_id}}" method="POST"> {% csrf_token %} <div class="form-row mb-4"> <div class="col-lg-8 mr-f"> <label class="h6" for="user_email">Assign Users:</label> <select name="user" class="custom-select my-1 mr-sm-2" id="user"> <option value="0" selected>Select</option> {% for user in users %} <option value="{{ user.user_email }}">{{ user.user_name }}</option> {% endfor %} </select> </div> </div> <input type="submit" class="btn btn-primary" value="Submit Changes"> </form> <ul class="list-group list-group-flush"> <li class="list-group-item d-flex align-items-center justify-content-between px-0 border-bottom"> <div> <p … -
Restrict access to multiple admin sites per user/group in Django
When using multiple admin sites in Django i want to seperate the depth / complexity of information availabe in different sites. The generally works but a user can still login to the other sites and see more than he is supposed to because he has view permission to a model. Imanine having morve levels between staff and superuser like "is_staff_trainee", "is_staff_junior", "is_staff_senior" and "is_staff_bigboss". They all have their own admin sites. On some models the admin is the same for all of them, so i register the same ModelAdmin to all of the sites. But on some model, let's say "Drinks", they all get their own DrinkAdminTrainee, DrinkAdminJunior, DrinkAdminBigBoss, you get it. A Trainee has most of the fields read only, a Junior can edit most of them on the edit page, a senior gets additional information about e.g. the price calculation an can choose from more expensive ingredients to create his drinks and the Big Boss can also see all the old (long deactivated) Drinks from the Past. That works perfectly. But any Trainee can still login to the Big Boss Admin site if he kows the URL and also use it because he still "is_staff" and has view … -
Lock editing page in django
i have a single page application and a django server with the django rest framework. As an example, I have a resource called House. User 1 is on the /houses/5/edit page and is currently editing the house with ID 5. Now I want to block editing from the house with ID 5 for other users. Only one user should be able to access the editing page of a particular house at a time. All other users should see on the detail page of the house with ID 5 (/houses/5/) that the house is already being edited. Only when user 1 leaves the page /houses/5/edit, another user should be able to edit the house. I want to have this blocking mechanism because otherwise changes to the house could be overwritten by another user. So the mechanism should be similar to the blocking mechanism in Wordpress CMS for blocking a page or post. How can I implement this? I already use django-channels for push notifications. My idea was to use websockets for blocking. Also, I saw that django-redis offers a blocking mechanism. However, I still have no idea how to implement my requirements with it and whether these technologies are the best … -
Understanding and setting the order of Django migrations
I have models that look like: class FubarCategory(models.Model): class name = models.CharField(max_length=32) class FubarScenarioType(models.Model): class name = models.CharField(max_length=32) class FubarProduct(models.Model) category = models.ForeignKey( FubarCategory, on_delete=models.DO_NOTHING, related_name="products" ) scenario = models.ForeignKey( FubarScenarioType, on_delete=models.DO_NOTHING, related_name="products" ) class FubarTransaction(models.Model): product = models.ForeignKey( FubarProduct, on_delete=models.DO_NOTHING, related_name="transactions" ) I expect a brand new migration to look like: Migrations for 'fubar': apps/fubar/migrations/0001_initial.py - Create model FubarCategory - Create model FubarScenarioType - Create model FubarProduct - Create model FubarTransaction Instead, I see this: Migrations for 'fubar': apps/fubar/migrations/0001_initial.py - Create model FubarCategory - Create model FubarProduct - Create model FubarScenarioType - Add field scenario_type to Fubarproduct - Create model FubarTransaction Why is FubarScenarioType being created after FubarProduct instead of before? -
How to authenticate selenium before running `pytest`?
I'm using pytest-django with selenium for testing features. Some features require being logged in. Here's how I create a test user: import sqlite3 import uuid import pytest from django.conf import settings from django.contrib.auth.models import User from django.core.management import call_command from selenium.webdriver import Chrome, ChromeOptions @pytest.fixture(scope='session', autouse=True) def browser(): options = ChromeOptions() options.add_argument('--no-sandbox') options.add_argument('headless') chrome = Chrome(options=options) yield chrome chrome.close() @pytest.fixture(scope='session') def test_user(): return {'username': uuid.uuid4().hex[:10], 'password': uuid.uuid4().hex} @pytest.fixture(scope='session') def django_db_setup(django_db_blocker, test_user): db_path = settings.BASE_DIR / 'test-db.sqlite3' sqlite3.connect(db_name := db_path.as_posix()) settings.DATABASES['default']['NAME'] = db_name with django_db_blocker.unblock(): call_command('migrate', '--noinput') User.objects.create_user( username=test_user['username'], password=test_user['password'], email=f'{test_user["username"]}@test', ) Now that a test user is created, I need to use it with selenium before tests that require logging in. A typical test class looks like: class TestSomeUrl: def test_feature1(browser): ... def test_feature2(browser): ... But I need to login first. What would be the proper way to do so? I tried first to login inside the browser fixture by doing: @pytest.fixture(scope='session', autouse=True) def browser(live_server, test_user): options = ChromeOptions() options.add_argument('--no-sandbox') options.add_argument('headless') chrome = Chrome(options=options) chrome.get(f'{live_server}/login') browser_login(chrome, test_user) yield chrome chrome.close() But I get a Bad Request (400) because live_server seemingly has no started yet, otherwise it should get f'{live_server}/login' without issues. Answers here are outdated and do not work anymore. … -
How can I pass an attribute value inside a StructBlock in Wagtail 4.1?
I am trying to create a StructBlock in Wagtail that contains a ChoiceBlock. The choices for this ChoiceBlock should be generated from an import that takes an id from a previous ModelChooserBlock value. However I am doing something wrong as I am unable to read the value from the ModelChooserBlock to be able to get it's id. Is there a way to get the value.id of the ModelChooserBlock and pass it back to the StructBlock to generate the choices? See my code: class StartListBlock(blocks.StructBlock): """ Display the start list for a specific race """ class Meta: template = 'blocks/startlist_block.html' icon = 'site' label = _('race_startlist') title = blocks.CharBlock( required=False, label=_("title"), ) # model id will be passed to import race choices race_day = ModelChooserBlock( target_model=RaceDay, label=_("race day"), ) race = blocks.ChoiceBlock( required=False, label=_('race'), choices=[], # choices will be generated outside the block ) I tried to create a new ChoiceBlock inside get_context and pass it back to the StructBlock with the new choices, but for the choices to show I needed to refresh the page and the selected race value did not get pass to the context. Please advise if this is not the correct approach and how it might … -
Chartjs data not loading when working with Django templates
I created a base template for my project and then tried to load data for a page that is using this template. The html {% block content %} works just fine but the {% block script %} doesnt seem to load. When each page had its own code this problem didn't occur; but now since I'm trying to inherit from a base template even console.log('test') doesn't seem to work. Base.html <!DOCTYPE html> <html> <body> <main> {% block content %} {% endblock content %} </main> <script> {% block footer_scripts %} {% endblock footer_scripts %} </script> </body> </html> page.html <!DOCTYPE html> <html> <body> <main> {% block content %} <div class="relative p-4 h-72"> <canvas id="doughnutChart"></canvas> </div> {% endblock content %} </main> <script> {% block footer_scripts %} <script> const SubscriptionData=[] {% for i in SubscriptionStatus %} SubscriptionData.push({{ i }}); {% endfor %} const doughnutChart = new Chart(document.getElementById('doughnutChart'), { type: 'doughnut', data: { labels: ['Subscribed','Renew', 'Unsubscribed'], datasets: [ { data: SubscriptionData, backgroundColor: [colors.primary, colors.primaryLighter], hoverBackgroundColor: colors.primaryDark, borderWidth: 0, weight: 0.5, }, ], }, options: { responsive: true, maintainAspectRatio: false, legend: { position: 'bottom', }, title: { display: false, }, animation: { animateScale: true, animateRotate: true, }, }, }) </script> {% endblock footer_scripts %} </body> </html> -
Django File Upload using a self-made dropzone
I am at the moment trying to build a practice-project where I implement different ways to upload files using django 4.17. Upon creating my dropzone, I receive the following error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/upload/ Django Version: 4.1.7 Python Version: 3.10.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'upload_files'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', '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'] Traceback (most recent call last): File "/home/kevin/PycharmProjects/uploader/venv/lib/python3.10/site-packages/django/utils/datastructures.py", line 84, in getitem list_ = super().getitem(key) During handling of the above exception ('upload'), another exception occurred: File "/home/kevin/PycharmProjects/uploader/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 56, in inner response = get_response(request) File "/home/kevin/PycharmProjects/uploader/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/kevin/PycharmProjects/uploader/upload_files/views.py", line 16, in upload_file if request.method == 'POST' and request.FILES['upload']: File "/home/kevin/PycharmProjects/uploader/venv/lib/python3.10/site-packages/django/utils/datastructures.py", line 86, in getitem raise MultiValueDictKeyError(key) Exception Type: MultiValueDictKeyError at /upload/ Exception Value: 'upload' My upload.html looks like this, I for now, extend a base.html: {% block content %} <h1>Upload your files</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="upload" accept=" .txt"> <!-- <div type="file" name="upload" accept=" .txt" id="drop-zone" ondrop="dropHandler(event);" ondragover="dragOverHandler(event);" style="width:400px;height:300px;background:grey;"></div> --> <button type="submit"> Go</button> </form> <h2> Uploads so far</h2> {% if file_url %} <p> uploaded to <a href="{{ file_url }}"> {{ file_url }}</a></p> {% else %} <ol> {% … -
Rest Framework serializer to create parent and add different child typess
I will want create form app and i have one problem I want add two different type child to parent how can help me That is my model class Answer(models.Model): question_id = models.ForeignKey( "app.Question", on_delete=models.CASCADE, related_name='answers') answer_title = models.CharField(max_length=100, null=True, blank=True) answer_weight = models.DecimalField(max_digits=9, decimal_places=4, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) #parent=models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) class Meta: verbose_name = 'Answer' verbose_name_plural = 'Answers' def __str__(self): return self.answer_title class Question(models.Model): question_title = models.CharField(verbose_name='question', max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) stage=models.ForeignKey('app.Stage', related_name = 'questions', on_delete=models.CASCADE) class Meta: verbose_name = 'Question' verbose_name_plural = 'Questions' def __str__(self): return self.question_title That is my serializer class QuestionListSerializer(serializers.ModelSerializer): answers = AnswerListSerializer(many=True, read_only=True) class Meta: model = Question exclude = ['created_at', 'updated_at', 'stage'] class AnswerListSerializer(serializers.ModelSerializer): class Meta: model=models.Answer exclude=["question_id"] That is my apiviews class QuestionListApiView(APIView): def get(self, request): question = Question.objects.prefetch_related('answers') serializer = QuestionListSerializer(question, many = True) return Response({"questions": serializer.data}) That is my code i want when user send get method to my question api i want send api structur look like this [ { "id": 1, "question": "dsdsdssd?", "answers": { "A": [ { "id": 1, "answer": "tehsil alitem" }, { "id": 2, "answer": "sen necesen?" } ], "B": [ { "id": 1, "answer": … -
Geodjango cache
I'm using geodjango and wrote an API to paginate stores by distance, all stores can be 20 or something, so I can just cache them, but how to order them by distance for each user? evaluated queryset is just a list so I can't use the query functions here's my queryset code: def get_queryset(self): user_location = self.request.user.location qs = Store.objects.all() qs = qs\ .annotate(distance=Distance('location', user_location))\ .order_by('distance') return qs Any ideas? -
Unable to connect Websocket with wss using SSL Certificate
I have added SSL certificate from letsencrypt and did configuration using Nginx but unable to connect to the websocket using WSS. It works fine if change the configuration to ws. Here is the configuration file -
Django_eventstream to send notifications from backend to frontend: the stream is established but it's empty
I'm trying to send notification from backend (Django) to frontend (Vue.js) using django_eventstream Following the library quide, I create endpoint in asgi.py: import django_eventstream import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application django_asgi_app = get_asgi_application() from django.urls import path, re_path import sv.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') application = ProtocolTypeRouter({ "http": URLRouter([ path( 'frontend-notifications/', AuthMiddlewareStack( URLRouter(django_eventstream.routing.urlpatterns) ), { 'channels': ['test'], }), re_path(r'', django_asgi_app), ]), "websocket": URLRouter(sv.routing.websocket_urlpatterns), }) At the frontend: const es = new ReconnectingEventSource(url+ '/frontend-notifications/'); es.addEventListener('success', function (e) { const data = JSON.parse(e.data); console.log('message', data); }, false ); The event stream channel is established, it can be seen in the browser debug panel. Then at the backend I send an event to the stream: from django_eventstream import send_event send_event( "test", "success", { "success": True } ) But there is no data in the stream. I've tried to send data to the stream via requests as well: import requests session = requests.Session() r = session.post(url, headers={'Connection': 'keep-alive', 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache'}, data='data: Hello World\n\n', stream=True) The request returns 200 OK, but again no any data in the stream. How to send notification from back to front via SSE? Working example would be great. -
Django does not translate variables loaded on init
When I define a constant in Django file that is loaded while the app is initiating, it does not translate the value when I change the language. Example: # widgets.py from django.translation import ugettext_lazy as _ MY_CONSTANT = _('some text') When I try to use MY_CONSTANT its value is translated to the default init language but not evaluated to the current language on demand. How could I fix this? -
I want any language translation functionality in my "Next.js(version 13) + Django" project. As react-google-translate does not support my tech version
The user wants to add language translation functionality to their project. The project is built using Next.js (version 13) and Django. The user has tried using react-google-translate but it doesn't support their tech version. They need an alternative solution for language translation. The user can consider using a Python package called "translate" to implement translation functionality. The package supports multiple languages and can be installed using pip. To use the package, the user can create an instance of the Translator class and specify the source and target languages. The translate() method can then be used to translate text. The user should also handle any errors that may occur during the translation process. I tried react0google-translate library. I want to translate my website text on single selection of languge. -
How to take file name from file in body, not from header when uploading file in Django Rest framework REST API?
I have method which should upload file ( to be specific - image in JPG format) to some external storage (it does not matter where in this issue). Im sending Post request using Postman. I want that uploaded file to take name from file which I pass in my request body. In Postman this file is passed in body as binary. Lets say this file is called dog.jpg. However my request does not work If I won't add "Content-Disposition" header, and as value of this header I need to pass ": attachment; filename=dog2.jpg". My file will be uploaded then as dog2.jpg, instead of dog.jpg. Also it is a little bit burdensome to have to change that name directly in headers everytime. Is there any way to avoid that header? Beginning of my post method: @api_view(['POST']) @parser_classes([FileUploadParser]) @csrf_exempt @login_required def upload_image(request): print(request.FILES['file']) file = request.data.get('file') For now print(request.FILES['file']) Would dog2.jpg file = request.data.get('file') Would also return dog2.jpg The rest of method I think is not important, as it is only logic to upload file to storage, which works perfectly fine. -
Django: Admin Panel - Select an existing image from any folder without creating duplicates
I'm looking for a way to use images that are already in the media folder. models.ImageField(upload_to = "madia/images/pages" verbose_name=('img')) Selecting images for a post in the admin panel creates a duplicate image. Is there a field that allows you to select an existing image from any folder on the server, without being tied to a specific folder - without duplicating images? -
Python django auth test
I want to write tests for my python django application. For tests, I need to get an API token, I tried it through APIClient with this code: client = APIClient() responce = json.loads(client.post('/api-token-auth/',data={"username":"root", "password":"root"}).content) But in return I get {'non_field_errors': ['Unable to login with provided credentials.']} Through the "requests" library and Postman everything works with the same data -
Error: 'Id' can only be used as a field name if the field also sets 'primary_key=True'. Removal of id doesn't change anything
I used an id field in my django models.py file. Whenever I try to make migrations, I get the following error: `SystemCheckError: System check identified some issues: ERRORS: text_modifier.Posts: (models.E004) 'id' can only be used as a field name if the field also sets 'primary_key=True'.` I'm trying to insert id = models.PositiveIntegerField() I'm trying to add the models to postgres I have tried removing the id field from the models.py file, but the error arises again (I have entirely no idea why). Also, I have tried setting the argument primary_key=True myself, this also didn't help. I understand now that id field is default in django, but the removal of it doesn't change anything. I have another problem of django not being able to see the app I'm trying to put the id field in. I have copied the name of the app from the apps.py file and used set DJANGO_SETTINGS_MODULE=search_simple.settings to ensure it works properly. Can it be the issue? My python: Python 3.11.2 My django: 4.1.7 -
DJango pick Operating system username instead of user name present in settings file
About the issue I created the project using command django-admin startproject test and updated the settings file to have mysql database details. Apart from that nothing added/updated/deleted in code. Database details in config file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', "Name": "django", "User": "root", "Password": "", "Host": "localhost", "Port": "3306" } } Then ran the command python manage.py runserver and gave me very strange error. It says Access denied for user pankaj@localhost Question Settings file has username = root, why django pick operating system username -
Django form not getting value for clean method
I'm trying to write a clean method form one of my forms in Django 3.0.Here when the user selects the production_process the clean method is not getting any value.And rising an error in my template page as Production process: Select a valid choice. That choice is not one of the available choices. Here is my forms.py class ProductionCapacityForm(forms.ModelForm): date = forms.DateField(required=True, widget=forms.DateInput(attrs= { 'class':'datepicker' })) def __init__(self, *args, **kwargs): self.client = kwargs.pop('client') self.request = kwargs.pop('request') try: self.work_time = kwargs.pop('work_time') except: pass super(ProductionCapacityForm, self).__init__(*args, **kwargs) self.fields['production_process'].queryset = ProductionProcess.objects.filter(is_deleted=False).values_list("name", flat=True).distinct() self.fields['date'].widget.attrs\ .update({ 'placeholder': 'Select Date', 'class': 'input-class_name' }) def clean(self): production_process = self.cleaned_data.get('production_process') number_of_people = self.cleaned_data.get('number_of_people') datee = self.cleaned_data.get('date') pk = self.instance.pk if production_process: try: if production_process not in ProductionCapacity.objects.get(client=self.client, date=datee,production_process=production_process.id): self.cleaned_data['production_process'] = get_object_or_404(ProductionProcess,client=self.client,id=production_process.id) except: if ProductionCapacity.objects.filter(client=self.client, date=datee, production_process=production_process.id).exists(): raise forms.ValidationError('Production Process is already exists') self.cleaned_data['number_of_people'] = number_of_people self.cleaned_data['date'] = datee return super(ProductionCapacityForm, self).clean() class Meta: model = ProductionCapacity widgets = { "date": McamDateInput1, } fields = ['date', 'production_process', 'number_of_people'] Here is my models.py class ProductionCapacity(models.Model): client = models.ForeignKey(Client,on_delete=models.CASCADE) date = models.DateField(blank=True, null=True) production_process = models.ForeignKey(ProductionProcess,on_delete=models.CASCADE,blank=True,null=True) number_of_people = models.IntegerField(blank=True, null=True) Here