Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change Boolean value inside template?
In Django I am creating registration form for multiple user types. I have set in models Boolean field which is set to false. My form file has registration fields where Boolean equal to false. I have registration view. Is there any possibility to change Boolean value inside template? I need that after registration in created user Boolean field has become true. I do not need to print Boolean at all. -
How to get Custom made Django Model Form's id in html Template
I want to get the Form id if is possible from the templates using django : my form.py class Post_Votes_form(forms.ModelForm): class Meta: model = Post_votes fields = ['vote',] my models.py class Post_votes(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) post_id = models.ForeignKey(Post, on_delete=models.CASCADE,) vote = models.BooleanField() In my html i tried something like this to get this forms's id "{{vote_form.auto_id}}" but with this i am getting in the template this "id_%s" : {% if vote_form %} <form method="post" id="{{vote_form.auto_id}}" > {% csrf_token %} {{ vote_form.vote }} {% endif %} </form> I know i can add by myself any id name for this form id, but i wanted to know if there is any other way to get id for the whole form like we have for the form.fields id with this code : form.field.auto_id. -
How to take only the integer items and calculate sum from the list? [duplicate]
This question already has an answer here: Understanding slice notation 31 answers Filter a list in python get integers 4 answers Here i have list with product name and product price but i want to take only the products price from the list and calculate the total price of all products. How can i do it ? For example i have a list: all_products = ['food',1000,'pasta',500,'beer',400] how can i do : 1000+500+400 = 1900 -
How to fill user field in any QuerySet from template by pressing button - Django?
In models: class Match(models.Model): user = models.ManyToManyField(User, blank=True) player_name = models.CharField(max_length=30, null=True, blank=True) player_credit = models.IntegerField(null=True, blank=True) hot_league = models.ManyToManyField('HotLeague', blank=True) class HotLeague(models.Model): user = models.ManyToManyField(User, blank=True) price_pool = models.IntegerField() winner = models.IntegerField() entry = models.IntegerField() In views: def hot_league_details(request, match_id, hot_league_id): match = get_object_or_404(Match, pk=match_id) hot_league = get_object_or_404(match.hot_league, pk=hot_league_id) context = { 'match': match, 'hot_league': hot_league, } return render(request, 'main/hot_league_details.html', context=context) In templates: <div class="col"> Price Pool <h4 style="color:red;" class="pt-1">TK. {{ hot_league.price_pool }}</h4> </div> <div class="col text-center" style="font-size: 12px; padding-top: 5px;"> <div>{{ hot_league.winner }} Winners</div> <div class="d-flex justify-content-end"> <button type="button" class="btn btn-danger btn-sm">TK. {{ hot_league.entry }}</button> </div> </div> In admin site, I put the value for Match and HotLeague model without filling user field. user field is now empty. It will be filled by user. In template, when any logged in user press the button then in my Match and HotLeague model's QuerySet(specifically the user field) will update with this logged in user automatically..That means, now user field is not be empty. It is now filled by user and other fields remain same.... Like, in any online market place when user add any product in cart, then all the information of that product can be accessed by this user … -
Create object when created another object in Django
Is it possible to create object when I created another object in Django? I have code like this and I would like to create AnotherModel instance firstly and then Model instance (when creating AnotherModel). class Model(models.Model): name = models.CharFiled(max_length=50) class AnotherModel(models.Model): model = models.ForeignKey(Model, on_delete=models.CASCADE) description = models.TextField() I tried use Django signals - pre_save. @receiver(pre_save, sender=AnotherModel) def save_model(sender, **kwargs): # some code But I have exception like this: ValueError: Cannot assign "u'Test": "AnotherModel.resource" must be a "Model" instance. -
How to prepare django app for deploying on server?
I followed a tutorial from a site and I deployed my django app on pythonanywhere.com.For this purpose I had to use git to upload codes.As a result my settings.py file was accessible by anybody.so any one could see my secret key on settings.py .It is not good right? I also left DEBUG = True later I found it is not secure.Then I set DEBUG = False on my local machine and it showed it need allowed hosts.What are those things? what should I do? Where can I learn about these? -
Can't restart nginx in django deployment app
I'm trying to follow this tutorial for deployment a django app in my droplet, but in the step four, when said: Now restart NGINX with the command below and you should be set: I have to run the follow command: sudo service nginx restart but I got this error: Failed to restart ngnix.service: Unit ngnix.service not found. I know that I need the file nginx.service but I didn't find a question about this... How can I fix it? -
Difference between debugger output and console output on Post return
I have a page with a table where the user selects records that they want to view using tags. When they hit submit I get the request.POST response that I am expecting. In the Pycharm debugger I can see all the responses that the user selected <QueryDict: {'csrfmiddlewaretoken': ['bkyQPyYtqh8ewWMPKIx34Lm9RPcBXq12FfYaidlbPQkotFxMi6vwWXhCqZjk48pA'], 'record': ['employer_addr_id=32003931&employer_trd_id=32004927&employer_reg_id=None', 'employer_addr_id=32005506&employer_trd_id=32006550&employer_reg_id=None', 'employer_addr_id=32006030&employer_trd_id=32007075&employer_reg_id=None', 'employer_addr_id=32006957&employer_trd_id=32008002&employer_reg_id=None']}> However, in the code and when I am using the console debugger if I type request.POST['record'] I only get the last record 'employer_addr_id=32006957&employer_trd_id=32008002&employer_reg_id=None' Any suggestions on what is going on here? -
change function based view in Class Based View for Form "request" handling
I am following a tutorial where a Cart is made for Products handling. the is a function to add the items in the cart as @require_POSTdef cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') and the second one is def product_detail(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, available=True)cart_product_form = CartAddProductForm() return render(request,'shop/product/detail.html',{'product':product,'cart_product_form': cart_product_form}) How can I change these two codes into ClassBasedViews? What will be better? using thesamefunction based views or the ClasBased? from django import formsPRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)]class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField( choices=PRODUCT_QUANTITY_CHOICES, coerce=int) update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) this is forms.py in CartApp. The cart has a class called Cart which requires request,Product from the form. How can I pass that information to cart using CBV? -
How can I do to filter on the dates
I am programming using django and I have this variable : a = '2019-08-03' And I have a database with two columns start and end like this : start = 2019-08-01 00:00:00.000000 end = 2019-08-15 00:00:00.000000 Obviously start and end have many values. I would like to get the rows which a is between start and end. How can I do ? I thought to something like this : c = myObject.objects.filter(mycondition) but I guess I have to do a conversion right and then something like between... Could you help me please ? I precise I can modify a like thisa = 2019-08-03 00:00:00.000000 -
How to migrate HUE 4.2 to HUE 4.4 on EMR cluster
I'm currently running an EMR 5.17.0 cluster with HUE 4.2, now I'm planning to upgrade my EMR to 5.24 and migrate the HUE from 4.2 to 4.4. I've followed the instruction from AWS "How to migrate a Hue database from an existing Amazon EMR cluster" But I got below exception when I try to import the hue-mysql.json from my new cluster! seems the schedule not be supported on HUE 4.4, does anyone have any good suggestions on how to fix this? [hadoop@ip-172-31-21-127 ~]$ sudo /usr/lib/hue/build/env/bin/hue loaddata hue-mysql.json Traceback (most recent call last): File "/usr/lib/hue/build/env/bin/hue", line 14, in <module> load_entry_point('desktop', 'console_scripts', 'hue')() File "/usr/lib/hue/desktop/core/src/desktop/manage_entry.py", line 216, in entry execute_from_command_line(sys.argv) File "/usr/lib/hue/build/env/lib/python2.7/site-packages/Django-1.11.20-py2.7.egg/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/lib/hue/build/env/lib/python2.7/site-packages/Django-1.11.20-py2.7.egg/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/hue/build/env/lib/python2.7/site-packages/Django-1.11.20-py2.7.egg/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib/hue/build/env/lib/python2.7/site-packages/Django-1.11.20-py2.7.egg/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/lib/hue/build/env/lib/python2.7/site-packages/Django-1.11.20-py2.7.egg/django/core/management/commands/loaddata.py", line 69, in handle self.loaddata(fixture_labels) File "/usr/lib/hue/build/env/lib/python2.7/site-packages/Django-1.11.20-py2.7.egg/django/core/management/commands/loaddata.py", line 109, in loaddata self.load_label(fixture_label) File "/usr/lib/hue/build/env/lib/python2.7/site-packages/Django-1.11.20-py2.7.egg/django/core/management/commands/loaddata.py", line 166, in load_label for obj in objects: File "/usr/lib/hue/build/env/lib/python2.7/site-packages/Django-1.11.20-py2.7.egg/django/core/serializers/json.py", line 88, in Deserializer six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2]) File "/usr/lib/hue/build/env/lib/python2.7/site-packages/Django-1.11.20-py2.7.egg/django/core/serializers/json.py", line 82, in Deserializer for obj in PythonDeserializer(objects, **options): File "/usr/lib/hue/build/env/lib/python2.7/site-packages/Django-1.11.20-py2.7.egg/django/core/serializers/python.py", line 129, in Deserializer field = Model._meta.get_field(field_name) File "/usr/lib/hue/build/env/lib/python2.7/site-packages/Django-1.11.20-py2.7.egg/django/db/models/options.py", line 619, in get_field raise … -
Is there any downside to Django proxy models?
I'm getting rather tired of paging through lots of irrelevant little fiddly properties while looking for the actual database structure of my models. Would it be a bad thing to use proxy models universally just to keep my code better organized / more readable? I.e. class Foo_Base( models.Model): title = models.CharField( ...) # other DB fields. As little as possible anything else. class Bar_Base( models.Model): foo = models.ForeignKey( Foo_Base, ... ) etc. not many more lines than there are columns in the DB tables. Then at the bottom or elsewhere, class Foo( Foo_Base): class Meta: proxy=True @property def some_pseudo_field(self): # compute something based on the DB fields in Foo_Base return result @property # etc. pages of etc. The fact that makemigrations and migrate tracks proxy models makes me slightly concerned, although this usage seems to be exactly what the Django documentation says they are for (wrapping extra functionality around the same database table). Or is there another way to organize my code that accomplishes the same (keeping fundamental stuff and fiddly little support bits apart). (About the only thing I dislike about Python, is that it does not have include functionality for reading in a heap of code from another … -
Exception ocurred when processing wsgi script
I have a Django 2.0.5 app and a Centos7 server with httpd. I would like to deploy the app with httpd but I'm receiving an error when apache is processing the wsgi script mod_wsgi (pid=17647): Exception occurred processing WSGI script '/var/www/html/quiq/apache.conf/web.wsgi'. TypeError: 'NoneType' object is not iterable mod_wsgi (pid=17648): Exception occurred processing WSGI script '/var/www/html/quiq/apache.conf/web.wsgi'. TypeError: 'NoneType' object is not iterable WSGI script import os, sys #import django.core.handlers.wsgi sys.path.append('/var/www/html/quiq/') os.environ['DJANGO_SETTINGS_MODULE'] = 'Rest_SL_Algorithm.settings' # avoid UnicodeEncodeError os.environ.setdefault("LANG", "en_US.UTF-8") os.environ.setdefault("LC_ALL", "en_US.UTF-8") from django.core.wsgi import get_wsgi_application ##activamos nuestro virtualenv activate_this = '/var/www/html/quiq/quiqenv/bin/activate_this.py' #execfile(activate_this, dict(__file__=activate_this)) #exec(open('/var/www/html/quiq/quiqenv/bin/activate_this.py').read()) exec(compile(open(activate_this, "rb").read(), activate_this, 'exec'), dict(__file__=activate_this)) #_application = django.core.handlers.wsgi.WSGIHandler() _application = get_wsgi_application() def application(environ, start_response): environ['PATH_INFO'] = environ['SCRIPT_NAME'] + environ['PATH_INFO'] if environ['wsgi.url_scheme'] == 'https': environ['HTTPS'] = 'on' return _application(environ, start_response) and my httpd conf for the project <virtualhost *:80> ServerName algorithm DocumentRoot /var/www/html/quiq <Directory /var/www/html/quiq> Order allow,deny Allow from all </Directory> WSGIDaemonProcess dev.algorithm.com processes=2 threads=15 display-name=%{GROUP} WSGIProcessGroup dev.algorithm.com WSGIScriptAlias / /var/www/html/quiq/apache.conf/web.wsgi Alias /media /var/www/html/quiq/media/ <Directory /var/www/html/quiq/media> Require all granted </Directory> Alias /static/ /var/www/html/quiq/staticfiles/ <Directory /var/www/html/quiq/staticfiles> Require all granted </Directory> ErrorLog /etc/httpd/logs/pyerror.log CustomLog /etc/httpd/logs/pyaccess.log combined </virtualhost> I had to make several work arounds when installing on centos such installing centos-release-scl and rh-python The extrange thing is when I execute the … -
Django serialize object with information from other model
Current Code I have two models (Post and View) as seen below. View is for which user has seen which Post. Post Model: class Post(models.Model): creator = models.ForeignKey(User, on_delete = models.CASCADE) text = models.CharField(max_length = 255) timestamp = models.DateTimeField(default=now) def __str__(self): return str(self.pk) View Model: class View(models.Model): viewer = models.ForeignKey(User, on_delete = models.CASCADE) post = models.ForeignKey(Post, on_delete = models.CASCADE) timestamp = models.DateTimeField(default=now) def __str__(self): return str(self.post.pk) class Meta: unique_together = ('post', 'viewer') My views.py currently looks like this: @api_view(['GET']) @login_required def get_posts(request): posts = list(Post.objects.all()) data = serialize('json', posts, use_natural_foreign_keys=True) return HttpResponse(data, content_type="application/json") The problem Now I want to be able to serialize many Post objects and add an attribute to each object that says if the user that made the request (request.user) has viewed the Post. Example of result I would like to receive: [ { "model": "posts.post", "pk": 1, "fields": { "creator": ..., "content": "This is a sample post", "timestamp": "2019-07-07T19:56:07.220Z", "viewed_by_user": true <--- I want this attribute } }, { "model": "posts.post", "pk": 2, "fields": { "creator": ..., "content": "This is another sample post", "timestamp": "2019-07-10T13:04:19.220Z", "viewed_by_user": false <--- I want this attribute } } ] Can I achieve this with django serializers? Should I structure my … -
Django mptt get_cached_trees() hits database
I am using get_cached_trees() method from django mptt library As in the docs: Takes a list/queryset of model objects in MPTT left (depth-first) order and caches the children and parent on each node. This allows up and down traversal through the tree without the need for further queries. I am tracking db queries like this: >>> from django.conf import settings >>> settings.DEBUG = True >>> from django.db import connection >>> Model.objects.count() >>> # python 3 uses print() >>> print(len(connection.queries)) Taken from here. Then I do MyModel.objects.count() print(len(connection.queries)) # 1 Then first_object = MyModel.objects.first() root_object = first.object.get_root() print(len(connection.queries)) # 3 Then cache = root_tree.get_cached_trees() print(len(connection.queries)) # 4 Then cache[0].get_descendants() print(len(connection.queries)) # 5 Why at the last step it gives me 5? It was supposed not to make a query to the DB. -
Integrity Error Not Null Constraint Failed When Attempting to Migrate
I am receiving this error when attempting to migrate: "return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: unit_manifests.product_name_id" This is in reference to the product_name field in the model below. 1) Why do I need to set a default value for a foreign key field? 2) I initially ran without default = none, blank = true, null = true. I have now run makemigrations again but when I migrate I still get the error, I believe it is attempting to run an old migrations first. How can I get around this? MODELS.PY class Manifests(models.Model): reference = models.ForeignKey(Orders) cases = models.IntegerField() product_name = models.ForeignKey(Products, default=None, blank=True, null=True) count = models.IntegerField() CNF = models.DecimalField(max_digits=11, decimal_places=2, default=None, blank=True, null=True) FOB = models.DecimalField(max_digits=11, decimal_places=2, default=None, blank=True, null=True) def __str__(self): return self.description -
Django decorator keyError
I wanted to write a decorator to restrict users from viewing/editing/deleting other users entries but it's causing a value error. here's the decorators.py from django.core.exceptions import PermissionDenied from functools import wraps from .models import Mymodel # decorator for checking objects created by users and restricting access to them def user_is_entry_creator(function): @wraps(function) def wrap(request, *args, **kwargs): entry = Mymodel.objects.get(pk=kwargs['pk'])#the error here if entry.user == request.user: request.entry = entry return function(request, *args, **kwargs) else: raise PermissionDenied return wrap I know where's the error from but i don't know how to write it right. -
How to made a loop and not to use destination function again and again? [duplicate]
This question already has an answer here: How to make a loop in views.py in django 2 answers I want to make this Destination() once. But whenever I add c and more alphabets to the target, the pictures and description repeats itself. I don't want this destination function to be repeated again and again. def index(request): target = a, b, c, d = [Destination() for __ in range(4)] a.img = f'0{1}.jpg' b.img = f'0{2}.jpg' c.img = f'0{3}.jpg' d.img = f'0{4}.jpg' a.desc = 'Hello, How are you!' b.desc = 'Hello, How are you!' c.desc = 'Hi, I am fine.' d.desc = 'Hi, I am fine.' context = { 'target': target, } return render(request, 'index.html', context) -
Uncaught TypeError: $(...).skillbar is not a function at HTMLDocument.<anonymous>
I am currently learning Django. At the moment, I want to apply Jquery in my Web, and I receive this error: jquery-3.4.1.min.js:2 Uncaught TypeError: $(...).skillbar is not a function at HTMLDocument.<anonymous> (VM350 main.js:2) When I open my main.js, I surprisingly find that my main.js become $(document).ready(function () { $('.skillbar').skillbar({ speed: 1000, }); }); I have attached my main.js here. Thanks for any help and advice (function ($) { "use strict"; /*================================================================== [ Focus input ]*/ $('.input100').each(function(){ $(this).on('blur', function(){ if($(this).val().trim() != "") { $(this).addClass('has-val'); } else { $(this).removeClass('has-val'); } }) }) /*================================================================== [ Validate ]*/ var input = $('.validate-input .input100'); $('.validate-form').on('submit',function(){ var check = true; for(var i=0; i<input.length; i++) { if(validate(input[i]) == false){ showValidate(input[i]); check=false; } } return check; }); $('.validate-form .input100').each(function(){ $(this).focus(function(){ hideValidate(this); }); }); function validate (input) { if($(input).attr('type') == 'email' || $(input).attr('name') == 'email') { if($(input).val().trim().match(/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{1,5}|[0-9]{1,3})(\]?)$/) == null) { return false; } } else { if($(input).val().trim() == ''){ return false; } } } function showValidate(input) { var thisAlert = $(input).parent(); $(thisAlert).addClass('alert-validate'); } function hideValidate(input) { var thisAlert = $(input).parent(); $(thisAlert).removeClass('alert-validate'); } })(jQuery); -
I keep getting the following error when I submit my register form data
I am trying to the create a bank system using DRF. I need to automatically assign users an account number immediately they fill in their registration details. Other than this, kindly pardon me if I do not have the right question-asking skills. I am using django --version 2.2.3 models.py class AccountDetails(models.Model): GENDER_CHOICE = ( ("M", "Male"), ("F", "Female"), ) user = models.OneToOneField( User, related_name='account', on_delete=models.CASCADE, ) account_no = models.AutoField( unique=True, primary_key=True, null=False, validators=[ MinValueValidator(10000000), MaxValueValidator(99999999) ] ) views.py def register_view(request): if request.user.is_authenticated: return redirect("home") else: user_form = UserRegistrationForm( request.POST or None, ) account_form = AccountDetailsForm( request.POST or None, request.FILES or None ) address_form = UserAddressForm( request.POST or None ) if user_form.is_valid() and account_form.is_valid() and address_form.is_valid(): user = user_form.save(commit=False) account_details = account_form.save(commit=False) address = address_form.save(commit=False) password = user_form.cleaned_data.get("password1") user.set_password(password) user.save() account_details.user = user account_details.save() address.user = user address.save() new_user = authenticate( account_no=user.account_no, password=password ) login( request, new_user, backend='accounts.backends.AccountNoBackend' ) messages.success( request, '''Thank You For Creating A Bank Account {}. Your Account Number is {}, Please use this number to login '''.format(new_user.full_name, new_user.account_no)) return redirect("home") context = { "title": "Create a Bank Account", "user_form": user_form, "account_form": account_form, "address_form": address_form, } return render(request, "accounts/register_form.html", context) the following is the output: AttributeError at /accounts/register/ … -
Unable deserialize non-model field in modelSerializer in DRF3
This question might seem redundant but I have searched for other answers and they didn't seem to solve the problem. I am using GeoDjango with DRF3. I have a field in my models named location, whose value is given as Point instance which takes longitude and latitude as argument. Therefore, in serializer I have two non-model fields - latitude and longitude. However, when I print the validated_data, lat and lng aren't getting deserialized. models.py class Site(models.Model): site_id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="site") location = models.PointField(geography=True, null=True, blank=True) area = models.FloatField(null=True) objects = SiteManager() managers.py class SiteManager(BaseManager): use_in_migrations = True def create(self, owner, **kwargs): print('kwargs is ',kwargs) site = self.model( owner = owner, area = kwargs['area'], location=Point(float(kwargs['longitude']), float(kwargs['latitude'])), ) site.save(using=self._db) print('site is ',site) return site serializers.py class SiteSerializer(serializers.ModelSerializer): latitude = serializers.SerializerMethodField() longitude = serializers.SerializerMethodField() def get_latitude(self, validated_data): print(validated_data['latitude']) def get_longitude(self, validated_data): print(validated_data['longitude']) class Meta: model = Site fields = ('latitude', 'longitude', 'area') # Serializer to get user details class UserSiteSerializer(serializers.ModelSerializer): site = SiteSerializer() class Meta: model = User fields = ('fullName', 'email', 'site') def create(self, validated_data): site_data = validated_data.pop('site') user = InterestedUser.objects.create(**validated_data) Site.objects.create(owner=user, **site_data) return user Request data is {'fullName': 'rtyhgf', 'email': '8sdfggfs@er.com', 'site': {'longitude': 77.48538458919909, 'latitude': … -
Creating Profile with rest-social-auth
I have recently used rest-social-auth for my project and it returns me a jwt token with this token users should be able to create their profile but I do not know if my method is right or wrong because I am relatively new to Django world. To create a profile my models.py class Profile(models.Model): user = models.OneToOneField('authentication.CustomUser', primary_key=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) avatar = models.ImageField(upload_to=path) nationality = models.CharField(max_length=20) def __str__(self): return self.user.email my serializers.py file as follow class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['first_name', 'last_name', 'avatar', 'nationality'] is this method to create a profile correct? but when I test the api it gives me a error Foreign Key constraint failed please can you tell me the correct way to create a profile? -
Unable to save new databse item with foreignkey
I have an issue with django app. I have a form to add new Category and an other one to add Subcategory. Subcategory has a foreignkey to Category, you can find models.py below: models.py nom = models.CharField(primary_key=True, max_length=100) description = models.TextField(blank=True) class SousCategorie(models.Model): nom = models.CharField(primary_key=True, max_length=100) categorie = models.ForeignKey(Categorie, on_delete=models.DO_NOTHING) description = models.TextField(blank=True) I have a form to create new Subcategory item in forms.py nom = forms.CharField() categorie = forms.ModelMultipleChoiceField(queryset=Categorie.objects.all()) description = forms.CharField() class Meta: model = SousCategorie fields = ['nom', 'categorie', 'description'] Problem is i use a queryset to make a list with all category items but when i want to save my item, it says that cannot assign queryset because it have to be a category instance: views.py form = SousCategorieForm(request.POST) nom = request.POST["nom"] categorie = request.POST["categorie"] description = request.POST["description"] souscategorie = form.save(commit=False) souscategorie.nom = nom souscategorie.categorie = categorie souscategorie.description = description souscategorie.save() And the error : Cannot assign "]>": "SousCategorie.categorie" must be a "Categorie" instance. Can you help me to solve this issue? Thank you, Romain BOULAY -
Django allauth access request in custom signup form
I want to access the request object in the init method of django allauth the custom form code i have class CustomSignupForm(SignupForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if 'email' in self.request.session: self.fields['email'].value = self.request.session['email'] self.fields['email'].disabled = True def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() return user -
How to add key value pair to django queryset
I want to show stats for account by account in for loop of template. In list of dicts or querysets. I have 3 models: (1)AdvertisingAccount, (2)Campaign, UserProfile. I need to sum() clicks and views of Campaigns that belongs to certain AdvertisingAccounts by Foreign Key. (AdvertisingAccount also belongs to UserProfile ) Im trying to retrieve, calculate and add new key-value to dicts of queryset, but seems like I cant do it in dict method… views.py def ad_accounts(request): user = request.user accounts = user.userprofile.advertising_accounts.all() accounts = accounts.values() for d in accounts: d.update(('clicks', d.campaigns.all().aggregate(Sum('clicks')) ) for k,v in d.items()) d.update(('views', d.campaigns.all().aggregate(Sum('views')) ) for k,v in d.items()) models.py class AdvertisingAccount(models.Model): balance = models.DecimalField(max_digits=12, decimal_places=2, default=0, blank=True, null=True) foreign_system_name = models.CharField(max_length=30, blank=True, default=None) foreign_system_id = models.IntegerField(default=None, blank=True, null=True) def __str__(self): return self.foreign_system_name + '--' + str(self.foreign_system_id) class Campaign(models.Model): userprofile = models.ForeignKey('users.UserProfile', on_delete=models.PROTECT, related_name='campaigns') trade = models.ForeignKey('payments.Trade', on_delete=models.PROTECT, related_name='campaigns') ad_account = models.ForeignKey('AdvertisingAccount', on_delete=models.PROTECT, related_name='campaigns') views = models.IntegerField(default=0, blank=True, null=True) clicks = models.IntegerField(default=0, blank=True, null=True) ad_spent = models.DecimalField(max_digits=12, decimal_places=2, default=0, blank=True, null=True) def __str__(self): return str(self.userprofile) + '--' + str(self.ad_account.foreign_system_name) + '--' + str(self.trade.ad_budget) template {% for i in accounts %} {{i.clicks}} {{i.views}} {% endfor %} I got error :'dict' object has no attribute 'campaigns' As I …