Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My django form returns empty cleaned_data
I have a simple Form, view and a html that renders the form. but the problem is that the form always returns form.is_valid == False. So I have checked the cleaned data but I noticed that self.cleaned_data returns an empty list. Here is the relevant code: class GraphForm(forms.Form): from_month = forms.DateField(widget=forms.Select(choices=MONTHS)) from_year = forms.DateField(widget=forms.Select(choices=YEARS)) to_month = forms.DateField(widget=forms.Select(choices=MONTHS)) to_year = forms.DateField(widget=forms.Select(choices=YEARS)) def clean(self): return self.cleaned_data <<< will always stay be empty def showgraph(request): if request.method == 'POST': form = GraphForm(request.POST) if form.is_valid(): >>> will never happen <<< ... ... ... else: form = GraphForm() return render(request, 'graph.html', {"form": form}) <form method="post"> {% csrf_token %} {{ form.from_month }} {{ form.from_year }} <br> {{ form.to_month }} {{ form.to_year }} <br> <p align="center"> <button type="submit" class="btn btn-primary">send</button> </p> </form> Can anyone help with this peculiar problem? -
Django - In Detail View Tabs Displaying Partial View when Tab Selected
`I am using Django and have a detail view that is collecting all of the information I want to display; however, I would like to use Tabs to consolidate the view and not have 4 pages displayed. In the anchor tab, there is no need to reference another URL since I am having no issues pulling the data into the single view. I just want to create If Statements for the tabs and corresponding partial display. Can anyone provide me with guidance on the following? I have been searching for anchor tag attributes that I can use with if statements, but I am not finding anything here or in general Google searches. This seems like it should be a pretty easy fix. <div class="nav nav-tabs" id="nav-tab" role="tablist"> <a class="nav-item nav-link" id="portfolio" data-toggle="tab" href="" role="tab">Portfolio</a> <a class="nav-item nav-link" id="securities" data-toggle="tab" href="" role="tab">Securities</a> </div> {% include 'partials/_portolio.html' %} {% include 'partials/_securities.html' %} My ideal result is that if the Tab Portfolio is selected, that only the partial view for Portfolio will be displayed (Also, I would want this as the default). If I selected the Securities tab, that would be the only partial view displayed. -
Django first migration issue
Using PyCharm and following a step-by-step guide to setup a cookiecutter django project. Can't seem to get past the migrate command. This is my first time using the cookiecutter project template and I haven't had issues before when creating projects from scratch. Not sure what the issue is but it looks like it may be related to the PyCharm installation files. Error is listed below: "C:\Program Files\JetBrains\PyCharm 2018.3\bin\runnerw64.exe" C:\Users\willi\AppData\Local\Programs\Python\Python36-32\python.exe "C:\Program Files\JetBrains\PyCharm 2018.3\helpers\pycharm\django_manage.py" migrate C:/Users/willi/PycharmProjects/fishgutz Tracking file by folder pattern: migrations Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2018.3\helpers\pycharm\django_manage.py", line 52, in run_command() File "C:\Program Files\JetBrains\PyCharm 2018.3\helpers\pycharm\django_manage.py", line 46, in run_command run_module(manage_file, None, 'main', True) File "C:\Users\willi\AppData\Local\Programs\Python\Python36-32\lib\runpy.py", line 205, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File "C:\Users\willi\AppData\Local\Programs\Python\Python36-32\lib\runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "C:\Users\willi\AppData\Local\Programs\Python\Python36-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:/Users/willi/PycharmProjects/fishgutz\manage.py", line 30, in execute_from_command_line(sys.argv) File "C:\Users\willi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\willi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\willi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management__init__.py", line 216, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Users\willi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management__init__.py", line 36, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "C:\Users\willi\AppData\Local\Programs\Python\Python36-32\lib\importlib__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", … -
Django Edit Form Secure Way
I have edit form (modelform) and for that form I created a url something like /contacts/edit// My view is method base view and I am passing the contact_id from my template to the view as parameter. Then that's what I am doing: def edit_contact(request, contact_id): is_user_authenticated(request.user.is_authenticated) contact_person = get_object_or_404(domain.Contact.contacts, pk=contact_id) if request.method == 'POST': form = forms.ContactPersonForm(request.POST, instance=contact_person) if form.is_valid(): form.save() return HttpResponseRedirect('/contacts/') However that url can be reached by any user with just giving ID and basically you can edit any person you want. I could do one more query to DB in order to find if a person is the right person to edit contact information but is that right way to do that? What's best practice for my situation? -
Google Charts not showing data
I have this template: {% block header %} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <div align="center" style="margin-top:35px;"><a href="/"><button type="button" class="btn btn-primary">Back to latest</button></a></div> {% endblock %} {% block body %} <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <div id="chart_div" style="width: 900px; height: 500px;"><div> <script type='text/javascript'>//<![CDATA[ google.charts.load('current', {packages: ['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Currency', 'Rate', { role: 'style' }], ['USD', parseFloat({{rates.0}}), 'gold'], ['GBP', parseFloat({{rates.1}}), 'silver'], ['HKD', parseFloat({{rates.2}}), 'brown'], ['AUD', parseFloat({{rates.3}}), 'blue'], ['SEK', parseFloat({{rates.1}}), 'red'], ['JPY', parseFloat({{rates.2}}), 'yellow'], ['NOK', parseFloat({{rates.3}}), 'orange'], ['EUR', parseFloat({{rates.3}}), 'orange'], ]); var options = { title: 'Exchange rate overview', chartArea: {width: '50%'}, hAxis: { title: '', minValue: 0 }, vAxis: { title: '' } }; var chart = new google.visualization.BarChart(document.getElementById('chart_div')); chart.draw(data, options); } //]]> </script> {% endblock %} Right now, it shows me this: What's wrong with it? It should show some bars with data, any ideas? The json data is actually being feteched by the way, it's from a Django application. If You need further explanation, please let me know. -
"No module named x.y" error in Heroku but works locally
My project works perfectly locally but a ModuleNotFoundError arises from my INSTALLED_APPS when I deploy the app on Heroku. Particularly: "No module named x.y", and AttributeError: "Module x has no attribute y" My project structure is like this: main -settings.py x -y and in my settings.py I have import sys sys.path.append('x') INSTALLED_APPS{ x.y } This works fine locally, but triggers those two errors when I deploy the app on Heroku. Any help is welcome, thank you in advance! -
The current path, accounts/home.html, didn't match any of these
I've been reading the docs and several questions already answered, but nothing seems to work, so here it the question. I'm starting with django and I can't manage to get rid of the following error: Using the URLconf defined in alpha_trader.urls, Django tried these URL patterns, in this order: __debug__/ [name='home'] accounts/update [name='user_change'] accounts/ login/ [name='login'] accounts/ logout/ [name='logout'] accounts/ password_change/ [name='password_change'] accounts/ password_change/done/ [name='password_change_done'] accounts/ password_reset/ [name='password_reset'] accounts/ password_reset/done/ [name='password_reset_done'] accounts/ reset/<uidb64>/<token>/ [name='password_reset_confirm'] accounts/ reset/done/ [name='password_reset_complete'] accounts/signup [name='user_signup'] The current path, accounts/update.html, didn't match any of these. Hereby my settings.py: # Custom Django auth settings AUTH_USER_MODEL = 'accounts.User' LOGIN_URL = 'login' LOGOUT_URL = 'logout' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' Hereby urls.py: from django.urls import include, path from django.conf import settings from accounts import views urlpatterns = [ path('', include('accounts.urls')), path('accounts/', include('django.contrib.auth.urls')), path('accounts/signup', views.SignUpView.as_view(), name='user_signup'), ] hereby accounts/urls.py: from django.urls import include, path from accounts import views urlpatterns = [ path('', views.home, name='home'), path('accounts/update', views.UserUpdateView.as_view(), name='user_change'), ] hereby accounts/views.py: def home(request): if request.user.is_authenticated: return redirect('accounts/home.html') return render(request, 'accounts/home.html') and finally accounts/models.py: from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.html import escape, mark_safe class User(AbstractUser): is_student = models.BooleanField(default=False) num_of_saved_backtests=models.IntegerField(default=0) num_of_online_indicators=models.IntegerField(default=0) Does anyone sees the error in my code? … -
Django - Setting current form to update (Function Based View)
How do I set my current form to update on form submit based on the current logged in user and not repeat form submissions in the django admin? This may be a stupid question but I'm new to django. Any help i gladly appreciated, Cheers Screenshot user_profile/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from user_profile.forms import HomeForm from users.forms import CustomUserCreationForm, CustomUserChangeForm from user_profile.models import Listing from users.models import CustomUser # Register models here. class UserProfileAdmin(admin.ModelAdmin): list_display = ['name', 'address', 'zip_code', 'mobile_number', 'created', 'updated', 'user'] list_filter = ['name', 'zip_code', 'created', 'updated', 'user'] admin.site.register(Listing, UserProfileAdmin) user_profile/models from django.contrib import auth from django.db import models from django.urls import reverse from django.contrib.auth.models import AbstractUser, UserManager from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from users.forms import CustomUserCreationForm, CustomUserChangeForm from users.models import CustomUser class Listing (models.Model): image = models.ImageField(default='default.jpg', upload_to='profile_pics') user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=100) address = models.CharField(max_length=100) zip_code = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = Listing.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=CustomUser) user_profile/views.py from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from … -
Stacked Bar Chart using Django and high chart
I am new to Highcharts. I am using Django QuerySet data to create stacked column highchart but I am not getting it correct. Here is the QuerySet data ` <QuerySet [{ 2013: {comp1 : 1000,comp2:1500, comp3 : 1400, comp4: 2000}, 2014: {comp1 : 900,comp2:1600, comp3 : 1200, comp4: 2500}, 2015: {comp1 : 1200,comp2:1500, comp3 : 1440, comp4: 2000}, 2016: {comp1 : 1400,comp2:1300, comp3 : 900, comp4: 2200} }]` In my template I am passing the series like this <div id="container"></div> <script src="https://code.highcharts.com/highcharts.src.js"></script> <script> Highcharts.chart('container', { chart: { type: 'column' }, title: { text: 'Stacked column chart' }, xAxis: { categories: [ {% for year in years_profit %}{{ year.season }}{% if not forloop.last %}, {% endif %}{% endfor %} ] }, yAxis: { min: 0, title: { text: 'Total Match Won' }, stackLabels: { enabled: true, style: { fontWeight: 'bold', color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray' } } }, legend: { align: 'right', x: -30, verticalAlign: 'top', y: 25, floating: true, backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white', borderColor: '#CCC', borderWidth: 1, shadow: false }, tooltip: { headerFormat: '<b>{point.x}</b><br/>', pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}' }, plotOptions: { column: { stacking: 'normal', dataLabels: { enabled: true, color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white' } } … -
I can not alter my my serializer before saving it
I can not alter my my serializer before saving it at first try modifying the method def perform_create but the error was this using this code def perform_create(self, serializer): key = self.request.META.get('HTTP_APIKEY', b'') store_obj = StoreApiKey.objects.get(key=key) serializer.save(store=store_obj.store) but got that. Got aTypeErrorwhen calling Order.objects.create () . This may be because you have a writable field on the serializer class that is not a valid argument toOrder.objects.create (). You may need to make the field read-only, or override the CreateOrderSerializer.create () method to handle this correctly. then try to modify the serializer method def create (self, validated_data): validated_data ['store'] = self.context ['store'] super (CreateOrderSerializer, self) .create (validated_data) but this tells me Field name customer_number is not valid for modelOrder. Do you have any ideas that you can give me? I will place my code here class OrderAPIView(generics.ListCreateAPIView): authentication_classes = (ApiKeyAuth,) queryset = Order.objects.all() serializer_class = CreateOrderSerializer def list(self, request): # queryset = self.filter_queryset(self.get_queryset()) # key = self.request.META.get('HTTP_APIKEY', b'') # store_obj = StoreApiKey.objects.get(key=key) # filter_kwargs = {'store': store_obj} # obj = get_object_or_404(queryset, **filter_kwargs) serializer = ListOrderSerializer(self.queryset, many=True) return Response(serializer.data) def perform_create(self, serializer): key = self.request.META.get('HTTP_APIKEY', b'') store_obj = StoreApiKey.objects.get(key=key) serializer.save(store=store_obj.store) def get_serializer_context(self): ctx = super().get_serializer_context() key = self.request.META.get('HTTP_APIKEY', b'') store_obj = StoreApiKey.objects.get(key=key) … -
"Column 'story' cannot be null", even though fill the column in views.py
I got this error when I tried posting a new story: IntegrityError at /rubies/new_story/ (1048, "Column 'story' cannot be null") I do not understand why this is happening, since I did input a column story. Here is my code: models.py class Story(models.Model): title = models.CharField(max_length=200) story = models.TextField(default="") date = models.DateTimeField(default=datetime.now()) author = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.IntegerField(default=0) comments = models.IntegerField(default=0) def __str__(self): return "%s %s %s " % (self.title, self.story, self.date) forms.py class NewStoryForm: title = forms.CharField(max_length=200, required=True, help_text='Required.') story = forms.CharField(required=True, help_text='Required.') date = datetime.now() class Meta: model = Story fields = ('title', 'story', 'date') views.py def new_story_view(request): s = Story() if request.method == 'GET': form = NewStoryForm() else: s.title = request.POST.get('title') s.story = request.POST.get('story') s.date = timezone.now() s.save() return render(request, "rubies/new_story.html", {'form': form}) new_story.html {% extends "rubies/base.html" %} {% block content %} <div class="post-preview"> <h2 class="post-title" style="font-size: 36px; color: #F2968A; margin-top: -25px; margin-bottom: 10px;"> Write a new story </h2> </div> <form action="{% url 'rubies:new_story' %}" method="post"> <div class="form-group"> <input type="text" id="title" name="title" class="form-control" placeholder="Title" value="{{ story.title }}"/> </div> {% csrf_token %} <div class="form-group"> <textarea id="text" name="text" class="form-control" placeholder="Your story" rows="20">{{ story.story }} </textarea> </div> <button type="submit" class="btn btn-primary" style="float:right; background-color: #F2968A; border-color: #F2968A;">Save </button> </form> {% endblock … -
i have a django code where if we enter url/music it displays a line and url/music /65 (any integer) then it shows another page
the page with the integer provided is showing not found 404 from django.urls import path from . import views urlpatterns = [ path('',views.index,name='index'), path('(?p<album_id>[0-9]+)',views.detail,name='detail'), #[0-9]for 10 albums [0-9]+for infinity ] inside views.py from django.http import HttpResponse def index(request): return HttpResponse("<h1>this is the music app homepage</h1>") def detail(requests,album_id): return HttpResponse("<h2>details for "+ str(album_id)+"</h1>") expected - details for 65(entered integer) actual-404 not found -
How can I display images from media directory into template? Django
I'm using Django to create my own administration panel. But if I try to display the images uploaded from the Django Admin Panel, the browser tell me that not found the image. I've added the MEDIA_URL and the MEDIA_ROOT to the settings.py but if I get and try to print this variable I don't see anything in the template. settings.py MEDIA_ROOT = '/' MEDIA_URL = '/media/' models.py class HomePhoto(models.Model): image_path = models.ImageField(upload_to='media/home/photos/', null=False, blank=False) home = models.ForeignKey(Home, on_delete=models.CASCADE, related_name='home_photos', null=False, blank=True) views.py ... def get_context_data(self, **kwargs): context = super(HomeDetailView, self).get_context_data() context['title'] = context['home'].address context['home_photos'] = home_models.HomePhoto.objects.filter(home=context['home'].pk) return context template.html {% load static %} {% get_media_prefix as MEDIA_URL %} {% block content %} ... {% for photo in home_photos %} <div class="{% if forloop.first %}active{% endif %} item" data-slide-number="0"> <img src="{{ MEDIA_URL }}{{ photo.image_path }}"> </div> {% endfor %} ... {% endblock %} -
Django auth: self.request.user is always Anonymous in viewset
I'm trying to make the server only return documents which were created by the logged-in user. I'm following this post and this one but the logged in user is returned as "Anonymous". I am using Django Rest Framework with Django Rest Auth, and a custom user, but no other customisations. Django 2.0.10 Here is my viewset in api.py: from rest_framework import viewsets, permissions from .models import List, Item from .serializers import ListSerializer, ItemSerializer class ListViewSet(viewsets.ModelViewSet): # queryset = List.objects.all() # permission_classes = [permissions.AllowAny, ] model = List serializer_class = ListSerializer def get_queryset(self): print(self.request.user) return List.objects.filter(created_by=self.request.user) def pre_save(self, obj): obj.created_by = self.request.user Settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], } AUTH_USER_MODEL = 'users.CustomUser' # django rest auth ACCOUNT_AUTHENTICATION_METHOD = 'email' I've read other posts about this issue which all talk about custom middleware, but I haven't created a custom middleware unless django-rest-framework or django-rest-auth is actually such a thing? And the posts don't seem to show how to get the user in the viewset. Also the posts are old, so Django has probably changed. From this post I tried the following, it did not work: class ListViewSet(viewsets.ModelViewSet): # queryset … -
Running specific views.py method on django_cron
I have this method on my views.py file: def getHistoricRates(): """ Here we have the function that will retrieve the historical rates from fixer.io, since last month """ rates = {} response = urlopen('http://data.fixer.io/api/2018-12-31?access_key=c2f5070ad78b0748111281f6475c0bdd') data = response.read() rdata = json.loads(data.decode(), parse_float=float) rates_from_rdata = rdata.get('rates', {}) for rate_symbol in ['USD', 'GBP', 'HKD', 'AUD', 'JPY', 'SEK', 'NOK', 'EUR']: try: rates[rate_symbol] = rates_from_rdata[rate_symbol] except KeyError: logging.warning('rate for {} not found in rdata'.format(rate_symbol)) pass return rates @require_http_methods(['GET', 'POST']) def historical(request): date_str = "2018-12-31" if datetime.datetime.strptime(date_str,"%Y-%m-%d").weekday()<5: rates = getHistoricRates() fixerio_rates = [Fixerio_rates(currency=currency, rate=rate) for currency, rate in rates.items()] Fixerio_rates.objects.bulk_create(fixerio_rates) return render(request, 'historical.html') I want to run historical at 9am every day, except for weekends. Now, I can't find any example on how to run an existent method, or how to call it from the cron.py file whatsoever. I do have everything configured, for django_cron but I just can't figure out how to "use" this method from my cron file to run it at specific times. This is my cron.py file so far: from django_cron import CronJobBase, Schedule from .views import historical class MyCronJob(CronJobBase): RUN_AT_TIMES = ['9:00'] schedule = Schedule(run_at_times=RUN_AT_TIMES) code = 'fixerio.my_cron_job' # a unique code def do(self): pass # do your thing here The … -
Django: Cannot assign "'Emma'": "Booking.boat" must be a "Boat" instance
I have been trying to make boat reservation system. # models.py class Boat(models.Model): name = models.CharField (max_length=10, unique=True, blank=False) type = models.CharField (max_length=10, blank=False) class Booking(models.Model): date_from = models.DateField(auto_now=False, auto_now_add=False) date_to = models.DateField(auto_now=False, auto_now_add=False) rent = models.DecimalField(max_digits=7, decimal_places=2) boat = models.ForeignKey(Boat, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) A new boat is registered through this form: class newBoatform(forms.Form): name = forms.CharField(label='Name of the boat: ', max_length=15) type = forms.CharField(label='Type of the boat: ', max_length=15) class Meta: model = Boat fields = ('name','type',) A boat is booked through this form: class bookform(forms.Form): boat =forms.CharField(label='Select boat',max_length=15) date_from=forms.DateField(label='Date from', initial=date.today) date_to=forms.DateField(label='Date to') rent = forms.DecimalField(label='Pay $ ') class Meta: model = Booking fields = ('date_from','date_to','rent','boat','person',) To book a boat through the bookform, I am inserting an existing boat name and other field information. Then I am getting the error: Cannot assign "'Emma'": "Booking.boat" must be a "Boat" instance. The view function of the bookform: def bookBoat(request): if request.method == 'POST': form = bookform(request.POST) if form.is_valid(): obj = Booking() obj.boat = form.cleaned_data['boat'] obj.date_from = form.cleaned_data['date_from'] obj.date_to = form.cleaned_data['date_to'] obj.rent = form.cleaned_data['rent'] obj.save() return HttpResponseRedirect('/thanks/') else: form = bookform() return render(request, 'booking.html', {'form': form}) I can't understand what is wrong. Other answers on this same error are … -
How do I prevent Django from sending certain information to ADMIN when errors occur
My goal is to filter out some of the information going out via email when an error occurs in Django (production). if Debug=False Django sends an email to admin containing 3 areas: the Traceback, the Request and app Settings. The current default Django logging works for me, I'm only asking about the best way to filter out information under Settings from going out via email? Thanks -
Populating a Dropdown from Database in Django
Hi so basically i am trying to populate a dropdown menu from the database I currently have. This will enable the 'Teacher' to select the 'Student' they are inputting grades for. I am struggling to understand any of the tutorials online due to most of them being for django 1.9 where as im using 2.1. Please if you could help it would be much appreciated. Template <form action="{% url 'subject1_view' %}" method="post"> {% csrf_token %} <div class="form-group row"> <label class="col-2 col-form-label" for="information">Student Name</label> <div class="col-10"> <form method="POST"> <select class="form-control" name="student_name" id="information"> {% for ?? %} <option value="{{ ?? }}">{{ ?? }}</option> {% endfor %} </select> </form> </div> </div> Urls from django.urls import path, include from . import views urlpatterns = [ path('teacher_login', views.teacher_login, name='teacher_login'), path('t_dashboard', views.t_dashboard, name='t_dashboard'), path('subject1_view', views.subject1_view, name='subject1_view'), path('loguserout', views.loguserout, name='loguserout'), ] Views def subject1_view(request): if request.method == 'POST': student_name = (request.POST.get('student_name')) current_grade = (request.POST.get('current_grade')) previous_grade = (request.POST.get('previous_grade')) target_grade = (request.POST.get('target_grade')) incomplete_homework = (request.POST.get('incomplete_homework')) behaviour_rank = (request.POST.get('behaviour_rank')) i = Subject1(student_name=student_name, current_grade=current_grade, previous_grade=previous_grade, target_grade=target_grade, incomplete_homework=incomplete_homework, behaviour_rank=behaviour_rank) i.save() return render(request, 'Teacher/dashboard.html') else: return render(request, 'Teacher/subject1.html') Models from django.db import models from Student.models import Student # Create your models here. class Subject1(models.Model): student_name = models.ForeignKey(Student, on_delete=models.CASCADE) current_grade = models.CharField(max_length=2) previous_grade = … -
Celery: Why isn't my while loop running correctly
I am using celery to run a python script within a django environment to measure weight from a load cell using a raspberry pi. I am measuring a bottle of water and it relays the information to the webserver. The python code below runs perfectly when ran in a python environment inside the terminal, but when it is ran by a celery worker, the value from the hx.get_weight(5) function within the while loop never changes. The weight is suppose to be always changing, but the weight value from the function stays the same when ran by a celery worker. It seems like the while loop is running the weight function once at the beginning, but never runs it again, however it keeps running the print command that outputs the same weight value every second while the while loop is true. When I run the script in a regular python environment outside of celery, the weight is constantly changing every print output. The python code is working correctly, but celery seems to only want to run the following function in the while loop once... val = hx.get_weight(5) This function returns the weight of the load cell, but this function seems to … -
Missing manytomany field while rendering table with django-tables2
I have two Django models -- one of which contains a ManyToManyField field. I would like to have all the objects in that field rendered in a table with django-tables2. My latest approach is based on this question: many to many in django-tables2), however, when I look at the rendering, the field for list_pi is empty in every row and if I click on the table header list_pi, I get the following error: Cannot resolve keyword 'list_pi' into field. Choices are: id, pdf, pi, status, submission_date I have a definition for list_pi that should return a list of pi l_names, what am I missing? Any assistance is greatly appreciated. models.py class PI(models.Model): l_name = models.CharField('L Name', blank=False, max_length=100, default='') f_name = models.CharField('F Name', blank=False, max_length=100, default='') ... class Grant(models.Model): submission_date = models.DateField(null=True, blank=True) pi = models.ManyToManyField(PI) status_choices = (('Accepted', 'Accepted'), ('Rejected', 'Rejected')) status = models.CharField('Status', max_length=8, null=True, blank=True, choices = status_choices) pdf = models.CharField('PDF', default='', max_length=500, blank=True) def filename(self): return self.pdf def get_absolute_url(self): return reverse('grant-detail', args=[str(self.id)]) def __str__(self): #return f'{self.pi}, {self.submission_date}' return '%s, (%s)' % (self.submission_date, ', '.join(p.l_name for p in self.pi.all())) @property def list_pi(self): return ', '.join([p.l_name for p in self.pi.all()]) tables.py class GrantTable(tables.Table): #pi = tables.LinkColumn('pi-detail', args=[A('pk')]) list_pi … -
cannot find reference to charfield
i made a model of music with 2 classes album and song but Charfield keyword is shown as cannot find reference 'Charfield' in init.py i just started django so go easy on the answers from django.db import models class Album(models.Model): artist=models.Charfield(max_length=250) album_title=models.Charfield(max_length=500) genre=models.Charfield(max_length=100) album_logo=models.Charfield(max_length=1000) class Song(models.Model): album-models.ForeignKey(Album,on_delete=models.CASCADE) file_type=models.Charfield(max_length=10) song_title=models.Charfield(max_length=250) -
Registering Django App in Settings.py file
I would like to know what is the benefit of different method for registering in INSTALLED_APPS. Suppose i have create a new app named pages in Django Project. I can write name of app in INSTALLED_APPS like this- INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages', ] But i am totally confused why people write like this- INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages.apps.PagesConfig', ] Is this a standard way to write? Is this correct way? Are there any benefits? -
Display ManyToManyField attribute in the admin list_filter
I have the following django models: class Instrument(models.Model): name = models.CharField(max_length=700, blank=False) instrument_type = models.CharField(max_length=700, blank=False) class Student(models.Model): name = models.CharField(max_length=700, blank=False) instruments_played = models.ManyToManyField(Instrument) And I would like to be able to do a list_filter on the instruments (right panel) in the admin view. So I tried: class StudentAdmin(admin.ModelAdmin): list_display = ('name', 'instruments_played__name') list_filter = ('instruments_played__name') but it does not work, most likely because of the ManyToManyField. I would like to be able to filter the students based on the instruments they play (each student can play several of them). Thanks for your help! -
DJANGO 2.0 Can I replace a ForeignKey and add PositiveIntegerField to store the pk only
I want to replace the user ForeignKey by a PositiveIntegerField is it permitted? models.py from: from_user = models.ForeignKey(settings.AUTH_USER_MODEL,related_name = 'sender_%(class)s' ,on_delete = models.CASCADE) to: from_user = models.PositiveIntegerField(editable = False) -
Speech to text/Audio input in django
import speech_recognition as sr def speechToText(): r = sr.Recognizer() with sr.Microphone() as source: r.adjust_for_ambient_noise(source) print("Say something") audio = r.listen(source) try: print("You said\n" + r.recognize_google(audio)) except Exception as e: print(e) I have the following script to take input from mic and convert it to text using the API. Although, I am unable to figure out how to hook this code up with a template in Django. Plox help.