Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
find MAX,MIN and AVG of a set in Django
I have an object called meter and it has a set called powerConsumptionReport_set. This is the models.py : class Meter(models.Model): region = models.PositiveSmallIntegerField(null=1) IPAddress = models.GenericIPAddressField(default=0,null=False,blank=False,unique=True) PortNumber = models.IntegerField(default=1024) SerialNumber = models.IntegerField(default=00000000,null=False,blank=False,unique=True) class PowerConsumptionReport(models.Model): meter = models.ForeignKey(Meter, blank=True, null=True, on_delete=models.CASCADE) power = models.FloatField() I need to find Max value of power field from the powerConsumptionReport_set and display it in my template. This is the DetailView i used to show each Meter : class MeterDetailView(DetailView): model = Meter template_name = 'meter/specificMeter.html' And the template is here: <h1 class="card-text text-md-center"> *** here i want to show min value of the set **** - {{ meter.powerconsumptionreport_set.first.power }} </h1> how can i access Max,Min and AVG value of power field from the powerConsumptionReport_set related to each meter. Cheers. -
How can i remove videos from later for individual users?
views.py here in views.py i have tried to make logic for remove any song from watch later but, i am not able to build logic for it.Basically dont know how to bring watch_id(primary key) of my watch later model. def deletewatchlater(request): if request.method=="POSt": user=request.user video_id=request.POST['video_id'] # watch_id=request.POST['watch_id'] wat=Watchlater(user=user,video_id=video_id) wat.delete() messages.success(request,"Song delete from watch later") return render(request,'watchlater.html') def watchlater(request): if request.method=="POST": user=request.user video_id=request.POST['video_id'] watch=Watchlater.objects.filter(user=user) for i in watch: if video_id==i.video_id: messages.success(request,"Song is already added") break else: wl=Watchlater(user=user,video_id=video_id) wl.save() messages.success(request,"Song added to watch later") return redirect(f"/index/subpage/{video_id}") wl=Watchlater.objects.filter(user=request.user) ids=[] for i in wl: ids.append(i.video_id) preserved=Case(*[When(pk=pk,then=pos) for pos,pk in enumerate(ids)]) song=Allmusic.objects.filter(sno__in=ids).order_by(preserved) return render(request,'watchlater.html',{'song':song}) urls.py I have made post request for it when user clicks button remove from watch later than it will send details of user and song_id and watchlater id from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('postComment',views.postComment,name="postComment"), path('',views.home,name='home'), path('index/',views.index,name='index'), path('indexmovie/',views.indexmovie,name='indexmovie'), path('index/subpage/<str:sno>',views.subpage,name='subpage'), path('about/',views.about,name='about'), path('contact/',views.contact,name='contact'), #User Login Logout Signup path('signup',views.handleSignup,name='handleSignup'), path('login',views.handleLogin,name='handleLogin'), path('logout',views.handleLogout,name='handleLogout'), path('search/',views.search,name='search'), #User Saved path('index/watchlater',views.watchlater,name='watchlater'), path('index/history',views.history,name='history'), path('index/likedsongs',views.likedsongs,name='likedsongs'), path('index/deletewatchlater',views.deletewatchlater,name='deletewatchlater'), ] watchlater.html {% extends 'base.html' %} {% block title %} watch Later {% endblock %} {% block css %} <style> </style> {% endblock %} {% block body %} <h1 style="text-align:center;padding-top: 5%; "> WATCH LATER</h1> {% if song|length … -
Django: cannot render an empty modelform in template
I am trying to build a form that would let the user create one or many database table rows at once. Right now, what is being rendered from my view is the entire db table. I understand that it is a basic behavior of a modelform to return the entire db table data, but according to django docs there is a way to override the default behavior (https://docs.djangoproject.com/en/3.1/topics/forms/modelforms/). That's what I tried to do but it does not seem to work, the entire db table keeps being rendered. here is what my view look like: def New_Sales(request): context = {} form = modelformset_factory(historical_recent_data, fields=('Id', 'Date','Quantity', 'NetAmount')) if request.method == 'POST': formset = form(queryset= historical_recent_data.objects.none()) if formset.is_valid(): formset.save() for check_form in formset: quantity = form.cleaned_data.get('Quantity') id = form.cleaned_data.get('Id') update = replenishment.objects.filter(Id = id).update(StockOnHand = F(StockOnHand) - quantity) update2 = Item2.objects.filter(reference = id).update(stock_reel = F(stock_reel) - quantity) return redirect('/dash2.html') else: form = modelformset_factory(historical_recent_data, fields=('Id', 'Date','Quantity', 'NetAmount')) context['formset'] = form return render(request, 'new_sale.html', context) and my model: class historical_recent_data(models.Model): id = models.AutoField(primary_key=True, default= 0) Id = models.CharField(max_length=100, verbose_name= 'references') Date = models.DateField() Quantity = models.FloatField(default=0) NetAmount = models.FloatField(default=0) def __str__(self): return self.reference any help on this would be appreciated! -
Unable to login with correct username and password in Django with custom User model
I successfully created superuser and when I try to login it says your password is incorrect. I checked mu code and I tested it with deleting database and migrations and creating them again many times but couldn't figure out what is wrong. Here is my code From models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.core.validators import MinLengthValidator class UserManager(BaseUserManager): def create_user(self, email, phone_number, first_name, last_name, social_id, password=None, is_staff=False, is_superuser=False, is_active=False): if not email or not phone_number or not first_name or not last_name or not social_id: raise ValueError('fill all the fields') if not password: raise ValueError('must have pasword') user = self.model( email = self.normalize_email(email), phone_number = phone_number, first_name = first_name, last_name = last_name, social_id = social_id ) user.set_password(password) user.is_staff = is_staff user.is_superuser = is_superuser user.is_active = is_active user.save(using=self._db) return user def create_staffuser(self, email, phone_number, first_name, last_name, social_id, password=None): user = self.create_user( email, phone_number = phone_number, first_name = first_name, last_name = last_name, social_id = social_id, password=password, is_staff=True, ) return user def create_superuser(self, email, phone_number, first_name, last_name, social_id, password=None): user = self.create_user( email, phone_number = phone_number, first_name = first_name, last_name = last_name, social_id = social_id, password=password, is_staff=True, is_superuser=True, ) return user class User(AbstractBaseUser): first_name = models.CharField(max_length=50, blank=False) last_name = … -
ContentNotRenderedError: The response content must be rendered before it can be iterated over. Django REST
I am getting an error : The response content must be rendered before it can be iterated over. What's wrong with below line of code..?? if anybody could figure out where i have done mistakes then would be much appreciated. thank you so much in advance. serializers.py class GlobalShopSearchList(ListAPIView): serializer_class = GlobalSearchSerializer def get_queryset(self): try: query = self.request.GET.get('q', None) print('query', query) if query: snippets = ShopOwnerAddress.objects.filter( Q(user_id__name__iexact=query)| Q(user_id__mobile_number__iexact=query)| Q(address_line1__iexact=query) ).distinct() return Response({'message': 'data retrieved successfully!', 'data':snippets}, status=200) else: # some logic.... except KeyError: # some logic.... -
Where the refresh token and access token are stored while using JWT in Django rest framework?
I asked this question on other forums, but couldn't get answer that's why I am asking this question over stack overflow. I don't know whether I can ask this type of question over here or not. Sorry for that. I am trying to implement JWT using djangorestframework-simplejwt for my Django rest application. I noticed that refresh token and access token are not stored in database. Than where are they stored? Thanks in advance. -
Can't get data into my javaskript funktion using django
Hello I tried to get graphs but my buildDHTChart funktion didn't work I'm happy for every help Here is my views.py def sensor_main2(response): data={} sensors=Sensor.objects.all() for sensor in sensors: if 'DHT' in sensor.name: data[sensor.name]=pd.DataFrame({'humidity':Sensorreading.objects.filter(measured_value='humidity',name=sensor.name).values_list('value', flat=True)[:2], 'temperature':Sensorreading.objects.filter(measured_value='temperature',name=sensor.name).values_list('value', flat=True)[:2]}) elif 'ds18b20' in sensor.name: data[sensor.name]=pd.DataFrame({'temperature':Sensorreading.objects.filter(measured_value='temperature',name=sensor.name).values_list('value', flat=True)[:2]}) time=Sensorreading.objects.order_by('time').reverse().filter(measured_value='temperature').values_list('time',flat=True)[:2] return render(response,"sensor/sensor_main2.html",{"data":data,"time:":time}) The data comes from an SQLite3 database my model looks like this: class Sensor(models.Model): pi = models.CharField(max_length=30) name = models.CharField(max_length=30) type_field = models.CharField(max_length=30, db_column='type_') # Field renamed because it ended with '_'. pin = models.IntegerField() location = models.CharField(max_length=30) id_field = models.CharField(max_length=30, db_column='id_') # Field renamed because it ended with '_'. class Meta: managed = False db_table = 'sensor' def __str__(self): return self.name class Sensorreading(models.Model): time = models.DateTimeField() name = models.CharField(max_length=30) location = models.CharField(max_length=30) measured_value = models.CharField(max_length=30) value = models.FloatField() class Meta: managed = False db_table = 'sensorreading' def __str__(self): return self.name And at least my html page, in the beginning i've checked if i get some data from my database and data comes. But for some reason it didn't workt in my funktion at the end {% extends "main/base.html" %} {% block title %}Daten der Sensoren{% endblock %} {% block subtitle %}Daten der Sensoren{% endblock %} {% block content %} <div class="jumbotron"> <div class="container"> … -
Special input field in Django
I dont know how to do this on django, can you please help me do so. i use this field in class: special_number = models.CharField(max_length=17) but need that user enter number in field like this: 00:00:000000000:00 Users enter only number, ":" is enter automatically in field. Any please help? Thanks! -
AWS lambda in python: how to specify a callback function once it has finished?
I'm working with Django 2 and Python 3.6. I need to defer some work to an AWS Lambda function and do it asynchronously. It would be something like rendering (asynchronously) a complex template from its HTML code. Once the asynchronous rendering process has finished, I want to do some extra work in the server (not in the Lambda), like saving the result to the DB, etc. This is the code that should go in the "callback" function. My question is, what would be the way to define that "callback" function that would come into play once the Lambda has finished doing its work? -
Render data passed from Django to Vue
I get my data through axios with this: get_questions: function (){ axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.xsrfHeaderName = 'X-CSRFToken' axios.post('{% url 'sw_app:api_get_questions' %}', this.test) .then(response=>{ this.questions = response.data.questions console.log(response.data.questions) }) } Here's the view function: def do_get_questions(request): data = json.loads(request.body.decode('utf-8')) test_code = data['code'] is_owner = check_test_owner(request, test_code) response = {} if is_owner: # Get Questions questions = models.Question.objects.filter(test__code=test_code) ser_questions = serializers.serialize('json', questions) response['result'] = 'ok' response['message'] = 'Questions fetched!' response['questions'] = ser_questions return JsonResponse(response) else: response['result'] = 'failed' response['message'] = 'You are not the owner of this test!' return JsonResponse(response) It returns this: [{"model": "sw_app.question", "pk": 2, "fields": {"test": 40, "content": "What is the phrase that beginner coders commonly use to display a string on the screen?"}}] models.py for reference: class Question(models.Model): test = models.ForeignKey(Test, on_delete=models.CASCADE) content = models.CharField(max_length=900) def __str__(self): return "Question: {} - Test: {}".format(self.id, self.test.id) Back in my vue (template), I store the questions here: data: { test: { code: '', }, questions: {} }, Now when I do this: <li class="list-group-item" v-for="question in questions" :key="question.pk"> [[ question.content ]] </li> It just display a lot of empty list objects. When I try doing this: <li class="list-group-item" v-for="question in questions" :key="question.pk"> [[ question]] </li> It displays this: Any ideas? Thanks … -
How do I view multiple api's in Django REST api?
So I have two models, and I'm trying to get both models in my api view. So here's the code: @api_view(['GET']) def mainPage(request, pk): thisQuestion = Question.objects.filter(question_number=pk) thisAnswer = Answer.objects.filter(authuser_id=request.user.id, question_number=pk) questionSerialized = QuestionSerializer(thisQuestion, many=True) answerSerialized = AnswerSerializer(thisAnswer, many=True) return Response(answerSerialized.data, questionSerialized.data) Obviously, the problem is in the return part. How do I get both in this case? Thank you very much in advance. -
Assigning a datetime object as the url parameter
I want to give the value of Datetime type to url as parameter using date filter. My url must be such: /account/detail-of-cash-flow/2020-8-10 This command: {{item.date_field|date:'Y-m-d'}} = '2020-8-10'. But, not working when i this commands implement to template url. template.html {% for item in cash_flow_data %} <tr class='clickable-row' data-href="{% url 'account:detail_of_cash_flow' item.date_field|date:'Y-m-d' %}"> <td>{{ item.date_field }}</td> <td>{{ item.EUR }}</td> <td>{{ item.USD }}</td> <td>{{ item.GBP }}</td> <td>{{ item.TRY }}</td> </tr> {% endfor %} urls.py app_name = "account" urlpatterns = [ path('daily-cash-flow/', views.daily_cash_flow, name = "daily_cash_flow"), path('detail-of-cash-flow/<slug:slug>/', views.detail_of_cash_flow, name = "detail_of_cash_flow") ] I hope I was able to explain my problem. -
Batch loading with Pygrametl
right now i'm using a fact table that insert in to the database one row at a time using pygrametl like the two snippets below: self.targetconnection = Etl_Common.get_database_connection(settings.DATAMART_DATABASE) self.fact_table = FactTable( name='fct_efficency', keyrefs=( 'key', ), measures=( 'measure_1' 'measure_2' ), targetconnection=self.targetconnection, ) def insert_measure_data( self, key, measure_1, measure_2, ): row_dict = { 'key': key, 'measure_1': measure_1, 'measure_2': measure_2, } try: self.fact_table.insert(row_dict) except Exception as exc: logger.error('got exception {}'.format(exc)) The problem with this solution obviusly is that if i try to insert lots of rows it takes ages to put all data into the database. Looking at the pygrametl documentation i found a very fitting solution for my problem : BatchFactTables. the problem is that following the documentation i couldn't find an example to follow regarding the insertion of multiple lines togheter... is there any guide/snippet i could use as a guide for my problem? many thanks -
django admin and models
enter image description here Hello Guys I hope all of you are doing great,I have a problem in django3,I have been given a problem and I have to solve it ,I have tried it but not able to solve this,see the image I have given link, <----question starts here This list of help1, help2,... gets stored in a database table. You could do a first version of models.py and enable the admin interface for it. ----->question ends here Can anyone give me a idea?or how to do it or in more simpler words?any ideas or suggestions is appreciated -
Is possible to save a queryset in db in django?
I need to save the result of this query: foo = WordCount.objects.filter(lesson__course=course).values('lesson__course', 'word').annotate(totWords=Sum('count')) which results in a queryset consisting of 'word', 'course' and 'totWords' I have a model with those fields and i need to save foo in it. It si possible only with a for loop or there is a clever way? -
GET IMAGE FIELD NOT ASSOCIATED TO A MODEL IN DJANGO REST FRAMEWORK
I have stored some cover images on my server. These files are not uploaded by the user and I want to pass them through REST API endpoints without relate the view/serializer/ImageField to a specific model. Here is my serielizer: class TagSerializer(serializers.Serializer): tag = serializers.CharField() updated_at=serializers.DateTimeField(format="%d-%m-%Y %H:%M:%S") image=serializers.ImageField() And this is my APIVIEW: class TagAPIView(APIView): def get(self, request, *args, **kwargs): tags=Tag.objects.filter(level=3) qs = [] for t in tags: image=settings.MEDIA_ROOT+'/tags/'+t.tag_id+'.png' (???????) qs.append({'tag':t.tag_title, 'updated_at': t.updated_at,'image':image}) results = TagSerializer(qs, many=True).data return Response(results) I've stored correctly my png files in a "tags" folder. I would like to have an output like this one: [ { "tag": "tag 1", "updated_at": 06/10/2020, "image": "http://127.0.0.1:8000/media/tags/tag_1_id.png" }, { "tag": "tag 2", "updated_at": 04/10/2020, "image": "http://127.0.0.1:8000/media/tags/tag_2_id.png" } ] Thanks a lot for your help! I love this community <3 -
Cannot log in to admin site with superuser account, which was created with console // Django
I have custom user model. After creating superuser in console I can't log in this account. Django says "Invalid username or password". But username and password are valid. I tried to fix this problem with next solution (Click), but it hadn't helped me. My models.py: class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, username, password, **extra_fields): if not email: raise ValueError('Email required') email = self.normalize_email(email) user = self.model( email=email, username=username, is_active=True, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, username, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, username, password, **extra_fields) def create_superuser(self, email, username, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True') return self._create_user(email, username, password, **extra_fields) My settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.RemoteUserBackend', ) AUTH_USER_MODEL = "backend.User" -
Can't push my Django Application to Heroku Keep getting KeyError and No modulenotfounderror
I am trying to deploy my Django app on heroku but keep getting several errors. I have tried every solution here and still haven't figured out the issue. This is my first time deploying and app so please help. remote: Created wheel for psycopg2: filename=psycopg2-2.8.6-cp38-cp38-linux_x86_64.whl size=484087 sha256=7fd888a521a172ddbf2250127088186479f5314fed7eda847376249ff36b35aa remote: Stored in directory: /tmp/pip-ephem-wheel-cache-r32vyema/wheels/70/5e/69/8a020d78c09043156a7df0b64529e460fbd922ca065c4b795c remote: Successfully built psycopg2 remote: Installing collected packages: dj-database-url, asgiref, pytz, sqlparse, Django, gunicorn, idna, Pillow, psycopg2, soupsieve, whitenoise remote: Successfully installed Django-3.1 Pillow-7.1.2 asgiref-3.2.10 dj-database-url-0.5.0 gunicorn-20.0.4 idna-2.8 psycopg2-2.8.6 pytz-2019.1 soupsieve-2.0.1 sqlparse-0.3.0 whitenoise-5.2.0 remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 224, in fetch_command remote: app_name = commands[subcommand] remote: KeyError: 'collectstatic' remote: During handling of the above exception, another exception occurred: remote: Traceback (most recent call last): remote: File "manage.py", line 15, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 231, in fetch_command remote: settings.INSTALLED_APPS remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in __getattr__ remote: self._setup(name) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 70, in _setup remote: self._wrapped = Settings(settings_module) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 177, in __init__ remote: mod = importlib.import_module(self.SETTINGS_MODULE) remote: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, … -
Get id of an looped in html element
{% for product in products %} ... <form class="form-inline"> <div class="input-group"> <input type="hidden" name="productId" id="productId" value="{{product.id}}"> <input type="text" class="form-control" name="productQuantity" id="productQuantity" style="width: 40px; height: 40px;" placeholder="1"> <div class="input-group-append"> <button type='button' name="addToCart" id="addToCart" value="+" class="btn btnother"><i class="fas fa-plus fa-sm" style="color: white;"></i></button> </div> </div> </form> ... {% endfor %} This is a simplified code! So I have an e-commerce Django website. On the main page I represent cards of different products with possibility of adding them to cart. Every time someone adds item to a cart, I want to only update cart image in header. So I want to use AJAX to pass productId and productQuantity to my views.py. Here is my JS: $(document).ready(function(){ $('form').click(function() { var productId = $('#productId').val(); var productQuantity = $('#productQuantity').val(); if (Number.isInteger(Number(productQuantity))){ productQuantity = productQuantity; } else { productQuantity = 1; } $.ajax({ url: 'update', type: 'post', cache: false, data: { 'productId' : productId, 'productQuantity' : productQuantity } }); }); }); However, when I add to cart, the productId being printed is the same for all products. I think it is because after the for loop it stores only the last productId What would be a way to get the id of every individual element? -
AJAX GET request is not showing an error in console but also not firing
I have a bit of an issue I'm hoping some fresh eyes can help with. I have an ajax get request that is supposed to pull some data from my database via Django views class and then display it on an html page. After doing a bit of debugging I've gotten it to the point where it is not throwing an error, however it is also not providing any data now. I'm wondering if someone could have a look and offer some feedback? Here is the AJAX request $(document).ready(function(){ console.log('Document Ready') $.ajax({ type: "GET", url : '/electra/playlist/', dataType: "json", //contentType: "application/json", data: { 'venue': 'venue', 'list': 'list', }, success: function(data){ $("#cafe-playlist").html(data); console.log(data) }, failure: function(errMsg) { alert(errMsg); } }); }); Here is the urls: urlpatterns = [ [...] path('electra/playlist', views.user_playlist.as_view()), Here is the views.py class user_playlist(ListView): template_name = 'testingland/dashboard.html' context_object_name = 'playlist' model = UserVenue def get_queryset(self): venue_name = self.request.GET.get('venue', None) list_name = self.request.GET.get('list', None) return UserList.objects.all() Here is the html template <body> {% block content %} <div class="container-fluid" style="padding:15px"> <!--location --> <div class="row"> <div class="col-sm-3" id="playlist"><p>Lists</p> <ul id = "cafe-playlist"> {% for item in playlist %} <li> <div> <h6 class="playlist-name">{{ item.list }}</h6> </div> </li> </div> {% endfor %} {% … -
Django: Duplicated logic between properties and queryset annotations
When I want to define my business logic, I'm struggling finding the right way to do this, because I often both need a property AND a custom queryset to get the same info. In the end, the logic is duplicated. Let me explain... First, after defining my class, I naturally start writing a simple property for data I need: class PickupTimeSlot(models.Model): @property def nb_bookings(self) -> int: """ How many times this time slot is booked? """ return self.order_set.validated().count() Then, I quickly realise that calling this property while dealing with many objects in a queryset will lead to duplicated queries and will kill performance (even if I use prefetching, because filtering is called again). So I solve the problem writing a custom queryset with annotation: class PickupTimeSlotQuerySet(query.QuerySet): def add_nb_bookings_data(self): return self.annotate(db_nb_bookings=Count('order', filter=Q(order__status=Order.VALIDATED))) The issue And then, I end up with 2 problems: I have the same business logic ("how to find the number of bookings") written twice, that could lead to functional errors. I need to find two different attribute names to avoid conflicts, because obviously, setting nb_bookings for both the property and the annotation don't work. This forces me, when using my object, to think about how the data is … -
TypeError: Field 'id' expected a number but got (()
Hello i need ur help :) Im at this Django project in school. I replaced the auth_user table with the AbstractBaseUser Class and created a new class called UserLogin one. So creating a superuser works fine, but creating the user with the signup page does not work I spent now about 10hours at that error, trying to solve. Hope u can help me Thank u If u need more information, please write it This is the whole error message TypeError: Field 'id' expected a number but got ((), {'email': 'admin@adminator.ch', 'first_name': 'ksfd', 'last_name': 'dfsg', 'location': 'Bern', 'date_of_birth': datetime.datetime(2020, 9, 29, 0, 0, tzinfo=<UTC>), 'plz': 4589, 'license_plate_number': 80291, 'license_plate_char': 'BE', 'country': 'CH', 'address': 'adminstrasse', 'phone_number': '0453268', 'raw_password': 'Balmistar45!', 'is_staff': False, 'is_superuser': False}). [08/Oct/2020 09:03:08] "POST /accounts/signup HTTP/1.1" 500 176373 This is my model: from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.db import models from django.contrib.auth.models import PermissionsMixin from django.utils.translation import gettext_lazy as _ from django.utils import timezone class UserAccountManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): """ Create and save a user with the given email, and password. """ if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def … -
How to get Option field value in Request in Django?
I am trying to update my foem, and I have Country value in dropdown and I want to get this value in request, so that i can update my form using this value in request, Please check my code and let me know where I am mistaking. Here is my test.html file... <select name='country'> <option>Select One</option> {% for countries in country %} <option value="{{country.id}}" {% if countries.id == datas.country_id %}selected{% endif %}>{{countries.country}}</option> {% endfor %} </select> here is my views.py file... datas = MyModelName.objects.get(pk=id) if request.method == "POST" datas.country = request.POST.get('country') datas.save() it's not selecting the country, it's giving me error, Please guide me how i can solve this issue. -
How to group by using Django query
I have next data in the database: Start 08:00:00 , Stop 13:00:00, reference: 0a220a79-83fc-4957-a8c2-7f8f5414abd1, type: workplace Start 08:00:00 , Stop 13:00:00, reference: 0a220a79-83fc-4957-a8c2-7f8f5414abd1, type: showroom Start 09:00:00 , Stop 14:00:00, reference: 54f7beb6-75b5-4489-ba62-99f750693a1f, type: workplace Start 09:00:00 , Stop 14:00:00, reference: 54f7beb6-75b5-4489-ba62-99f750693a1f, type: showroom I want to group it by reference using django. I tried with: query = OpeningsHours.objects.filter(location_id=loc_id).query query.group_by = ['reference'] results = QuerySet(query=query, model=OpeningsHours) But it doesnt work. The query works fine but the result is not grouped by reference. Any idea? -
Django Add ManyToMany choices to existing ManyToMany
I am trying to add ManyToMany choices from a form to existing ManyToMany choices I have tried in views.py instance = form.save(commit=False) id.attendees.add(instance.attendees) instance.save() and in views.py instance = form.save(commit=False) for choice in instance.attendees: id.attendees.add(choice) form.save() The overall code is forms.py class LessonAddForm(forms.ModelForm): def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(LessonAddForm, self).__init__(*args, **kwargs) self.fields['attendees'].queryset = CustomUser.objects.filter( Q(username=user) | Q(customuser__username=user) ) class Meta: model = models.Lessons fields = ['attendees'] views.py def lessonRecord(request,id): if request.method == "POST": id = Lessons.objects.get(id=id) form = forms.LessonAddForm(request.POST,user=request.user,instance=id) if form.is_valid(): instance = form.save(commit=False) for choice in instance.attendees: id.attendees.add(choice) form.save() return redirect('lessons:lessonsView') else: id = Lessons.objects.get(id=id) #form = forms.LessonAddForm(instance=id) form = forms.LessonAddForm(instance=id , user=request.user) return render(request,'lessons/lesson_record.html',{'id':id,'form':form}) I just can't get my head round how to add my choices from the form to the existing choices