Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django throws 'Direct assignment to the forward side of a many-to-many set is prohibited
while posting data from the postman i am getting this error(Django throws 'Direct assignment to the forward side of a many-to-many set is prohibited.' error) my models class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True) user_name=models.CharField(max_length=10,blank=True,null=True,unique=True) date_of_birth=models.DateField(null=True,blank=True) mobile_number=models.CharField(max_length=20,blank=True,null=True) address=models.CharField(max_length=100,blank=True,null=True) country=models.CharField(max_length=20,blank=True,null=True) joining_date=models.DateField(null=True,blank=True) Rating_CHOICES = ( (1, 'Poor'), (2, 'Average'), (3, 'Good'), (4, 'Very Good'), (5, 'Excellent') ) Rating=models.IntegerField(choices=Rating_CHOICES,default=1) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] def __str__(self): return str(self.user_name) def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin class Meta: ordering=('user_name',) class Session(models.Model): Host=models.ForeignKey(MyUser,on_delete=models.CASCADE,related_name='host') game=( ('cricket','cricket'), ('football','football'), ('basketball','basketball'), ('hockey','hockey'), ('gym','gym'), ('baseball','baseball'), ) Sport=models.CharField(max_length=20,choices=game) SPORT=( ('Indoor','Indoor'), ('Outdoor','Outdoor'), ) Sports_category=models.CharField(max_length=10,choices=SPORT) SESSIONS=( ('General','General'), ('Business','Business'), ) Session_category=models.CharField(max_length=15,choices=SESSIONS) TYPE=( ('Paid','Paid'), ('Free','Free'), ) Session_type=models.CharField(max_length=10,choices=TYPE) Created=models.DateField(null=True,blank=True) Session_Date=models.DateField(null=True,blank=True) Location=models.ForeignKey(MyUser,related_name='street',on_delete=models.CASCADE) Player=models.CharField(max_length=100,blank=False) Start_time=models.TimeField(auto_now=False, auto_now_add=False) End_time=models.TimeField(auto_now=False, auto_now_add=False) Duration=models.DurationField() status=( ('1','Active'), ('2','UnActive'), ) Status=models.CharField(max_length=20,choices=status) Equipment=models.TextField() Duration=models.CharField(max_length=20,blank=False) #Level=models.ForeignKey(IntrestedIn,blank=True,on_delete=models.CASCADE) GENDER=( ('Male','Male'), ('Female','Female'), ('Male and Female','Male and Female'), ('Other','Other'), ) Gender=models.CharField(max_length=20,choices=GENDER ,blank=True) Fee=models.CharField(max_length=50,blank=True,default='0') User_Id=models.CharField(max_length=10,blank=True,null=True) Players_Participating=models.ManyToManyField(MyUser,related_name='related') def __str__(self): return str(self.Host) class Meta: ordering=('Host',) while posting data from the postman i am getting this error(Django throws 'Direct assignment to the forward side of a many-to-many set is prohibited.' error) my viewset class SessionViewSet(viewsets.ViewSet): def create(self, request): try: Host= request.data.get('Host') Sport = request.data.get('Sport') … -
How to used python filter json string based on key that given in array form?
I have below json string: a={"44":[ { "16":{ "unitData":[ ], "unitHeader":{ "t9u":"P3P34", "sum":"807", } } }, { "16":{ "unitData":[ ], "unitHeader":{ "t9u":"BFB", "sum":"8A", } } } ], "49":[ { "16":{ "unitData":[ ], "unitHeader":{ "t9u":"P3P34", "sum":"807", } } }, { "17":{ "unitData":[ ], "unitHeader":{ "t9u":"BFB", "sum":"8A", } } } ], "7":[ { "16":{ "unitData":[ ], "unitHeader":{ "t9u":"P3P34", "sum":"807", } } }, { "6":{ "unitData":[ ], "unitHeader":{ "t9u":"BFB", "sum":"0A", } } } ], } The key from above json string get by a.keys() is: dict_keys(['44', '49', '7']) How to filter the a so that it remain the key of 44 and 49 only if the array given is ['44', '49'], below is my expected output: {"44":[ { "16":{ "unitData":[ ], "unitHeader":{ "t9u":"P3P34", "sum":"807", } } }, { "16":{ "unitData":[ ], "unitHeader":{ "t9u":"BFB", "sum":"8A", } } } ], "49":[ { "16":{ "unitData":[ ], "unitHeader":{ "t9u":"P3P34", "sum":"807", } } }, { "17":{ "unitData":[ ], "unitHeader":{ "t9u":"BFB", "sum":"8A", } } } ], } -
Can you please guide me to implement Dual Factor Authentication in Django?
I am currently working on a scenario where a user after login has the option to switch to private mode by means of flipping a switch button. Whenever a user logs in and then switches on to private mode for the first time, then the user must be verified by dual factor authentication once and then he can switch back and forth between private and public mode, without triggering 2FA Authentication every subsequent time when he switches to private mode till he logs out. That is the 2FA must be triggered every first time per session when a user switches to private mode. Can you please provide some suggestions or ideas on how to implement this functionality? I am not clear on how to implement this. I have tried reading documentations and feel that a concise approach would be better. Please do suggest. -
Using commas to separate large numbers in Django FloatField
I'm setting up an app with Django and I need to show large numbers (sometimes many billions) on my home page. Right now I have set up my model with a classic: required_number = models.FloatField() Which yields me a number similar to 126645602100.0. Naturally I find this very hard to read, and it becomes really problematic to compare this number to another one which would be in the order of millions instead of billions. Would there be a way to format this number in order to get something like 126,645,602,100 or even 126'645'602'100? I'm thinking maybe FloatField is not adequate, or maybe the answer lies in my html treatment of this variable. Thank you very much for your help! -
FileField PDF Won't Open Django
I am creating and saving a PDF as such in my views: views.py @login_required(login_url="/login") def PackingListView(request): if request.method == "POST": form = PackingListForm(request.POST) if form.is_valid(): if 'preview' in request.POST: ... elif 'save' in request.POST: pdf_contents = form file = ContentFile(pdf_contents) item = PackingListDocuments.objects.get(pk=1) item.PackingListDocument.save('test.pdf', file) #saving as FileField in model form.save() messages.success(request, "Success: Packing List Has Been Created!") return redirect('HomeView') I see that the test.pdf is saved. I can see it in my file explorer as well as in the admin, but every time that I attempt to open it, the file seems to be corrupted. What do I need to add or subtract in my code to get this working? Thanks! -
Django without Page Refresh using AJAX
When the teacher update the student behavior, There is a pop up message "Update Success", in my case when the teacher update the student behavior the page is appear blank this is the source https://www.youtube.com/watch?v=KgnPSmrQrXI <form method="POST" id="DogForm" action="/Updatestudentbehavior/" class="myform" style="width: 100%" enctype="multipart/form-data">{% csrf_token %} <table class="tblcore"> <input type="text" value="{{teacher}}" name="teacher" id="teacher"> {% for students in student %} <tr> <td colspan="2"><input type="hidden" value="{{students.id}}" >{{students.Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname}} {{students.Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname}}</td> {% for corevalues in studentsbehaviorgrade %} <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="id" id="student"> <select name="Marking" id="marking"> <option value="{{corevalues.Marking.id}}" >{{corevalues.Marking.id}}-{{corevalues.Marking.Marking}}</option> {% for behaviors in behavior %} <option value="{{behaviors.id}}">{{behaviors.id}}-{{behaviors.Marking}}</option> {% endfor %} </select> </td> {% endfor %} </tr> {% endfor %} </table> <input type="submit" value="Update"> </form> this is my script <script type="text/javascript"> $(document).on('submit', '#DogForm', function(e)){ e.preventDefault(); $.ajax({ type:'POST', url:'/Updatestudentbehavior/' data:{ teacher:$('#teacher').val(), student:$('#student').val(), marking:$('#marking').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, succes:function(){ alert('Update Success'); } }) } </script> my views.py def Updatestudentbehavior(request): ..... return HttpResponse('') urls.py path('Updatestudentbehavior/', Homepage.views.Updatestudentbehavior, name='Updatestudentbehavior'), -
Automatically assigning User token to custom profile model django rest framework
I currently have a signal that automatically creates a Token object for a User when they sign up to the website. I also have a custom User model, UserProfileInfo, in which I have a field that connects a Token to the User token = models.OneToOneField(Token,related_name='token',on_delete=models.CASCADE,blank=True,null=True) However, I want this to be automatically assigned when the userprofileinfo is created, which happens in a signal. @receiver(post_save, sender=User) def create_auth_token(sender, instance, created, **kwargs): if created: token = Token.objects.create(user=instance) UserProfileInfo @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: UserProfileInfo.objects.create(user=instance) else: instance.userprofileinfo.save() (the first signal creates a token, the second creates the userprofileinfo) I want to know how I can automatically assign a token to a user when the userprofileinfo is created. -
Django ModelAdmin use custom query
Hi currently i'm having trouble add a custom ModelAdmin section to the app admin side without using any defined model in the models.py For example i have 3 models(topups, withdrawals, transfers) and i would like to add a separate ModelAdmin transactions section that a combination from those 3 model, because i like it's paging, change listing and detail view. So if i have a query for example like so: cursor = connection.cursor() cursor.execute(''' SELECT * FROM (SELECT id, user_id, 1 AS transaction_type, method, NULL AS to_bank, NULL AS to_address, user_id AS to_account, NULL AS to_card, currency_id, amount, fee, status, UNIX_TIMESTAMP(created) AS created, UNIX_TIMESTAMP(received) AS confirmed FROM topups WHERE deleted IS NULL UNION ALL SELECT id, user_id, 2 AS transaction_type, method, NULL AS to_bank, to_address, to_account, NULL AS to_card, currency_id, amount, fee, status, UNIX_TIMESTAMP(created) AS created, UNIX_TIMESTAMP(confirmed) AS confirmed FROM transfers WHERE deleted IS NULL UNION ALL SELECT id, user_id, 3 AS transaction_type, method, to_bank, to_address, NULL AS to_account, to_card, currency_id, amount, fee, status, UNIX_TIMESTAMP(created) AS created, UNIX_TIMESTAMP(confirmed) AS confirmed FROM withdrawals WHERE deleted IS NULL ) AS T WHERE (user_id =''' + str(user.id) + ''' OR to_account =''' + str(user.id) + ''') ORDER BY created DESC''' ) row = namedtuplefetchall(cursor) … -
need help separating a Django function into 2 distinct parts
I'm continuing to make progress on a personal cycling data website. What I'm currently working on is trying to take a function which, at the moment, is run all at once, and turn it into two separate pieces. I'm pulling data from Strava via their API, and what I hope to do is first, via a button, pull and display a list of recent rides (this part is accomplished) and then once that list is displayed select an individual ride to import. At the moment, it's a bit of an all or nothing scenario where I can extract all ride files at once but I wanted to do it more "on-demand" So what I'm hoping to do is get the portion which collects the streams and make that into it's own function that can receive data from this first rendering function and call upon a single ride stream to add to a model/file/whatever. Just curious to see if someone had any insight on what stuff to explore def stravadownload(request): adict={} actdict={} activitydict={} if "downstrav" in request.POST: client = Client() activity=Activity() with open("stravtoken.json", "r") as stravtoken: tokendict = json.load(stravtoken) access_token = tokendict["access_token"] refresh_token = tokendict["refresh_token"] expires_at = tokendict['expires_at'] client.access_token=access_token client.refresh_access_token= refresh_token … -
Failed to push an app in heroku with python
im trying to deploying an app with python django.. But when i get this error: From my build log in heroku.. -----> Python app detected .... -----> Installing requirements with pip ... Collecting psycopg2==2.6.2 Downloading psycopg2-2.6.2.tar.gz (376 kB) ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-a0nakbaj/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-a0nakbaj/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-a0nakbaj/psycopg2/pip-egg-info cwd: /tmp/pip-install-a0nakbaj/psycopg2/ Complete output (7 lines): ..... Error: could not determine PostgreSQL version from '12.2' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. ! Push rejected, failed to compile Python app. ! Push failed Here is my requeriments.txt if you need it: colorama==0.4.1 dj-database-url==0.5.0 Django==2.2.1 django-qr-code==1.0.0 gunicorn==19.9.0 Pillow==6.0.0 psycopg2==2.6.2 pytz==2019.1 qrcode==6.1 six==1.12.0 sqlparse==0.3.0 whitenoise==4.1.2 Anyone can help me with whis? Thank you! -
Django: no module named "django_haystack" but here it is, I think
pip3 install django-haystack ... comfortingly says: Successfully installed django-haystack-2.8.1 But then `./manage.py migrate' ... says ModuleNotFoundError: No module named 'django-haystack' In my .virtualenvs/[...]/ I find these directories: django_haystack-2.8.1-py3.6.egg-info haystack ... but pip3 uninstall haystack says Skipping haystack as it is not installed. ... and pip3 uninstall django-haystack is ready to delete the directories aforementioned. Okay, so if pip3 install finds it, what's migrates problem? My INSTALLED_APPS hash includes django-haystack ... -
Multiple database router
The project is about two databases, the first one: default (which I've been working and contains several models) and the second one: customer (it must handle only 1 model). App name: cities Database's names: default and customer Model in customer's db: mail_receiver I've been following some Django's manuals but it doesn't work. The routers that I'm using are: routers.py class defaultRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'cities': return 'default' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'cities': return 'default' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'cities' or \ obj2._meta.app_label == 'cities': return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'cities': return db == 'default' return None class customerRouter(object): def db_for_read(self, model, **hints): """ Attempts to read user models go to default. """ if model == 'mail_receiver': return 'customer' return None def db_for_write(self, model, **hints): if model == 'mail_receiver': return 'customer' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'cities' or \ obj2._meta.app_label == 'cities': return True return None def allow_migrate(self, db, app_label, model_name='mail_receiver', **hints): if app_label == 'cities': return db == 'customer' return None settings.py DATABASES = { 'default': { 'NAME':'cities', 'USER': 'root', ... }, … -
Django - model with several tag fields
I need a model with several "tag" fields. For example: class Food(models.Model): type = SomeTagField() manufacturer = SomeTagField() It could be done using many-to-many relationships, but I'm not sure if this is a correct approach. It looks a little bit overcomplicated. I've tried django-tagit and its TaggableManager but without luck: ValueError: You can't have two TaggableManagers with the same through model. What would be a correct way to handle that? -
Django sqlmigrate not showing raw sql
I tried to get the raw sql from Django migrate file. I took the following steps: $ python manage.py makemigrations $ python manage.py sqlmigrate app_name 0001 and raw sql command should display, but the result only contains: BEGIN; -- -- Create model User -- -- -- Create model Config -- COMMIT; How to get the raw sql from sqlmigrate? -
Call function when call another function
I want to call some function from django view. Class view(view): Def get(self): Some stuff... Return httpresponse Def a(): Some stuff I want to call a() function when view is called, without calling a() in view body. Maybe there is any decorator or something else, which helps me with it. Something like: Class view(view): Def get(self): Some stuff from view Return httpresponse @call_with_view Def a(): Some stuff from a >> View() >> some stuff from view >> Some stuff from a -
Django Rest Framework: Custom Forms, Custom JSON output
I have to use Django Rest Framework to develop a form that accepts 2 inputs, customer ID and seat number, and this form is to be limited to 10 customers. My Output JSON should have customer ID, seat number, customer_occupancy (which is 2*customer_id) and total customer occupancy (which is sum of all customer_occupancy values entered up until that point). I've added my code for models.py and views.py down below. I have no idea how to ensure the form doesn't have more than one field for which value is to be entered (seat number) nor why the queryset.update() is not resulting in any change in the output. Any help to resolve this would be much appreciated. models.py: from django.db import models class Hero(models.Model): seat_number = models.CharField(max_length=160, default='No Comment') customer_occupancy = models.IntegerField(default = 0) total_cust_occupancy = models.IntegerField(default = 0) def __int__(self): return self.id views.py: from django.shortcuts import render from rest_framework import viewsets from .serializers import HeroSerializer from .models import Hero global total total = 0 class HeroViewSet(viewsets.ModelViewSet): global total queryset = Hero.objects.all().order_by('id') for idx, i in enumerate(queryset): queryset[idx].customer_occupancy = 2*int(queryset[idx].id) total += queryset[idx].customer_occupancy queryset[idx].total_customer_occupancy = total print(queryset[idx].customer_occupancy) print(total) print(queryset[idx].total_customer_occupancy) queryset.update() serializer_class = HeroSerializer serializers.py: from rest_framework import serializers from .models import Hero … -
Whats the most performant way to reverse a lookup on a dict of tuples?
I have a choices field, with a list of tuples: EVENT_CHOICES = [(1, "queued"), (2, "sent"), (3, "failed")] This is stored as a PositiveSmallIntegerField rather than a CharField for performant reasons: event_type = models.PositiveSmallIntegerField(choices=EVENT_TYPE_CHOICES) In my app, the field is populated by a webhook to an external source, which POSTS the str component of the tuple. E.g. I receive queued, sent, or failed as a POST variable. What's the easiest/most performant way to reverse a lookup on EVENT_CHOICES to return the int from the str? E.g, a clumsy long form way would be: if event == "queued": event_type = 1 if event == "sent": event_type = 2 if event == "failed": event_type = 3 Given I actually have a lot of choices, I assume there has to be a neater way for this? -
I tried to load a web page created with django framework but it give me an error while loading it
[enter image description he][1] To start, I have created a web page containing a form with post method and with csrf_token and I put a button to submit the information, then after clicking the button there is a new page that is apearing, and when I try to load this second page it gives me the error above in the picture. thanks for interesting :) -
django-imagekit throwing AttributeError exception in ImageCacheFile default ctor function
I am working on a project, using the following components: django: v2.2.10 django-podcasting: 1.3.2 django-imagekit: 4.0.2 django-photologue: 3.11 When I try to add a new podcast show, I get the following error message: AttributeError at /admin/podcasting/show/add/ Here is the full stack trace: Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: /admin/podcasting/show/add/ Traceback (most recent call last): File "/path/to/project/env/lib/python3.6/site-packages/imagekit/cachefiles/__init__.py", line 37, in __init__ name = generator.cachefile_name File "/path/to/project/env/lib/python3.6/site-packages/imagekit/specs/__init__.py", line 95, in cachefile_name return fn(self) File "/path/to/project/env/lib/python3.6/site-packages/imagekit/cachefiles/namers.py", line 40, in source_name_as_path '%s%s' % (generator.get_hash(), ext))) File "/path/to/project/env/lib/python3.6/site-packages/imagekit/specs/__init__.py", line 134, in get_hash self.source.name, File "/path/to/project/env/lib/python3.6/site-packages/photologue/models.py", line 345, in __getattr__ raise AttributeError AttributeError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/path/to/project/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/path/to/project/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/path/to/project/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/path/to/project/env/lib/python3.6/site-packages/django/contrib/admin/options.py", line 606, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/path/to/project/env/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/path/to/project/env/lib/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/path/to/project/env/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 223, in inner return view(request, *args, **kwargs) File "/path/to/project/env/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1645, in add_view return self.changeform_view(request, None, form_url, extra_context) … -
aws lambda deployed by zappa is not able to connect to remote database
I'm deploying a django project using zappa to aws-lambda and using mongodb atlas as my database. I'm tring to connect to the database using djongo. I set my django_setting in the zappa_settings.json to my project's django settings. The connection to the database with this settings works just fine in localhost. when deploying, it fails to connect to the server and I suspect that it tries to connect to a default local db (the db sent to mongo_client.py isnt valid or something and it needs to connect to default HOST). The actual error I get is: pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused The above exception was the direct cause of the following exception: djongo.sql2mongo.SQLDecodeError: FAILED SQL: SELECT If anyone has an idea I'd would love to hear. attaching the settings with some fields unset (but set at my settings) DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'db', 'HOST': 'mongodb://<username>:<password>@<> 'USER': 'username', 'PASSWORD': 'password', } } { "dev": { "aws_region": "eu-west-1", "django_settings": settings, "profile_name": "default", "project_name": name, "runtime": "python3.6", "s3_bucket": bucket, "timeout_seconds": 900, "manage_roles": false, "role_name": name, "role_arn": arn, "slim_handler": true } } -
ORM trouble with Django
I want two lists of books, 1 of books that has already been "liked" by the user aka 'myBooks', and another list of all other books, 'otherBooks'. Instead, I can only get 1 book on the first list (the first one liked) and after that the list doesn't change (it doesn't even disappear from second list which excludes any liked books). I am using the filter command which I know is for multiple, and my queries work fine in shell, and yet in my actual program I only get that single query. def books(request): if 'userid' not in request.session: return redirect('/') else: num = request.session['userid'] thisUser = User.objects.get(id=num) myfavorites = Favorite.objects.filter(user=thisUser) context = { "user" : thisUser, "otherBooks" : Book.objects.exclude(favorites=myfavorites), "myBooks" : Book.objects.filter(favorites=myfavorites) } return render (request, 'app1/books.html', context) -
Django DRF : how change to change Date format in my serializer.py?
I am new to Django DRF and I need a small tip. My Problem : I want to change the standart models.DateField to the following format "%d-%m-%Y". I want to do it for the field "birthday" or in general for the project. I tried in directlty in the model.py with : .... birthday = models.DateField(null=True , input_formats= "%d-%m-%Y" ) but it did not work . .... I also added in the setting.py REST_FRAMEWORK = { "DATE_INPUT_FORMATS": ["%d-%m-%Y"],} but it did not work. Now i want to try in the serializer.py but given my class I don't know where to do it . My serializer.py looks like that : from rest_framework import serializers from payload.models import Payload class PayloadSerializer(serializers.ModelSerializer): class Meta: model = Payload fields = ['first_name', 'last_name', 'email', 'birthday',] def create(self, validated_data): """ Create and return a new `payload` instance, given the validated data. """ return Payload.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `payload` instance, given the validated data. """ instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.email = validated_data.get('email', instance.email) instance.birthday = validated_data.get('birthday',instance.birthday) instance.save() return instance SO the question : Where and how do I change in this class the the format of the … -
How to get the minimum value of an instance of django model
I am trying to get the minimum or the lowest value of a model field in django model. The field is room_Price. I am therefore trying to get the minimum of value of this field for each instance of a model. My model are as as follows class Hotels(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=255) city = models.CharField(max_length=255) country = models.CharField(max_length=255) mobile_number = models.CharField(max_length=12) created_at = models.DateTimeField(default=timezone.now) last_modified = models.DateTimeField(auto_now=True) description = models.TextField() slug = models.SlugField(unique=True) property_photo = models.ImageField(default='default.jpg', upload_to='hotel_photos') star_rating = models.PositiveIntegerField() contact_person = models.ForeignKey(UserProfile, on_delete = models.CASCADE, null=True, blank=True,) class Room(models.Model): hotel = models.ForeignKey(Hotels,on_delete = models.CASCADE, null=True, blank=True,) room_photo = models.ImageField(default='default.jpg', upload_to='room_photos') room_Name = models.CharField(max_length = 200) room_details = models.CharField(max_length = 500) room_Capacity = models.PositiveIntegerField(default = 0) slug = models.SlugField(unique=True) # guest_numbers = models.IntegerField(default=0) room_Price= models.PositiveIntegerField(default = 0) total_Rooms = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, blank=True,) More details From the above models, a hotel can have as many rooms as possible. Now i want to fetch the lowest priced room for each hotel. I tried to use Hotels.objects.aggregate(min_price=Min('room__room_Price')) but it is fetching the overall minimum price of all the hotel rooms. Kindly assist -
Loading Django model data into HTML from specific model
When I click on a link on my homepage I want to go to a page with a dynamic URL. I managed this by changing my URLS.py to urls.py urlpatterns = [ path('', views.home, name='home'), path('<str:god_url>', views.godpage, name='godurl'), ] homepage.html <a class="button" href="{{ GodList.god_name }}">Watch now</a> This post is in a for loop, cycling trough godnames. So when clicking on the button above, the god name of that button is added to the url and a new page is loaded. views.py def godpage(request, god_url): godlink = GodList.objects.get(god_link=god_url) context = {'godlink': godlinklink} return render(request, 'my_app/god.html', context) models.py class GodList(models.Model): godName = models.CharField(max_length=50, unique=True) godFoto = models.CharField(max_length=100, unique=True) godlink = models.CharField(max_length=100, unique=True) def __str__(self): return self.godName In this new page I want to load a link which is in the database / models (using postgresql) This link can be found in the same model as the god name that was added to the url. How can I find this link inside of the models and get it in the HTML? <img src="{{ context }}"/></a> -
Django Celery task received, execute, but not finished with GlobalBestPSO pyswarms
I have Django app with Celery in Docker. Have Django container, Celery container. django==1.11.4 gunicorn==19.7.1 celery==4.4 redis==3.4.1 sqlalchemy==1.3.13 raven==6.1.0 requests==2.22.0 numpy==1.13.3 pandas==0.20.3 keras==1.2.1 theano==0.9 scikit-learn==0.18.1 matplotlib==2.1.1 seaborn==0.8.1 salib==1.1.2 pyswarms==1.1.0 deap==1.3.0 In my celery task I have code: from celery import shared_task from pyswarms.single.global_best import GlobalBestPSO @shared_task() def predict_task(): # Some code for i in range( print ('print 111') optimizer = GlobalBestPSO(n_particles=n_part, dimensions=sample_vals.shape[0], \ options=options, bounds=bounds, \ init_pos=positions) print ('print 222') cost, pos = optimizer.optimize(predict_seeded_func, iters=1000, **kwargs) costs.append(cost) poses.append(pos) # Some code Run task with delay function: predict_task.delay(19, test_id, sample_data.to_json()) Then I see, that [2020-03-16 22:26:11,689: INFO/MainProcess] Received task: app.tasks.predict_task[f207ac10-5eb5-464b-aed7-b3ec3d2d029d] [2020-03-16 22:26:11,750: WARNING/ForkPoolWorker-2] print 111 And after then nothing happens. But, if I run without celery delay(): predict_task(19, test_id, sample_data.to_json()) Then code is successfully executed to the end. And I get the result. What can be wrong? Why GlobalBestPSO not executed in task?