Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Max occurrences of a foreign key inside query
I'm trying to get an item with the most occurrences of a foreign key (votes), inside of a queryset (Questions, Choices). I.E. I need to get the most popular vote to set the 'winner' attribute in the JsonResponse. Any help on how I can figure this out? Here is my view. allchoices = [{ 'id':i.id, 'question':i.question.id, 'choice_text':i.choice_text, 'votes':i.voter_set.all().count() } for i in poll_choices] return JsonResponse({ "votes":choice.voter_set.all().count(), 'winner':True, 'success':True, 'allchoices':allchoices },safe=False,) These are my models: class Voter(models.Model): # Authentication of anonymous users choice = models.ForeignKey('PollChoice', on_delete=models.CASCADE) question = models.ForeignKey('PollQuestion', on_delete=models.CASCADE) class PollChoice(models.Model): question = models.ForeignKey('PollQuestion', on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) def __str__(self): return self.choice_text class PollQuestion(models.Model): question = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) creator = models.ForeignKey('poll_creator',/\ on_delete=models.CASCADE, null=False, blank=False) uuid = ShortUUIDField(length=8, max_length=12) def poll_choices(self): return self.pollchoice_set.all().annotate(voters=/\ models.Count(models.F('voter'))).order_by('-voters') def choices(self): return self.pollchoice_set.all() def __str__(self): return f'{self.question}' -
Django - how to see ALL column results of a join using .select_related()?
I am having difficulty seeing the foreign table's field from a resulting join using select_related(). Any idea what my issue is here? Define 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 Register from mainsite.models import Magazine, Issue admin.site.register(Magazine) admin.site.register(Issue) Migrate python ../manage.py makemigrations python ../manage.py migrate Loading data import os import sys import django sys.path.append(os.path.dirname(os.getcwd())) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mags.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)]) 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) for i,j in zip(issueNames, issueWeeks)]) #QUERY Issue.objects.select_related("name").values_list() <QuerySet [(1, 'journal science', '1'), (2, 'journal science', '2'), (3, 'naughty mag', '3'), (4, 'funny cartoons', '4'), (5, 'comic fans', '5'), (6, 'lawncare', '6'), (7, 'lawncare', '7')]> -
AttributeError at /app/ 'numpy.ndarray' object has no attribute 'read'
I am making a wep app for face recognition by django and face_recogntion api, I don't how to solve this error from django.http import HttpResponse from django.shortcuts import redirect, render from .models import * import face_recognition import cv2 import urllib.request import numpy as np import dlib def Home(request): print(f'request method is {request.method}') if(request.method=='GET'): return render(request, "app.html") elif(request.method=='POST'): print(f'printing req body {request.POST["imageURL"]}') imageURL = urllib.request.urlopen(request.POST["imageURL"]) imageURL = face_recognition.load_image_file(imageURL) image = face_recognition.load_image_file(imageURL) image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB) imgLoc = face_recognition.face_locations(image); print(f'Image imagLoc {imgLoc}') cv2.imshow(image) cv2.waitKey(3000) return redirect('/app/') I am asking question on stackoverflow for the first time so sorry for any mistakes. -
How to check if there was a call of service function from APIView?
I'm trying to implement the service layer in my API. Now im trying to test create function with unittest lib. I dont really figure out, how to code it right. views.py class AuthorListApi(APIView): class InputSerializer(serializers.Serializer): name = serializers.CharField() def post(self, request): serializer = self.InputSerializer(data=request.data) serializer.is_valid(raise_exception=True) create_author(**serializer.validated_data) return Response(serializer.data, status=status.HTTP_201_CREATED) services.py def create_author(name: str) -> Author: """ Create a Author model object. """ author = Author(name=name) author.full_clean() author.save() return author test_view.py @mock.patch('books.views.AuthorListApi.create_author') def test_view_calls_service(self, service_mock): self.client.post(self.url, data=self.data) service_mock.assert_called_once_with(**self.data) Assertion error is: AttributeError: <class 'books.views.AuthorListApi'> does not have the attribute 'create_author' -
unsupported operand type(s) for -: 'DateField' and 'DateField'
I am working on creating a contract model with Django and I came cross on how to get the time duration from the start_date to the end_date?? class Contract(models.Model): name = models.CharField(max_length=100) price = models.IntegerField(max_length=10) start_date = models.DateField(auto_now_add=True) end_date = models.DateField(auto_now_add=True) duration = models.IntegerField(end_date - start_date) # how get the duration by hours created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name -
I cant figure out how to post angular's input form data in database (mongodb) using Django Rest API
I cant figure out how to post angular's input form data in database (mongodb) using Django Rest API. There are not enough tutorials and documentations on the internet regarding the set of django and angular along with mongodb. or maybe im tunnel visioned now. If anyone has a link which might solve my problem it would be great. Below is my angular's html file where you can see the form <form (ngSubmit)="onSubmit()"> <div class="form-group"> <label for="InputAttackTitle">Attack Title</label> <input ngModel type="text" class="form-control" name="AttackTitle" id="InputAttackTitle" placeholder="Enter Attack Title"> </div> <div class="form-group"> <label for="InputAttackDescripton">Attack Description</label> <textarea ngModel class="form-control" name="AttackDescription" id="InputAttackDescripton" placeholder="Enter Attack Description" ></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> <br> </div> Here you can see component.ts file export class IconsComponent implements OnInit { form: FormGroup; constructor(config: NgbModalConfig, private modalService: NgbModal,private http:HttpClient, public fb:FormBuilder) { config.backdrop = 'static'; config.keyboard = false; this.form = this.fb.group({ AttackTitle: [''], AttackDescription: [null] }) } AttackTitle:any; AttackDescription:any; onSubmit(){ var formData:any = new FormData(); formData.append("AttackTitle",this.form.get('AttackTitle').value); formData.append("AttackDescription",this.form.get('AttackDescription').value); this.http.post('http://127.0.0.1:8000/attackinfo', formData).subscribe( (response) => { return console.log(response); }, (error) => console.log(error) ) Below is the django's models class class AttackInfo(models.Model): AttackTitle=models.CharField(max_length=70, blank=False) AttackDescription = models.TextField(default='',blank=False) And Below is the view file @csrf_exempt def AttackInfoAPI(request,id=0): if request.method=='GET': attackinfo = AttackInfo.objects.all() attackinfo_serializer=AttackInfoSerializer(attackinfo,many=True) return JsonResponse(attackinfo_serializer.data,safe=False) elif …