Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to capture Django CSFR Cookie in Postman?
I am trying to send my first POST request that isn't handled inside Django to my Django server. I read in several tutorials from 3 years ago that I should somehow see the CSFR token value in the cookie, eg.: https://hackernoon.com/automatically-set-csrf-token-in-postman-django-tips-c9ec8eb9eb5b I cannot achieve that and I have problems finding tutorials on how to capture that cookie to use it later. Please help. -
Does't work django-admin startproject mfdw_site
I installed Python,and then Django.I checked that Django is installed with --version command.I installed VENV. Now I want to start a Project,but django-admin startproject my_site does't work. I'm working with VScode. What can I do? -
Appropriate Framework or Library in python for agent based or actor model algorithm service
Which Framework or Library in python suitable for agent based or actor model algorithm service? I've worked on develop new algorithmic trading platform which tend to active 24/7 for multiple crypto markets. I use django as a platform's framework but I don't know which framework or library are suitable for design agent-based or actor-based services. I used to django framework as a my framework to develop my algorithmic trading platform. But for scale up project I faced some problems to choose right framework -
selected option is not unselected while clicking on the element twice
select2 ajax select elements clicking once and unselect element clicking twice. This is by default .but in my case element is selecting by one click but not unselecting clicking twice. what is the problem here views.py def search(request): query=request.GET.get("q") print(query) vid=Video.objects.filter(tags__name__icontains=query).order_by("name").distinct() print(vid) vid_list=\[{'id':k.id,"name":k.name,"tags":','.join(k.tags.names())} for k in vid\] print(type(vid_list)) return JsonResponse(vid_list,safe=False) home.html <div class="form-group"> <label>Example of multiple select</label> <select class="form-control" multiple placeholder="Choose skills" id="some" required> </select> </div> scripts <script> $("p").click(function(){ $.ajax({ url:"{%url 'home' %}", success:function(data){ alert("this is a ajax alert") } }) }) $("#some").select2({ ajax:{ url:"{% url 'search'%}", data: function(params){ return{ "q":params.term } }, processResults:function(data){ console.log(data) return{ results:data.map(function(item){ return{id:item.id,name:item.name,tags:item.tags} }) } }, delay:250, cache:true, }, minimumInputLength:1, closeOnSelect: false, allowClear:true, multiple:true, placeholder: "Search Video", templateResult:function(repo){ console.log(repo) if (repo.loading) return repo.name; if (repo && !repo.selected){ return` <span> ${repo.name}(${repo.tags}) </span> ` } }, templateSelection:function(data){ return` <span > ${data.name} </span> ` }, escapeMarkup: function (markup) { return markup; }, }) </script> Now i want to know what is the reason behind this .i mean why option is not unselecting when i click second time on the option -
How to include a select2 multiselect box in a OpenStreetMap widget for Django Admin?
I have the following model, which contains a MultiPolygonField: class MyArea(models.Model): polygon = models.MultiPolygonField( _("Polygon"), null=False, blank=False, ) I have this model registered in Django Admin: @admin.register(MyArea) class MyAreaAdmin(admin.GISModelAdmin): # --> GISModelAdmin to render an OSM map for `polygon` pass Which renders the map, as desired: But now, I would like to include a select2 multiselect box on top of this map, where the user would be able to search another model in our database that contains polygons for administrative regions. class Locality(models.Model): polygon = models.MultiPolygonField( _("Locality Polygon"), null=False, blank=False, ) So the user would still be able to draw manual polygons if he wants too. But he could also search and select Locality objects that already contain complex administrative regions (polygons). Once a Locality object is selected the map should be refreshed to include the new region. How should I go about this? I have tried to create custom templates and custom forms, but did not got anywhere close to the solution -
Chart in javascript doesn't change color
I have a problem in javascript with building financial candlestick charts. I made a chart with apex.js and it displays the correct data where it should be but the color of the chart doesn't change, when the stock price is going up candlestick should be green when it goes down it should be red but on some stocks candlestick in always red and on some stocks it works fine. Here are the images, both charts use the same code but different data because it's different stock but that doesn't mean it should be displayed like this. Here is code for chart: <div id="chart"> </div> <script> var options = { series: [{ name: 'OHLC', data: [ {% for stock in stocks %} { x: new Date("{{stock.date}}"), y: [Number("{{stock.open}}"), Number("{{stock.high}}"), Number("{{stock.low}}"), Number("{{stock.price}}")], }, {% endfor %} ] }, ], chart: { type: 'candlestick', }, title: { text: '{{ticker}} Stock ', align: 'center' }, yaxis: { tooltip: { enabled: true } } }; var chart = new ApexCharts(document.querySelector("#chart"), options); chart.render(); </script> I am using Django in the backend so here is a function that returns chart data: @login_required(login_url='stock:login') def chart(request, ticker): stocks = Stock.objects.filter(ticker = ticker).order_by('date') context = {'stocks':stocks, 'ticker':ticker} return render(request, 'stock_app/chart.html', … -
2023 Everybody! We made it. I want to update my form, but my details are not pulling through to the form
I want to Update/Edit my details on my form. I want to pull the existing details from the database and have them populate on the form, without having the user start from the beginning. Views.py def Client_Update(request, Client_id): ClientUpdate = TestModel.objects.get(pk=Client_id) ClientUpdates = TestForm(request.POST or None, instance=ClientUpdate) if request.method == 'POST': if ClientUpdates.is_valid(): ClientUpdates.save() return redirect('/Client_Details') return render(request, 'GymApp/ClientUpdate.html', {'ClientUpdate':ClientUpdate, 'ClientUpdates':ClientUpdates}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.Home, name='Home'), path('ClientList/', views.Client_list, name='Client_list'), path('ClientDetails/<int:Client_id>', views.Client_Details, name='Client_Details'), path('ClientUpdate/<int:Client_id>', views.Client_Update, name='Client_Update'), path('ClientDelete/<int:Client_id>', views.Client_Delete, name='Client_Delete'), path('DownloadingCSV/', views.DownloadingCSV, name='DownloadingCSV'), path('Search/', views.Search, name='Search'), ] HTML Page {% extends 'GymApp/Layout.html' %} {% block content %} <h1>Updating status</h1> <form action="" method="POST"> {% csrf_token %} <div class="mb-3"> <input type="text" class="form-control" name="Name" placeholder="Client's Name"><br> <input type="text" class="form-control" name="Surname"placeholder="Client's Surname"><br> <select name="Gender" class="form-control"> <option selected disabled> Open this select menu </option> <option value="Male">Male</option><br> <option value="Female">Female</option> </select> </div> <div class="mb-3"> <input type="text" class="form-control" name="Weight" id="Weight" placeholder="Client's Weight"><br><br> <input type="text" class="form-control" name="Height" id="Height" placeholder="Client's Height"><br><br> <button type="button" onclick="calculation()">Calculation update</button> <br> </div> <br> <div class="mb-3"> <input type="text" class="form-control" name="Outcome" id="Outcome" placeholder="BMI Outcome"><br> <select name="Activity_log" class="form-control"><br> <option selected disabled>Open this select menu</option> <option value="Not Active">Not Active</option><br> <option value="Active">Active</option> </select> <br> <button type="submit">Finalising update!</button> </div> </form> <script> function calculation(){ … -
Django-kafka. Distributed requests to an endpoint to handle millions of requests
Can anyone share some source to read. I have an api (django app), lots of people use it, i want this api handle millions requests. How can i make it distributed so this api can handle many requests. Should i make producer and consumer in one file? -
usage of require_POST in django
I wanna know is there a usage or security tip to use required-post or require-get decorators in django? from django.views.decorators.http import require_GET, require_POST -
Django: Webp conversion fails and creates empty picture element while all debugging efforts fail
I'm trying to create an upload form to upload multiple images that need to be converted to webp. Everything worked fine until i added the webp conversion bits. I tried adding exceptions and print statements to track down the issue but it just doesn't print any exceptions. Instead it shows all signs of success and creates an empty "picture" element in the database. I`m using the django cookiecutter project with pillow. models.py def upload_gallery_image(instance, filename): # Print a message to indicate that the function was called print(instance, filename) return f'galleries/{instance.facility.id}/{filename}' class Picture(models.Model): picture = models.ImageField(upload_to=upload_gallery_image) class Gallery(models.Model): facility = models.ForeignKey(Facility, on_delete=models.CASCADE, related_name='tourphotos') pictures = models.ManyToManyField(Picture, related_name='galleries') views.py class GalleryView(APIView): parser_class = (FileUploadParser,) def post(self, request): # Extract the facility ID and list of pictures from the request print('post method called') facility_id = request.data.get('facility') pictures = request.data.getlist('pictures') print(facility_id, pictures) facility = get_object_or_404(Facility, id=facility_id) try: gallery = Gallery.objects.get(facility=facility) except Gallery.DoesNotExist: gallery = Gallery.objects.create(facility=facility) for picture in pictures: print('for loop executing') try: webp_image = BytesIO() image = Image.open(picture) image.save(webp_image, format='webp', quality=75) print(webp_image) file_object = ContentFile(webp_image.getvalue()) print(file_object) picture_obj = Picture.objects.create(picture=file_object) print(picture_obj) gallery.pictures.add(picture_obj) print(gallery) except Exception as e: print(type(e)) continue webp_image.close() serializer = GallerySerializer(gallery) return Response(serializer.data, status=201) serializers.py class PictureSerializer(serializers.ModelSerializer): class Meta: model = Picture … -
DRF .as_viewset on {'post': 'list'} return attribute error?
I am trying to send some text: example: "Hello World" to DRF end-point. This endpoint on receiving this text is to send me a e-mail with the text. When I hit the end-point with Postman, I get the error: Internal Server Error: /api/errors Traceback (most recent call last): File "/Users/sid/eb-virt/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/sid/eb-virt/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/sid/eb-virt/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/sid/eb-virt/lib/python3.8/site-packages/rest_framework/viewsets.py", line 117, in view handler = getattr(self, action) AttributeError: 'ErrorMsgViewSet' object has no attribute 'list' To test this out: urls.py from django.urls import path from .api import * urlpatterns = [ path('api/errors', ErrorMsgViewSet.as_view({'post': 'list'}), name='errors'), ] # I tried .as_view(), which gave me an error to change to the above format # i tried using router.register() and got errors on using generic.GenericAPIview api.py from rest_framework import viewsets from email_alerts.serializers import ErrorsSerializer class ErrorMsgViewSet(viewsets.GenericViewSet): serializer_class = ErrorsSerializer permission_classes = [ ] def post(self, request, *args, **kwargs): print(request.data) models.py from django.db import models # Create your models here. class ErrorsModel(models.Model): error_msg = models.CharField(max_length=5000, blank=True, null=True) serializers.py from rest_framework import serializers from email_alerts.models import ErrorsModel class ErrorsSerializer(serializers.ModelSerializer): error_msg = serializers.CharField( required=False, allow_null=True, allow_blank=True) class … -
Django: How to show a message in a custom admin action with a download?
I'm defining a custom admin action called Download CSV. In this action I want to download a .csv file and show a message to the user. I have not been able to make both happen. I tried this way: @admin.action(description=gettext_lazy("Download CSV")) def download_csv(self, request, queryset): self.message_user(request=request, message=gettext_lazy("Downloaded")) return self.create_csv() @staticmethod def create_csv() -> HttpResponse: headers = {'Content-Disposition': f'attachment; filename="download.csv"'} response = HttpResponse(content_type='text/csv', headers=headers) response.write(codecs.BOM_UTF8) csv.writer(response).writerows([['example']]) return response actions = [download_csv] Does anyone know how to do it correctly? Thanks. -
My celery-beat works locally but not in production?
my task: @shared_task def my_test(): # Executes every 2 minutes UserStatisticStatus.objects.filter(id=1).update(loot_boxes=+234) print('Hello from celery') app.conf.beat_schedule = { 'my-task-every-1-minutes': { 'task': 'user_statistic_status.tasks.my_test', 'schedule': crontab(minute='*/1'), }, } my settings: if 'RDS_DB_NAME' in os.environ: CELERY_BROKER_URL = 'redis://<myurl>/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_BROKER_TRANSPORT_OPTIONS = { 'region': 'eu-central-1', 'polling_interval': 20, } CELERY_RESULT_BACKEND = 'redis://<myurl>/1' CELERY_ENABLE_REMOTE_CONTROL = False CELERY_SEND_EVENTS = False CELERY_TASK_ROUTES = { 'my_test': {'queue': 'default'}, } my celery.py : import os from celery import Celery from project import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('celery_app') app.conf.task_routes = { 'my_test': {'queue': 'default'}, } app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) The worker connects and shows the tasks correctly and the beat starts too but nothing happening. I've tested it with the local redis server and everything works fine. Any help will be much appreciated Thank you -
Reverse for 'profile' with arguments '(None,)' not found. 1 pattern(s) tried: ['profile/(?P<user_id>[0-9]+)\\Z']
I'm getting the above error and I've tweaked my code based on answers I saw online but still getting the same error VIEWS.PY ` def profile(request, user_id): profile_user = User.objects.get(pk = user_id) # user_profile = Profile.objects.get(user=user_object) profile_post = NewTweet.objects.filter(user = user_id) post_count = len(profile_post) follower = request.user.id user = user_id if Followers.objects.filter(follower=follower, user=user).first(): button_text = "Unfollow" else: button_text = "Follow" context = { "profile_user": profile_user, "post_count": post_count, "profile_post": profile_post, "button_text": button_text, } return render(request, "network/profile.html", context) ` URL.PY path("profile/<int:user_id>", views.profile, name="profile"), LAYOUT.HTML ` <li class="nav-item"> <a class="nav-link" href="{% url 'profile' user.id %}"> <img src= {% static 'network/images/profile.svg' %} alt="Profile" class="left-sidebar-menu-icon"> Profile </a> <img src= {% static 'network/images/profile.svg' %} alt="Profile" class="left-sidebar-menu-icon"> Profile </li> ` MODELS.PY class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() bio = models.TextField(blank=True) def __str__(self): return self.user.username class Followers(models.Model): follower = models.CharField(max_length=100) user = models.CharField(max_length=100) # follower = models.ForeignKey('User', on_delete=models.CASCADE, related_name='targets') # target = models.ForeignKey('User', on_delete=models.CASCADE, related_name='followers') def __str__(self): return self.user In Layout.html, I try '{{ user.id }}' to see what is reflecting and it shows 'None'. Please advise In Layout.html, I try '{{ user.id }}' to see what is reflecting and it shows 'None'. I also adjusted this as adviced in a different thread but same … -
django unknown column after migrations
I have a weird problem. I've added the below to the model. I have run migrations, but I still still get the error no such column: Linked_OKR linked_OKR = models.ForeignKey(okrtasks, on_delete=models.CASCADE,db_column='okrid', blank=True, null=True) Weirdly in the admin view, it also shows up not in bold, unlike all other columns Any idea what's going on? -
Django - Linking Models
I am using django and I want to link two models. The first model is comment and the second model is image. I want to have multiple images for one comment and an image should be linked with only one comment. Comment model has its fields and image model looks like this: class Image(models.Model): image = models.ImageField(upload_to=f'{hash(id)}/', null=True, blank=True) def __str__(self): return self.image.name And this is the model that I used to link comment and image: class CommentImage(models.Model): comment = models.OneToOneField(Comment, models.CASCADE, null=True) image = models.ForeignKey(Image, models.CASCADE, null=True) class Meta: ordering = ["-id"] verbose_name = _("Image") verbose_name_plural = _("Images") def __str__(self): return self.image.image.name Here is the admin panel of django: enter image description here As you can see I could be able add only one image and there is no button as well to add multiple image. What should I change to be able to add multiple images? I have tried using ManytoManyField and removing comment field from CommentImage but it did not work. -
How to communicate django api with frontend react native?
I have a django application and I have a react native app. I am running the android emulator from android studio. And now I try to connect the backend with the frontend. I studied the example from: https://reactnative.dev/docs/network And the example url: https://reactnative.dev/movies.json' works. But now I try to connect with my own localhost data. So this is my component: import { ActivityIndicator, FlatList, Text, View } from "react-native"; import React, { Component } from "react"; export default class App extends Component { constructor(props) { super(props); this.state = { data: [], isLoading: true, }; } async getMovies() { try { const response = await fetch("http://127.0.0.1:8000/api/movies/"); const json = await response.json(); this.setState({ data: json.movies }); } catch (error) { console.log(error); } finally { this.setState({ isLoading: false }); } } componentDidMount() { this.getMovies(); } render() { const { data, isLoading } = this.state; return ( <View style={{ flex: 1, padding: 24 }}> {isLoading ? ( <ActivityIndicator /> ) : ( <FlatList data={data} keyExtractor={({ id }, index) => id} renderItem={({ item }) => <Text>{item.title}</Text>} /> )} </View> ); } } But if I try to run this example. I get this error: Network request failed at node_modules\whatwg-fetch\dist\fetch.umd.js:null in setTimeout$argument_0 at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in _allocateCallback$argument_0 … -
Store Data From API [closed]
I want to store data in Django Database from external API. I have a company software to store data. that data is stored in API, I want to get those data and store in Django database. company store data in API, and I want that data direct to my Django website. Django API please give the solution to store data from external API. -
why does my cart page doesnt show its content properly?
{% extends 'app/base.html' %} {% load static %} {% block title %}Cart{% endblock title %} {% block main-content %} <div class="container my-5"> <div class="row"> {% if cart %} <h1 class="text-center mb-5">Shopping Cart</h1> <div class="col-sm-8"> <div class="card"> <div class="card-body"> <h3>Cart</h3> {% for item in cart %} <div class="row"> <div class="col-sm-3 text-center align-self-center"><img src="{{item.product.product_image.url}}" alt="" srcset="" class="img-fluid img-thumbnail shadow-sm" height="150" width="150"></div> <div class="col-sm-9"> <div> <h5>{{item.product.title}}</h5> <p class="mb-2 text-muted small">{{item.product.description}}</p> <div class="my-3"> <label for="quantity">Quantity:</label> <a class="minus-cart btn" pid={{item.product.id}}><i class="fas fa-minus-square fa-lg"></li></a> <span id="quantity">{{item.quantity}}</span> <a class="plus-cart btn" pid={{item.product.id}}><i class="fas fa-plus-square fa-lg"></li></a> </div> <div class="d-flex justify-content-between"> <a href="#" class="remove-cart btn btn-sm btn-secondary mr-3" pid={{item.product.id}}>Remove item </a> <p class="mb-0"><span><strong>₱ {{item.product.discounted_price}}</strong></span></p> </div> </div> </div> </div> <hr class="text-muted"> {% endfor %} </div> </div> </div> <div class="col-sm-4"> <div class="card"> <div class="card-body"> <h3>The Total Amount of</h3> <ul class="list-group"> <li class="list-group-item d-flex justify-content-between align-items-center border-0 px-0 pb-0" >Amount<span id="amount">₱{{amount}}</span></li> <li class="list-group-item d-flex justify-content-between align-items-center px-0">Shipping<span>₱144.00</span></li> <li class="list-group-item d-flex justify-content-between align-items-center border-0 px-0 mb-3"> <div> <strong>Total</strong> <small>(including GST)</small> </div> <span id="totalamount"><strong>₱ {{totalamount}}</strong></span> </li> </ul> <div class="d-grid"><a href="{% url 'checkout' %}" class="btn btn-primary">Place Order</a></div> </div> </div> </div> {% else %} <h1 class="text-center mb-5">Cart is Empty</h1> {% endif %} </div> </div> {% endblock main-content %} The code above is the addtocart html and when … -
How to not save into database if document upload is failed
When a user uploads a document and clicks submit the file is stored in a folder and a database entry is created along with bunch of other details. What I am looking for is to avoid the save if the document doesn't get uploaded into the specific location. serializer.py class DocumentSerializer(serializers.ModelSerializer): class Meta: model = Request fields = ['file', 'doc_type'] def create(self, validated_data): msg = self.__construct_message_body() validated_data['type'] = Request.request_types[-1][0] validated_data['input_message'] = msg instance = ParseRequest.objects.create(**validated_data) msg['request_id'] = instance.id instance.input_message = msg instance.save() return instance views.py class DocumentView(CreateAPIView, ResponseViewMixin): parser_classes = (MultiPartParser, FileUploadParser,) serializer_class = DocumentSerializer def create(self, request, *args, **kwargs): try: data = request.data serializer = self.get_serializer( data=data, context={'request': request}) serializer.is_valid() serializer.save() except Exception as e: logger.error(e) return self.error_response(message=ERROR_RESPONSE['UPLOAD_DOCUMENT']) return self.success_response(message=SUCCESS_RESPONSE['UPLOAD_DOCUMENT']) -
Django generate thumbnail from video, but it encodes it
Im using django-video-encoding this and django-rq to generate a thumbnail but instead it generates another video AND it makes it smaller(in size) here is signals.py: ` from django.db.models.signals import post_save from django.dispatch import receiver from typing import Type from . import tasks , signals from .models import Post from django_rq import enqueue @receiver(post_save, sender=Post) def create_thumbnail(sender, instance, **kwargs): enqueue(tasks.create_thumbnail, instance.pk) here is tasks.py: ` from django.core.files import File from video_encoding.backends import get_backend import os from .models import Post def create_thumbnail(post_pk): video = Post.objects.get(pk=post_pk) if not video.video: print('no video file attached') # no video file attached if video.thumbnail: print('thumbnail has already been generated') # thumbnail has already been generated encoding_backend = get_backend() thumbnail_path = encoding_backend.get_thumbnail(video.video.path) path = video.video.url filename = os.path.basename(path), try: with open(thumbnail_path, 'rb') as file_handler: django_file = File(file_handler) video.thumbnail.save(filename[0], django_file) video.save() finally: os.unlink(thumbnail_path)` and models.py: `from django.db import models from django.contrib.auth.models import User from django.core.validators import FileExtensionValidator from django.contrib.contenttypes.fields import GenericRelation from video_encoding.fields import VideoField, ImageField from video_encoding.models import Format class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=500) description = models.TextField() format_set = GenericRelation(Format) video = VideoField(upload_to='uploads/video_files/%y/%d', validators = [FileExtensionValidator(allowed_extensions=['mp4'])]) thumbnail = ImageField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return self.title + "\n" … -
ERROR: (gcloud.app.deploy) INVALID_ARGUMENT: Deploying a django app using google app engine
I keep getting error INVALID_ARGUMENT: Filename cannot contain '.', '../', '\r', start with '-', '_ah/', or '\n': --project. Whenever I try to deploy my django Portfolio website using google app deploy. #for my app.yaml file runtime: python37 First I tried using gcloud app deploy and then this below- gcloud app deploy app.yaml --project afroweb -
save() got an unexpected keyword argument 'force_insert' in serializer
My Product model has a many-to-many field warehouse_stocks and to save this I have been using: class ProductSerializer(serializers.ModelSerializer): warehouse_stocks = ProductsInWarehouseSerializer(many=True) class Meta: model = Product fields = "__all__" def create(self, validated_data): print("validated data", validated_data) items_objects = validated_data.pop('warehouse_stocks', []) prdcts = [] for item in items_objects: i = ProductsInWarehouse.objects.create(**item) prdcts.append(i) instance = Product.objects.create(**validated_data) instance.warehouse_stocks.set(prdcts) return instance and this has been working fine in the project but I recently started getting this error: TypeError: save() got an unexpected keyword argument 'force_insert' Full error: Traceback (most recent call last): File "C:\Users\Rahul Sharma\PycharmProjects\multitennant_v2\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Rahul Sharma\PycharmProjects\multitennant_v2\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Rahul Sharma\PycharmProjects\multitennant_v2\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Rahul Sharma\PycharmProjects\multitennant_v2\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\Rahul Sharma\PycharmProjects\multitennant_v2\venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Rahul Sharma\PycharmProjects\multitennant_v2\venv\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\Rahul Sharma\PycharmProjects\multitennant_v2\venv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\Rahul Sharma\PycharmProjects\multitennant_v2\venv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "C:\Users\Rahul Sharma\PycharmProjects\multitennant_v2\venv\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\Rahul Sharma\PycharmProjects\Trakkia-Backend\masters\views.py", line 76, in post serializer.save() File "C:\Users\Rahul Sharma\PycharmProjects\multitennant_v2\venv\lib\site-packages\rest_framework\serializers.py", line 212, in save self.instance = self.create(validated_data) File "C:\Users\Rahul … -
django: foreign key issues when creating a model object
I am trying to write a row to database, with data gathered in a form. I need to work with two foreign keys and one of them is causing the creating to fail, although I am unable to figure out why: here is my model: def upload_path(instance,file): file_dir = Path(file).stem print('usr',instance.user.id) path = '{}/{}/{}/{}'.format(instance.user.id,"projects",file_dir,file) return path class BuildingFilesVersions(models.Model): version_id = models.AutoField(primary_key=True) building_id = models.ForeignKey(Building, on_delete=models.CASCADE,related_name='building_id_file') user = models.ForeignKey(Building, on_delete=models.CASCADE,related_name="user_file") created_at = models.DateTimeField(auto_now_add=True, blank=True) description = models.TextField(max_length=200, blank=True, null=True) modification_type = models.CharField(choices=WORK_TYPE_CHOICES, max_length=200, blank=True, null=True) filename = models.CharField(max_length=200, blank=True, null=True) file = models.FileField(upload_to=upload_path, null=True, blank=True) and here is my view: @login_required @owner_required def RegisterFileView(request,pk): form = AddBuildingFileForm() if request.method == 'POST': form = AddBuildingFileForm(request.POST,request.FILES) if form.is_valid(): description = form.cleaned_data["description"] modification_type = form.cleaned_data["modification_type"] filename = form.cleaned_data["modification_type"] file = request.FILES['file'].name BuildingFilesVersions.objects.create(building_id_id=pk, user_id=request.user, description=description, modification_type=modification_type, filename=filename, file=file) return redirect('home') else: form = AddBuildingFileForm() context = {'form':form} return render(request, 'building_registration/register_file.html', context) what gets me confused is that the error is Field 'building_id' expected a number but got <SimpleLazyObject: <User: Vladimir>> even though pk return the proper building_id Can anyone see where I messed up? -
Change properties of a foreign key field in default django table
I am trying to use an existing database with django ORM. I have created the models for the tables that I want to use. python manage.py makemigrations ran without any problem. python manage.py migrate returns the error File "/home/s30python-02/anaconda3/envs/test/lib/python3.10/site-packages/pymysql/err.py", line 143, in raise_mysql_exception raise errorclass(errno, errval) django.db.utils.OperationalError: (1005, 'Can't create table site_db.django_admin_log (errno: 150 "Foreign key constraint is incorrectly formed")') I had read that the FOREIGN KEY references in MySQL is that both columns of the constraint must the same column definition. So I checked and the DataType of primary key of user table is int(11) unsigned and the user_id in django_admin_log table is bigint(20). And I think the problem is due to that. Is there a way to override LogEntry which is responsible for the django_admin_log table and change the user_id field properties or is there anything else that can be done. Need your insight on this one. Thanks for your time...