Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pass username from token to save username in model
This is my model file which has the owner field name class PotholeImages(models.Model): """Upload images with details """ image = models.ImageField( upload_to='photos/%Y/%m/%d', ) owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default = 'unknown', ) state_name = models.CharField( blank = False, max_length = 30, default = 'unknown', ) country_name = models.CharField( blank = False, max_length = 30, default = 'unknown', ) name = models.CharField(default=uuid.uuid4, max_length=40) cordinate_X = models.DecimalField(max_digits=22, decimal_places=16) cordinate_Y = models.DecimalField(max_digits=22, decimal_places=16) created_date = models.DateTimeField(auto_now_add=True) road_name = models.CharField(max_length = 100, default = 'unknown') def __str__(self): return self.name Serializer file class ImageSerializer(serializers.ModelSerializer): """Uploading Pothoele Images""" class Meta: model = PotholeImages fields = ('image','state_name', 'country_name','cordinate_X', 'cordinate_Y','road_name',) def to_representation(self, instance): rep = super(ImageSerializer, self).to_representation(instance) rep['owner'] = instance.owner.username # print(rep) return rep views file class ImageViewSet(viewsets.ModelViewSet): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) queryset = PotholeImages.objects.all() serializer_class = serializers.ImageSerializer def perform_create(self, serializer): print(self.request.user) serializer.save(user=self.request.user) I want whenever a person sends a post request on http://127.0.0.1:8000/images_api/imageView/ Then from the token, username gets detected and it should be passed in the owner field name. Could anyone please help Thanks -
How can to get data from related model in Django Rest Framework?
I'm beginner in DRF. I have next models class User(AbstractUser): ip_address = models.CharField(max_length=15) class Statistic(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='statistics') clicks = models.PositiveSmallIntegerField() and serializers class UserListSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'first_name', 'ip_address'] class UserStatisticSerializer(serializers.ModelSerializer): class Meta: model = Statistic How can I get in Response data in following format: { 'user_data': { 'id': 1, 'first_name': 'name', ..., statistics: {[ {'id': 1, 'clicks': 100}, {'id': 3, 'clicks': 550} ]} } I go to the link /api/v1/users/<int:pk>/ and call next function: class UserDetailStatisticApiView(RetrieveAPIView): queryset = ??? serializer_class = ??? Thnx for help -
How to slove this Error in creating a new Django project?
I was trying to create a new Django project in new folder,located in Desktop (Windows 7). But, when I type 'django-admin startproject mysite' in cmd I got this error. Can anybody help me with this? enter image description here -
Django TypeError: sequence item 0: expected str instance, NoneType found
I tried sending email through smtp and email.mime with Django. I have decided not to use the django email because I want to automate sending of emails to several other emails from any user so the user will be required to put in his email and password to his gmail so smtp can send emails using his account to other emails Internal Server Error: /api/email/1/send/ Traceback (most recent call last): File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/home/taycode/Desktop/emailsenderapi/api/views.py", line 71, in post serializer.send(email_object_id=pk, validated_data=serializer.validated_data) File "/home/taycode/Desktop/emailsenderapi/api/serializers.py", line 61, in send sender.send() File "/home/taycode/Desktop/emailsenderapi/api/utils.py", line 44, in send self.s.send_message(msg=self.msg) File "/usr/lib/python3.6/smtplib.py", line 936, in send_message from_addr = email.utils.getaddresses([from_addr])[0][1] File "/usr/lib/python3.6/email/utils.py", line 112, in getaddresses all = COMMASPACE.join(fieldvalues) TypeError: sequence item 0: expected str … -
Django Rest Framework Date field serialization problems
im trying to post the recruitment date of an employee , but i keep having the 400 bad request error and recruitment_date: ["This field is required."] ,after searching i added the Date Formats on the settings but i still have the same error serializers.py : class EmployeeSerializer(serializers.ModelSerializer): url = serializers.SerializerMethodField(read_only=True) recruitment_date =fields.DateField(format="%Y-%m-%d",input_formats=['%Y-%m-%d']) class Meta: model = Employee fields =['url','id','f_name','l_name','job','telephone','recruitment_date','salary'] def get_url(self,obj): request = self.context.get("request") return obj.get_api_url(request=request) settings.py : "DATE_INPUT_FORMATS": ["iso-8601","%Y-%m-%d"], -
Where to store translations in microservice architectre
For today I have 2 microservice apps. The first one is a backend application built with Django and Django Rest Framework. The second one is the frontend application built with React. I store some info that needs to be translated in the DB. Let's perhaps I have a table named "furniture_types" with only one column the name. And data is 4 rows: "chair", "sofa", "table", "bed". On front-end, I want to display translations for "furniture_types" in other languages for example Russian and Ukrainian. And what I do I store translation files on the frontend and and use intl frameworks. So if user chose Ukrainian he will see "стілець" instead of "chair" and so on. Everything works well know but I see two problems that I still don't mind of solution for. I use django admin and I want to have the admin panel and some tables data in the admin panel be translated into the Russian. What I mean is when the user go to admin panel and want to create an Order in the field furniture type will see the list of options in russian language not as the stored in the DB. (['стул', 'диван'] instead of ['chair', 'sofa']). … -
After Installing Mysql also I am not able to connect with dajngo
Traceback (most recent call last): File "C:\Users\saikr\Python38\lib\site-packages\django\db\backends\base\base.py", line 220, in ensure_connection self.connect() File "C:\Users\saikr\Python38\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\saikr\Python38\lib\site-packages\django\db\backends\base\base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\saikr\Python38\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\saikr\Python38\lib\site-packages\django\db\backends\mysql\base.py", line 233, in get_new_connection return Database.connect(**conn_params) File "C:\Users\saikr\Python38\lib\site-packages\MySQLdb__init__.py", line 84, in Connect return Connection(*args, **kwargs) File "C:\Users\saikr\Python38\lib\site-packages\MySQLdb\connections.py", line 179, in init super(Connection, self).init(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (1045, "Access denied for user 'saikrishna'@'localhost' (using password: YES)") -
SimpleListFilter has no effect to admin form, Django 2.2.8
I'm using Django 2.2.8. I have an entity "AppSettings" with such attributes as [category: str, name: str, value: str, description: str]. Pair [category, name] is unique. There're no foreign key relations. Now I want to make an editable grid in admin page. And I want this grid to be filtered by categories in the right pane using list_filter property. I have following classes in admin.py: class AppSetsListFilter(admin.SimpleListFilter): title = 'Category' parameter_name = 'category' default_value = 'All' def lookups(self, request, model_admin): cats = set([v for v in AppSettings.objects.all().values_list('category', flat=True)]) return sorted([(c, c) for c in cats], key=lambda c: c[0]) def queryset(self, request, queryset): if not self.value() or self.value() == 'All': return queryset return queryset.filter(category=self.value()) class AppSetsAdminForm(forms.ModelForm): class Meta: model = AppSettings fields = ['category', 'name', 'value', 'description'] widgets = { 'value': forms.Textarea( attrs={ 'rows': '2', 'cols': '95' } ) } class AppSettingsAdmin(admin.ModelAdmin): list_display = ['category', 'name', 'value', 'description'] search_fields = ['name', 'description'] list_editable = ['value'] list_display_links = ['category'] list_filter = (AppSetsListFilter, ) def get_changelist_form(self, request, **kwargs): return AppSetsAdminForm I've got no error. "Value" cell is editable. It has 2-rows text area in. But no "filter" pane appear, although there're about 60 records displayed. I thought there might be an issue with … -
How to get form postdata that uses field names with square brackets as structured objects in Django?
I have such a form: <form action="{% url 'requerimento' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="requerente[nome]"> <input type="text" name="requerente[endereco]"> <input type="text" name="representante[nome]"> <input type="text" name="representante[endereco]"> <input type="file" name="anexo[0]"> <input type="file" name="anexo[1]"> <button type="submit">Enviar</button> </form> It is evaluated by this view: def teste(request): if request.method == 'POST': if request.POST: pp(request.POST.dict()) if request.FILES: pp(request.FILES.dict()) return render(request, 'interface/teste.html') It outputs this to console: {'csrfmiddlewaretoken': 'iEokZx8pJz73BtT8nNiIPH9oBkepgFLN5AfgBTgGstg4WixbBG3gF1XeELVvEUW3', 'requerente[nome]': 'a', 'requerente[endereco]': 'b', 'representante[nome]': 'c', 'representante[endereco]': 'd'} {'anexo[0]': <InMemoryUploadedFile: file1.pdf (application/pdf)>, 'anexo[1]': <InMemoryUploadedFile: file2.pdf (application/pdf)>} Is it possible, instead, to retrieve or easily convert these data in a structured fashion so like below? {'csrfmiddlewaretoken': 'iEokZx8pJz73BtT8nNiIPH9oBkepgFLN5AfgBTgGstg4WixbBG3gF1XeELVvEUW3', 'requerente': {'nome': 'a', 'endereco': 'b'}, 'representante': {'nome': 'a', 'endereco': 'd'} } {'anexo': [ <InMemoryUploadedFile: file1.pdf (application/pdf)>, <InMemoryUploadedFile: file2.pdf (application/pdf)> ]} -
All the users name who liked a post in django
I cannot show all the users name who liked the post in django. I have tried many ways to do that but its not working. my models.py: class post(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to='post_pics', null=True, blank=True) video = models.FileField(upload_to='post_videos', null=True, blank=True) content = models.TextField() likes = models.ManyToManyField(User, related_name='likes', blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def delete(self, *args, **kwargs): self.image.delete() super().delete(*args, **kwargs) def get_absolute_url(self): return reverse ('blog-home') in views.py : def like_post(request): # posts = get_object_or_404(Post, id=request.POST.get('post_id')) posts = get_object_or_404(post, id=request.POST.get('post_id')) is_liked = False if posts.likes.filter(id=request.user.id).exists(): posts.likes.remove(request.user) is_liked = False else: posts.likes.add(request.user) is_liked = True return render(request, 'blog/home.html') def post_likes(request, pk): posts = get_object_or_404(post, pk=pk) post_likes = posts.likes.all() context = {'post_likes': post_likes,} return render(request, 'blog/post_likes.html', context) in urls.py: path('post/<int:pk>/postlikes/', views.post_likes, name='post-likes'), and in post_like.html: {% extends "blog/base.html" %} {% block content %} {% for likes in posts %} <p>{{ posts.likes.user.all }}</p> {% endfor %} {% endblock content %} How can i see the usernames who liked the particular post? -
what's happend to me ? "django-admin : command not found"
I make a new Environment for django-project but as you can see when I typed pip list I could see django in the list. but when did django-admin it returned command not found and also when I tried pip3 install django or pip install django it said requirement is already safisfied.. I'm very new to Mac and coding, so It's feel too burden to me. Please give any advise to me.. in PyCharm, I set "Project interpreter" as Desktop/my_project/venv/bin/python3 and PyCharm project is in the differenct location like myname/PyCharm/django-project Here's below terminal message ( and now I use PyCharm for this) ⇣1% pip list Package Version ---------------------------------- --------- alabaster 0.7.12 anaconda-client 1.7.2 anaconda-navigator 1.9.7 anaconda-project 0.8.3 appnope 0.1.0 appscript 1.0.1 asgiref 3.2.3 asn1crypto 1.0.1 astroid 2.3.1 astropy 3.2.2 atomicwrites 1.3.0 attrs 19.2.0 Babel 2.7.0 backcall 0.1.0 backports.functools-lru-cache 1.5 backports.os 0.1.1 backports.shutil-get-terminal-size 1.0.0 backports.tempfile 1.0 backports.weakref 1.0.post1 beautifulsoup4 4.8.0 bitarray 1.0.1 bkcharts 0.2 bleach 3.1.0 bokeh 1.3.4 boto 2.49.0 Bottleneck 1.2.1 certifi 2019.9.11 cffi 1.12.3 chardet 3.0.4 Click 7.0 cloudpickle 1.2.2 clyent 1.2.2 colorama 0.4.1 conda 4.7.12 conda-build 3.18.9 conda-package-handling 1.6.0 conda-verify 3.4.2 contextlib2 0.6.0 cryptography 2.7 cycler 0.10.0 Cython 0.29.13 cytoolz 0.10.0 dask 2.5.2 decorator 4.4.0 defusedxml 0.6.0 … -
How can i send requests to another service from a Django view?
I'm trying to create a simple microservice structure on my Django project where, when a certain Django view is called, this view will send a JSON post request to a Flask microservice containing some user's data; the Flask microservice should receive the request, take that user's data and send back to Django some additional data using Requests again, so that my Django view can receive that data and perform some operations, such as showing it to the user. Right now i'm just sending some dummy data, to test if this Django > request to Flask > Flask > Request to Django system works, but i'm encountering some problems. To debug my code, right now, i'm trying to just print the received data, but i'm having some troubles. Here is my view: def myView(request): mydict = {} # The request is sent to my external Python script.. req = requests.post('http://127.0.0.1:5000/', json={"one": 1}) # Some dummy data # .. Once the external script sends back a request with data, this should handle it if request.method == 'POST': # The data is inside this variable data = request.POST for key in data.items(): if float(key[1]) > 0: mydict.update({key[0]: key[1]}) print(mydict) #FIRST PRINT STATEMENT print(mydict) … -
How to upload select option values using django form through CSV in django?
I have a form which includes select input in it. class StockAdd(forms.ModelForm): stock_name = MyModelChoiceField(queryset=Company.objects.all(), initial=0) trans_price = forms.FloatField() trans_quantity = forms.FloatField() trans_date = forms.DateField(initial=datetime.date.today, widget=DateInput()) class Meta: model = Portfolio fields = [ "stock_name", "trans_price", "trans_quantity", "trans_date", ] I am adding a feature to upload this data using CSV. def upload_csv(request): if request.method == 'POST': csv_file = request.FILES['csv_portfolio'] file_data = csv_file.read().decode('utf-8') lines = file_data.split('\n') for line in lines: fields = line.split(',') print(fields) data_dict = {"stock_scripcode": 12, "stock_name": "t", "trans_price": 12, "trans_quantity": 1, "trans_date": '2019-10-10'} try: form = forms.StockAdd(data_dict) print(form.errors) if form.is_valid(): form.save() except Exception as e: print(e) pass return render(request, 'portfolio_management/csv.html') This makes form invalid with form error : <ul class="errorlist"><li>stock_name<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul> -
Configuring django to pass request to another service
I’m using django rest framework as the backend for my mobile app. I want to use golang for my websockets backend instead of Channels because it’s kind of an MMO-like app that uses a lot of data. How can I configure my app and webserver to do something like: https://app.com/chats/1 <- Django wss://app.com/chats/1 <- golang -
Filtering and paginating in django fails to run simultaneously
The code has many filters which are being rendered during an AJAX call, every time the user changes the inputs it sends the data to the server using JQUERY on ready document function. Even though I have added pagination at the very end of the function and calling it in urls via "?page=2" or "?page=3" the output is the same, so the Paginator works but the iteration throughout the products doesn't display. @csrf_exempt def productViews(request): allproduct = Products.objects.order_by( '-Memory', '-Core_Speed', '-Boost_Clock') ########################################################################################### # this code works # if request.method == 'POST' and 'Boost_Clock_min' in request.POST: Boost_Clock_minimum = request.POST.get('Boost_Clock_min') allproduct = allproduct.filter(Boost_Clock__gte=Boost_Clock_minimum) if request.method == 'POST' and 'Boost_Clock_max' in request.POST: Boost_Clock_maximum = request.POST.get('Boost_Clock_max') allproduct = allproduct.filter(Boost_Clock__lte=Boost_Clock_maximum) if request.method == 'POST' and 'Core_Clock_min' in request.POST: Core_Clock_minimum = request.POST.get('Core_Clock_min') allproduct = allproduct.filter(Core_Speed__gte=Core_Clock_minimum) if request.method == 'POST' and 'Core_Clock_max' in request.POST: Core_Clock_maximum = request.POST.get('Core_Clock_max') allproduct = allproduct.filter(Core_Speed__lte=Core_Clock_maximum) if request.method == 'POST' and 'ram[]' in request.POST and request.is_ajax(): ram_list = request.POST.getlist('ram[]') ram_list = [int(i) for i in ram_list] print("The ram sizes are \t") print(ram_list) allproduct = allproduct.filter(Memory__in=ram_list) if request.method == 'POST' and 'brand[]' in request.POST and request.is_ajax(): brand_list = request.POST.getlist('brand[]') #brand_list = [int(i) for i in brand_list] print("The brand names are \t") print(brand_list) allproduct = … -
ModuleNotFoundError: No module named 'users' --showing in django
My directory MLG >.vscode >blog >users -db.sqlite3 -manage.py This is users views.py from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm def register(request): form = UserCreationForm() return render(request, 'users/regsiter.html', {'form': form}) This is users apps.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' This is mlg settings.py INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] This is mlg urls.py from django.contrib import admin from django.urls import path, include from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('', include('blog.urls')), ] What i am doing wrong please help... P.S. - I have shown templates just as i am trying to run register.html file .. cant able to run it bcz of above error .. -
Can't be redirected after form action in Django
I created a form for creating a new item in Django. The app should be redirected to item_new but it's not working. This below error occurs. Page not found http://127.0.0.1.8000/item/new show.html <form action="{% url 'item_new' %}" method="POST" enctype="multipart/form-data" > {% csrf_token %} <div class="formItem"> <label>Name</label> <input type="name" name="name" /> </div> <div class="formBtn"> <input type="submit" class="btn btnPrimary" value="Submit" /> </div> </form> urls.py urlpatterns = [ path('item/<slug:slug>/', views.item_detail, name='item_detail'), path('item/new/', views.item_new, name='item_new'), ] views.py def item_detail(request, slug): item = get_object_or_404(Item, slug=slug) return render(request, 'item/show.html', {'item': item}) def item_new(request): return redirect('home') -
Using LoginView with custom template
I am trying to use the django.contrib.auth.LoginView and auth_views.LogoutView.as_view() with custom templates, without interfering with the admin site in any way, regardless the order at which the apps are loaded in the settings.py file. So far not succeeded. This is my urls.py: from django.urls import path, include from django.contrib.auth import views as auth_views from . import views urlpatterns = [ # ... path('login/', auth_views.LoginView.as_view(), {'template_name': 'registration/login.html'}, name = 'login'), path('logout/', auth_views.LogoutView.as_view(), {'template_name': 'registration/logged_out.html'}, name = 'logout') ] The login view loads my custom template, but the logout does not and uses the default one. Can't figure out why. Please help. Thanks! -
Django admin's `add_form` doesn't shows `CustomUserCreationForm` in admin
I created the following CustomUserCreationForm: class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = CustomUser fields = ['username', 'email', 'age'] I used this form on SignUpView and it works as expected, namely shows all fields we stated above, but when I use it in admin it only shows username, password1 and password2 fields. class CustomUserAdmin(UserAdmin): # The forms to add and change user instances add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username', 'age', 'is_staff', ] admin.site.register(CustomUser, CustomUserAdmin) when I add a user in admin page, it shows following fields and not all fields stated in UserCreationForm: why is this happening and how do I solve it? -
I am confused with django default server for testing.How django project run on http without local server
I have installed django and local envirement for test purpose but i am little bit confused how django run their project on http without having server. -
Django local runserver error (won't start)
new into this. Can't run localserver from python manage.py runserver. give below error (venv) C:\Users\DeeDee\Desktop\dtre_project\btre>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\DeeDee\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\DeeDee\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\DeeDee\Desktop\dtre_project\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) ..bla bla bla. and last line OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '' -
Hello, how can i load two path with different django modal forms?
i was trying django modals form . i create a model called "devices" i got one view working which makes the device form load up on the index device page. After that created another model called "Customers" and made forms and view for it but, when i load the files from URL it only loads the first Form which is devices and not the customer. so when i click the create customer button; device model is loaded in the form and if put the customer path at first in in my URL it loads fine but in "create device" button in device html; the form loads up with customer modal form this is Path Fil examples/URL from django.urls import path from . import views from examples.views import login_view,register_view,logout_view urlpatterns = [ path('', views.Home.as_view(), name='home'), path('home/', views.Home.as_view(), name='home'), # Device URL path('device', views.DeviceIndex.as_view(), name='indexDevice'), path('create/', views.DeviceCreateView.as_view(), name='create_device'), path('update/<int:pk>', views.DeviceUpdateView.as_view(), name='update_device'), path('read/<int:pk>', views.DeviceReadView.as_view(), name='read_device'), path('delete/<int:pk>', views.DeviceDeleteView.as_view(), name='delete_device'), # Customer URL path('customer', views.CustomerIndex.as_view(), name='indexCustomer'), path('create/', views.CustomerCreateView.as_view(), name='create_customer'), path('update/<int:pk>', views.CustomerUpdateView.as_view(), name='update_customer'), path('read/<int:pk>', views.CustomerReadView.as_view(), name='read_customer'), path('delete/<int:pk>', views.CustomerDeleteView.as_view(), name='delete_customer'), Setup/URL from django.conf.urls import include from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path('', include('examples.urls')), ] indexCusctomer {% extends 'base.html' … -
Apply Django admin m2m with Intermediary TabularInline on Generic Views
I have a m2m field with through fields, When I am putting fields of m2m fields on my generic views it is just showing multiple select. I have accomplished what I want but on Admin with my admin.py using admin.TabularInline my admin.py is class RatioInline(admin.TabularInline): model = Ratio class MenuAdmin(admin.ModelAdmin): inlines = (RatioInline,) What I need is make this adding row forms on Admin to put in my views. Is it possible to achieve this form in admin to class based views? I am still looking for widget and forms but I am lost. My code in models below for m2m through: class Menu(models.Model): name = models.CharField(max_length=24) ratio = models.ManyToManyField('Ingredient', through='Ratio') class Ratio(models.Model): menu = models.ForeignKey('Menu', on_delete=models.CASCADE) ingredient = models.ForeignKey('Ingredient', on_delete=models.CASCADE) quantity = models.DecimalField(max_digits=12, decimal_places=2) class Ingredient(models.Model): name = models.CharField(max_length=24) -
Getting " MultiValueDictKeyError at /button/ 'text " error in a Django project
Tring to create a demo Todo web app using Django and Bootstrap, Whenever I am trying to trigger a function using a button it's raising a "MultiValueDictKeyError at /button/" Error. I have set an input form name "text" and receiving it This is the view function def index(request): todoData = Todo.objects.all().order_by("date") return render(request, 'index.html',{ "todo": todoData } ) @csrf_exempt def submit(request): current_date = timezone.now() content = request.POST["text"] Todo.objects.create(date = current_date , text = content) return render(request,'index.html') Here's the "index.html" {% extends "base.html" %} {% load static %} {% block content %} <div class='row mt-4'> <div class='col'> <h2>Add Task :</h2> <form class='form-inline'action='button/' method='POST' name="text"> <input type="text" class="form-control mb-2 mr-sm-2" placeholder="text here..."> <button type="submit" class="btn btn-primary mb-2">Add</button> </form> </div> </div> <div class='col mt-4'> <ul class="list-group"> <li class="list-group-item">Dapibus ac facilisis in</li> </ul> </div> {% endblock content %} -
Passing calculated value to Django template
I'm pretty new to Django and I'm having trouble with passing a variable to a Django template. My code finds the average of an Integer field from the database (using Django's AVG) then perform a calculation on the result. Ultimately I would like to pass the result of this calculation to a template. My model.py is: from django.db import models class Post(models.Model): fname = models.CharField(max_length=20) lname= models.CharField(max_length=25) reading=models.IntegerField(default=100) entrytime=models.DateTimeField(auto_now_add=True) def __str__(self): return self The view is: from django.views.generic import TemplateView, ListView from django.db.models import Avg from .models import Post class ShowCalcView(ListView): model=Post template_name = 'calc.html' def calca1c(request): context = Post.objects.aggregate(Avg('reading')) r=context['reading__avg'] rs = (46.7 + r) / 28.7 context['calc'] = rs return context The template is: <h1>Approximate A1C</h1> <p>Approximate A1c: {{ calc }}</p> I have tried using {{ calc }}, {{ calc.rs}}, {{ calc['rs'] }}, and just about every other combination I can think of but the value is not being passed. I have checked the function in the shell, and it produces the desired result. I'm probably missing something obvious but I cannot figure it out. Thank you for your assistance.