Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django factory boy post_generation in field with default value don't work
I have a model with a field that is a int type, that field have a default value I'm trying to set a value in that field with post_generation but nothing is happening, the field stay with the default value, when I try to use .set I get the following error: AttributeError: 'int' object has no attribute 'set' this is the field that I'm trying to populate @factory.post_generation def priority(obj, create, extracted, **kwargs): for series in range(obj.patrimony.count()): # this is a sequence of numbers series += 1 obj.priority.set(series) and this is the model, is just a simple model class Series(models.Model): priority = models.IntegerField(_("Priority"), default=0, null=True) Can someone open my eyes please? -
Complex Query from several models in django
I'm trying to query into three models. I need to get the amount products that are in the stores region location. These are my models: class Store(models.Model): name = models.CharField(max_length=255) logo = models.URLField(null=True, blank=True) user = models.OneToOneField(get_user_model(), models.CASCADE, related_name="user_store") region = models.CharField("Departamento", max_length=100) city = models.CharField("Ciudad", max_length=100) class Product(models.Model): name = models.CharField("Nombre del Producto", max_length=255) description = models.TextField() stock = models.PositiveIntegerField() seller = models.ForeignKey(User, on_delete=models.CASCADE) Product is related with user and it is related to store, what I want to do is something like this: { "Risaralda": 1523, "Cundinamarca": 8541 } where keys "Risaralda" and "Cundinamarca" are regions and values are the product amount in these places I tried something like this products = Product.objects.filter( seller__user_store__region__in=Store.objects.filter() .values("region").distinct()) And I got products in stores regions but i need to count how many products are in every store regions thank you a lot -
Django Session Form is not JSON Serialized
I'm trying to pass data from one view to another and im getting the following error . Exception Type: TypeError at /points/k8_points Exception Value: Object of type K8Points_ClassroomForm is not JSON serializable Here is my Views.py @login_required def K8_Points_Classroom(request): context_from_k8_points = request.session['k8_points_context'] if request.method == 'POST': form = K8Points_ClassroomForm() if form.is_valid(): form.save(commit=False) form.save() return render(request, 'points/k8_points_classroom.html', {'form': form}) else: return render(request, 'points/k8_pointsclassroom.html', {'form': form} ) else: form = K8Points_ClassroomForm() return render(request, 'points/k8_points_classroom.html', {'form': form} ) context_from_k8_points = request.session['k8_points_context'] @login_required def K8_Points(request): if request.method == 'POST': form = K8PointsForm(request.POST) if form.is_valid(): form.save(commit=False) classname = form.cleaned_data.get('class_name') date = form.cleaned_data.get('date') getstudents = Student.objects.filter(class_name = classname) students = getstudents.all() form = K8Points_ClassroomForm() context = {'form': form , 'students': students, 'classname': classname,'date': date,} request.session['k8_points_context'] = context return redirect('k8_points_classroom') else: return render(request, 'points/k8_points.html', {'form': form} ) else: form = K8PointsForm() return render(request, 'points/k8_points.html', {'form': form} ) Thank you for the help in advance ! -
QQplot using python and react
I want to display a qqplot in react webapp. My backend is Django and I can create a qqplot using import numpy as np import statsmodels.api as sm import pylab test = np.random.normal(20,5, 1000) sm.qqplot(test, line='r') pylab.show() sm.qqplot returns a matplotlib figure but I need the scatter plot and line data to send back to UI. Is there way extract that from the figure or is there a better way to do this ? -
Why can I access the Apache Tika server when using PyCharm but not from the command line?
I wrote a Python 3 program in PyCharm, and the program utilizes Apache Tika's parser. The relevant code looks like this. from tika import parser ... raw = parser.from_file(file_path) When I run the program using PyCharm, it works fine. I read that Java is required in order to access Tika, but as far as I know I don't have Java installed (interestingly, this post implies that Java is also needed for PyCharm). The only issue I experience is that I receive an error message as the program starts to run. So when I run the program in PyCharm, the initial output is... 2019-12-04 14:06:11,401 [MainThread ] [WARNI] Failed to see startup log message; retrying... and then the program runs successfully without me interacting with it. Parses beautifully. Well now I'm trying to use the same sort of Tika functionality in a Django project. I've got some code in views.py inside the Django project, and I can access it easily enough through urls.py. But when I add the Tika components and do my Django 'runserver' from the command line (the only way to do it as far as I know) this is what I receive. from tika import parser ... raw … -
Change bootstrap4 button "search" text
When I click to "Search" button on my site http://junjob.ru/ I go to http://junjob.ru/search/?q=&q2=ALL How can I change text "search" to "my_search" in this link? I need http://junjob.ru/my_search/?q=&q2=ALL I am using django web-framework. And fix should support queries from form My code vacancy_list.html <div class="container" style="margin-top: 40px; font-size: 2rem; padding-left: 0px;"> <form action="{% url 'search_results' %}" method="get"> <div class="row"> <div class="col-lg-8 col-md-6 col-xs-12"> <input name="q" type="text" placeholder="Search..." class="form-control"> </div> <div class="col-lg-3 col-md-4 col-xs-12"> <select name="q2" class="form-control" id="exampleFormControlSelect1"> <option>Other</option> </select> </div> <div class="col-lg-1 col-md-2 col-xs-12" style="padding-left: 0px;"> <button class="btn btn-primary">Search</button> <!-- BUTTON --> </div> </div> </form> </div> views.py class HomePageView(ListView): model = Vacancy template_name = 'vacancy_list/vacancy_list.html' paginate_by = 5 page_kwarg = 'vacancy' context_object_name = 'vacancies' queryset = Vacancy.objects.order_by('-published_date') def paginate_queryset(self, queryset, page_size): """Paginate the queryset, if needed.""" paginator = self.get_paginator( queryset, page_size, orphans=self.get_paginate_orphans(), allow_empty_first_page=self.get_allow_empty()) page_kwarg = self.page_kwarg page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1 try: page_number = int(page) except ValueError: if page == 'last': page_number = paginator.num_pages else: raise Http404(_('Page is not “last”, nor can it be converted to an int.')) try: page = paginator.page(page_number) return (paginator, page, page.object_list, page.has_other_pages()) except InvalidPage as e: raise Http404(_('Invalid page (%(page_number)s): %(message)s') % { 'page_number': page_number, 'message': str(e) }) def vacancy_detail(request, pk): vacancy = … -
Django Social Auth - Google: AttributeError: 'NoneType' object has no attribute 'provider'
I am receiving this error when trying to login via google, I've tried just about everything I can think of and similar issues on SO don't seem to help. I have a custom user model setup as such: models.py from django.contrib.auth.models import AbstractUser from django.db import models class Departments(models.Model): name = models.CharField(max_length=255, unique=True) def __str__(self): return self.name class AlluredUser(AbstractUser): departments = models.ManyToManyField(Departments) def __str__(self): return self.username forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import AlluredUser class CustomUserCreationForm(UserCreationForm): class Meta: model = AlluredUser fields = ('username', 'email') class CustomUserChangeForm(UserChangeForm): class Meta: model = AlluredUser fields = ('username', 'email') Social Auth Pipeline SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details' ) Error Traceback http://dpaste.com/12TG5RZ I'm guessing it has something to do with the custom user model I created since I didn't have this problem beforehand. Any help would be much appreciated. -
Django - Multiple Select Box - Save Changes to Database
I was able to get a multiple select box working for edit mode: <section class="container"> <div> <select id="leftValues" size="5" multiple></select> </div> <div> <input type="button" id="btnLeft" value="&lt;&lt;" /> <input type="button" id="btnRight" value="&gt;&gt;" /> </div> <div> <select id="rightValues" size="4" multiple> {% for device in devices %} <option>{{ device }}</option> {% endfor %} </select> </div> </section> <div> <input type="text" id="txtRight" /> </div> </section> But when I select the save button, after making changes to the table, again in the template, edit_maintenance.html, it does not feed into the database. I'm still fairly new to this so any tips, examples, would be great. -
How can I add CSS to my Django project website?
How can i add css to my django site? Map structure: pychache static css main.css templates Now I have this in my html: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Portfolio</title> {% load static %} <link href="{% static './css/style.css' %}" rel="stylesheet"> </head> <body> <p>portfolio</p> </body> </html> -
How to "load" dependent drop down upon page load?
I have a form with a dependent drop-down. This secondary drop-down is hidden whenever the primary option selected does not have any secondary options, and when the page first loads. Whenever the form is submitted, only the first field gets cleared out, since most of the time the drop-downs remain the same, however, since the script works whenever there is a change in the primary drop-down, since the load upon does not constitute a change, it just keeps the selected/submitted option on the primary drop-down, and will just display an empty secondary drop-down, even when the primary option selected does have secondary options. I got most of the JS from the drop-down from a tutorial, as I am not very familiar with it. For a more visual understanding: This is the form when the page first loads When you select an option that has secondary options, the other dropdown appears After you select a Station and submit, the Employee # clears, but the other two are supposed to remain, however, when the page reloads upon submission, it looks like this, and the station has been cleared according to the debugger since there are none technically. I don't care so much … -
Upgrading to Django 3 from Django 2.2.x
I'm trying to upgrade Django 2.2.7 to Django 3. I have an Exception with the load of static library in my template when it's called by tag {% load static from staticfiles %}. Stacktrace: Internal Server Error: / Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/template/defaulttags.py", line 1021, in find_library return parser.libraries[name] KeyError: 'staticfiles In the settings.py, staticfiles is config like this: STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = '/static/' And when requested by browser, Django answered: 'staticfiles' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log' Github code is here, PR is here Many thanks ! -
how do I connect my Django app with telegram to fetch channel messages?
I need some help in getting telegram messages in my Django app. I want to connect my django app with telegram user account and get the list of all channel. After user selects a specific channels, the messages of that channel should be displaying in my application The application should have the real-time messages. I'm using Mysql database to store the channel list and messages. Any help would be appreciated for this project. -
DataTable (JQuery): how to switch language with browser language?
I use DataTable in my Django project and currently doing internationalisation of my apps I would like DataTable change with browser language as for my templates. I have found the way to change language with DataTable option var table = $('#table_id').DataTable({ lengthMenu: [5,10], "language": { "url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/French.json" } }); is their a simple way doing it? or should I test for browser language and have a switch to initialize var table? something like that (pseudocode): if browser.lang == 'english'{ var table = $('#table_id').DataTable({ lengthMenu: [5,10], }); } else { var table = $('#table_id').DataTable({ lengthMenu: [5,10], "language": { "url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/French.json" } }); }``` -
Post a file to Django REST Framework without Headers/Footers
I am attempting to store a .csv file uploaded to Django REST Framework in its original format. I am following the instructions and the Django REST Framework page for uploading files. When I PUT a .csv file to a defined endpoint I end up waith a file with additional headers and footers. I am trying to save this file into a FileField in its original format so I can run some post-processing steps more easily. Steps I've taken: I created a model to store the file. from django.db import models class OriginFile(models.Model): uploaded_at = models.DateTimeField(auto_now_add=True) file = models.FileField(upload_to="origin_files/") And I created an APIView to handle the upload. from rest_framework import views from rest_framework.parsers import FileUploadParser from rest_framework.response import Response from reference.reference_model.models import OriginFile class OriginFileView(views.APIView): parser_classes = [FileUploadParser] def put(self, request, filename, format=None): f = request.data["file"] load_origin_file = OriginFile() load_origin_file.file.save(filename, f, save=True) return Response(status=204) What I am seeing: The first couple of lines of my original file look like: SPID,SA_ID,UOM,DIR,DATE,RS,NAICS,APCT,0:15,0:30,0:45,1:00,1:15,1:30,1:45,2:00,2:15,2:30,2:45,3:00,3:15,3:30,3:45,4:00,4:15,4:30,4:45,5:00,5:15,5:30,5:45,6:00,6:15,6:30,6:45,7:00,7:15,7:30,7:45,8:00,8:15,8:30,8:45,9:00,9:15,9:30,9:45,10:00,10:15,10:30,10:45,11:00,11:15,11:30,11:45,12:00,12:15,12:30,12:45,13:00,13:15,13:30,13:45,14:00,14:15,14:30,14:45,15:00,15:15,15:30,15:45,16:00,16:15,16:30,16:45,17:00,17:15,17:30,17:45,18:00,18:15,18:30,18:45,19:00,19:15,19:30,19:45,20:00,20:15,20:30,20:45,21:00,21:15,21:30,21:45,22:00,22:15,22:30,22:45,23:00,23:15,23:30,23:45,0:00 5001,5001,KWH,R,05/20/2018,A6,722000,100.0,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000200,0.022600,0.058100,0.100500,0.148500,0.251400,0.295800,0.359500,0.321400,0.365300,0.509800,0.571900,0.734700,1.121900,1.312700,1.358400,1.573900,1.270300,1.512500,1.359400,1.735500,1.759900,1.806400,1.501400,1.343900,1.396900,1.660400,1.924500,2.074300,2.037100,1.409000,1.371600,1.646600,1.591100,1.674500,1.751400,1.366200,1.404300,1.449400,1.405700,1.197900,0.679400,0.793800,0.772400,0.768200,0.969800,0.967400,0.833900,0.623500,0.474100,0.446600,0.368700,0.233500,0.133600,0.043800,0.011100,0.000300,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000 The first handful of lines of the stored file look like: ----------------------------434117419534676393692068 Content-Disposition: form-data; name="file"; filename="filename.csv" Content-Type: text/csv SPID,SA_ID,UOM,DIR,DATE,RS,NAICS,APCT,0:15,0:30,0:45,1:00,1:15,1:30,1:45,2:00,2:15,2:30,2:45,3:00,3:15,3:30,3:45,4:00,4:15,4:30,4:45,5:00,5:15,5:30,5:45,6:00,6:15,6:30,6:45,7:00,7:15,7:30,7:45,8:00,8:15,8:30,8:45,9:00,9:15,9:30,9:45,10:00,10:15,10:30,10:45,11:00,11:15,11:30,11:45,12:00,12:15,12:30,12:45,13:00,13:15,13:30,13:45,14:00,14:15,14:30,14:45,15:00,15:15,15:30,15:45,16:00,16:15,16:30,16:45,17:00,17:15,17:30,17:45,18:00,18:15,18:30,18:45,19:00,19:15,19:30,19:45,20:00,20:15,20:30,20:45,21:00,21:15,21:30,21:45,22:00,22:15,22:30,22:45,23:00,23:15,23:30,23:45,0:00 5001,5001,KWH,R,05/20/2018,A6,722000,100.0,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000200,0.022600,0.058100,0.100500,0.148500,0.251400,0.295800,0.359500,0.321400,0.365300,0.509800,0.571900,0.734700,1.121900,1.312700,1.358400,1.573900,1.270300,1.512500,1.359400,1.735500,1.759900,1.806400,1.501400,1.343900,1.396900,1.660400,1.924500,2.074300,2.037100,1.409000,1.371600,1.646600,1.591100,1.674500,1.751400,1.366200,1.404300,1.449400,1.405700,1.197900,0.679400,0.793800,0.772400,0.768200,0.969800,0.967400,0.833900,0.623500,0.474100,0.446600,0.368700,0.233500,0.133600,0.043800,0.011100,0.000300,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000 And the last couple of lines of the stored file look like this. 5090,5090,KWH,D,11/04/2018,A6,713910,104.2,0.333000,0.319000,0.332000,0.309000,0.326500,0.321000,0.322500,0.320000,0.296000,0.322000,0.323000,0.334000,0.321000,0.334000,8.098000,7.043000,1.422000,0.322000,0.323000,0.335000,0.322000,0.322000,0.322000,0.334000,0.336000,0.340000,0.392000,0.584000,0.200000,0.054000,0.176000,0.156000,0.090000,0.000000,0.002000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.002000,0.001000,0.009000,0.014000,0.020000,0.032000,0.054000,0.055000,0.086000,0.127000,0.151000,0.168000,0.220000,0.245000,0.299000,0.282000,0.317000,0.328000,0.314000,0.327000,0.315000,0.328000,0.316000,0.328000,0.318000,0.323000,0.328000,0.319000,0.327000,0.325000,0.320000,0.332000,0.319000,4.420000,3.531000,2.584000,0.458000,1.001000,0.263000,0.263000,0.261000,0.260000,0.258000 ----------------------------434117419534676393692068-- Is there a way … -
Upgrading Python 3.6 to 3.8
I downloaded python 3.8 expecting it to update python 3.6 with all my packages intact. instead it installed as a separate version so i now have two python versions installed on windows 10. -
How to create model objects of one model automatically when a model object of another has been added in django
Say for example I have a Model called Player. I want Model objects of Player created when new Users are added in django (from django.contrib.auth.models.User) such that each User object in User model has its own object in Player model. I know that I would technically have to use models.ForeignKey() to create a field in Player model and relate it to the User model and that I don't have to worry about deletion of users if I use the on_delete=models.CASCADE parameter in models.ForeignKey() but how do I automatically create these objects with like default values and such. Initially this was my code to do so: for name in User.objects.all().values_list('username', flat=True): if name not in Player.objects.all().values_list('player_name', flat=True): new_player = Player(player_name=name, current_level_no=None, no_of_moves=None) new_player.save() else: pass But this would give me a DatabaseIntegrityError that "Models aren't loaded yet". So I am confused about what to do or how to go forward. As always, I greatly appreciate all answers! -
Django POST error: tuple has no attribute get, despite similar code working previously
I'm working on a page that autofills an html dropdown with data from a Django model, then on submit, sends that data to another page that will do things with it. I have the html dropdown populated, but am having issues POSTing to another page. I keep getting "AttributeError at /battleSim/ 'tuple' object has no attribute 'get' as my error despite similar code working in my characterCreator template. I get this error as soon as I attempt to navigate to battleSim.html on the development server, despite the fact it shouldn't be trying that until a POST method runs. (I think?) Below is the relevant code: views.py: class CharacterCreatorView(TemplateView): template_name = "characterCreator.html" # this solution courtesy of Eliakin Costa on StackOverflow: https://stackoverflow.com/a/59112612/12352379 def post(self, request, *args, **kwargs): userID = 'testUser' addCharacter( userID, str(request.POST.get('characterName')), str(request.POST.get('race')), str(request.POST.get('class')), str(request.POST.get('strength')), str(request.POST.get('dexterity')), str(request.POST.get('constitution')), str(request.POST.get('intelligence')), str(request.POST.get('wisdom')), str(request.POST.get('charisma')) ) return render(request, self.template_name, {}) class battleSimView(TemplateView): template_name = "battleSim.html" def get(self, request, *args, **kwargs): character = characterTable.objects.all() # use filter() when you have sth to filter ;) monster = monsterTable.objects.all() return render(request, self.template_name, {'characters':character, 'monsters':monster},) def post(self, request, *args, **kwargs): if(request.method == "POST"): characterID = str(request.POST.get('character_id')) monsterID = str(request.POST.get('monster_id')) return(render(request, template_name ="battle.html"), {'characterID': characterID, 'monsterID': monsterID},) battleSim.html form: <div … -
Highcharts graph not displaying in Django template html
I am making a website using Django/python/sqlite3. I am also using the ebay-python-sdk to query ebay database and get back information based off of keywords. I am trying to convert the timestamp into milliseconds and pass those values into a Highcharts x-axis, and the final sell price of the item to the y-axis. The graph is not displaying in the Django template (called 'graphs.html'). My code is below: display_graphs/views.py from django.shortcuts import render from ebaysdk.finding import Connection as finding import xmltodict from json import loads, dumps import pandas as pd import datetime import matplotlib.pyplot as plt import io from matplotlib.backends.backend_agg import FigureCanvasAgg from django.http import HttpResponse content_df = pd.DataFrame() def display_the_graphs(request): keywords = request.POST.get('search') api = finding(appid='JohnHein-homepage-PRD-392e94856-07aba7fe', config_file=None, siteid='EBAY-US') api_request = {'keywords':keywords, 'itemFilter':[{'name':'SoldItemsOnly', 'value':True},]} response = api.execute('findCompletedItems', api_request) content = response.content xml_dict = xmltodict.parse(content) content_dict = to_dict(xml_dict) count = content_dict['findCompletedItemsResponse']['searchResult']['@count'] item_dict = content_dict['findCompletedItemsResponse']['searchResult']['item'] print('count:', count) content_df = extract_values(item_dict) x_values = content_df['endPrice'].tolist() y_values_b = content_df['endTime'].tolist() y_values = convert_datetime(y_values_b) context = { 'response': content_df.to_html(), 'content_df': content_df, 'x_v': x_values, 'y_v': y_values } return render(request, 'display_graphs/graphs.html', context) ''' def get_time_graph(request): fig, ax = plt.subplots() ax.set_title('Scatter plot of prices over time') ax.set_xlabel('dates') ax.set_ylabel('sell prices') ax.scatter(content_df.endDate.values, content_df.endPrice.values, s=10, label='sell prices over time') canvas = FigureCanvasAgg(fig) buf … -
How to add two fields of django model and save the sum in another field?
class example(models.Model): var1 = models.IntegerField(default=0) var2 = models.IntegerField(default=0) var3 = models.IntegerField(default=0) sum = var1 + var2 + var3 Can anyone help me to save the sum of the three field and save it in the sum field of the model? -
How do I fix Django changes made outside of my virtual environment?
I am new to Django and new to the virtualenv scene. I have been working on a Django project for a couple of days and completely forgot to activate my venv on my second day. I am using this tutorial to guide me and I have been working from within my activated environment up until this point.... Is it enough to just re-run manage.py after activating my venv? -
Simple operations with data requested from a Django model
I am trying to write a simple web application, where i can upload csv files and return the headers from each file. Everything is working fine. The id, the path to the file, gets saved in a database. This is the response i am getting: { "id": 1, "filefield": "http://127.0.0.1:8000/api/merged/1/uploads/header_body_test_zZr4Cea.csv" } What i do not understand is, where or how can i actually work with the data i request from the database? What i am imagining is a different url route, where i can specify an id and the response would be something like this: { "id": 1, "filefield": "http://127.0.0.1:8000/api/merged/1/uploads/header_body_test_zZr4Cea.csv" "headers_of_csv": "Date;Amount" } Its hard for me to explain (or google) what my problem actually is. I dont understand where or how the code to do this would actually be (is it part of the serializer, or the view, or in the model?). Or even in simpler terms, lets say i have a model, that had an id and a 3 digit number and returns this: { "id": 1, "number": 567 } How or where could i create a respone like this: { "id": 1, "number": 567 "first_digit_or_number": 5 } Any help is greatly appreciated, i just dont understand what … -
How to use crud operation in django?
I facing the issue in the Django crud operation. I tried to create a crud operation using Django. All operations are working fine but update operation only is not working. because I tried to click the edit button and show the data in the edit form and also change the data in the form and click the update button in the URL is changing this type (http://localhost:8000/show/6/update/6) . I need this URL (http://localhost:8000/update/6). I tried many ways but I could not get an error where is occurred.any one can run my code and give comments. How to solve this issue. Project urls.py from django.contrib import admin from django.conf.urls import url,include urlpatterns = [ url('admin/', admin.site.urls), url(r'^',include('olcapp.urls')) ] Application urls.py from django.conf.urls import url from olcapp import views urlpatterns = [ url(r'^$',views.get), url(r'^post/$',views.post), url(r'^show/([0-9]+)/$',views.getId), url(r'^update/([0-9]+)/$',views.update,name='update'), url(r'^delete/([0-9]+)/$',views.delete), ] views.py from django.shortcuts import render from django.http import HttpResponse from .models import CrudOperation from .forms import CrudForm # Create your views here. def get(request): form = CrudForm() data = CrudOperation.objects.all() return render(request,'index.html',{'form':form,'data':data}) def getId(request,id): form = CrudForm() data = CrudOperation.objects.get(id=id) return render(request,'edit.html',{'form':form,'data':data}) def post(request): form = CrudForm(request.POST) if form.is_valid(): form.save() return HttpResponse('<h1>post Method</h1>') def update(request,id): print(id) data = CrudOperation.objects.get(id=id) form = CrudForm(request.POST,instance=data) if(form.is_valid()): form.save() … -
How to properly serialize a Django querySet into json format
I use a QuerySet to fetch data from PostgreSQL database in Django. To serialize the returned Object into json I use the built-in from django.core import serializers. Estimated Outcome: Get a json object to work with Issue: Though the object doesn't look that bad (like the example in the docs), it seems I end up with a str rather than a json format. def getAccountInfo(): account_information = serializers.serialize('json', AccountInformation.objects.all()) print(account_information) print(type(account_information)) profit = account_information[2].fields[0].account_information print(profit) return HttpResponse() getAccountInfo() Print: [{"model": "Dashboard.accountinformation", "pk": "30e61aec-0f6e-4fa0-8c1b-eb07f9347c1f", "fields": {"version": "1.00", "accountNumber": 1925323, "broker": "Activtrades Plc", "leverage": "100", "account_balance": 99943.49, "account_profit": -245.4, "account_equity": 99698.09, "account_margin": 328.59, "account_margin_free": 99369.5, "account_margin_level": 30340.73, "account_currency": "EUR"}}, {"model": "Dashboard.accountinformation", "pk": "8b46c7c7-1bc8-4736-8dc5-7d5f012d594b", "fields": {"version": "1.00", "accountNumber": 1925323, "broker": "Activtrades Plc", "leverage": "100", "account_balance": 99943.49, "account_profit": -247.42, "account_equity": 99696.07, "account_margin": 328.59, "account_margin_free": 99367.48, "account_margin_level": 30340.11, "account_currency": "EUR"}}] <class 'str'> Traceback (most recent call last): File "C:/Users/Jonas/Desktop/Dashex/Dashex/Dashex/urls.py", line 28, in <module> from Dashboard.views import getAccountInfo File "C:\Users\Jonas\Desktop\Dashex\Dashex\Dashboard\views.py", line 22, in <module> getAccountInfo() File "C:\Users\Jonas\Desktop\Dashex\Dashex\Dashboard\views.py", line 17, in getAccountInfo profit = account_information[2].fields[0].account_information AttributeError: 'str' object has no attribute 'fields' Process finished with exit code 1 Human-eye-version of account_information object: -
Django: return count of items after filter is applied in ListView
I want to render the total items for a filtered queryset. I've a model UnitaryProduct and I can return the total of items with: context['total_stickers'] = UnitaryProduct.objects.all().count() Inside get_context_data, but I wouldlike to also return the particular amount of items when users apply a filter by category. This is how I filter items based on user selection: This is the ListView, get_queryset I've a condition to use the captured filter_val: class CatalogoListView(ListView): model = UnitaryProduct template_name = "shop/catalogo.html" paginate_by = 10 def get_queryset(self): filter_val = self.request.GET.get('filtro', 'todas') order = self.request.GET.get('orderby', 'created') if filter_val == "todas": context = UnitaryProduct.objects.all().filter(available=True).order_by('-created') return context else: context = UnitaryProduct.objects.filter( subcategory2=filter_val, ).filter(available=True).order_by('-created') return context def get_context_data(self, **kwargs): context = super(CatalogoListView, self).get_context_data(**kwargs) context['filtro'] = self.request.GET.get('filtro', 'todas') context['orderby'] = self.request.GET.get('orderby', 'created') context['category'] = Category.objects.get(slug="catalogo") context['total_stickers'] = UnitaryProduct.objects.all().count() return context I've tried to put add stickers_por_categoria to the queryset but nothing gets rendered in template: def get_queryset(self): filter_val = self.request.GET.get('filtro', 'todas') order = self.request.GET.get('orderby', 'created') if filter_val == "todas": context = UnitaryProduct.objects.all().filter(available=True).order_by('-created') return context else: context = UnitaryProduct.objects.filter( subcategory2=filter_val, ).filter(available=True).order_by('-created') context['stickers_por_categoria'] = UnitaryProduct.objects.filter( subcategory2=filter_val, ).filter(available=True).order_by('-created').count() return context template: <div class="margin-bottom5"> <h2> Actualmente contamos con {{ total_stickers }} stickers en nuestro catálogo</h2> <span>Revisa todos utilizando nuestro filtro por categoría y … -
Files getting erased whenever i run deployment
whenever i run a new deployment on heroku, all already uploaded files will be removed, It's a Django application which i deployed on heroku through my github repository, please how can i stop this from happening? Any help will be appreciated.