Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
self.cleaned_data.get returns none even if field was declared
When i'm in the admin page and trying to create a new instance of MyUser I am unable to create it. When I print out password and confirm_password, I get the proper value for password but None for confirm_password. In my admins.py file, I have the following: class MyUserCreationForm(forms.ModelForm): """ A form for creating new users. """ password = forms.CharField(label='Password', widget=forms.PasswordInput) confirm_password = forms.CharField( label='Confirm password', widget=forms.PasswordInput) class Meta: models = MyUser fields = ('email', ) def clean_password(self): """ Check if two password entries match. """ password = self.cleaned_data.get('password') confirm_password = self.cleaned_data.get('confirm_password') if (password == confirm_password): return password else: raise forms.ValidationError("Passwords don't match") def save(self): """ Save the provided password in hash format. """ user = super().save(commit=False) user.set_password(self.cleaned_data['password']) user.save() return user What could be causing as to why confirm_password always have the value None? -
Should I use the Vue JS combined with Django or separate?
We will start a new project and want to learn Vue JS and apply it in our project. We found two styles to apply Vue JS into our project. The first one using Vue js inside the django template and the second one is separating the Vue JS with vue-cli and he uses Django-rest to implement into the frontend. What are the pros and cons of the two usages? my idea is: by embedding VUE JSC in the Django template. Doing some pages SPA while not making some pages SPA. -
Django Template For Loop Iterator Not Usable
In a Django template the following syntax works just fine: {% for test in testing.1 %} but when replacing the fixed 1 with a dynamic variable from an outer for loop it doesn't work at all: {% for i in range %} {% for test in testing.i %} When printing {{ i }} it shows 1, 2 and 3 like it should. Do I have to convert the i-variable somehow? Or can't I use the iterator variable there? -
Gunicorn: Worker failed to boot
I'm trying to setup my django app with Gunicorn, Supervisor and Nginx. Nginx works fine. When i check the status of Supervisor i have the following message: FATAL Excited too quickly I think the problem comes from Gunicorn as i can't make it work on its own. I also use virtualenv. So this is my project structure: - home - justine - bin - include - my_project_name - app - my_project - settings.py - wsgi.py - manage.py - requirements.txt - logs - run - share - lib - locale - requirements.txt - pip-selfcheck.json In /home/bin i have a file gunicorn_start : NAME="justine_cv" DIR=/home/justine/my_project_name/ USER=justine GROUP=justine WORKERS=3 BIND=unix:/home/justine/run/gunicorn.sock DJANGO_SETTINGS_MODULE=/my_project.settings DJANGO_WSGI_MODULE=/my_project.wsgi LOG_LEVEL=error cd $DIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- Also i have a supervisor file as follows at etc/supervisor/conf.d/: [program:program-name] command=/home/justine/bin/gunicorn_start user=justine autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/justine/logs/gunicorn-error.log When i try to start Gunicorn at home/justine/ and typing gunicorn my_project.wsgi:application i get the following error message: ImportError: No module named my_project.wsgi [2019-04-27 21:20:14 +0000] [24448] [INFO] Worker exiting (pid: 24448) [2019-04-27 21:20:14 +0000] [24444] [INFO] Shutting down: Master [2019-04-27 21:20:14 +0000] [24444] [INFO] Reason: … -
Can I get the value of Sum(amount_sold) from sales table inside the annotate
I'm trying to display a html table that is populated with sum values from the database. I have sum_amount_purchased and sum_total_price_purchased working fine but I am struggling with sum_amount_sold to get this value I need to query the sales table. Is this possible to do this inside an annotate? I want the sum of all sales for the each currency for that user. Any advice would be much appreciated. Table Below {% for transaction in transactions %} <tr> <td>{{transaction.currency}}</td> <td>{{transaction.sum_amount_purchased}}</td> <td>{{transaction.sum_total_price_purchased }}</td> <td>{{transaction.sum_amount_sold}}</td> </tr> {% endfor %} Transaction model below class Transaction(models.Model): currency = models.CharField(max_length=20) amount = models.IntegerField() total_price = models.DecimalField(max_digits=8, decimal_places=2) date_purchased = models.DateTimeField() note = models.TextField(default="") owner = models.ForeignKey(User, on_delete=models.CASCADE) amount_per_coin = models.DecimalField(max_digits=8, decimal_places=2, editable=False) def save(self, *args, **kwargs): self.amount_per_coin = self.total_price / self.amount super(Transaction, self).save(*args, **kwargs) def __str__(self): return str(self.pk)+','+self.currency + ', '+str(self.amount) def get_absolute_url(self): return reverse('transaction-detail', kwargs={'pk': self.pk}) Sale model below class Sale(models.Model): amount_sold = models.IntegerField() total_price_sold = models.DecimalField(max_digits=8, decimal_places=2) date_sold = models.DateTimeField(default=timezone.now) note = models.TextField(default="") transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE, related_name="sales") amount_per_coin_sold = models.DecimalField(max_digits=8, decimal_places=2, editable=False) def __str__(self): return str(self.pk)+','+str(self.amount_sold) + ', '+self.note def save(self, *args, **kwargs): self.amount_per_coin_sold = self.total_price_sold / self.amount_sold super(Sale, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('sale-detail', kwargs={'pk': self.pk}) -
How to properly make models dynamic for django_tables2
I'm trying to make the model in my table class dynamic (using django_tables2). class DynamicTable(tables.Table): class Meta: model = dynamic_model_here template_name = 'django_tables2/bootstrap-responsive.html' I am using the SingleTableView (which is pretty much SingleTableMixin) and have not found a good way to pass information (the model) from my view to the 'Meta' section of the Table class. How can I do this? <--this is the main question. Below is my current attempt which seems a bit hacky. I can successfully, dynamically import the model in the before_render() function (thanks to having access to the request) but I can not expose it to Meta since before_render does not return anything. class DynamicTable(tables.Table): def before_render(self, request): path_info = request.path_info current_model_name = path_info.replace('/','') current_model_import = __import__(module_path, fromlist = current_model_name) current_model = getattr(current_model_import, current_model_name) model = current_model return #The source code shows that before_render just returns nothing class Meta: model = dynamic_model_here template_name = 'django_tables2/bootstrap-responsive.html' What this shows me is that if I could some how handle the request within the same object as Metal.model I would be good-to-go. So my current route is to try to access request which is a django.core.handlers.wsgi.WSGIRequest from the view in the same object as Meta. How could I … -
Django-imagekit AdminThumbnail: how to display a thumbnail but link to original uploaded file
I'm using django-imagekit in the admin, and I cannot get the listing to display a cached thumbnail but link it to the original file. How do I use original image in link, and a thumbnail in the img src? Thumbnails are created properly, they are displayed correctly, but when I click on a thumbnail I want to go to the original file, not the thumbnail in media/CACHED/.../... -
How can I create a vCard qrcode with pyqrcode using Python?
I am trying to generate a vCard QR code with the pyqrcode library but I cannot figure out the way to do it. I have read their documentation 5 times and it doesn't say anything about vCard, only about URL and on the internet, I could found only about wifi. Does anybody know how can I do it? I want to make a vCard QR code and afterward to display it on django web page. -
Issues with pytz 2019.1, Django 2.2?
I noticed that my Django-server crashes when I update pytz==2018.7 to pytz==2019.1. The Pytz library is in charge for all Timezone calculations. I ask myself if something changed and where I can find a changelog? I did not change anything time related in my Django project and when I go back to pytz==2018.7 everything works fine. I am using Django 2.2 with virtualenv, here is my list Python==3.7.2 Django 2.2 Virtualenv==16.5.0 Django==2.2 django-widget-tweaks==1.4.3 djangorestframework==3.9.2 Pillow==6.0.0 Pygments==2.3.1 pytz==2018.7 sqlparse==0.3.0 Settings.py # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True <…> latest crash (env2) D:\coding\Webprojects\phone>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "D:\coding\virtual_env\env2\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "D:\coding\virtual_env\env2\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\coding\virtual_env\env2\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "D:\coding\virtual_env\env2\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "D:\coding\virtual_env\env2\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "D:\coding\virtual_env\env2\lib\site-packages\django\core\management\commands\runserver.py", line 95, in handle self.run(**options) File "D:\coding\virtual_env\env2\lib\site-packages\django\core\management\commands\runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "D:\coding\virtual_env\env2\lib\site-packages\django\utils\autoreload.py", line 579, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "D:\coding\virtual_env\env2\lib\site-packages\django\utils\autoreload.py", line 564, in … -
How to store Indented python code in MySQL Database using Django ORM
I am working on a python interpreter visualization where I need to save and execute python code, but the problem is that I am using Django TextField to save the python code but when I am querying the database I am getting Unformatted , Unindented code like: Original code a=3 for i in range(0,5): a+=i print(a) Code after retrieving from database a=3\012for i in range(0\0545):\012 a+=i\012print(a) I have tried to play with the string encoding but that doesn't worked too. Models.py (Code attribute only) code = models.TextField() -
Is this correct way of doing it?
I am complete novice in Jquery, my code works but I am not sure if it's the right way of doing it. I have django app which lets user select grade, subject and year fields sequentially to query relevant exam in the index page. The 'grade' field in the django form is already populated, therefore based on change in grade field, ajax request is sent to populate the 'subject' field. Similarly, once the user select subject from dropdown list, the 'year' field is populated. Finally, once the three fields are in place, it redirects the user to exam page. It works without any issues. However, what I noticed is that if the user clicks back button in the browser to go back from exam page index page, the grade field has still its value while the subject and year fields are empty. I wanted to fix this by instead of waiting grade field to change, just send ajax request whenever there is numeric value in grade field. Here is the code to populate the subject field. Thanks in advance selectedGrade=$("#id_grade").val(); if( $.isNumeric( selectedGrade )) { var urlSubjects = $('#searchForm').attr('data-url-subjects'); var gradeId = selectedGrade; $.ajax({ statusCode: { 404: function() { alert( … -
Django Channels websocket.recieve sending empty strings Python
I've finally got my websockets working using Django Channels 2.1.2. When a user submits a message, the message is submitted along with another blank instance. The more messages a user sends, the more blank instances get sent as well (they build up and the only way to get it to stop happening is do a CNTRL-R hard refresh of the page). This is what it looks like 127.0.0.1:54917 - - [27/Apr/2019:19:04:05] "WSCONNECTING /messages/trilla" - - connected {'type': 'websocket.connect'} 127.0.0.1:54917 - - [27/Apr/2019:19:04:05] "WSCONNECT /messages/trilla" - - receive {'type': 'websocket.receive', 'text': '{"message":"hi there"}'} websocket.receive receive {'type': 'websocket.receive', 'text': '{"message":""}'} websocket.receive receive {'type': 'websocket.receive', 'text': '{"message":""}'} websocket.receive receive {'type': 'websocket.receive', 'text': '{"message":""}'} websocket.receive I am a beginner so this is probably totally obvious. I am also trying to get notification_id (a field from my Notification model) to append along each message but so far, no luck. I assume notification_id should be defined as a new object in the Notification model, created each time a message is sent? consumers.py class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): print('connected', event) other_user = self.scope['url_route']['kwargs']['username'] me = self.scope['user'] thread_obj = await self.get_thread(me, other_user) self.thread_obj = thread_obj chat_room = f"thread_{thread_obj.id}" self.chat_room = chat_room # below creates the chatroom await … -
How to create an object and save as new instance in another model
My model B has Model A as PK. In this question i am creating a model A. In my form clean method, i did the code below. I got an error: "save() prohibited to prevent data loss due to unsaved related object 'transac'." I understand that this may be because i am saving 2 instance of transac. 1 coming from the form itself, and another here in the clean method. But i dont know the right way to do it... def clean(self): from Ticketing.models import Ticket,Transaction cleaned_data = super(TransactionForm, self).clean() computerid = cleaned_data.get('id_comp') newticket = Ticket(transac=Transaction(id_comp=computerid)) newticket.save() return self.cleaned_data -
How to make: 'enter' typed in the textfield result in a break in the paragraph?
I made a blog app in django. But when the user presses enter in the blog creation form it doesn't work in the database eg. if I type, this is an example blog in the database its stored as: this is an example blog the enter I pressed to insert a break isn't reflected in the database -
Display Data for Logged in User in model
Django version 2.2 I have models in django class Class_teacher(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) empid = models.CharField(max_length=10) standard = models.IntegerField() division = models.CharField(max_length=1) subject = models.CharField(max_length=200) email = models.EmailField(max_length=30) def __str__(self): return self.first_name + ' -- ' + str(self.school) class Student(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) classteacher = models.ForeignKey('Class_teacher', on_delete=models.CASCADE, ) reg_id = models.CharField(max_length=15) parent_first_name = models.CharField(max_length=200) parent_second_name = models.CharField(max_length=200) email = models.EmailField(max_length=100) def __str__(self): return self.first_name + ' ' + self.last_name views for adding student class StudentCreate(LoginRequiredMixin, CreateView): login_url = '/signin/' model = Student fields = ['first_name', 'last_name', 'parent_first_name','parent_second_name', 'email', 'reg_id'] success_url = '/dashboard/' The webapp has login feature as below , def signin(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect('../dashboard/') else: return HttpResponse("Your account was inactive.") else: return HttpResponse("Invalid login details given") else: return render(request, 'webapp/login.html') def dashboard(request): email = request.user.email if Class_teacher.objects.filter(email__iexact=email).count() == 1: students = Student.objects.values('classteacher') context = { 'students' : students} return render(request, 'webapp/dashboard.html',context) dashboard.html template {% if students %} <ol> {% for student in students %} <li>{{student.first_name}} {{student.last_name}}</li> {% endfor %} </ol> {% else %} <h3>No Students Added</h3> {% endif %} {% endblock %} I used … -
PyCharm Community Edition: how to debug Django application
I wrote a very simple Django application. I ran it by creating the following configuration: However, when I debug the application, it doesn't stop in the breakpoints I put. Do you know why and how I can resolve it? -
Django Friend req system issue
I am building a friend request system for my project. For this , i have implemented the below where one user can send a request to another. If users are not friends(relationship does not exist in friends object), then ADD FRIEND option is visible. If users are friends , then being logged in as "from_user" , the "to_user" profile page now shows REQUEST SENT. My query comes after this, when i log in from "to_user" account and open "from_user" profile , the button should be ACCEPT ! Cant figure out the if else for that ! In my set up it shows ADD FRIEND. Hence need help to do this. Models.py class Friend(models.Model): from_user = models.ForeignKey(User, on_delete=models.CASCADE ) to_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="added" ) Views.py class ProfilePage(DetailView): model = models.UserCreation context_object_name = 'profile' def get_context_data(self, *args, **kwargs): context = super(ProfilePage, self).get_context_data(*args, **kwargs) user = User.objects.get(username=UserCreation.objects.get(id=self.kwargs.get('pk'))) print(user) print(self.request.user) try: context['data'] = ProfileData.objects.get( user=user) context['userdata'] = User.objects.get( username=user) context['creationdata'] = UserCreation.objects.get( user=user) context['sorted'] = sorted(chain(AddStatus.objects.filter(user=user), ImageLib.objects.filter(user=user)),key=lambda instance: instance.date, reverse=True) context['friend'] = Friend.objects.get(from_user=self.request.user , to_user = user) except ProfileData.DoesNotExist: context['data']= None except Friend.DoesNotExist: context['friend']= None return context Template {% if user.get_username|stringformat:'s' != creationdata.user|stringformat:'s' and creationdata.user|stringformat:'s' != friend.to_user|stringformat:'s' %} <a href="{% url 'usercreation:addfriend' data.user.usercreation.pk … -
Im trying to implement tests into django application but am getting errors. what am I doing wrong?
Im trying to implement some unit tests into my project but am getting errors. what am I doing wrong. the errors im getting are "File "C:\Users\phily\AppData\Local\Programs\Python\Python37\lib\site-packages\django\conf__init__.py", line 42, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings." Any help would be much apprecited Transaction model below class Transaction(models.Model): currency = models.CharField(max_length=20) amount = models.IntegerField() total_price = models.DecimalField(max_digits=8, decimal_places=2) date_purchased = models.DateTimeField() note = models.TextField(default="") owner = models.ForeignKey(User, on_delete=models.CASCADE) amount_per_coin = models.DecimalField(max_digits=8, decimal_places=2, editable=False) def save(self, *args, **kwargs): self.amount_per_coin = self.total_price / self.amount super(Transaction, self).save(*args, **kwargs) def __str__(self): return str(self.pk)+','+self.currency + ', '+str(self.amount) def get_absolute_url(self): return reverse('transaction-detail', kwargs={'pk': self.pk}) @property def coins_remaining(self): return self.amount - sum(self.sales.all().values_list('amount_sold', flat=True)) @property def coin_value(self): return get_currency_price(self.currency) @property def total_value(self): value = self.coin_value * self.amount return round(value, 2) @property def profit_loss(self): value = float(self.total_value) - float(self.total_price) return round(value, 2) @property def profit_loss_percent(self): value = ((float(self.total_value) - float(self.total_price))/self.total_value)*100 return round(value, 1) def get_absolute_profit_loss(self): return abs(self.profit_loss) def get_absolute_profit_loss_percent(self): return abs(self.profit_loss_percent) Sales model below class Sale(models.Model): amount_sold = models.IntegerField() total_price_sold = models.DecimalField(max_digits=8, decimal_places=2) date_sold = models.DateTimeField(default=timezone.now) note = models.TextField(default="") transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE, related_name="sales") amount_per_coin_sold = models.DecimalField(max_digits=8, decimal_places=2, editable=False) def … -
view that outputs user input on a different url
i created a view + form that creates two widgets + a button for a user. One to select a choice and another to type something in. Now i want to redirect the user after the clicking the button to another webpage displaying his input. (Generally i want to know how to access the userinput and further use it). This is my form: class Eingabefeld(forms.Form): eingabefeld = forms.CharField(label="Flight Number",max_length=20) a = Auswahlmoeglichkeiten.objects.all() flughafenname = forms.ModelChoiceField(label="Target Airport",queryset=a,empty_label="-------") source = forms.CharField( max_length=50, widget=forms.HiddenInput(), required=False ) This is my views.py: def get_eingabe(request): log = logging.getLogger(__name__) if request.method =="POST": eingabe = Eingabefeld(request.POST) log.warn(eingabe) if eingabe.is_valid(): return HttpResponseRedirect("answerrequest") else: eingabe = Eingabefeld() return render(request, "app_one/labels.html", {"eingabe": eingabe}) def answerrequestseite(request): return render(request, "app_one/answerrequest.html") and this is my html ( the included html in this one is just for layout): <head> <title>Home</title> </head> <form method="post" novalidate> {% csrf_token %} {% include "app_one/bootstrap_layout2.html" with form=eingabe %} <div class="row"> <div class="col-sm-5"></div> <div class="col-sm-2"> <button type="submit" class="btn btn-primary btn-block">Let's Go!</button> </div> <div class="col-sm-5"></div> </div> </form> So basically when opening my webpage "get_eingabe" gets called, and the template gets rendered, now when clicking the button the input is validated and after successfull validation a different URL is opened which will trigger … -
Design of JWT authentication?
I am using DjangoRest Framework simple-jwt package found at https://github.com/davesque/django-rest-framework-simplejwt. this provides two api endpoints to get access token and refresh token. Currently I store the access token in localStorage in browser. Is this the best place to store it, or would sessionStorage be better? When I need a new access token because the current access token expired, should I pass the refresh token (stored in localStorage) in a POST request? Is this the best implementation? It seems insecure to have this crucial refresh token string stored in the browser. -
error from template tags: 'str' object has no attribute 'as_widget'
I made a template tag and when I am using that in my template I get this error: 'str' object has no attribute 'as_widget' This is the code of my template tag: from django import template register = template.Library() @register.filter def field_type(bound_field): return bound_field.field.widget.__class__.__name__ @register.filter def input_class(bound_field): css_class = '' if bound_field.form.is_bound: if bound_field.errors: css_class = 'is-invalid' elif field_type(bound_field) != 'PasswordInput': css_class = 'is-valid' return 'form-control {}'.format(css_class) and my template is here: {% extends 'board/account.html' %} {% load widget_tweaks %} {% load form_tags %} {% block title %}Sign up{% endblock title %} {% block content %} <div class="accountform"> <form method="POST"> <h4 class="display-6 text-white p-3">Create your account</h4> {% csrf_token %} <div class="alert alert-danger p-0" style="border:none;"> {% for field in form.visible_fields %} {% for error in field.errors %} <span class="err">{{ error }}</span><br> {% endfor %} {% endfor %} </div> <div class="form-group"> <label for="id_username">Username</label> {% render_field form.username|input_class class='form-control' placeholder='John Doe' %} </div> <div class="form-group"> <label for="id_email">Email</label> {% render_field form.email|input_class class='form-control' placeholder='johndoe@email.com' %} </div> <div class="row"> <div class="form-group col-md-6"> <label for="id_password1">Password</label> {% render_field form.password1|input_class class='form-control' placeholder='****' %} </div> <div class="form-group col-md-6"> <label for="id_password2">Confirm Password</label> {% render_field form.password2|input_class class='form-control' placeholder='****' %} </div> </div> <input type="submit" value="Sign up" class="btn btn-primary btn-block"> <p class="display-6 bg-signup p-3">Have an … -
I'm Trying to access HTML form data in Python Django,
I am trying to access HTML form data. I'm struggling to write views for this. <form> <input type="text" class="form-control"id="inline"placeholder="Username"> <div class="input-group"> <div class="input-group"> <div class="input-group-text"><i class="pass"></i></div> </div> <input type="email"class="form control"id="example"placeholder="Password"> </div> <button type="submit" class="button-primary mt-3">Submit</button> -
Django: download does not start after returnig a file from view
Having gathered info from various Stack Overflow threads, I have came up with the following view function in Django to return a text file through HttpResponse object: def serve_file(request): filepath = sampler_settings.ZIP_PATH + '/test_file' f = open(filepath, 'r') response = HttpResponse(f, content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename="test_file"' return response The function is called from the front-end like this: function serve_file() { let url = 'http://127.0.0.1:8000/serve_file' fetch(url) .then(response => response.text()) .then(text => console.log(text)) } However, the only thing that happens is that the file contents get printed in the browser console, but the download does not start: there is no prompt or anything. This is on development server on Ubuntu and Firefox. What might be the reason? -
Can I Sum up properties in an annotate
I'm creating a html table in my project that is populated by some sum values from my database, I,m trying to sum (coins_remaining) which is a property of my database model. Coins_remaining is calculated by subtracting (sum_amount sold from sales table) from (amount from transaction table). Is this possible?, if so how would I go about it? HTML Table below {% for transaction in transactions %} <tr> <td>{{transaction.currency}}</td> <td>{{transaction.sum_amount_purchased}}</td> <td>{{transaction.sum_total_price_purchased}}</td> <td>{{transaction.sum_total_price_purchased}}</td> </tr> {% endfor %} Function Below @login_required def portfolio(request): context = { 'transactions': Transaction.objects.filter(owner=request.user).values('currency').annotate( sum_amount_purchased=Sum('amount'), sum_total_price_purchased=Sum('total_price')), sum_amount_current= } return render(request, 'webapp/portfolio.html', context, {'title': 'Portfolio'}) Transaction model below class Transaction(models.Model): currency = models.CharField(max_length=20) amount = models.IntegerField() total_price = models.DecimalField(max_digits=8, decimal_places=2) date_purchased = models.DateTimeField() note = models.TextField(default="") owner = models.ForeignKey(User, on_delete=models.CASCADE) amount_per_coin = models.DecimalField(max_digits=8, decimal_places=2, editable=False) def save(self, *args, **kwargs): self.amount_per_coin = self.total_price / self.amount super(Transaction, self).save(*args, **kwargs) def __str__(self): return str(self.pk)+','+self.currency + ', '+str(self.amount) def get_absolute_url(self): return reverse('transaction-detail', kwargs={'pk': self.pk}) @property def coins_remaining(self): return self.amount - sum(self.sales.all().values_list('amount_sold', flat=True)) Sale model below class Sale(models.Model): amount_sold = models.IntegerField() total_price_sold = models.DecimalField(max_digits=8, decimal_places=2) date_sold = models.DateTimeField(default=timezone.now) note = models.TextField(default="") transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE, related_name="sales") amount_per_coin_sold = models.DecimalField(max_digits=8, decimal_places=2, editable=False) def __str__(self): return str(self.pk)+','+str(self.amount_sold) + ', '+self.note def save(self, *args, **kwargs): self.amount_per_coin_sold = self.total_price_sold … -
Got AttributeError when attempting to get a value for field `xxx` on serializer `xxx`
Hi i'm trying to access this url : http://192.168.1.5:8000/api/parents/ but I'm getting this error : AttributeError at /api/parents/ Got AttributeError when attempting to get a value for field `nom` on serializer `ParentSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Adresse` instance. Original exception text was: 'Adresse' object has no attribute 'nom'. It was working last week , but i don't remember what did I exactly changed Here is my file models.py : class Adresse(models.Model): id=models.AutoField(primary_key=True) ville=models.CharField(max_length=20) region=models.CharField(max_length=20) quartier=models.CharField(max_length=20) codePostal=models.IntegerField() rue=models.CharField(max_length=50) def __str__(self): return 'Ville :{} ,Région: {},Quartier : {},Code Postal : {},Rue : {} .'.format(self.ville,self.region,self.quartier,self.codePostal,self.rue) class Ecole(models.Model): NIVEAU=(('Maternelle','Maternelle'),('Primaire','Primaire'), ('College','Collège'),('Lycee','Lycée')) id=models.AutoField(primary_key=True) niveau=models.CharField(max_length=10,choices=NIVEAU,default='') nom=models.CharField(max_length=30,unique=True) adresse=models.ForeignKey(Adresse,on_delete=models.CASCADE,default='') def __str__(self): return '{}'.format(self.nom) class Etudiant(models.Model): id=models.AutoField(primary_key=True) nom=models.CharField(max_length=20) prenom=models.CharField(max_length=20) email=models.EmailField() tel=models.CharField(max_length=10) adresse=models.ForeignKey(Adresse,on_delete=models.CASCADE,default='') ecole=models.ForeignKey(Ecole,on_delete=models.CASCADE,default='') def __str__(self): return 'Nom : {} , Prénom : {}'.format(self.nom,self.prenom) class Parent(models.Model): id=models.AutoField(primary_key=True) nom=models.CharField(max_length=20) prenom=models.CharField(max_length=20) email=models.EmailField() tel=models.CharField(max_length=10) etudiant=models.ForeignKey(Etudiant,on_delete=models.CASCADE,default='') def __str__(self): return 'Nom : {} , Prénom : {}'.format(self.nom,self.prenom) Any recommendations ?