Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Static files are not loaded generating pdf from html when application run in ASGI layer
I use Weasyprint to generate pdf from HTML. When I configure ASGI static files are not loaded in pdf, if I run the application in WSGI then the static file loads correctly. How can I solve this issue? -
Django - annotate query for if queried user is followed by current user
So I have this code below that given a user_uuid I look up the info of a user. All request come with a auth token that contains the current user's uuid. If the current user queried for their own profile then the is_current_user key should be true, which is done with the item['is_current_user'] = user_uuid == request.user.uuid line and then I have another flag for if the current user is following the queried user which is item['is_following'] = FollowUser.objects.filter(follower=str(request.user.uuid), followee=user_uuid).exists(). As you can see these are very ugly hacks and I was wondering if I could add these values to the annotate function. def get_user_info(request, user_uuid): try: query_annotated = User.objects.annotate( follower_count=Count('followee_id', distinct=True), followee_count=Count('follower_id', distinct=True)).get(pk=user_uuid) except User.DoesNotExist as e: return Response(dict(error=str(e), user_message='User not found.'), status=status.HTTP_404_NOT_FOUND) serializer = FullUserSerializer(query_annotated) # TODO: This is a hack the above annotation is not working item = serializer.data item['is_following'] = FollowUser.objects.filter(follower=str(request.user.uuid), followee=user_uuid).exists() item['is_current_user'] = user_uuid == request.user.uuid return Response(item, status=status.HTTP_200_OK) -
Websocket connection using djangochannelsrestframework
Websocket connection connects and disconnects after a second and shows the following error. Tried different ports still gives the same error Error image -
Django, csrf token not set
in settings.py: #SESSION_COOKIE_SAMESITE = 'Strict' SESSION_COOKIE_HTTPONLY = True #CSRF_COOKIE_SECURE = True #SESSION_COOKIE_SECURE = True CSRF_TRUSTED_ORIGINS = [ "http://localhost:3000",'http://127.0.0.1:8000'] in views.py: @method_decorator(csrf_protect,name='dispatch') class LoginView(views.APIView): permission_classes = [AllowAny,] serializer_class = serializer.LoginSerializer def post(self,request): data = serializer.LoginSerializer(data=request.data) print(data.is_valid()) print(data.errors) if data.is_valid(): email = data.data['email'] password = data.data['password'] auth = authenticate(username=email,password=password) if auth: login(request,auth) return HttpResponse(request.session.session_key ,status=200) else: print(password == "") if email == "" and password =="": return HttpResponse('both email and password field are empty',status=400) elif email == "": return HttpResponse('email field is empty',status=400) elif password == "": print("Here") return HttpResponse('passowrd field is empty',status = 400) the problems occur in frontend, (localhost:3000) but here is part of login component: let handleSubmit = (e)=>{ e.preventDefault() axios.post('http://127.0.0.1:8000/login/',login,{withCredential:true},{headers: {'Content-Type': 'application/json','X-CSRFToken':Cookies.get('csrftoken')}}).then( (res)=>{ console.log(res.data) } } I am getting: Forbidden-Csrf token not set on the backend, but when i login from backend 127.0.0.1:8000/login it works fine, and session id is set as https only cookie, csrf is set in cookies, but when i do it from frontend, it gives an error any idea? -
Django exposes raw html on rendered website
I am learning Django with the documentation tutorial: https://docs.djangoproject.com/en/4.0/intro/tutorial03/ I have just completed the "Write views that actually do something" part, but somethings is definitely amiss. Even though I copied the code 1:1, this is the render I get: Last two bits of code I edited: index.html in polls/templates/polls directory: {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} views.py in polls directory: from django.http import HttpResponse from django.template import loader from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request)) def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) -
Getting CORS error only when running django app through docker-compose
I have a Django backend app using Django-rest-framework. Currently, I'm developing the frontend with React using Axios to make HTTP requests. Whenever I run my app using python manage.py runserver and make a request from the React client, I get the expected response. Nevertheless, if I start my app using docker-compose, I get the No 'Access-Control-Allow-Origin' header is present on the requested resource response. This is my docker-compose.yaml services: db: image: postgres volumes: - /var/lib/docker/volumes/mobilequoter/db/data:/var/lib/postgresql/data ports: - ${DB_PORT}:5432 environment: - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} - POSTGRES_DB=${DB_NAME} web: build: . command: gunicorn mobilequoter.wsgi --bind 0.0.0.0:${PORT} env_file: .env volumes: - .:/code ports: - 8000:${PORT} environment: - DB_HOST=db - DB_PORT=5432 depends_on: - db This is is my settings.py (with the settings related to CORS: handler = EnvHandler() SECRET_KEY = handler.SECRET_KEY DEBUG = handler.DEBUG ALLOWED_HOSTS = handler.ALLOWED_HOSTS CORS_ALLOWED_ORIGINS = handler.CORS_ALLOWED_ORIGINS SHELL_PLUS = 'ipython' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # third party 'rest_framework', 'drf_yasg', 'storages', 'django_extensions', 'corsheaders', # local 'mobilequoter.helper', 'mobilequoter.authentication', 'mobilequoter.client', 'mobilequoter.quote', 'mobilequoter.sale', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] This are my env vars related to hosts: ALLOWED_HOSTS=127.0.0.1,localhost CORS_ALLOWED_ORIGINS=http://127.0.0.1:3000,http://localhost:3000 This is my axios client: import axios from "axios"; const axiosClient = axios.create({ baseURL: process.env.REACT_APP_BACKEND_URL … -
MySQLdb._exceptions.OperationalError: (2002, "Can't connect to server on '<servername>.database.windows.net') | Django+Azure+MySql
I'm having issues connecting my Django app in my local machine to MySql Database in Azure? I added my IP in the Rules and am connecting with this: 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '<servername>.database.windows.net', 'PORT': '3306', 'NAME': '<database_name>', 'USER': '<admin>@<servername>', 'PASSWORD': '<cecret>', 'OPTIONS': {'ssl': {'pem': 'tls.pem'} } }, I can connect using AzureDataStudio, but not with this configuration in django. I Nmaped my host, found a bunch of open ports but 3306 and 1433 are bound to Sql servers. Django's runserver shows MySQLdb._exceptions.OperationalError: (2002, "Can't connect to server on '<servername>.database.windows.net' (115)") with this configuration even if I have that server and database within it running. One example php query string in Azure portal has: $conn = new PDO("sqlsrv:server = tcp:<server_name>.database.windows.net,1433; Database = <database_name>", "<admin>", "{your_password_here}"); So, I'm assuming I should connect to 1433 but only 3306 works from DataStudio. From python manage.py runserver it shows django.db.utils.OperationalError: (2013, "Lost connection to server at 'handshake: reading initial communication packet', system error: 104") if I try port 1433. I'm at the limit of my knowledge regarding this. -
My form is not saving for some reason... did I made a mistake on my HTML?
I wanted to modify the way my forms is displayed using html and css. Here is the <form> part of my HTML: <form action="" method="post" enctype='multipart/form-data'> {% csrf_token %} <div> <input type="text" name="post_title" placeholder="Forum title" id="id_post_title"> <textarea name="post_body" placeholder="Forum content" id="id_post_body"></textarea> <div class="authors"> <!-- This class is to call my Users model --> <select name="author" id="id_author"> <option value="">----Select Author----</option> {% for author in authors %} <option value="{{ author.first_name }} {{ author.last_name }}">{{ author.first_name }} {{ author.last_name }}</option> {% endfor %} </select> </div> <div> <label> <input type="file" accept="image/" name="forum_image" required id="id_forum_image" >Upload Image </label> </div> <input type="submit" value="Save Post" class="save_post"> </div> </form> I tried form.as_p and it all worked just fine. Did I made a mistake in my HTML? Here is my forms.py: class AddForum(forms.ModelForm): class Meta: model = Forum fields = 'all' labels = { 'post_title': 'Title of your post:', 'post_body': 'Content of your post:', 'author': 'Author:', 'forum_image': 'Attach image:', } def __init__(self, *args, **kwargs): super(AddForum, self).__init__(*args, **kwargs) self.fields['forum_image'].required = False -
QuerySet of a ManyToManyField object is returning an empty list
I wanted to have a list of foreign keys for a field, so I had used Django's ManyToManyField. I have the following models: models.py class Community(models.Model): title = models.CharField(max_length=25, unique=True) total_users = models.IntegerField(default=0) active_users = models.IntegerField(default=0) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='+' ) posts = models.ManyToManyField('Post', null=True, blank=True, symmetrical=False) created_date = models.DateTimeField() members = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='+', blank=True, null=True, symmetrical=False ) def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=300) content = models.TextField(max_length=50000, blank=True) upvotes = models.IntegerField(default=0) downvotes = models.IntegerField(default=0) comments = models.ManyToManyField('Comment', null=True, blank=True, symmetrical=False) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) created_date = models.DateTimeField() awards = models.JSONField(default=dict) community_id = models.ForeignKey('Community', on_delete=models.CASCADE, related_name='+', null=True, blank=True) additional_fields = models.JSONField(default=dict) def __str__(self): return self.title I'm able to view the list of foreign keys from the admin panel, but when I try to get the list of posts or members from the community object using community_object.members.all() and community_object.posts.all(), I get an empty list/queryset. I'm new to Django and I don't think I understand ManyToManyFields very well. -
Parent field name in not rendering in django while adding new data
I am working on one project where i am facing issue in field value rendering. I added one product and now i want to add the record of it means for how much rupee it cost etc. But the problem now is once it click on add form the product name here it should be product1 is not rendering automatically but the category is rendering automatically i can select the item from drop down list but it should render automatically. Once i click on add product it should automatically display that product name but it's not displaying but the category is displaying. Guide me what's wrong here. class Category(models.Model): name = models.CharField(max_length=200) def __str__(self) -> str: return self.name class Storage(models.Model): product_name = models.CharField(max_length=500) quantity = models.CharField(max_length=500, default='1') MRP = models.CharField(max_length=500, default='', blank=True) selling_price = models.DecimalField(max_digits=8, decimal_places=0) class ProductRecord(models.Model): storage = models.ForeignKey(Storage, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) model = models.CharField(max_length=1000, null=True, blank=True, unique=True) -
Why is it that when I enter `{{ something }}`, it also gets displayed in `HTML`?
I tried entering this code in my HTML: <div> <input type="file" name="{{ form.forum_image }}" accept="image/*"> </div> And this produces a site with the usual input file but after that is the text " accept="image/*"></div> What should I do with this so that it doesn't desplay the text? I included a picture. -
Django bulk create, ignore failed foreign keys?
Is there a way to ignore foreign key errors when doing a Model.objects.bulk_create and postgres? I'm aware of the ignore_conflicts=True flag and this seems to fix some errors, but I'm specifically dealing with data where the ForeignKey is not guaranteed to exist for one reason or another (such as the data being incomplete, deleted or more). I'm aware that this can be done at the database level using FOREIGN_KEY_CHECKS but I just want this for a particular bulk_create call. What can I do here? -
Django Generate Excel and save as Object with Celery and RabbitMQ
I am using Django 2.2.5, Celery 5.2.6 and RabbitMQ and I am new to the last 2. I want to generate an Excel sheet and store it in a FileField inside a newly created object (not download it), and this is what I did: project/settings.py: CELERY_RESULT_BACKEND = "django-db" CELERY_CACHE_BACKEND = "django-cache" CELERY_BROKER_URL = "amqp://localhost" CELERY_ACCEPT_CONTENT = ["application/json"] CELERY_TASK_SERIALIZER = "json" CELERY_RESULT_SERIALIZER = "json" CELERY_TIMEZONE = "Africa/Casablanca" project/celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "verautonoapi.settings") app = Celery("verautonoapi") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print("Request: {0!r}".format(self.request)) project/init.py : from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ("celery_app",) app/tasks.py: from __future__ import absolute_import, unicode_literals from django.http import HttpResponse, FileResponse from celery import shared_task from celery.utils.log import get_task_logger from time import sleep from openpyxl import Workbook from datetime import date from .models import Dossier, Export logger = get_task_logger(__name__) @shared_task(bind=True, track_started=True) def exp_en_cours(request): print("task activated") sleep(7) print("now starting generating the file") dossier_queryset = Dossier.objects.filter(status_admin="Validation OR Requise") today = str(date.today()) response = FileResponse( content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ) response["Content-Disposition"] = ( "attachment; filename=" + today + … -
There is no current event loop in thread 'uWSGIWorker1Core13'
We are running into a bug with one of our API endpoints that handles fetching tiktok user info. Our app is written in Django and is using the Django rest framework. We are using uwsgi to serve our app. We are able to serve our app locally using uwsgi and our tiktok API endpoint works as intended. However, when building and deploying our docker container to our production server, we see the following error response when making a request to our tiktok API endpoint: There is no current event loop in thread 'uWSGIWorker1Core13'. It's also important to point out that we are running our app in a synchronous environment. The PyTitktokApi has some async parts. We are thinking the the bug is related to this. It should be possible to run async code in a sync environment. Here is some sample code of our API endpoint and the function responsible for fetching tiktok user info: # rest API call class TikTokConnectView(GenericAPIView): """ Connect TikTok App View """ serializer_class = TikTokConnectSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) access_token = serializer.validated_data['access_token'] open_id = serializer.validated_data['open_id'] response_status, username = tiktok_username(open_id, access_token) if not response_status: return Response({'detail': 'Error fetching username'}, status=status.HTTP_404_NOT_FOUND) # … -
How to display progress bar for multi file upload form in Django?
I'm developing an application that requires users to upload a massive directory of multiple files/file types/subfolders. It will be handling 10's possibly 100s of GB per user, so having a progress bar displayed while uploading will be very helpful in informing the user the progress of the massive files. My current setup is based on the following answer to another question: https://stackoverflow.com/a/52016594/15739035 Here is a simplified setup: models.py: class Feed(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE) text=models.TextField(blank=False, max_length=500) class FeedFile(models.Model): file = models.FileField(upload_to="files/%Y/%m/%d") feed = models.ForeignKey(Feed, on_delete=models.CASCADE) forms.py: class FeedModelForm(forms.ModelForm): class Meta: model = Feed fields = ['text'] class FileModelForm(forms.ModelForm): class Meta: model = FeedFile fields = ['file'] widgets = { 'file': ClearableFileInput(attrs={'multiple': True}), } # widget is important to upload multiple files views.py: def upload_files_view(request): user = request.user if request.method == 'POST': form = FeedModelForm(request.POST) file_form = FileModelForm(request.POST, request.FILES) files = request.FILES.getlist('file') # field name in model if form.is_valid() and file_form.is_valid(): feed_instance = form.save(commit=False) feed_instance.user = user feed_instance.save() total_files = len(files) # Get the number of files in 'files' files_count = 0 # Use to show user the progress out of 'total_files' for f in files: file_instance = FeedFile(file=f, user=use, feed=feed_instance) file_instance.save() progress = f"{total_files}/{files_count}" # render(request, 'some_folder/upload_progress.html', {'file_form': file_form, 'form': form, 'progress': … -
The field items.Item.owner was declared with a lazy reference to 'items.user', but app 'items' doesn't provide model 'user'
I have extended User Django model using AbstractUser and I have pointed AUTH_USER_MODEL = 'items.User' in my settings/base.py, then I repointed all the FK to 'items.User'( was User before the change), but I am getting this error in every class I have mentioned 'items.User' when I run python manage.py migrate Approach 1 ======items/models.py======= from django.contrib.auth.models import AbstractUser class User(AbstractUser): bio = models.TextField(max_length=500, null=True, blank=True) birth_date = models.DateField(null=True, blank=True) address = models.CharField(max_length=100,null=True, blank=True) ----------------------------------------------- ======core/settings/base.py======= .... ALLOWED_HOSTS = [] AUTH_USER_MODEL = 'items.User' .... ----------------------------------------------- =====contracts/models.py======= class Contract(models.Model): ....... owner = models.ForeignKey('items.User', on_delete=models.CASCADE) ......... Approach 2 I have imported User model from core.settings.base.py ======core/settings/base.py===== .... ALLOWED_HOSTS = [] AUTH_USER_MODEL = 'items.User' .... ----------------------------------------------- =======contracts/model.py===== from core.settings.base import AUTH_USER_MODEL User = AUTH_USER_MODEL class Contract(models.Model): ....... owner = models.ForeignKey('items.User', on_delete=models.CASCADE) ......... and still getting the same error, do I need to drop Db or something because I kind of start to think about a conflict with migrations file with the new change(kind of circulation-alike issue)!!??? -
How to send a POST to Django Rest passing only ID on relationships, instead of whole dictionary after using Serializers for related fields?
I'm doing a little tutorial on Django Rest Framework, as I never used it before even though I have some experience with Django using templates. So I'm diverging a little from the tutorial class as I think I learn better this way, so I got to a point where in a Movie Rating simple application, when you do a GET from the Ratings serializer, you get just the FK IDs and the "stars" rating I added: [ { "id": 1, "user": 1, "movie": 1, "stars": 5 }, { "id": 2, "user": 1, "movie": 4, "stars": 4 } ] As I learned in a previous lesson from the said course, I know you can specify a serializer for each field, so instead on a GET request you get the dictionary with the whole data. class RatingSerializer(serializers.ModelSerializer): movie = MovieSerializer(many=False) user = UserSerializer(many=False) class Meta: model = Rating fields = ('id', 'user', 'movie', 'stars') That way the return from the GET to the Ratings route shows relational data instead of only the IDs: [ { "id": 1, "user": { "id": 1, "username": "admin", "email": "admin@admin.com" }, "movie": { "id": 1, "title": "Matrix 2", "synopsis": "Neo is back." }, "stars": 5 }, { … -
Trouble understanding the task of Django and Django rest framework?
Here I have trouble understanding the above question. I have a task given as above. It says I have to make an api (get api) in Django which contains the above four fields id, name, latitude and longitude. It is simple to make a get api, if I can save the data to the database from Django-admin. But here, I suppose it says to use google map apis. Ok, somehow I can get the data from the google apis ( I am not so sure which python package is best for this), but how to save that data to the db, and later show it while calling get api?? -
Django rest framework valid related field not found by serializer but present in request
I have 2 related models and I am trying to perform an ajax 'multipart/form' post request. But it seems like data regarding the related model is not identified by the serializer for some reason. I have tried editing the 'create' method of the viewset, to understand why the data is not passed, but to no avail. I think the issue is related to json serialization, but i do not know how to fix it Here are some things i tried: models.py class Dream(models.Model): # Some fields ... class Milestone(models.Model): title = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) description = models.TextField(max_length=500) dream = models.ForeignKey( Dream, on_delete=models.CASCADE, related_name='milestones') serializers.py class DreamSerializer(TaggitSerializer, serializers.ModelSerializer): milestones = MilestoneSerializer(many=True, read_only=False) class Meta: model = Dream fields = (..., 'milestones') class MilestoneSerializer(serializers.ModelSerializer): class Meta: model = Milestone fields = ('id', 'title', 'user', 'date', 'description', 'dream') read_only_fields = ('user', 'dream', 'date') views.py class DreamViewSet(viewsets.ModelViewSet): queryset = Dream.objects.prefetch_related('user').all() serializer_class = DreamSerializer permission_classes = [permissions.IsAuthenticated] # Tried to manually override the create function to fix the error def create(self, request, *args, **kwargs): print(request.data) # <QueryDict: {'title': ['test'], 'image':[<InMemoryUploadedFile: somePhoto.jpg (image/jpeg)>], ... , 'milestones': ['[{"title":"test1","description":"test1"}]']}> # seems like it is evaluating to string literal '[{"title":"test1","description":"test1"}]' print(request.data['milestones']) # [{"title":"test1","description":"test1"}] print(type(request.data['milestones'])) … -
How to navigate to a new link from the search box results in Django template with ajax?
I am creating a chat application in Django. I am using ajax to get search results to show up after each character is typed in the input box. It works fine. But now I am trying to add a link to the search results(which are just a name) so that if I click on one of the search results it goes to that link and views.chat_from_search is called where I handle all the logic of creating a chat and the rendering the page. I tried to add an event listener and then redirect to the new link (the code I tried to add the link is inside ** ** tags) but it results in this error Reverse for 'chatSearch' with arguments '('',)' not found. 1 pattern(s) tried: ['chat/search/(?P<chat_user_name>[^/]+)/\Z'] My code for the ajax search and where I create the div that holds the search results (and my failed attempt to add a link) is inside sendSearchData (which is below). the ajax returns an array of objects which only has a username attribute. This is the structure of the objects (I am creating this and appending it to a list which I return) indiv_user = { 'name': user.username, } const sendSearchData … -
Django get_or_create | update_or_create
I'm trying to implement get_or_create | update_or_create but I'm receiving the following error message: TypeError: Field 'id' expected a number but got <SimpleLazyObject: <User: admin>>. MORE DETAILS: File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/models/query.py", line 657, in get_or_create return self.get(**kwargs), False File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/models/query.py", line 496, in get raise self.model.DoesNotExist( wallet.models.SelectedWallet.DoesNotExist: SelectedWallet matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/models/fields/init.py", line 1988, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'SimpleLazyObject' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Volumes/HDD/Allan/django/venv/project_onefinance/onefinance/views.py", line 43, in select_wallet obj, created = SelectedWallet.objects.update_or_create( File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) class SelectedWallet(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) wallet = models.name = models.ForeignKey(Wallet, default=1, on_delete=models.CASCADE) created = models.DateField(verbose_name='Created', auto_now_add=True) modified = models.DateField(verbose_name='Modified', auto_now=True) created_by = models.ForeignKey('auth.User', related_name='selected_wallet_created_by', blank=True, null=True, default=None, on_delete=models.SET_DEFAULT) modified_by = models.ForeignKey('auth.User', related_name='selected_wallet_modified_by', blank=True, null=True, default=None, on_delete=models.SET_DEFAULT) class Meta: db_table = 'myapp_selected_wallet' ordering = ['wallet__name'] verbose_name = 'Selected_Wallet' verbose_name_plural = 'Selected_Wallets' def __str__(self): """String for representing … -
CORS is not activating my POST request. CSRF Cookie 'not set'
I am attempting to replicate this project using Vue instead of React. My goal is to authenticate a Django user from my Vue frontend. I am using the django-cors-headers package with the following settings. INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ ..., 'django.contrib.messages.middleware.MessageMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:9000" ] CSRF_TRUSTED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:9000" ] CORS_ALLOW_HEADERS = [ ... 'x-csrftoken', 'csrfmiddlewaretoken', 'credentials' ] CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False Right now, the initial request to obtain the CSRF cookie is working and seems to be returning a proper CSRF token which I can include in my request: const login = async () => { const cookie = getCookie("csrftoken"); console.log(cookie) const data = new FormData(); data.append("username", username); data.append("password", password); const headers = new Headers() headers.append('X-CSRFToken', cookie) const response = await fetch("http://localhost:8000/auth/", { method: "POST", // cookies: { // "X-CSRFToken": cookie ? cookie : "" // }, headers: headers, credentials: "same-origin", body: data, }); return response.ok; }; However, things still keep getting tripped up in the CORS process, because the request never makes it to the view: [21/May/2022 14:26:18] "OPTIONS /auth/ HTTP/1.1" 200 0 Forbidden (CSRF cookie not set.): /auth/ [21/May/2022 14:26:18] "POST … -
"detail": "Method \"GET\" not allowed." and JSON parse error Expecting property name enclosed in double quote
So I made a POST method but everytime I try to send a request I get this error. This is my method @api_view(['POST']) def CreateCustomService(request): x=CustomService.objects.create( Title=request.data['Title'], Description=request.data['Description'], PreConditions=request.data['PreConditions'], Duration=request.data['Duration'], HomeSampling=request.data['HomeSampling'], HomeSamplingPrice=request.data['HomeSamplingPrice'], Communication=request.data['Communication'], CommunicationPrice=request.data['CommunicationPrice'], ServicePrice=request.data['ServicePrice'], ) jsonobject=CustomServiceSerializer(x) return Response("DATA STORED") And this is the request that I am trying to send POST http://127.0.0.1:8000/Inventory/CreateCustomService HTTP/1.1 Content-Type: application/json { "Title": "TbGold", "Description": "Done to detect TB", "PreConditions": ["Drink water"], "Duration":"30 mins", "HomeSampling": "True", "HomeSamplingPrice": 200, "Communication": "True", "CommunicationPrice": 100, "ServicePrice": 18000, } This is my Model class CustomService(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Title = models.CharField(max_length=100) Description = models.TextField() PreConditions = ArrayField(models.CharField( max_length=100), blank=True, null=True) Duration = models.DurationField() HomeSampling = models.BooleanField(default=False) HomeSamplingPrice = models.IntegerField(default=0) Communication = models.BooleanField(default=False) CommunicationPrice = models.IntegerField(default=0) ServicePrice = models.IntegerField(default=0) def __str__(self): return self.Title Error when I open url Error when I send request through test.http file -
Django - uploading data to a model with pandas ".to_sql()" causes problems for the foreign key field
I identified a problem that ".select_related()" doesn't work if the table with a foreign key was uploaded using pandas. Uploading data the alternative way using a loop is not an option because the table is too big. Here's an example: Set up #Models class Magazine(models.Model): name = models.CharField(max_length=20, unique=True, primary_key=True) founded = models.CharField(max_length=20, unique=True, primary_key=True) def __str__(self): return self.name class Issue(models.Model): name = models.ForeignKey(Magazine, on_delete=models.CASCADE, db_column="name") week = models.CharField(max_length=10, unique=False) def __str__(self): return self.week #Admin from mainsite.models import Magazine, Issue admin.site.register(Magazine) admin.site.register(Issue) #Migrated python ../manage.py makemigrations python ../manage.py migrate Fill first table import os import sys import pandas as pd import django sys.path.append(os.path.dirname(os.getcwd())) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') #configures the settings for the project. Need to do this before manipulating models django.setup() from mainsite.models import Magazine, Issue magazineNames = ['journal science', 'naughty mag', 'funny cartoons', 'comic fans', 'lawncare', 'NEVERISSUED'] magazineFounded = ['1901', '1995', '2005', '2011', '1993', '1900'] Magazine.objects.bulk_create([Magazine(name=i, founded=j) for i,j in zip(magazineNames, magazineFounded)]) Fill second table 1.) THIS WORKS for Issue.objects.select_related("name"), but uses a loop. It works because I can specify the names being a Magazine() instance. issueNames = ['journal science', 'journal science', 'naughty mag', 'funny cartoons', 'comic fans', 'lawncare', 'lawncare'] issueWeeks = ['1', '2', '3', '4', '5', '6', '7'] Issue.objects.bulk_create([Issue(name=Magazine(name=i), week=j) … -
Invalid signature Django rest framework simple_jwt token
Hiii i am faced with a problem of invalid token. I am testing simple_jwt with django rest framework When i log on the endpoint of TokenObtainPairView i receive refresh and access token but when i verify that token on jwt.io, I have invalid signature. It is obvious that my simple_jwt deliver me the wrong token. I don't know where the problem come from. After research I am thinking may be I need to Change 'SIGNING_KEY': SECRET_KEY,but I don't know how. I mentioned that I am using the pure TokenObtainPairView whithout any customization. If someone can help me. I am new here