Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to iterate through dictionary in Django model?
Each brand in our Campaign model has an order count. The count is retrieved by a GET request to the respective brand's site. The GET request requires an API key and password for each respective brand. The keys and passwords are stored and decoupled in settings.py and the count is passed through to a template with a table. How do we loop through our dictionary of keys and passwords (as in the below) to map an order count to each brand? class Campaign(models.Model): brand = models.CharField(max_length=140, default='') api_key = { 'BRAND1': settings.BRAND1_API_KEY, 'BRAND2': settings.BRAND2_API_KEY, } password = { 'BRAND1': settings.BRAND1_PASSWORD, 'BRAND2': settings.BRAND2_PASSWORD, } orders_url = 'https://{}:{}@site.com/admin/orders/count.json'.format(api_key['brand'], password['brand']) orders_response = requests.get(orders_url) orders_json = orders_response.json() orders = mark_safe(json.dumps(orders_json)) -
Django User object disappears from request object after successful login and redirect
I have the following very simple test view: def login_user(request): user = auth.authenticate(username='me', password='letmein') #works auth.login(request, user) #works return redirect(reverse('my_app:login_check')) All of which works as specified in the docs. But when I inspect the request object in the view to which I redirect I see that user is an instance of AnonymousUser and also that the session attribute of request is empty. The database still has the data. I am using Django 1.10, Python 3.4 and my db is MySQL 5.7. Please help--many hours already lost on this issue! -
Daemonize python websocket
I'm using ubuntu 16, django 1.9, and running everything on top of docker. I'm making a bitcoin bot for fun just to try and build something to show off. I'm stuck getting the Binance API which is a websocket to daemonize correctly. Here is how I'm going about it: Run containers in docker in websocket.sh script execute a docker command that runs the scrapping function in the live docker container: websocket.sh: docker exec <container name> <something to run, bash etc...> <args> docker exec 817d359aff51 python myproject/scrapping.py I'm using this command to run the websocket.sh file: Terminal: nohup ./websocket.sh script args > script.out 2>&1 However it never gives me back my terminal, and instead indefinitely runs. When I tail -f script.out it shows the correct behavior. How can I daemonize this task better? I've looked into django-celery, cron jobs, and the & function but none seem to be what I want. I just want to execute the task from the command line and have it scrape data as a background process. I've determined this is the best way to do it because I can't find any proper way to do it within the django framework upon startup. If I use init.py … -
Django csrf unwanted token rotation
Using Django 1.97 the following view: @staff_member_required def admin_news_categories_json(request): nodes_list = [] for node in NewsCategory.objects.filter(parent__isnull = True): n = { 'id' : node.id 'title' : node.title, } nodes_list.append(n) return HttpResponse(json.dumps(nodes_list)) is causing the CSFR token to be change (rotated) everytime it is loaded. It is called via ajax from an admin form so is causing the form submission to fail through CSFR token mismatch. If I remove @staff_member_required decorator the CSFR remains unchanged! I have another view with the csfr_exempt decorator and that view also changes the csfr token. Is this a known bug or a feature? :) -
AttributError: 'str' object has no attribute 'path' django
I am getting the error above when I attempt 'manage.py migrate' in django 1.11.7: full traceback below. (also, using python 3.5) I get the error regardless of anything that I change. I even deleted from the site everything that I have done to models.py, views.py, urls.py, and forms.py, etc. and still the same error comes along when I attempt to migrate. I could really use some help working out what is going on! Traceback: Applying app.0041_auto_20180221_2033...Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/aristarchusthefish/my-blog/myvenv/lib/python3.5/site- packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/aristarchusthefish/my-blog/myvenv/lib/python3.5/site- packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/aristarchusthefish/my-blog/myvenv/lib/python3.5/site- packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/aristarchusthefish/my-blog/myvenv/lib/python3.5/site- packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/aristarchusthefish/my-blog/myvenv/lib/python3.5/site- packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/aristarchusthefish/my-blog/myvenv/lib/python3.5/site- packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/aristarchusthefish/my-blog/myvenv/lib/python3.5/site- packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/aristarchusthefish/my-blog/myvenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/aristarchusthefish/my-blog/myvenv/lib/python3.5/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/aristarchusthefish/my-blog/myvenv/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/home/aristarchusthefish/my-blog/myvenv/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 515, in alter_field old_db_params, new_db_params, strict) File "/home/aristarchusthefish/my-blog/myvenv/lib/python3.5/site- packages/django/db/backends/postgresql/schema.py", line … -
Override JsonField Django REST framework
I've used JSONfield in my serilizer and as the user in the thread store json as dict points out, DRF with Mysql stores JSONfield as a dict However I would rather store it as JSON {"tags":{"data":"test"}} instead of the default behavior of storing it as Dict - {'tags': { 'data': 'test'}} - Daniel suggests using over riding the JSONfield as: class JSONField(serializers.Field): def to_representation(self, obj): return json.loads(obj) ...... However the data is still stored as dict. In my serializers.py I've the overridden the JSONField class and then used it as such class schemaserializer(serializers.ModelSerializer): js_data=serializers.JSONField() However it still saves it as as a dict. Expected behavior: Save it as JSON - POST retrieve it as dict - GET (so that the render can parse it as JSON) Am currently doing this manually using json dumps and json loads, but looking for a better way. The reason to do this is because although I have an API there are instances where users read my DB directly and they need the field to be in a JSON. Django (2.0.1) Python 3.5 djangorestframework (3.7.7) -
Building a form from three models in Django - need some minor tweaks
I am currently having three models linked together, but the main model is Lecture. I wanted to allow the user to add lectures data to my models. The thing is that the user needs to be able to add lectures only for a course, but to able to upload many files to the lecture. What I tried is this: def classroom(request): if request.method == 'POST': form = LectureForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = LectureForm() context = { 'form': form } return render(request, 'courses/classroom.html', context) class LectureForm(forms.ModelForm): course = forms.ModelChoiceField(queryset=Course.objects.all()) lecture_category = forms.ChoiceField(choices=LECTURE_CHOICES) lecture_title = forms.CharField(max_length=100, required=True) content = forms.Textarea() files = forms.FileField(queryset=FileUpload) class Meta: model = Lecture fields = ('course', ' lecture_category', 'lecture_title', 'content', 'files') class Course(models.Model): name = models.CharField(max_length=50, unique=True) class Lecture(models.Model): LECTURE_CHOICES = ( ('Courses', 'Courses'), ('Seminars', 'Seminars'), ) course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures') lecture_category = models.CharField(max_length=10, choices=LECTURE_CHOICES, default='Courses') lecture_title = models.CharField(max_length=100) content = models.TextField() class FileUpload(models.Model): files = models.FileField(upload_to='documents', null=True, blank=True) lecture = models.ForeignKey('Lecture', related_name='files', on_delete=None, default=None) But I get following errors: Unknown field(s) ( lecture_category) specified for Lecture. I also do not know how to bind properly FileUpload and Course to the form. Little advice ? -
Don't know how to change the background photo of bootstrapping template
I am learning the django framework and using bootstrap as my frontend. I tried to use the bootstrap theme (https://startbootstrap.com/template-overviews/creative/) However, I cannot find where to replace the background photo of the first page. I cannot locate where is the 'scr img=' code in the html file. Can anyone advise. Thanks. -
Response returned before save complete django
There are two calls that happen back to back on client side: Create the order, return the order id Charge the customer, pass the order id The order model is fairly large and calls Order.save() a couple times during the first call. However, the response from (1) is returned before the saving has finished because the wrong price is charged to the customer. Basically, the order price gets updated once the drink price and modifier price gets calculated and the response is returned after the drink price is calculated but does not wait for the modifier price. I have narrowed down the logic to here: def create(self, request): ... self.perform_create(serializer, request, drinks, foods) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) ... def perform_create(self, serializer, request, drinks, foods): serializer.save(drinks=drinks, foods=foods) ... def save(self, *args, **kwargs): ... super(Order, self).save(*args, **kwargs) ... def customerdrinkorder_presave(sender, instance, **kwargs): """ custom pre_save processes of :model:'drinks.CustomerDrinkOrder' """ try: milk_price = instance.milk.price except AttributeError: milk_price = Decimal(0) instance.price = instance.quantity * (instance.customer_drink.store_drink.price + milk_price) def customerdrinkorder_postsave(sender, instance, created, **kwargs): """ custom post_save processes of :model:'drinks.CustomerDrinkOrder' """ order = instance.order print("LIMES1") update_order_total(order) def customerdrinkmodifier_presave(sender, instance, **kwargs): """ custom pre_save processes of :model:'drinks.CustomerDrinkModifier' """ instance.price = instance.quantity * instance.modifier.price def … -
Django doesn't check for a csrf token with Ajax post
According to the Django docs, Django should have csrf token validation enabled by default, using a middleware. When I look in my settings file I indeed see the middleware being included. However, when I do a post request without a csrf token using Ajax, Django will just allow it. Should it not return an error saying the csrf token is invalid? I am seeing a lot of questions from people who can't get their csrf token validated, but I can't get it INvalidated. This is my Ajax post function (I collect the data from my inputs with js, and pass it to this function): function ajaxPost(url, data, success) { fetch(url, { method: 'POST', // or 'PUT' body: JSON.stringify(data), headers: new Headers({ 'Content-Type': 'application/json' }) }).then(res => res.json()) .then(response => { if (response.status !== success) { //errors } updateView(response); }) .catch(error => console.error('Error:', error)) } And this is my view function: @api_view(['POST']) # API endpoint for posting bulk properties def bulk(request): new_properties = [] if request.method == 'POST': for obj in request.data: discipline = Discipline.objects.get(pk=obj['discipline.id']) root_function = Function.objects.get(pk=obj['root_function']) new_property = Property(name=obj['name'], value=obj['value'], unit=obj['unit'], discipline_id=discipline) new_property.save() new_property.function.add(root_function) new_properties.append(new_property) new_properties = json.loads(serializers.serialize('json', new_properties)) return JsonResponse({'status': 201, 'new_properties': new_properties}) -
Django - Sqlite Database
Any help is greatly appreciated. I am using Django and SQLite, I am trying to join the auto generated auth_user table with an input table that I have created using a model. Models.py; class Input(models.Model): height = models.IntegerField(default=0) waist = models.IntegerField(default=0) bust = models.IntegerField(default=0) hips = models.IntegerField(default=0) class Meta: db_table = "Project_input" The purpose of joining the tables is so that when a user logs in the information they enter into my input table is only associated with them. I understand that I have to add a foreign key to this model! But how do I reference the auth_user table? -
Position absolute for <img/> when using xhtml2pdf (Django)?
Can I generate PDF with CSS position: absolute; for <img src="..."/> html tag? I need to place handwritten signature and company stamp (PNG files) to bottom of order voucher. Something like this: -
'User' object has no attribute 'backend' using Python 3.5 and Django 1.8
I am making a project using python 3.5 and Django 1.8 ,there is a feature for login and signup, so login and signup are two different apps THIS image shows my directory structure of apps Now in login app's form , I import from signup.models allusers1 (a class in signup.models) Using view I pass the form .and when I enter the credentials in the database eg checkit and 12345 (username and password) ,I get this error AttributeError at /login/ 'User' object has no attribute 'backend' This is login/forms.py from django import forms from signup.models import allusers1 from django.contrib.auth import ( authenticate, login, logout, get_user_model, ) User=get_user_model() class UserLoginForm(forms.ModelForm): class Meta: model = allusers1 fields=['username','password'] widgets = { 'password': forms.PasswordInput(), } def clean(self ,*args,**kwargs): username=self.cleaned_data.get("username") password=self.cleaned_data.get("password") user_qs = User.objects.filter(username=username) if user_qs.count() == 0: raise forms.ValidationError("The user does not exist") else: if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("Incorrect password") if not user.is_active: raise forms.ValidationError("This user is no longer active") return super(UserLoginForm,self).clean(*args,**kwargs) This is signup/models.py from django.db import models from django import forms # Create your models here. class allusers1(models.Model): username=models.CharField(max_length=40) password=models.CharField(max_length=40) phoneno=models.CharField(max_length=10,primary_key=True) otp=models.IntegerField(blank=True,null=True,default=0000) def __str__(self): return self.username login/views.py from django.shortcuts import render,redirect from .forms import UserLoginForm … -
Django single website structure
I want to start a new django project. This will just be a relatively simple website to test django itself. So the way all tutorials structure their project is this: mysite mysite some_app ... For me it's not very clear what does what. I don't really need any app right now. Could I implement my website without using any app? Should I use an app? What would it be called for a simple website? -
AttributeError: 'unicode' object has no attribute 'create_connection' in Django Push Notification
In my project, I am using django-push-notifications for sending push notification to mobile devices. But I am getting following error. [2018-02-22 13:41:20,881: ERROR/ForkPoolWorker-1] Task ballogyApi.tasks.notification_tasks.send_notification_task[e6a5984a-d3b9-4570-a24e-be61702ca4e5] raised unexpected: AttributeError("'unicode' object has no attribute 'create_connection'",) Traceback (most recent call last): File "/home/hassan/venv/ballogy/local/lib/python2.7/site-packages/celery/app/trace.py", line 374, in trace_task R = retval = fun(*args, **kwargs) File "/home/hassan/venv/ballogy/local/lib/python2.7/site-packages/celery/app/trace.py", line 629, in __protected_call__ return self.run(*args, **kwargs) File "/home/hassan/Project/ballogy/ballogyApi/tasks/notification_tasks.py", line 41, in send_notification_task data=data File "/home/hassan/Project/ballogy/ballogyApi/tasks/notification_tasks.py", line 16, in send_notification android_response_function, ios_response_function, bulk, **data) File "/home/hassan/Project/ballogy/ballogyApi/utils/notification_utils.py", line 37, in perform_notification_process to_user, android_response_function, ios_response_function, bulk, **kwargs) File "/home/hassan/Project/ballogy/ballogyApi/utils/notification_utils.py", line 47, in send_notification_to_user to_user, android_response_function, ios_response_function, *args, **kwargs) File "/home/hassan/Project/ballogy/ballogyApi/utils/notification_utils.py", line 90, in send_single_notification badge=not_count + total_requests) File "/home/hassan/venv/ballogy/local/lib/python2.7/site-packages/push_notifications/models.py", line 167, in send_message **kwargs File "/home/hassan/venv/ballogy/local/lib/python2.7/site-packages/push_notifications/apns.py", line 113, in apns_send_message certfile=certfile, **kwargs File "/home/hassan/venv/ballogy/local/lib/python2.7/site-packages/push_notifications/apns.py", line 66, in _apns_send client = _apns_create_socket(certfile=certfile, application_id=application_id) File "/home/hassan/venv/ballogy/local/lib/python2.7/site-packages/push_notifications/apns.py", line 38, in _apns_create_socket use_alternative_port=get_manager().get_apns_use_alternative_port(application_id) File "/home/hassan/venv/ballogy/local/lib/python2.7/site-packages/apns2/client.py", line 39, in __init__ self._init_connection(use_sandbox, use_alternative_port, proto) File "/home/hassan/venv/ballogy/local/lib/python2.7/site-packages/apns2/client.py", line 48, in _init_connection self._connection = self.__credentials.create_connection(server, port, AttributeError: 'unicode' object has no attribute 'create_connection' Kindy help me solving this issue. -
Django: User.object.get() logs user in
I am just a beginner in Django but I have come across very interesting problem. I am not logged in on my webpage, but after I want to see someone's profile it automatically logs me in that user. It seems like a huge security hole. I also put print statement in and it says that user is authenticated. Answers will be appreciated. views.py def login_view(request): form = UserLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request, user) return render(request, "home/login.html", {'form': form}) def user_feedView(request, username): try: userU = User.objects.get(username=username) print(userU.is_authenticated) except User.DoesNotExist: raise Http404("User does not exist") return render(request, 'home/user_feed.html', {'user': userU}) urls.py urlpatterns = [ path('user/<username>/', views.user_feedView, name='username'), path('logout/', views.logout_view, name='logout'), path('login/', views.login_view, name='login'), path('', views.index, name='home') ] -
Setting up django with celery,
I am trying to set up celery with django on my development server, running on windows. Following are changes i made. I followed steps by this link http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html Filestructure Noisebox -Noisebox --__init__.py --celery.py --settings -rehearsalbooking --tasks.py init.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'noisebox.settings') app = Celery('noisebox') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py from celery import shared_task from .models import Room from django.utils import timezone @shared_task def calculate_timeslots(room_id): room = Room.objects.get(id=room_id) room.create_timeslots_until_license_expires(timezone.now()) return True When i run the task, the task gets sent to the celery server, but is not executed. (noisebox-env) C:\Users\jonas>celery worker -------------- celery@DESKTOP-MH2SD2S v4.1.0 (latentcall) ---- **** ----- --- * *** * -- Windows-10-10.0.16299-SP0 2018-02-22 14:22:38 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: default:0x29efc50 (.default.Loader) - ** ---------- .> transport: amqp://guest:**@localhost:5672// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [2018-02-22 14:22:39,439: ERROR/MainProcess] Received unregistered task of type … -
Django mapping tables - concatenate?
ive seen a few questions on here sort of similar but none that assist me in creating what I actually need. Im using Django 1.11 and I have some mapping tables as an example below, where the site and circuit values are foreign IDs id | site | circuit ------------------- 1 | 1 | 1 2 | 1 | 11 3 | 2 | 4 4 | 3 | 6 5 | 2 | 1 so from the data above I can see circuit 1 is used on site 1 and site 2. so I would like a query that will show site | circuit -------------- 1,2 | 1 1 | 11 2 | 4 ... I found the this How to concat two columns of table django model but it seems to concat on a set string? where as I need to concat on site_id where circuit_id is the same can anyone assist with this, these sorts of functions are beyond my skill level. Thanks -
Django does not seem to account for DayLightSavings
In my models I want to update the last_edited value of the Submission object everytime the UserAnwser object is saved. To this end I've written the following code from django.utils import timezone ... class UserAnswer(models.Model): answer = models.FloatField() question = models.ForeignKey(Question, related_name='answers') submission = models.ForeignKey(AssessmentSubmission, related_name='answers') #Update submission.last_edited on answer. def save(self, *args, **kwargs): submission = self.submission submission.last_edited = timezone.now submission.save() super(UserAnswer, self).save(*args, **kwargs) I've set the correct timezone in the settings.py file: LANGUAGE_CODE = 'nl' TIME_ZONE = 'Europe/Amsterdam' USE_I18N = True USE_L10N = True USE_TZ = True However, everytime I change the answer and lookup the submission.last_edited value in our django-rest api, the time is 1 hour behind the actual time. Its almost as if the time is being displayed in 'summer time' and the DST is not handled correctly. For example, if I edit an answer at 13:30, our api will return 12:30 Since the settings.TIMEZONE has been set and I am using django's django.utils timezone object its not clear to me what I doing wrong, could someone point me towards the right direction? -
Django test error arguments 0 given
I'm having trouble running this function: def test_custom_mail_server_connection(host, port, user, password, use_tls, recipient): ''' Test connection of mailing server with given user params returns None if mail is sent successfully, a string containg the error otherwise ''' result = None message_list = [] tenant = get_tenant_by_schema_name(connection.schema_name) # create new mail_connection mail_connection = mail.get_connection() mail_connection.host = host mail_connection.port = port mail_connection.username = user mail_connection.password = password mail_connection.use_tls = use_tls from_email = '%s <%s>' % (tenant.name, mail_connection.username) subject = _(u'%(name)s: SMARTFENSE - Prueba de servidor de correo propio') % {'name': tenant.name} mail_content = SimpleTemplateResponse("emails/email_server_test.html", { 'host': host, 'port': port, 'user': user, 'use_tls': use_tls, }, content_type="text/html", charset="utf-8").render().content msg = mail.EmailMessage( subject, mail_content, from_email, [recipient] ) msg.content_subtype = 'html' message_list.append(msg) try: mail_connection.open() mail_connection.send_messages(message_list) except Exception as e: result = "%s" % e finally: mail_connection.close() set_mail_connection_config(mail_connection, 'default') return result That basically checks if a given mail host is right in order to use it. I wrote this test: def test_test_custom_mail_server_connection(self): result = test_custom_mail_server_connection('smtp.gmail.com', 587, 'xxxxx@gmail.com', 'xxxxxxx', True, []) self.assertEqual(result, None) And I'm getting the next error: ERROR: Test connection of mailing server with given user params ---------------------------------------------------------------------- Traceback (most recent call last): File "/Volumes/Datos/Diamo/Smartfense/env/lib/python2.7/site-packages/nose/case.py", line 197, in runTest self.test(*self.arg) File "/Volumes/Datos/Diamo/Smartfense/env/lib/python2.7/site-packages/nose/util.py", line 620, in newfunc … -
How do I pass the request object to the method_decorator in django class views?
I have been working on this all day. I am trying to write custom permission for class views to check if user is in a certain group of permissions. def rights_needed(reguest): if request.user.groups.filter(Q(name='Admin')).exists(): pass else: return HttpResponseRedirect('/account/log-in/') @method_decorator(right_needed, name='dispatch') class AdminView(CreateView): model = Admin form_class = AdminForm def get_template_names(self): return 'clinic/visitform_list.html' Could help me know how I can achieve this? Or an easier way around it? I also tried this (code inside AdminView class): def dispatch(self, request): if request.user.groups.filter(Q(name='Admin')).exists(): return super().dispatch(*args, **kwargs) else: return HttpResponseRedirect('/account/log-in/') -
Dynamic Django-REST API Endpoint in jQuery
I have a view which calls results_chart.html which contains a jquery block which specifies an REST-API endpoint. This endpoint is currently hardcoded like: var endpoint = '/api/solgeo/projects/2.json'; However of course I want the correct project id, which I can access in the {% block content %} section using Django templating. I.e. the project Id is specified by {{project.id}}. How can I access this project.id in my jQuery section? The html template in question is given by: {% extends 'base.html' %} <script> {% block jquery %} var endpoint = '/api/solgeo/projects/2.json'; var defaultData = [] var labels = [] $.ajax({ method: "GET", url: endpoint, success: function(data){ var length = data.hourlys.length for (i=0; i<length; i++){ defaultData[i] = data.hourlys[i].clock_time labels[i] = i.toString() } console.log("The default data is: " + defaultData.toString()) setChart() }, error: function(error_data){ console.log("error") console.log(error_data) } }) function setChart(){ var ctx = document.getElementById("myChart").getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: labels, datasets: [{ label: '# ??????', data: defaultData, }] } }) } {% endblock %} </script> {% block content %} <h3>Project id: {{ project.id }}</h3> <div class='row'> <div class='col-sm-12'> <canvas id="myChart" width="400" height="400"></canvas> </div> </div> {% endblock content %} -
DRF - Django Url Filter - RelatedFieldError
I am working on DRF generic listview with DUF as filter backend. Could you please assist me to get around this error? I am sure i am doing something wrong here with related to related fields. When i try to filter on url I get the following error. I would like to filter on all columns of child model. http://127.0.0.1:8000/api/childlist/?customer_id=2 AttributeError at /api/childlist/ 'OneToOneField' object has no attribute 'rel' Below is my work so far: models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Parent(models.Model): customer_id = models.BigIntegerField(primary_key=True) customer_name = models.CharField(blank=True, null=True, max_length=50) age = models.IntegerField(blank=True, null=True) class Child(models.Model): customer_id = models.OneToOneField(Parent, on_delete=models.DO_NOTHING, related_name='customer_id_fk_parent') used_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='rel_user') comments = models.TextField(blank=True,null=True) views.py from rest_framework import generics from onetoone.models import Child from .serializers import Child_Serializer from url_filter.integrations.drf import DjangoFilterBackend #Required columns on Child -- All columns FILTER_REQ_COLUMNS = [field.name for field in Child._meta.get_fields()] class ChildList(generics.ListAPIView): queryset = Child.objects.all() serializer_class = Child_Serializer filter_backends = [DjangoFilterBackend] filter_fields = FILTER_REQ_COLUMNS serializers.py from rest_framework import serializers from onetoone.models import Child class Child_Serializer(serializers.ModelSerializer): class Meta: model = Child exclude = [] urls.py path('childlist/', ChildList.as_view(), name='api_child_list'), Current list data as below http://127.0.0.1:8000/api/childlist/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: … -
How to pass values from a dropdown list to the view in django
I have searched quite extensively for a clear answer to my problem but have not been able to find anything. I have am currently displaying the first 5 items from a database and want to add a feature that allows the user to toggle between ascending and descending order using the current rent column. But i am having trouble passing the request from the dropdown list and returning a new sql query dependant on the users input. HTML FILE Views.py -
Share Heroku postgresql with desktop app
I am using Heroku Postgresql in django(Python framework) app but now a days i am working on a desktop version of my application using same language that is Python. So, How can i connect my desktop(Python app) to heroku postgesql database. Or any other best option is always welcome.