Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to get image field of ForeignKey query elements?
I have the following code at views.py to sort TvShows by there latest released episode (release_date) within 90 days: def tv_show_by_set_just_released(request): latest_episodes = TvShows.objects.filter(episode_show_relation__release_date__gte=now() - datetime.timedelta(days=90)) ... For each element found, I now also want to display a cover. But the cover is located at a different table and I don't really know how to pull it out probably in this query context. In the end I want to display the very first TvShowSeasons.cover for each element of my query from above. Is it somehow possible to marry these two elements, latest_episodes and TvShowSeasons.cover to display them properly at a template? Please also see models.py class TvShows(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.TextField(verbose_name=_("Title"), blank=False, null=True, editable=False, max_length=255) genre_relation = models.ManyToManyField(through='GenreTvShow', to='Genre') date_added = models.DateTimeField(auto_now_add=True, blank=True, verbose_name=_("Date Added")) class TvShowSeasons(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) show = models.ForeignKey(TvShows, on_delete=models.CASCADE, related_name='season_show_relation') season_number = models.IntegerField(verbose_name=_("Season Number"), blank=True, null=True, editable=False) cover = models.ImageField(verbose_name=_("Cover"), blank=True, null=True, upload_to=get_file_path_images) cover_tn = models.ImageField(verbose_name=_("Cover Thumbnail"), blank=True, null=True, upload_to=get_file_path_images) total_tracks = models.IntegerField(verbose_name=_("Total Tracks #"), blank=True, null=True) rating = models.CharField(verbose_name=_("Rating"), blank=True, null=True, editable=False, max_length=255) copyright = models.TextField(verbose_name=_("Copyright"), blank=True, null=True, editable=False, max_length=255) date_added = models.DateTimeField(auto_now_add=True, blank=True, verbose_name=_("Date Added")) Thanks in advance -
Problem with Django Tests and Trigram Similarity
I have a Django application that executes a full-text-search on a database. The view that executes this query is my search_view (I'm ommiting some parts for the sake of simplicity). It just retrieve the results of the search on my Post model and send to the template: def search_view(request): posts = m.Post.objects.all() query = request.GET.get('q') search_query = SearchQuery(query, config='english') qs = Post.objects.annotate( rank=SearchRank(F('vector_column'), search_query) + TrigramSimilarity('post_title', query) ).filter(rank__gte=0.15).order_by('-rank'), 15 ) context = { results = qs } return render(request, 'core/search.html', context) The application is working just fine. The problem is with a test I created. Here is my tests.py: class SearchViewTests(TestCase): def test_search_without_results(self): """ If the user's query did not retrieve anything show him a message informing that """ response = self.client.get(reverse('core:search') + '?q=eksjeispowjskdjies') self.assertEqual(response.status_code, 200) self.assertContains(response.content, "We didn\'t find anything on our database. We\'re sorry") This test raises an ProgrammingError exception: django.db.utils.ProgrammingError: function similarity(character varying, unknown) does not exist LINE 1: ...plainto_tsquery('english'::regconfig, 'eksjeispowjskdjies')) + SIMILARITY... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. I understand very well this exception, 'cause I got it sometimes. The SIMILARITY function in Postgres accepts two arguments, and both need to be of … -
How to generate dynamic rows in page based on the response of the js request? (Django Template / HTML)
Is this possible to append the rows with data in an HTML table as a response of the JavaScript request without doing a page postback? Django: 3.1.7 I want to write a seprate HTML file (Like a file we can use with include tag) for the code so I don't have to append the html of entire table in the HTML string. For now I am appending the HTML by converting to the string concatination. Note: Need a solution without page postback. function GetCollection(myId) { var Urlgetallcom = "/sc/GetCollection/" + myId ; // alert(Urlgetallcom); $.ajax({ url: Urlgetallcom, // the endpoint type: "GET", // http method data: { Id: myId }, // handle a successful response success: function (json1) { var Collection = json1; console.log(Collection); for (var i = 0; i < Collection.length; i++) { $('#Comments_Div').append( '<div class="mt-comments" style="border-bottom: 1px solid #eef1f5">' + '<div class="mt-comment">' + '<div class="mt-comment-info">' + '<div class="mt-list-item done mt-comment-info" onclick="ShowCommentInfoWindow(' + Collection[i].f.latitude + ',' + Collection[i].f.longitude + ',\'' + Collection[i].f.commentDetails + '\')">' + '<div id="' + Collection[i].pk + '" class="mt-comment-details" style="display:block">' + '<span>' + Collection[i].f.commentDetails + ' </span>' + '<div class="mt-comment-actions ">' + '</div>' + '<br />' + '</div>' + '<div class="mt-comment-body">' + '<div class="mt-comment-details">' + '<span … -
Django form how do I make 2 drop box search result depending on how first one is selected?
I am trying to make form consist of two dropbox using query from model. so first dropbox get all distinct store name from Menu table and that part, I got it working. However, how do I make second dropbox filter result depending on what I pick on first dropbox? For example, If I pick store A for first dropbox, it shows sa, sb, sc as menu name and if I pick store B for first dropbox, it shows ma, mb, mc as menu name and so on. Also, second dropbox can have 2 filter condition like storename + day. How can I accomplish this? forms.py class MenuForm(forms.ModelForm): store_name = forms.ModelChoiceField(queryset=Menu.objects.distinct('store_name')) menu_name = forms.ModelChoiceField(queryset=Menu.objects.filter(??)) class Meta: model = Menu fields = {'store_name', 'menu_name'} -
How to get the value being referenced in django?
Here I need to get the student_id in the values. I have defined s_id but if values() is called it does not show. FeeSection.objects.get(id=1).section.sectionstudent_set.annotate(s_id=F('student__id')).get(student__id=1).qouta.feeqouta_set.all().values() This query returns: <QuerySet [{'id': 1, 'qouta_id': 2, 'type_id': 1, 'amount': Decimal('200.00')}, {'id': 2, 'qouta_id': 2, 'type_id': 2, 'amount': Decimal('10.00')}]> what I need is: 's_id':1 <QuerySet [{'id': 1,'s_id':1, 'qouta_id': 2, 'type_id': 1, 'amount': Decimal('200.00')}, {'id': 2, 's_id':1,'qouta_id': 2, 'type_id': 2, 'amount': Decimal('10.00')}]> -
Final Test: Set up Django app for production
I finalized my first django app and uploaded it to the webhosting service and I'm having trouble with that. However, I am not sure that I did not make any mistake setting it up before the upload. So my question is: Can I run my virenv locally again and should my django app still work locally? I try to locate where my mistake is and want to make sure, that it is set up correctly. If I run my virenv I get this error "This site can’t provide a secure connection". Any help? That would be great! -
Django how to sort objects by there foregein key relation?
at my Django application I want to display some TV-Show entries. Currently I want to build a filter for TV-Shows sorted by there latest released episodes. But I'm not sure how the query has to look like. This is how I pull episodes for the last 90 days def tv_show_by_set_just_released(request): latest_episodes = TvShowEpisodes.objects.filter( release_date__lte=datetime.datetime.today(), release_date__gt=datetime.datetime.today()-datetime.timedelta(days=90)).order_by('-release_date') But how can I reference the actual TV-Show of the Episode now? I want to Sort the Tv-Shows by there latest added episode (release_date) please have a look a my modeling: class TvShows(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.TextField(verbose_name=_("Title"), blank=False, null=True, editable=False, max_length=255) genre_relation = models.ManyToManyField(through='GenreTvShow', to='Genre') date_added = models.DateTimeField(auto_now_add=True, blank=True, verbose_name=_("Date Added")) class TvShowEpisodes(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) duration = models.FloatField(verbose_name=_("Duration"), blank=True, null=True, editable=False, max_length=255) title = models.TextField(verbose_name=_("Title"), blank=False, null=True, editable=False, max_length=255) release_date = models.DateField(verbose_name=_("Release Date"), blank=True, null=True, editable=False) track = models.IntegerField(verbose_name=_("Track #"), blank=True, null=True) show = models.ForeignKey(TvShows, on_delete=models.CASCADE, related_name='episode_show_relation') season = models.ForeignKey(TvShowSeasons, on_delete=models.CASCADE, related_name='episode_season_relation') episode_id = models.CharField(verbose_name=_("Episode ID"), max_length=255, blank=True, null=True, editable=False) episode_sort = models.IntegerField(verbose_name=_("Episode Number"), blank=True, null=True, editable=False) synopsis = models.TextField(verbose_name=_("Synopsis"), blank=True, null=True, editable=False, max_length=255) date_added = models.DateTimeField(auto_now_add=True, blank=True, verbose_name=_("Date Added")) -
failed to build wheel for psycopg2?
Hi after i re write my source code and cloning my website from heroku i get this error LOGS : psycopg/psycopgmodule.c: In function ‘psyco_is_main_interp’: psycopg/psycopgmodule.c:689:18: error: dereferencing pointer to incomplete type ‘PyInterpreterState’ {aka ‘struct _is’} 689 | while (interp->next) | ^~ error: command '/usr/bin/gcc' failed with exit code 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-t_xxbtyy/psycopg2-binary/setup.py'"'"'; __file__='"'"'/tmp/pip-install-t_xxbtyy/psycopg2-binary/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-cevcg2_6/install-record.txt --single-version-externally-managed --compile --install-headers /app/.heroku/python/include/python3.9/psycopg2-binary Check the logs for full command output. ! Push rejected, failed to compile Python app. ! Push failed Any fixes ?? Thanks -
ModuleNotFoundError when mocking while using pytest
I'm using pytest for writing unit tests in my django project. But when I want to mock a method in following code: @patch('smspanel.services.sms_panel_info_service.get_buinessman_sms_panel') def test_send_plain_sms_success(mocker, businessman_with_customer_tuple): mocker.return_value = SMSPanelInfo() customer_ids = list(map(lambda e: e.id, businessman_with_customer_tuple[1])) businessman = businessman_with_customer_tuple[0] message = 'message' result = services.send_plain_sms(user=businessman, customer_ids=customer_ids, message=message) smsq = SMSMessage.objects.filter( businessman=businessman, message_type=SMSMessage.TYPE_PLAIN, status=SMSMessage.STATUS_PENDING, message=message) assert smsq.exists() sms = smsq.first() receivers_count = SMSMessageReceivers.objects.filter(sms_message=sms, customer__id__in=customer_ids).count() assert receivers_count == len(customer_ids) I get following error: thing = <module 'smspanel.services' from 'C:\\Users\\Pouya\\Desktop\\programs\\python\\marketpine-backend\\smspanel\\services.py'> comp = 'sms_panel_info_service' import_path = 'smspanel.services.sms_panel_info_service' def _dot_lookup(thing, comp, import_path): try: return getattr(thing, comp) except AttributeError: > __import__(import_path) E ModuleNotFoundError: No module named 'smspanel.services.sms_panel_info_service'; 'smspanel.services' is not a package c:\users\pouya\anaconda3\lib\unittest\mock.py:1085: ModuleNotFoundError My test file is locate in smspanel/tests/test_services.py. -
Rendering database objects in Django
This is a basic question but I can't figure out what I'm doing wrong... I'm trying to render a detail view in my django site, but my calls to get the object are just failing or else not rendering. Here is what I have: views.py from django.template import loader from django.views.generic.base import TemplateView from django.http import HttpResponse from .models import user_profile def detail(request, content_id): template = loader.get_template('profiles/detail.html') profile = user_profile.objects.get(pk=content_id) context = {'profile': profile} return HttpResponse(template.render(context, request)) Within the template, I have simply been testing the calls using: <h1>{{ profile }}</h1> <h1>{{ profile.name }}</h1> This is my first time rendering this from scratch, I know I'm missing something dumb I just can't sort it. Thank you! edit This current setup receives a 500 error. Without the get(pk) statement it loads, but doesn't show the variables, just the rest of my HTML. -
postgresql psycopg2 django docker setup just cannot get it to connect to postgres at all
** Django==3.2.7 psycopg2==2.9.1 python=3.9.7(using this setup** for the hell of me i cannot get postgress to setup correctly iam very new to all this but so far this is the 4th hurdle ive hit but 2 i am having to seek help for i just cannot seem to setup postgres correctly ** my setup files ** ** docker compose ** version: "3.8" x-service-volumes: &service-volumes - ./:/app/:rw,cached x-database-variables: &database-variables POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_USER: postgres x-app-variables: &app-variables <<: *database-variables POSTGRES_HOST: postgres services: website: tty: true image: ashleytaylors_websites:latest command: python manage.py runserver 0.0.0.0:8000 volumes: *service-volumes environment: *app-variables depends_on: - db_migrate ports: - "8000:8000" db_migrate: image: ashleytaylors_websites:latest command: python manage.py migrate volumes: *service-volumes environment: *app-variables depends_on: - postgres postgres: image: postgres ports: - "5432" environment: - db-data:/var/lib/postgresql/data ** docker ** FROM python:3.9.7-slim-buster as production ENV PYTHONBUFFERED=1 WORKDIR /app/ RUN apt-get update && \ apt-get install -y \ bash \ build-essential \ gcc \ libffi-dev \ musl-dev \ openssl \ postgresql \ libpq-dev COPY requirements/prod.txt ./requirements/prod.txt RUN pip install --user -r ./requirements/prod.txt COPY manage.py .manage.py #COPY setup.cfg ./setup.cfg COPY ashleytaylors_website ./ashleytaylors_website EXPOSE 8000 FROM production as development COPY requirements/dev.txt ./requirements/dev.txt RUN pip install --user -r ./requirements/dev.txt COPY . . ** make file ** build: … -
Editing a Django package inside a docker container
In my Django docker file, I'm using the pip install -r requirements.txt file. Through this, I'm downloading a certain package but that package needs to be edited once installed. On my local computer, I can just go to the site-packages and edit it but I need to know where can I find it inside a container? Or is it even possible? I'm fairly new to docker so please help me out. -
Django import-export foregin key
I am trying to import data with a foreign key following the guide from the Django import-export library (foreign key widget). But I am getting the following error , I have tried to add an additional column with the header name id but I still get the same error. Errors Line number: 1 - 'id' None, 46, 19, LSD Traceback (most recent call last): File "/var/www/vfsc-env/lib/python3.6/site-packages/import_export/resources.py", line 635, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "/var/www/vfsc-env/lib/python3.6/site-packages/import_export/resources.py", line 330, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "/var/www/vfsc-env/lib/python3.6/site-packages/import_export/resources.py", line 318, in get_instance self.fields[f] for f in self.get_import_id_fields() File "/var/www/vfsc-env/lib/python3.6/site-packages/import_export/resources.py", line 318, in <listcomp> self.fields[f] for f in self.get_import_id_fields() KeyError: 'id' Here is what I did. class Clockin_Users(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. userid = models.IntegerField(db_column='UserID', unique=True) # Field name made lowercase. username = models.CharField(db_column='UserName', max_length=20, blank=True, facecount = models.IntegerField(db_column='FaceCount', blank=True, null=True) # Field name made lowercase. userid9 = models.CharField(db_column='UserID9', max_length=10, blank=True, null=True) # Field name made lowercase. depid = models.IntegerField(db_column='DepID', blank=True, null=True) # Field name made lowercase. empno = models.CharField(db_column='EMPNO', max_length=50, blank=True, null=True) # Field name made lowercase. def __str__(self): return self.name class Clockin_Department(models.Model): clockinusers = models.ForeignKey(Clockin_Users, on_delete=models.CASCADE) depid = models.AutoField(db_column='DepID', primary_key=True) # Field name made lowercase. … -
How to pass a javascript variable inside a url get in Django
I would like to send a radio_id to my view, Now I'm currently trying to get the ID of my radio by javascript, but I don't know how to pass it by get method inside my url and send to the view: html: <a href="{% url 'maintenance_issue_fix' %}?radio_id=checked"> <img src="{% static 'images/maintenance_list.jpg' %}"> </a> {% for list in issue_list %} <tr style="text-transform: capitalize;"> <td style="text-align:center;"> <input name="radio_id" type="radio" id="radio_id" value="{{list.id}}"> </td> <\tr> {% endfor %} javascript: <script> $(function(){ $('input[type="radio"]').click(function(){ if ($(this).is(':checked')) { var checked = $(this).val(); console.log(checked); } }); }); </script> views: def maintenance_issue_fix(request): if request.method == 'GET': issue_id = request.GET.get('radio_id') print(issue_id) When I try to get the javascript var to pass inside the url, occur the follow error: ValueError at /maintenance/maintenance_issue_fix/ invalid literal for int() with base 10: 'checked' How to do it? -
django.core.exceptions.FieldError: Unknown field(s) in ModelForm
After adding a ModelForm and specifying the fields, I get this error when I try to makemigrations. New to django and programming in general, so probably something dumb. django.core.exceptions.FieldError: Unknown field(s) (handling_time, holding_time, encounter_date, crate_time) specified for Encounter Models.py: from django.db import models from django.conf import settings import datetime class Animal(models.Model): Name = models.CharField(max_length=64, unique=True) Inactive_Date = models.DateField(null=True, default=None, blank=True) ANIMAL_TYPE_CHOICES = [ ('Alligator', 'Alligator'), ('Alpaca', 'Alpaca'), ('Anteater', 'Anteater'), ('Armadillo', 'Armadillo'), ('Cat', 'Cat'), ('Chicken', 'Chicken'), ('Chinchilla', 'Chinchilla'), ('Donkey', 'Donkey'), ('Frog', 'Frog'), ('Goat', 'Goat'), ('Horse', 'Horse'), ('Insect', 'Insect'), ('Lizard', 'Lizard'), ('Millipede', 'Millipede'), ('Owl', 'Owl'), ('Penguin', 'Penguin'), ('Pig', 'Pig'), ('Snake', 'Snake'), ('Spider', 'Spider'), ('Tenrec', 'Tenrec'), ('Turtle', 'Turtle'), ] Animal_Type = models.CharField( max_length=32, choices=ANIMAL_TYPE_CHOICES, default='Cassowary') Comments = models.CharField(max_length=255) def __str__(self) -> str: return ('Animal: ' + self.Name) def delete(self): self.Inactive_Date = datetime.datetime.today() self.save() class Encounter(models.Model): encounter_date = models.DateField animal = models.ForeignKey(Animal,null = True, on_delete=models.SET_NULL) user = models.ForeignKey(settings.AUTH_USER_MODEL,null = True, on_delete=models.SET_NULL) handling_time = models.BigIntegerField crate_time = models.BigIntegerField holding_time = models.BigIntegerField comments = models.CharField(max_length=255) def __str__(self) -> str: return ('Encounter: ' + self.User.username + '/' + self.Animal.Name) Forms.py: from django.forms import ModelForm from encounters.models import Animal, Encounter import datetime class Open_Encounter_Form(ModelForm): class Meta: model = Encounter fields = ['encounter_date', 'user','animal','handling_time','crate_time','holding_time','comments'] Views.py: from encounters.models import Animal, … -
Configure Nginx with Vue.js, Django Rest Framework as backend and /api/ on same server?
I am in a process of deploying my newly developed e-commerce to a Ubuntu server that I have. I have already set up Nginx for Frontend and for Backend. The whole application is working fine. The only problem is DRF API that doesn't get anything from the backend (it doesn't send emails, users can't register). All of that gets error 500. It seems to me that I still need to add /api/ to my Nginx configuration, but when I do that the whole app goes down. Could someone explain the best way to set this up in "sites-available"? Thank you! Here is my Sites-Available for Backend: upstream perulab_app_server { server unix:/webapps/perulab/venv/run/gunicorn.sock fail_timeout=0; } server { listen 8000; server_name 172.16.7.52; client_max_body_size 4G; location /static/ { root /webapps/perulab/web-backend; } location /media/ { root /webapps/perulab/web-backend; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://perulab_app_server; } } } And this is my Sites-Available for Backend: server { listen 8010; listen [::]:8010; server_name _; charset utf-8; root /webapps/perulab/web-frontend/dist; index index.html index.htm; location / { try_files $uri /index.html; } } When I use it the way it is right now, console prints this error: GET http://172.16.7.52:8000/api/v1/get-user-details/ 500 … -
Can't deploy Python Django Flask app to Heroku?
I keep trying to deploy my app and keep getting the following error: at=error code=H10 desc="App crashed" method=GET path="/" host=binary-background-generator.herokuapp.com request_id=9b6e3182-d90a-41ca-9a11-01da97047792 fwd="66.181.213.97" dyno= connect= service= status=503 bytes= protocol=https Procfile: web: gunicorn binary-background-generator.wsgi requirements.txt: aiohttp==3.7.4.post0 async-timeout==3.0.1 attrs==21.2.0 blinker==1.4 chardet==4.0.0 click==8.0.1 colorama==0.4.4 Cython==0.29.24 Flask==2.0.1 idna==3.2 itsdangerous==2.0.1 Jinja2==3.0.1 MarkupSafe==2.0.1 multidict==5.1.0 Pillow==8.3.2 pyudorandom==1.0.0 Send2Trash==1.8.0 typing-extensions==3.10.0.2 Werkzeug==2.0.1 yarl==1.6.3 settings.py: # Configure Django App for Heroku. import django_heroku django_heroku.settings(locals()) Folder and file structure: Screenshot from VS Code -
Filter django query set based on whether a foreign key relationship exists
So I have two models. class Post(models.Model): id = models.OidField('object id', unique=True) class ArchivedFlag(models.Model): commit = models.ForeignKey(Commit, on_delete=models.CASCADE, related_name='archived_flag') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='archives') In views.py I have generated a list of all posts by some criteria, 'plist'. I want to filter the list based on posts that DO NOT have an ArchivedFlag object relationship. Basically the ArchivedFlag model is a tool hide certain posts. How can I do this? I'm trying to do something along the lines of plist = plist.exclude(models.ForeignKey.commit exists) but I'm unsure of the exact syntax. -
Firebase admin FCM error: Exactly one of topic, token or condition is required
I have integrated fcm-django==1.0.5 in my project, with firebase-admin==5.0.2 sending push notifications by user_id is working perfectly, on the other hand sending messages to the topic is giving this error: File "project_name/.venv/lib/python3.8/site-packages/firebase_admin/_messaging_encoder.py", line 681, in default raise ValueError('Exactly one of token, topic or condition must be specified.') ValueError: Exactly one of token, topic or condition must be specified. I tried to resolve it and came to this answer, which says "Avoid sending empty fcm token to Firebase. When we send an empty fcm token, Firebase gives us the below error" for that I even listed by registrations token, they are not empty. from fcm_django.models import FCMDevice >>> list(FCMDevice.objects.all().values('registration_id')) [{'registration_id': 'dVA1234XtoEdxk0i9J6srWM:APA91bHM3EBHkLYTIR2wAkop28Kn4RmI0HouifDazT7zCU5MXDIvrbVvzpZC3YiKDoDR9Wj-2DJ-d4_yPIhSfe_XU7Ac8QB2PXcOFOxwLRp3AGCLM18NVQz_N5NLQqFmIaArB'}, {'registration_id': 'ekpeG8fKTzWKANLA4UtIDV:APA91bFKkc32o4ke85iMfMqOIylY9zo599eTBHJNlWFxUA52PtAFBC3RlAIPTZ5P4578-OY6Iy1jGjGh3irgcGnXC3f6YHN3nrsrvU7N7A2VVssN9uPLWM55N7Kn5EVk8oyz'}] I have put up a print statement in the virtual environment to debug this issue, and in the output, I can see that both token, and title is getting passed, even though I am not sending the token, but it is taking it automatically. My code to send user messages to topic: def send_user_messages_to_topic(topic_name,title=None,body=None,image=None,data=None, extra_notification_kwargs=None,api_key=None,**kwargs): # print(topic_name, title, body, data, image) # Subscribing # FCMDevice.objects.all().handle_topic_subscription(True, topic=topic_name) # Sending messages to topic result = FCMDevice.objects.all().send_message( Message( notification=Notification(title=title,body=body,image=image), topic=topic_name, data=data, ) ) I have recently upgraded to fcm-django--1.0.5, is this … -
django is not reading javascript form-data files
so when I try to send files to Django server it raises ton of errors: Traceback (most recent call last): File "C:\Users\TM\AppData\Local\Programs\Python\Python39\lib\site-packages\PIL\Image.py", line 2972, in open fp.seek(0) AttributeError: 'NoneType' object has no attribute 'seek' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\TM\AppData\Local\Programs\Python\Python39\lib\site-packages\asgiref\sync.py", line 482, in thread_handler raise exc_info[1] File "C:\Users\TM\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 38, in inner response = await get_response(request) File "C:\Users\TM\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 233, in _get_response_async response = await wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\TM\AppData\Local\Programs\Python\Python39\lib\site-packages\asgiref\sync.py", line 444, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "C:\Users\TM\AppData\Local\Programs\Python\Python39\lib\asyncio\tasks.py", line 442, in wait_for return await fut File "C:\Users\TM\AppData\Local\Programs\Python\Python39\lib\concurrent\futures\thread.py", line 52, in run result = self.fn(*self.args, **self.kwargs) File "C:\Users\TM\AppData\Local\Programs\Python\Python39\lib\site-packages\asgiref\sync.py", line 486, in thread_handler return func(*args, **kwargs) File "C:\Users\TM\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\TM\سطح المكتب\New folder\web\views.py", line 86, in makeAccountApi IMG=RESIZE(Image) File "C:\Users\TM\سطح المكتب\New folder\web\helpers.py", line 110, in RESIZE im = Image.open(Img) File "C:\Users\TM\AppData\Local\Programs\Python\Python39\lib\site-packages\PIL\Image.py", line 2974, in open fp = io.BytesIO(fp.read()) AttributeError: 'NoneType' object has no attribute 'read' when I print request.body and request files and request POST it prints: b'[object FormData]' <MultiValueDict: {}> <QueryDict: {}> when I print file it console.log: C:\fakepath\download.jpg and after it it console.log: request.js:62 [Deprecation] Synchronous XMLHttpRequest on the main thread … -
Django Customize PasswordResetView: __init__() missing 1 required positional argument: 'user'
I try to customize Django PasswordResetView in order to validate the length of the password but I get this error: TypeError at /accounts/password_reset/ __init__() missing 1 required positional argument: 'user' views.py from django.contrib.auth import views as auth_views class PasswordResetView(auth_views.PasswordResetView): form_class = PasswordResetForm template_name = "accounts/users/password_reset.html" email_template_name = "accounts/users/password_reset_email.html" subject_template_name = "accounts/users/password_reset_subject.txt" from_email = settings.EMAIL_HOST_USER success_url = reverse_lazy("accounts_password_reset_done") forms.py class PasswordResetForm(SetPasswordForm): def clean_new_password1(self): password = self.cleaned_data.get("new_password1") if len(password) < 12: raise forms.ValidationError("Password must be at least 12 characters.") return password It is obvious that SetPasswordForm class needs to be taken user upon initialization: class SetPasswordForm(forms.Form): . . . def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) I do not find a clear solution to how to pass user data to PasswordResetView and PasswordResetForm because user data is used upon PasswordResetForm instance creation. -
How To Fix Django ValueError: Field 'persons' expected a number but got ''
I Don't Know How To Fix This Error I Run The Command python manange.py makemigrations, python manage.py migrate But it's is not fixing. i am creating ordering form I added a IntField it's called person it's means how many number of persons you need? There is my forms.py: class LeadModelForm(forms.ModelForm): class Meta: model = Lead fields = ( "first_name", "last_name", "email", "phone_number", "foodlancer", "location", "persons", ) This my models.py: class Lead(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) organisation = models.ForeignKey(UserProfile,null=True, blank=True, on_delete=models.SET_NULL) location = models.CharField(max_length=250) foodlancer = models.ForeignKey("Agent",null=True, blank=True, on_delete=models.SET_NULL) catagory = models.ForeignKey("Catagory", related_name="leads" ,null=True, blank=True, on_delete=models.SET_NULL) date_added = models.DateTimeField(auto_now_add=True) phone_number = models.CharField(max_length=20) email = models.EmailField() persons = models.IntegerField(max_length=30) def __str__(self): return f"{self.first_name} {self.last_name}" class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) organisation = models.ForeignKey(UserProfile, on_delete=models.CASCADE) def __str__(self): return self.user.email If I Even Remove Persons Var I Get Same Error I Hope You Can Help Me Thanks <3 -
Django - How can add multiple forms according to input enter number or with click add more button
I have an input field where the will customer add a number for buy membership then will get forms according to numbers 1,2, or 5 then will show 1,2, or 5 forms with input fields in which will add data. How can add this type of functionality? Because I'm a beginner in python Django. Thanks For example: customer will come to the site and click on buy membership the first page will How many Memberships do you want to buy? ==> input Field in which add 1,2, or 5 based on how many members enter a show a page to collect information of members 3rd step collect customer/parent information -
Can I use a keyword argument from another app to connect the URLs of two different aps together?
I'm currently developing an application using the Django REST Framework and Vue in which people can monitor a device's signal outputs. For some context, I created a custom user model with a unique UUID4 user ID that would be assigned to each user. This model is in a Django app that I called accounts. Similarly, I have the user's data recording sessions and associated data in separate models in an app that I call studio. My problem is this: I realized I would like to associate the data collected to the user's account and whatever session they wish to tie this data to. However, since these models are in different Django apps, I am getting the error get() got an unexpected keyword argument 'user_id' when I try to tie the URLs of the account and studio apps together. Relevant code snippets are below: models.py (in studio) from django.db import models class Session(models.Model): user_id = models.ForeignKey( 'accounts.CustomUser', on_delete=models.CASCADE) session_id = models.CharField(max_length=100, unique=True, blank=False) def get_associated_user_id(self): return (f'{self.user_id}') def __str__(self): return (f"Session ID: {self.session_id}") class LaserData(models.Model): user_id = models.ForeignKey( 'accounts.CustomUser', on_delete=models.CASCADE) session_id = models.ForeignKey('Session', on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) laser_current = models.DecimalField(max_digits=8, decimal_places=3) laser_temperature = models.DecimalField(max_digits=8, decimal_places=3) laser_temperature_set = models.DecimalField(max_digits=8, decimal_places=3) tec_voltage_positive = … -
I can't filter get data from my url to save into
I want to save transaction and increase the number of votes base on the status which i get from a response url nd redirect user to success page. But all transactions goes to error page rather even if they are successful. I want to check from the URL if the status== 'Approved' then i save the model and update the the model with new votes and redirect user to success page. this is the url response i get http://127.0.0.1:8000/process-payment/robert-yenji/000000000050/?votes=1?status=Approved&code=000&reason=Approved%3A%20Transaction%20successful!&transaction_id=314304818998 this is my views.py def process_payment(request, slug, amount): trans_id = request.GET.get('transaction_id') status = request.GET.get('status') reason = request.GET.get('reason') transaction_id = request.GET.get('transaction_id') if status == 'Approved': transaction = SuccessfulTransactionHistory( nominee_name=slug, transaction_id=transaction_id, amount=amount ) transaction.save() nomination = Nomination.objects.filter(slug=slug).values('votes') Nomination.objects.filter(slug=slug).update(votes=F('votes') + int(request.GET['votes'])) return redirect('/success') else: context = { 'error': reason } transaction = FailedTransactionHistory( nominee_name=slug, transaction_id=transaction_id, amount=amount ) transaction.save() return render(request, 'payment_error.html', context=context)