Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to list the data dynamicly in html in django?
I tried to create a html page to list the all datas from my database with django, but it was not working. this is my code: item.html {% for p in product %} <div> <table> <tr><th>{{p.item}}</th><th>{{p.rate}}</th></tr> <tr><td></td><td></td></tr> </table> <button > addcard</button><br> <button> remove card </button> {% endfor %} views.py from .models import dishes def item(request): products = dishes.objects.all() return render(request, 'item.html', {'product' : products}) I got this code from online, it did not work and at the same time it did not show any error. please tell me how to solve this problem. -
Disable/Remove default permissions from django's third party library (django-celery-beat)?
When we setup django-celery-beat to my django project. It migrates the models from the library along with the default permissions. But, in my case I don't want those default permissions to be setup on my system permissions. I know it's possible to delete permissions for self created model by setting meta's default_permission = []. But how can I do that for a third party library in django? -
How to handle stale model instance with long db update in Django/Postgres?
Context: Medium-sized web app Django 3.2, DRF 3.13, python 3.8 Hosted in Google cloud and managed by goole kubernetes engine Google CloudSQL for PostgreSQL (v. 9) class Park(models.Model): <some fields> class City(models.Model): foo = models.IntegerField() # bar and baz are populated from a microservice at City creation bar = models.IntegerField() # baz was recently added and is null for some cities baz = models.IntegerField(null=True) @property def update_from_microservice(self): """Updates the row by making a call to a microservice hosted in the same cluster as the Django App""" new_data = call_to_microservice(self.foo) self.bar = new_data["bar"] self.baz = new_data["baz"] self.save() @property def get_data(self) """Helper method that returns some structured data from the instance""" return {"bar": self.bar, "baz": self.baz} class ParkListView(generics.ListAPIView): serializer = ParkSerializer http_method_names = ["get"] def get_queryset(self): return Park.objects.filter() def get_serializer_context(self): context = super().get_serializer_context() # Get the city from the uri `/parks/<int:city_foo>/` foo = kwargs.get("city_foo") this_city = City.objects.get(foo=foo)) city_data = this_city.get_data() # Check that the expected data is present. if None in city_data.values(): # If data is missing, try updating the fields # Tests indicate this step works as expected, # since the update_from_microservice() refers to self, this instance should # get the updated values once the microservice returns this_city.update_from_microservice() # Get the … -
how to print text on top of each bar graph in apexchart
I am using apexchart to output a chart. The code is as below, and I don't want the chart to include the ongo value, but only the value of ongo to be printed on top of each bar. ex) ongo: {{ ongo | safe }} I tried adding enabled: true, enabledOnSeries in the datalabels setting, but the result I want is not output. The values for I, S, P, E are reflected in the chart, output as datalabel, and only the ongo value is displayed as text on top of each bar. [dashboard.html] <div id="dashboard"> <script> var options3 = { series: [ { name: 'I', data: {{ I | safe }} }, { name: 'S', data: {{ S | safe }} }, { name: 'P', data: {{ P | safe }} }, { name: 'E', data: {{ E | safe }} }, { name: 'ongo', data: {{ ongo | safe }} }, ], chart: { type: 'bar', height: 550, stacked: true, }, plotOptions: { bar: { dataLabels: { position: 'center', }, } }, dataLabels: { style: { fontSize: '10px', colors: ["#304758"] } }, stroke: { width: 1, colors: ['#fff'] }, title: { text: 'I-S-P-E chart', offsetY: 0, align: 'center', }, … -
How to convert images produced by html canvas to .ai(adobe illustrator) file format in either frontend or backend process?
I'm developing a webapp to edit photos and trying to download them as adobe illustrator (.ai) file format. The webapp has two parts frontend and backend. React for frontend, and Django restframework for backend. The photos are edited within a html canvas element, and the canvas is controlled by JavaScript. Th code below converts the canvas element to a dataURL, so I can see the compiled image after hitting the url. The url shows it is png format. var canvas = document.getElementById("myCanvas"); var dataURL = canvas.toDataURL(); And the url looks like this. data:image/png;base64,iVBORw0KGgoAAA... Is there any way to convert the canvas image to .ai(adobe illustrator) file format using ether JavaScript, React for frontend, or python for backend process? -
adding addresses to a model via django's admin.py and with django-address
I am having a problem with my django app. I am trying to add a model of restaurants that has an address field, and I am using django-address to help me with this. So, my Restaurant model looks like this: class Restaurant(models.Model): name = models.CharField(max_length=64) address = AddressField(on_delete = models.CASCADE, default = None) However, when I go to add a specific restaurant using admin.py, it doesn't let me. As shown in the screenshot below, I type in one character and then it does not allow me to edit it: Screenshot of admin.py I have been able to add specific addresses themselves, but I can't figure out how to connect these addresses to a specific restaurant. Does anyone have any ideas about how to fix this? Or, does anyone have any nice work-arounds where I can add some specific restaurants without using admin.py? Thanks!! -
Django's Cast function returns DataError: invalid input syntax for type integer: "John"
I have the following models that allow me to dynamically create and track data for a contact: class DataField(models.Model): name = models.CharField() class Contact(models.Model): created_on = models.DateTimeField() class ContactField(moddels.Model): contact = models.ForeignKey(Contact) data_field= models.ForeignKey(DataField) value = models.CharField() For example I have two DataField models with the name field set as "First Name" and "Loan Amount". To create data for a contact, I create two ContactFields, the first I link to the "First Name" data field and give it the value "John", the second I link to the "Loan Amount" data field and give it the value 5000. e.g: ContactField(1) contact = Contact(1) data_field = DataField(First Name) value = "John" ContactField(2) contact = Contact(1) data_field = DataField(Loan Amount) value = "5000" Now I want to query the database to return Contacts that have a loan amount greater than X. The first problem is that the value field needs to be an integerfield to perform the greater than query, but it is a CharField. I cannot change it to an integer field because it needs to store both integers and strings (e.g it also stores the value "John" for first name). As a result I am trying to use the annotate and … -
Hiding header isn't working - Django ecommerce
I have a header I want to hide when scrolling down. The header is located in my templates folder in Django, file name is base.html - see code below: <body> <header class="container-fluid fixed-top"> <div id="topnav" class="row pt-lg-2 d-none d-lg-flex"> <div class="col-12 col-lg-4 my-auto py-1 py-lg-0"> <a href="{% url 'home' %}" class="logo-homepage"> <img src="/media/logo.jpg" width="150" height="150" alt="logo"> </a> </div> <div class="col-12 col-lg-4 my-auto py-1 py-lg-0"> <form method="GET" action="{% url 'products' %}"> <div class="input-group w-100"> <input type="text" class="form-control" placeholder="Search for your vinyl" name="search" aria-label="search_vinyl" aria-describedby="button-addon2"> <div class="input-group-append"> <button class="btn btn-outline-secondary" type="submit" id="button-addon2"> <span class="search-vinyl"><i class="fas fa-search"></i></span> </button> </div> </div> </form> </div> <div class="col-12 col-lg-4 my-auto py-1 py-lg-0"> <ul class="list-inline list-unstyled text-center text-lg-right my-0"> <li class="list-inline-item dropdown px-5 nav-item-bg"> <a class="text-black nav-link" href="#" id="user-options" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <div class="text-center"> <div><i class="fas fa-user fa-lg"></i></div> <p class="my-0">My Account</p> </div> </a> <div class="dropdown-menu border-0" aria-labelledby="user-options"> {% if request.user.is_authenticated %} {% if request.user.is_superuser %} <a href="{% url 'add_product' %}" class="dropdown-item">Product Management</a> {% endif %} <a href="{% url 'profile' %}" class="dropdown-item">My Profile</a> <a href="{% url 'account_logout' %}" class="dropdown-item">Log Out</a> {% else %} <a href="{% url 'account_signup' %}" class="dropdown-item">Sign Up</a> <a href="{% url 'account_login' %}" class="dropdown-item">Log In</a> {% endif %} </div> </li> <li class="list-inline-item px-5 nav-item-bg"> <a class="{% if … -
Having Docker-py commands in Celery tasks
i'm currently creating a Django web application and i'm having some issues. For one of my views, i'm trying to return a response asap while having a process run in the background. The process stated contains Docker-py commands(For certain reasons I can't show the code). I'm trying to use Celery but for some reason, it doesn't work(It just hangs and gets a timeout for running too long). I'm sure the code for the process is correct since i've already tested it out. Is Docker-py compatible with Celery?(As in can Celery help make the docker-py commands run in the background?) -
DataFrame with DateTimeIndex from Django model
My goal is to create a pandas dataframe with a datetimeindex from a django model. I am using the django-pandas package for this purpose, specifically, the 'to_timeseries()' method. First, I used the .values() method on my qs. This still returns a qs, but it contains dictionaries. I then used to_timeseries() to create my dataframe. Everything here worked as expected: the pivot, the values, etc. But my index is just a list of strings. I don't know why. I have been able to find a great many manipulations in the pandas documentation, including how to turn a column or series into datetime objects. However, my index is not a Series, it is an Index, and none of these methods work. How do I make this happen? Thank you. df = mclv.to_timeseries(index='day', pivot_columns='medicine', values='takentoday', storage='wide') df = df['day'].astype(Timestamp) raise TypeError(f"dtype '{dtype}' not understood") TypeError: dtype '<class 'pandas._libs.tslibs.timestamps.Timestamp'>' not understood AttributeError: 'DataFrame' object has no attribute 'DateTimeIndex' df = pd.DatetimeIndex(df, inplace=True) TypeError: __new__() got an unexpected keyword argument 'inplace' TypeError: Cannot cast DatetimeIndex to dtype etc... -
Getting type error when passing model in select tag in Django
I have a model called Department it has data College and HS, when I try to save my form I always get a TypeError. I've tried to validate the form and found out that it was an unbound form so I tried changing the Field type of department from ChoiceField to CharField and in my templates I tried calling {{form.department}} and it gives me the correct data yet it still gives TypeError. views.py class editProfile(UpdateView): model = Profile form_class = UpdateUserForm template_name = 'accounts/profile.html' success_url = reverse_lazy('homepage') #TypeError or ValueError def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['initial']=Profile.objects.get(user=self.request.user) context['department']=Department.objects.all() context['program']=Program.objects.all() context['year']=Year.objects.all() return context def form_valid(self, form): user = form.save(commit=False) user.username = form.cleaned_data.get('username') user.profile.department = form.cleaned_data.get('department') user.profile.program = form.cleaned_data.get('program') user.profile.year = form.cleaned_data.get('year') user.profile.save() user.save() forms.py class UpdateUserForm(forms.ModelForm): def __init__(self, *args, **kwargs) -> None: super(UpdateUserForm, self).__init__(*args, **kwargs) self.fields['username'].label = 'Username' self.fields['department'].label = 'Department' self.fields['program'].label = 'Program' self.fields['year'].label = 'Year' username = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Type your username' })) department = forms.CharField(widget=Select(attrs={ 'class': 'form-control' })) program = forms.CharField(widget=Select(attrs={ 'class': 'form-control', }, )) year = forms.CharField(widget=Select(attrs={ 'class': 'form-control', }, )) class Meta: model = User fields = ['department', 'program', 'year', 'username'] models.py class Department(models.Model): department=[ ('HS','Highschool Department'), ('College','College Department') ] name = models.CharField(_('Department'),max_length=50,choices=department) def … -
Django form creator
I am building a Django project which let users(teachers) create Forms for their students. they can add inputs and also options (for dropdown inputs). I solve this challenge by using dictionaries (I store their inputs and options in dictionaries and if they add options elements will be added to their keys as lists) I don't like the way that I am storing data (as dictionaries) in my database. I want to know if there are any features in Django that can let me produce module fields for my database. in short- I want to handle the database (create new fields) in my view. -
Iterate through non-queryset dictionary in a template
I have a dictionary that I am feeding into a chart.js line chart. It looks as follows: context['graph_data'] = {'day': [datetime.date(2022, 2, 28), datetime.date(2022, 3, 1), datetime.date(2022, 3, 2), datetime.date(2022, 3, 3), datetime.date(2022, 3, 4), datetime.date(2022, 3, 5), datetime.date(2022, 3, 6), datetime.date(2022, 3, 7), datetime.date(2022, 3, 8), datetime.date(2022, 3, 9), datetime.date(2022, 3, 10), datetime.date(2022, 3, 11), datetime.date(2022, 3, 12), datetime.date(2022, 3, 13), datetime.date(2022, 3, 14), datetime.date(2022, 3, 15), datetime.date(2022, 3, 16), datetime.date(2022, 3, 17), datetime.date(2022, 3, 18), datetime.date(2022, 3, 19)], 'response_totals': [0, 0, 0, 0, 12, 12, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]} The template section that I am getting tripped up on looks like the following: new Chart(ctx1, { type: "line", data: { labels: [{%for i in graph_data%}{{i.day}},{%endfor%}], datasets: [{ label: "Referrals", tension: 0.4, borderWidth: 0, pointRadius: 2, pointBackgroundColor: "#cb0c9f", borderColor: "#cb0c9f", borderWidth: 3, backgroundColor: gradientStroke1, data: [{%for j in graph_data%}{{j.response_totals}},{%endfor%}], maxBarThickness: 6 }, I am a bit of a newbie. I can handle querysets but I'm not sure how to transform non-qs dictionaries via the template. -
ModuleNotFoundError: No module named 'commerce.wsgi' Heroku
I'm trying to deploy my django application to Heroku using github (downloaded zip file) but receiving this error ModuleNotFoundError: No module named 'commerce.wsgi'. I've made some edits with previous stackoverflow responses to questions like this but having same error. Django Wsgi ModuleNotFoundError: No module named 'project_name' HEROKU PAGE Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail WSGI.PY """ WSGI config for commerce project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ """ import os import sys sys.path.append('/home/django_projects/commerce') sys.path.append('/home/django_projects/commerce/commerce') from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'commerce.settings') application = get_wsgi_application() PROCFILE web: gunicorn commerce.wsgi HEROKU LOG TAIL 2022-03-20T22:12:10.677933+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2022-03-20T22:12:10.677933+00:00 app[web.1]: return self.load_wsgiapp() 2022-03-20T22:12:10.677933+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2022-03-20T22:12:10.677933+00:00 app[web.1]: return util.import_app(self.app_uri) 2022-03-20T22:12:10.677934+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2022-03-20T22:12:10.677934+00:00 app[web.1]: mod = importlib.import_module(module) 2022-03-20T22:12:10.677935+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2022-03-20T22:12:10.677935+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-03-20T22:12:10.677935+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2022-03-20T22:12:10.677935+00:00 app[web.1]: File … -
Running Django management commands in Visual Studio with .env file environment variables
I need to remove all sensitive keys from the code in my Django app, even those keys that are just used for local testing. The Visual Studio debugger can load environment variables from a .env file. I followed the official tutorial and it's worked, the dev server runs and my Django app can access environment values that are stored in the .env file. But I've hit an issue when I run custom Django management comments. Is there a way to run the commands from the debugger so that they can also access the environment variables? Or some other way to run the commands so they can access the key-value pairs in the .env file? -
Why is my Python Django home url not working?
my first url in django is not working. Not sure what I am doing. My directories are as follows: Storefront playground urls.py views.py storefront urls.py playground.urls from nturl2path import url2pathname from django.urls import path from . import views urlpatterns = [ path('hello/', views.hello) ] playground.views from django.shortcuts import render from django.http import HttpResponse def hello(request): return HttpResponse('Hello World') storefront.urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include('playground.urls')) ] When I go to the website/playground/url, I get an error saying the urls wasn't found. What am I doing wrong? -
Django model queryset order objects in the same order as how they appear in filter_horizontal box
I am having trouble in figuring out how to query for objects in Django model, so that the queried results are exactly as how objects appear in the selected filter list. Let me explain this more clearer. We assume I have two models, one called TakeawayWebshop and one called Product. A TakeawayWebshop can sell many products, but when the customer views the product page, I want the product to appear in the order that I have included them in the filter box. In models.py class TakeawayWebshop(models.Model): name = models.CharField(max_length = 255, help_text = 'name of takeaway restaurant') products = models.ManyToManyField(Product) class Product(models.Model): name = models.CharField(max_length = 50, unique=True) description = models.TextField() price = models.DecimalField(max_digits=9, decimal_places=0, default=0.00) class Meta: ordering = ['-created_at'] In the admin.py I have added product in filter_horizontal. Is it possible to obtain a query set of product that is added to the TakeawayWebshop in the same order as how they appear in the filter_horizontal? Also currently, it is not possible to move the product up or down in the filter_horizontal box from admin. Is there a clever way to implement this feature? class TakeawayWebshopAdmin(admin.ModelAdmin): form = TakeawayWebshopAdminForm list_display = ['name'] ordering = ['name'] filter_horizontal = ('products',) admin.site.register(TakeawayWebshop, … -
Retrieving selected fields from a Foreign Key value with django-rest-framework serializers. (how to get some of the fields of the ForeignKey.)
My Model Class for the artist, album, and track. class Artist(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField() class Album(models.Model): album_name = models.CharField(max_length=100) artist = models.ForeignKey(Artist, related_name='albums', on_delete=models.CASCADE) class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE) title = models.CharField(max_length=100) duration = models.IntegerField() My serializer for the respective models. class ArtistSerializer(serializers.ModelSerializer): class Meta: model = Artist fields = '__all__' class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ['title', 'duration'] class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True, read_only=True) class Meta: model = Album fields = '__all__' depth = 1 For retrieve, The output is as {'id': 1, 'tracks': [{'title': 'Public Service Announcement', 'duration': 245}, {'title': 'What More Can I Say', 'duration': 264}], 'album_name': 'The Grey Album', 'artist': {'id': 1, 'first_name': 'lala', 'last_name': 'nakara','email':'lalanakara@yahoo.com'} } My desired output: I want to get rid of the email field. I looked at the Django-rest-framework documentation, but could not find anything related to the selective field from foreign keys. {'id': 1, 'tracks': [{'title': 'Public Service Announcement', 'duration': 245}, {'title': 'What More Can I Say', 'duration': 264}], 'album_name': 'The Grey Album', 'artist': {'id': 1, 'first_name': 'lala', 'last_name': 'nakara'} } -
How to pass error message for custom permission in Django Rest Framework?
I have a custom permission and it called IsVendor. Now I have two built in permission class and they are IsAdminUser, IsAuthenticated and when I try to hit those url without credentials or login information it shows me an error message like this one 'details':'Authentication Credentials are not provided' and I want the same for my custom permission error message. But it is showing Anonymoususer has no object vendor. class IsVendor(BasePermission): def has_permission(self, request, view): if request.user.vendor: return True else: return False this is my custom permission class. I want to pass error message like 'Authentication Credentials not provided' -
Celery makes print() not visibile
(portfolio) PS C:\Users\arund\Desktop\Code\Django\portfolio-project> celery -A portfolio beat -l info celery beat v5.2.3 (dawn-chorus) is starting. __ - ... __ - _ LocalTime -> 2022-03-19 14:41:16 Configuration -> . broker -> redis://:**@-// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%INFO . maxinterval -> 5.00 minutes (300s) [2022-03-19 14:41:16,221: INFO/MainProcess] beat: Starting... [2022-03-19 14:41:16,738: INFO/MainProcess] Scheduler: Sending due task print-message-once-and-then-every-minute (print_time) [2022-03-19 14:42:00,004: INFO/MainProcess] Scheduler: Sending due task print-message-once-and-then-every-minute (print_time) [2022-03-19 14:43:00,000: INFO/MainProcess] Scheduler: Sending due task print-message-once-and-then-every-minute (print_time) [2022-03-19 14:44:00,000: INFO/MainProcess] Scheduler: Sending due task print-message-once-and-then-every-minute (print_time) I am trying to setup a periodic task using celery but the print() function seems to not be visible even through it does run. Specifically in using the print_time in the tasks.py. tasks.py from celery import shared_task from datetime import datetime from __future__ import absolute_import, unicode_literals @shared_task(name = "print_time") def print_time(): now = datetime.now() current_time = now.strftime("%H:%M:%S") print("Current Time is ") celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings from decouple import config from celery.schedules import crontab # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'portfolio.settings') app = Celery('portfolio') app.conf.update(BROKER_URL=config('REDIS_URL'), CELERY_RESULT_BACKEND=config('REDIS_URL')) # Using a string … -
Django Q objects in model constraints
I am trying to extend a model in an Django App. The only problem I have is that I need to extend the model constraints as well and that does not work properly. This is the original constraint for the object in models.py: models.CheckConstraint( check=( models.Q(inventory_item__isnull=True, device_type__isnull=False) | models.Q(inventory_item__isnull=False, device_type__isnull=True) ), name="At least one of InventoryItem or DeviceType specified.", ) I have tried to extend it like that: models.CheckConstraint( check=( models.Q(inventory_item__isnull=True, device_type__isnull=False, module_type__isnull=False) | models.Q(inventory_item__isnull=False, device_type__isnull=True, module_type__isnull=False) | models.Q(inventory_item__isnull=False, device_type__isnull=False, module_type__isnull=True) ), name="At least one of InventoryItem, ModuleType or DeviceType specified.", ), This is how this looks in the migration: migrations.AddConstraint( model_name='hardwarelcm', constraint=models.CheckConstraint(check=models.Q(models.Q(('device_type__isnull', False), ('inventory_item__isnull', True), ('module_type__isnull', False)), models.Q(('device_type__isnull', True), ('inventory_item__isnull', False), ('module_type__isnull', False)), models.Q(('device_type__isnull', False), ('inventory_item__isnull', False), ('module_type__isnull', True)), _connector='OR'), name='At least one of InventoryItem or ModelType or DeviceType specified.'), ) My problem is that I tried all combinations and it fails every time, but I can see from the error message that only one value is set and the other are Null. DETAIL: Failling row contains (3, null, 1, null) Is there some limitation with Q objects that I don't understand? I have tried to read the Django documentation, but could not figure out what the problem is. -
How to design object model to show them like rectangular cards and add student in a class for a online clasroom project in django
I am doing an online classroom project like google classroom. So I created a model for teachers to add courses now if a teacher adds 2-3 or more courses how will I show all of his created courses on his homepage like rectangular cards we see on google classroom also how I add a student to that class I created a unique "classroom_id" field in course model how I will design that student can join that particular class by entering the classroom id. models.py from django.db import models Create your models here from jazzmin.templatetags.jazzmin import User class course(models.Model): course_name = models.CharField(max_length=200) course_id = models.CharField(max_length=10) course_sec = models.IntegerField() classroom_id = models.CharField(max_length=50,unique=True) created_by = models.ForeignKey(User,on_delete=models.CASCADE) views.py def teacher_view(request, *args, **kwargs): form = add_course(request.POST or None) context = {} if form.is_valid(): course = form.save(commit=False) course.created_by = request.user course.save() return HttpResponse("Class Created Sucessfully") context['add_courses'] = form return render(request, 'teacherview.html', context) -
Django mongodb annotate ExtractDay/Month
I'm not using ExtractDay, ExtractHour etc. in mongodb based Django. Example views.py code: data.filter(find_date__year=2022).annotate(day=ExtractDay('date')) Error status :) : No exception message supplied -
How to use django shell in multiple databases
I am trying to run django shell in different databases. But without success. What I have tried it's override the django Command, and setup my own connection. Take a look on the example bellow. But it's seems like not working solution. Any thoughts how to do that ? Unfortunately the solution with Model.objects.using("db_name")..... not a good one for my case. Code which I have tried: class Command(DefaultShell): def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( '--database', dest='database_name', help='Specific database to run shell', required=False, ) def __set_database_for_current_connection(self, database_name: str): connections.ensure_defaults(database_name) connections.prepare_test_settings(database_name) db = connections.databases[database_name] backend = load_backend(db['ENGINE']) return backend.DatabaseWrapper(db, database_name) def handle(self, *args, **options): database = options.get('database') conn = self.__set_database_for_current_connection(database) super().handle(*args, **options) conn.close() -
Django - unused import statement
I'm a beginner to Django and currently undertaking the codeacademy 'build web apps with django course'. To help better understand django and python I decided to use Pycharm rather than the website interface. I've setup my project, ran the server, migrated and setup an app called 'randomfortune'. I'm now up to the step where I create a view function in views.py: def myview(request): return request, 'randomfortune/fortune.html' In urls.py I use the below imports but I get an error saying 'unused import statement'. from django.urls import path from . import views I done some searching previously and my venv does point to python.exe and it still doesnt work can anybody help out as I'm stuck to the point that I cant continue with the course.