Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django with Firebase for a To-Do + Social App
Background: The Web/App im working on is a To-Do kind of app which has the features of user profile, to-do lists, reminders, events. The other imp feature is that users should be able to make friends(like social media) and also create group events. I already made a simple prototype (To-do web app) using Django but now I wanted to scale it using Firebase as database and many of its other services like Cloud functions/ notifications/auth etc.. From the things i read about Firebase, it can be used even as backend (with help of cloud funts) and also for hosting. Problem: Is it a good option to use Django as backend and firebase as database(NoSQL) for the type of project im doing keeping in mind that more focus is on the tasks and reminders and also allowing group events and friends list in user profile? I am also planning to scale the app to android once the web is done, So isnt it better to write the backend requests code on Firebase cloud functions and avoid using Django at all? (I also read that using a django like backend server is better for secuirty reasons) Need: I would be very happy … -
pytest django test viewset with nested object
There is an exaple in a documentaion: @pytest.mark.django_db def test_user_can_see_own_single_contract(api_rf, user_factory, user_contract_factory): view = UserContractViewSet.as_view({'get': 'retrieve'}) user = user_factory() user_contract = user_contract_factory(user=user) request = api_rf.get(f'user_contracts/{user_contract.pk}') force_authenticate(request, user=user) response = view(request, pk=user_contract.pk) assert response.status_code == status.HTTP_200_OK assert response.data == UserContractSerializer(user_contract).data Let's say a I have a request: request = api_rf.get(f'books/{book.pk}/pages/{page.pk}') I need to pass two primary keys to the view fuction somehow, or maybe there is another way to write it? response = view(request, pk=(book.id, page.id)) -
Django: Trying to catch ValidationErrors and return results as boolean
I don't understand why this try/except isn't working. I have a validation method that might raise a ValidationError (one of several). However, in another method that renames a schema, I want to catch all those errors in favor of one generic message. The validation method (edited for brevity): def validate_tenant_schema_name(tenant, value): if {some invalid condition in schema name}: raise ValidationError('Schema name may not be blank.') if {some other invalid condition in schema name}: raise ValidationError('Schema name may not begin or end with an underscore.') if {yet another invalid condition in schema name}: raise ValidationError('Schema name must have 2 to 30 characters.') return name My validation "wrapper" method: def is_valid_schema_name(name): try: _ = validate_tenant_schema_name(None, name) return True except ValidationError: # Debug got here return False # but didn't get here My schema_rename method: def schema_rename(tenant, new_schema_name): if schema_exists(new_schema_name): raise ValidationError("New schema name already exists") if not is_valid_schema_name(new_schema_name): raise ValidationError("Invalid string used for the schema name.") ...run the sql to rename the schema... tenant.save() When I stepped through it in debug, it got to the except in the is_valid method, but didn't get to the return False - as noted by the comments in the is_valid method. It just returned to the … -
Handling of django authentication with multiple apps
Cant find a solution to a simple problem from current SO questions. I have 2 apps in a django project. App1 is from the graph tutorial found here App2 will allow the users to list data from a DB in this case it will be branch names. If I try and access a page with @login_required decorator then the url route has /accounts/login/ added and I get the usual cant find error. Page not found (404) Request Method: GET Request URL: http://localhost:8000/accounts/login/?next=/calendar Using the URLconf defined in graph_project.urls, Django tried these URL patterns, in this order: [name='home'] about [name='about'] signin [name='signin'] signout [name='signout'] calendar [name='calendar'] callback [name='callback'] branches/ admin/ branches/ The current path, accounts/login/, didn't match any of these. If I am reading the django docs correctly then this is default and I can redirect the login path using the LOGIN_URL in the project settings. When I set that to the signin function created in the tutorial for App1 def sign_in(request): # Get the sign-in URL sign_in_url, state = get_sign_in_url() # Save the expected state so we can validate in the callback request.session['auth_state'] = state # Redirect to the Azure sign-in page return HttpResponseRedirect(sign_in_url) It will forever cycle the MS … -
getting This backend doesn't support absolute paths error with s3
I'm trying to get email to attach file and show images that is uploaded to s3 storage. this is the error I'm getting "This backend doesn't support absolute paths." the refrence is to this line msg.attach_file(file.file.path) the file is FileField. also when I'm trying to show an images inside the email template like this: {{ img.img.url }} I cant see the images in the email, only a broken images. when I copy image url I get something like this. "https://ci5.googleusercontent.com/proxy/5896u5jjiohjjo5i409ioghklgko67970-o=opoyt#http:///media/imagesfolder/image.png" -
Cannot access through model from the model that defines m2m field
I am trying to build a simple e-commerce website with django 2.2.4 . I have Product and Cart models connected with through model Quantity as shown below class Product(models.Model): title = models.CharField(max_length=120) description = models.TextField(null=True, blank=True) mrp = models.DecimalField(max_digits=10, decimal_places=2, default=0.0) final_price = models.DecimalField(max_digits=10, decimal_places=2, default=0.0) discount = models.DecimalField(max_digits=10, decimal_places=2, default=0.0) class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) products = models.ManyToManyField(Product, blank=True, through='Cart.Quantity') total_price = models.DecimalField(decimal_places=2, default=0.00, max_digits=10) class Quantity(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) val = models.PositiveIntegerField(default=1) Now in my views.py I want to to access quantities for each product in my cart. def home(request): cart_obj, is_new = Cart.objects.new_or_get(request) # my custom method to create new object print(cart_obj.quantity_set) # prints Cart.Quantity.None print(cart_obj.products.all()) # prints QuerySet of products in this cart return render(request, 'Cart/home.html',{"cart":cart_obj}) I am new to django. I don't know why i can't access quantity from cart object. Interesting thing i noticed that in python shell when i run same command >>> from Cart.models import Cart, Quantity >>> c1 = Cart.objects.first() >>> c1.quantity_set.all() <QuerySet [<Quantity: Quantity object (1)>]> Why am i unable to access something in my views.py while i access same thing in my python shell? -
forms data is not saving in sqlite3 (Django)
I cant able to Submit my forms data to database. All info. of user is coming in views.py I check that by print() but not saving to sqlite3. When I try to fill info. manually by Django administration it works perfectly without any error. Check the code I given below and let me know what mistake i did. html file: {% extends 'base.html' %} {% block title %} Contact {% endblock title %} {% block body %} <div class="container-fluid py-5"> <form method="POST" action="/contact"> {% csrf_token %} <div class="form-group"> <label for="exampleFormControlInput1">Name</label> <input type="text" class="form-control" name="name" id="exampleFormControlInput1" placeholder="name"> </div> <div class="form-group"> <label for="exampleFormControlInput1">Email address</label> <input type="text" class="form-control" name="email" id="exampleFormControlInput1" placeholder="name@example.com"> </div> <div class="form-group"> <label for="exampleFormControlInput1">Number</label> <input type="number" class="form-control" name="phone" id="exampleFormControlInput1" placeholder="0123456789"> </div> <div class="form-group"> <label for="exampleFormControlTextarea1">Message</label> <textarea class="form-control" name="desc" id="exampleFormControlTextarea1" rows="3"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> {% endblock body %} views.py : from django.shortcuts import render, HttpResponse from home.models import Contact # Create your views here. def index(request): return render(request, 'index.html') def about(request): return render(request, 'about.html') def contact(request): if request.method == "POST": name = request.POST.get('name') email = request.POST.get('email') phone = request.POST.get('phone') desc = request.POST.get('desc') cont = Contact(name=name, email=email, phone=phone, desc=desc) print(name,email,phone,desc) cont.save return render(request, 'contact.html') modules.py : from django.db import … -
how to sum array elements in flask python?
i am new in Python flask. i want to sum all array elements using flask python. i have Following array in python. numbers =["2", "3", "5"] i Want to Sum all the array Elements.and i want have 10 as my result. i tried this, numbers = [2,3,5] Sum = sum(numbers) print(Sum) However its not working,i Appreciate if anyone let me know. i don't know How to do it. -
Error while loding openedx student notes. [bitnami]
Note : This question is only for python-django openedx audience. When I try and load notes this is the error received. I am using openedx bitnami version Traceback (most recent call last): File "/opt/bitnami/apps/edx/venvs/edxapp/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/opt/bitnami/apps/edx/venvs/edxapp/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/opt/bitnami/apps/edx/venvs/edxapp/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/opt/bitnami/apps/edx/venvs/edxapp/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/bitnami/apps/edx/venvs/edxapp/lib/python2.7/site-packages/django/utils/decorators.py", line 185, in inner return func(*args, **kwargs) File "/opt/bitnami/apps/edx/venvs/edxapp/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 23, in wrapped_view return view_func(request, *args, **kwargs) File "/opt/bitnami/apps/edx/edx-platform/lms/djangoapps/edxnotes/views.py", line 62, in edxnotes notes_info = get_notes(request, course) File "/opt/bitnami/apps/edx/edx-platform/lms/djangoapps/edxnotes/helpers.py", line 346, in get_notes raise EdxNotesParseError(("Invalid JSON response received from notes api.")) EdxNotesParseError: \u067e\u0627\u0633\u062e JSON \u0646\u0627\u0645\u0639\u062a\u0628\u0631 \u0627\u0632 \u06cc\u0627\u062f\u062f\u0627\u0634$ -
Django-admin startproject mysite doesn't create directory
I use virtualenv and when I type "django-admin startproject mysite" then there are no errors but it also doesn't create directory, why? -
Django allauth send email verification code instead of email verification link
I am using Django allauth as an API for a mobile application. Currently, when you register Django will send you an email containing a link which you have to go to in order to verify your email. But what if I want to make it so that Django send an email with a verification code which you then enter into the app? I know it seems kind of redundant but I think it will help streamline the user experience (since my platform will primarly have an app). Is this possible to do? -
Django legacy database reverse relation not working
I have a database from Django site-1. I'm using the database in Django site-2 using legacy method. I can create records from site-2. but I can't use reverse relation serializer to fetch data. models.py class DepartmentCategory(models.Model): name = models.CharField(max_length=100) class Meta: managed = False db_table = 'department_category' class DepartmentDesignation(models.Model): name = models.CharField(max_length=100) categoryid = models.ForeignKey(DepartmentCategory, on_delete=models.CASCADE) class Meta: managed = False db_table = 'department_designation' serializers.py class DesignationListSerializer(serializers.ModelSerializer): class Meta: model = designation fields = '__all__' class CategoryListSerializer(serializers.ModelSerializer): designtion = DesignationListSerializer(source = 'designation_set', many = True) class Meta: model = category fields = '__all__' views.py queryset = category.objects.all() serializer = CategoryListSerializer(queryset, many = True) return Response(serializer.data) error Got AttributeError when attempting to get a value for field `designtion` on serializer `CategoryListSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `DepartmentCategory` instance. Original exception text was: 'DepartmentCategory' object has no attribute 'designation_set'. I ran the same code in site-1 and its working. -
Pandas, converting date time column format's changes the column type
I have a data frame where I convert an object column to DateTime column. def insert_cows_to_db(): df = pd.read_csv('/home/yovel/PycharmProjects/scr/rivendell/dairyPlanExample.csv') df['DOB'] = pd.to_datetime(df['DOB']) print(df) print(df.dtypes) output: Cow Transponder DOB 0 NaN NaN NaT 1 8.0 9.840007e+14 2016-09-13 2 9.0 9.840007e+14 2014-07-09 3 13.0 9.840007e+14 2015-02-22 4 16.0 9.840007e+14 2014-02-17 Cow float64 Transponder float64 DOB datetime64[ns] Now I want to change the date format for the column but when I use: def insert_cows_to_db(): df = pd.read_csv('/home/yovel/PycharmProjects/scr/rivendell/dairyPlanExample.csv') df['DOB'] = pd.to_datetime(df['DOB']).dt.strftime('%d-%m-%Y') print(df) print(df.dtypes) output Cow Transponder DOB 0 NaN NaN NaN 1 8.0 9.840007e+14 13-09-2016 2 9.0 9.840007e+14 09-07-2014 3 13.0 9.840007e+14 22-02-2015 4 16.0 9.840007e+14 17-02-2014 Cow float64 Transponder float64 DOB object Is there a way to save the date-time object Because I then upload this data to DB in Django and the field there expects DateTime objects ( If I understand it's error correctly) error when trying to upload to Django's DB match = date_re.match(value) TypeError: expected string or bytes-like object -
Django - Cannot update the form
my template has three columns in one form where they work separately. If I give input for contact column and male column it will save in my database. So basically I want to update the male only as contacts,male and female inputs are present in same html form. I can update the contact but male or female inputs. They all are in same page.I want to make them working separately so I can update them. The problem is that when I give inputs for the it gets posted but not for male and female inputs. Even when I include the contact1 of male class in forms.py,the form does not get submitted. from django.urls import path , include from . import views urlpatterns = [ path('', views.index, name='index'), path('info/', views.info, name='info'), path('features/', views.features, name='features'), path('add/', views.add, name='add'), path('add/' ,views.success, name='success'), path('update/<str:pk_test>/' ,views.update, name='update') ] views.py def update(request,pk_test): template_name = 'update.html' # if request.method =='POST': # c_form = commentForm(request.POST,instance=contacts) # if c_form.is_valid() : # contact = c_form.save() # messages.success(request, "Contact Updated") # return redirect("success") # else: # c_form = commentForm() # context = { # 'c_form' : c_form, # } contact = Contact.objects.get(id=pk_test) c_form = commentForm(instance=contact) m_form = maleForm(instance=contact) f_form = femaleForm(instance=contact) … -
How to Display Foreignkey data in view file?
I have a relation between the project and skuoption table, my skuoption table has a product_id table, but I am unable to display skuoption data on my view page, please check my code and let me know where I am mistaking. Here is my models.py file... class Product(models.Model): name=models.CharField(max_length=225) slug=models.SlugField(max_length=225, unique=True) brand=models.ForeignKey('Brand', related_name='product_brand', on_delete=models.CASCADE, blank=True, null=True) supplement= models.ForeignKey('Supplement', related_name='product_supplement', on_delete=models.CASCADE, blank=True, null=True) subcategory=models.ForeignKey('SubCategory', related_name='prosubcat', on_delete=models.CASCADE, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name and here is skuoption table code... class SkuOption(models.Model): product = models.ForeignKey('Product', null=True, blank=True, on_delete=models.CASCADE) variantflavour=models.ForeignKey('Flavour', related_name='varflavour', on_delete=models.CASCADE, null=True, blank=True) variantsize=models.ForeignKey('Size', related_name='varsize', on_delete=models.CASCADE, null=True, blank=True) sku=models.CharField(max_length=285, null=True, blank=True) price=models.CharField(max_length=285, null=True, blank=True) qty=models.CharField(max_length=285, null=True, blank=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) def __str__(self): return self.sku Here is my product-view.html file, where I am displaying data from product, brands, and skuoption table... <div class="product-right"> <h2 class="mb-0">{{product.name}}</h2> <h5 class="mb-2">Brand: <a href="javascript:void()">{{product.brand.brand_name}}</a></h5> <h5 class="mb-2">Supplement Type: <a href="/supplement-type/{{product.supplement.supplement_slug}}">{{product.supplement.supplement}}</a></h5> <h4><del>₹ {{product.totalprice}}</del></h4> <h3>₹ {{product.variant.name}}</h3> <ul class="color-variant"> <li class="bg-light0">Display `price` here from `skuoption` tble</li> <li class="bg-light1">Display `sku` here from `skuoption` tble</li> <li class="bg-light2">Display `qty` here from `skuoption` tble</li> </ul> </div> please display any value here (<li class="bg-light0">Display price here from skuoption tble</li>) from skuoption table -
How to resolve AWS Elastic Beanstalk Django health check problems
I've recently deployed my Django API backend to AWS EB to their Linux 2 system (exact platform name is Python 3.7 running on 64bit Amazon Linux 2). Almost everything is working as expected, but my application health status is Severe and after hours of debugging I've no idea why. The application's health check is being handled using the following endpoint (django-health-check module). url(r'^ht/', include('health_check.urls')) 100% of the requests have a status code of 200 but my overall health status is the following: |--------------------|----------------|---------------------------------------------------| | instance-id | status | cause | |--------------------|----------------|---------------------------------------------------| | Overall | Degraded | Impaired services on all instances. | | i-0eb89f... | Severe | Following services are not running: release. | |--------------------|----------------|---------------------------------------------------| The strangest thing is the fact that the message Following services are not running: release. is unique to the internet (seems like no one has had such problem before). The other weird thing are the contents of my /var/log/healthd/daemon.log file which are lines similar to W, [2020-07-21T09:00:01.209091 #3467] WARN -- : log file "/var/log/nginx/healthd/application.log.2020-07-21-09" does not exist where the time changes. The last thing that may be relevant are the contents of my single file inside .ebextensions directory: option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "app.settings" "PYTHONPATH": "/var/app/current:$PYTHONPATH" "aws:elasticbeanstalk:container:python": … -
Django Rest Framework Export CSV/XLSX
How to download XLSX file using django-rest-framework-csv(https://github.com/mjumbewu/django-rest-framework-csv)?? I followed the documentation but it only downloaded the xlsx data as no Extension file. it downloaded like this from rest_framework import viewsets from rest_framework_csv.renderers import CSVRenderer from rest_framework.settings import api_settings from rest_framework_csv import renderers as r from employees.serializers import EmployeeSerializer from employees.models import Employee # Create your views here. class ExportEmployeeViewSet(viewsets.ModelViewSet): queryset = Employee.objects.all() http_method_names = ['get'] serializer_class = EmployeeSerializer renderer_classes = (r.CSVRenderer, ) + \ tuple(api_settings.DEFAULT_RENDERER_CLASSES) def get_queryset(self): if 'code' in self.request.GET: code = self.request.GET['code'] return Employee.objects.filter(code=code) return Employee.objects.all() -
Quering Django model object
I can query the user's profile using the user_id in the UserProfile model below. But I would like to use the username in the django.contrib.auth.models.User.username in the urls instead. The urls.py currently looks like: path('profile/<int:user_id>', login_required(views.UserProfileDetail), name='userprofile'), So as against the above urls, I would like to use something like: path('profile/<str:username>', login_required(views.UserProfileDetail), name='userprofile'), Any idea how to write the query correctly? All attempts so far returns an error views.py: def UserProfileDetail(request, user_id, *args, **kwargs): profile = UserProfile.objects.get(user_id = user_id) profile_display = {'profiledetail': profile } return render(request, 'main/userprofile.html', context=profile_display) this is what the model looks like: from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='userprofile') userPhone = models.IntegerField(blank=True, null=True) location = models.CharField(max_length=100, blank=True, null=True) -
Django, add data from csv with dates raises Type Error
I'm trying to write some raw CSV data into my DataBase using pandas. One of the columns is a date field so I converted it to DateTime in pandas and changed the format to the one specified in My serializer. When trying to create the objects I get an error: match = date_re.match(value) TypeError: expected string or bytes-like object My pandas to DB function: def insert_cows_to_db(): df = pd.read_csv('/home/path/to/file/dairyPlanExample.csv') df['DOB'] = pd.to_datetime(df['DOB']).dt.strftime('%d-%m-%Y') print(df) cows = [] for i in range(len(df)): cows.append(Cow(management_id=df.iloc[i][0], eid_number=df.iloc[i][1], date_of_birth=df.iloc[i][2] ) ) return Cow.objects.bulk_create(cows) My model and serializer: class Cow(models.Model): management_id = models.CharField(max_length=255) eid_number = models.CharField(max_length=255, primary_key=True, blank=False, ) group = models.ForeignKey(Group, on_delete=models.PROTECT, default=None, null=True, blank=True, related_name=RelatedNames.COWS) date_of_birth = models.DateField(null=True, default=None, blank=True) cow_ear_tag_id = models.CharField(null=True, default=None, blank=True, max_length=255) def __str__(self): return self.eid_number class CowSerializer(serializers.ModelSerializer): date_of_birth = serializers.DateField(input_formats=["%d-%m-%Y"], format="%d-%m-%Y") class Meta: model = Cow fields = '__all__' -
How to save old data in database after database migration no Django?
After adding new field to a model and making migration, I get an error that says column does not exist when operating the old data in database. Should I alter database table adding the new column to solve this problem? Is there any solution of this kind of error preserving the old database data? -
while adding a group in django channels layer using rabbitmq server? rabbitmq server not connecting
I am using django-channels with rabbitmq server. Installed packages: channels==2.4.0 channels-rabbitmq==1.2.1 rabbitmq_server-3.5.7 consumer.py: import asyncio import json from django.contrib.auth import get_user_model from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from asgiref.sync import async_to_sync class NotificationConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) await self.send({ "type": "websocket.accept" }) user = self.scope['user'] await self.send({ "type": "websocket.send", "text": "Hello World" }) print(self.channel_name) async_to_sync(self.channel_layer.group_add("gossip", self.channel_name)) print(f"Added {self.channel_name} channel to gossip") async def websocket_received(self, event): print("receive", event) async def websocket_disconnect(self, event): print("disconnected", event) await self.channel_layer.group_discard("gossip", self.channel_name) print(f"Removed {self.channel_name} channel to gossip") routing.py: from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from django.urls import path from channels.security.websocket import AllowedHostsOriginValidator, OriginValidator from problems.consumer import NotificationConsumer import problems.routing application = ProtocolTypeRouter({ 'websocket':AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ path('', NotificationConsumer), ] ) ) ) }) Channels setting in settings.py: `ASGI_APPLICATION = 'codeyoda.routing.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_rabbitmq.core.RabbitmqChannelLayer", "CONFIG": { "host": "amqp://guest:guest@127.0.0.1/asgi", }, }, } Error: (codeyodaEnv) vagrant@ubuntu-xenial:/vagrant/codeyoda-project$ python manage.py runserver 0.0.0.0:8080 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 21, 2020 - 12:07:56 Django version 2.2.4, using settings 'codeyoda.settings' Starting ASGI/Channels version 2.4.0 development server at http://0.0.0.0:8080/ Quit the server with CONTROL-C. HTTP GET / 200 [0.24, 10.0.2.2:62960] HTTP GET … -
Don't Update An Object If Someone Is On The Related Page
I have a database and my cronjob updates it's objects every 5 min. But I need to bypass an object if someone is on the related page. For example if someone is reading an article on my website, I don't want my cronned api update that article. I coudn't think how to do it. Any idea? -
Reverse for 'reply_section' with arguments '('',)' not found when accessing detail page
I am currently trying to make a comment-reply function, but the detail page is not getting rendered properly and showing this error Reverse for 'reply_section' with arguments '('',)' not found . What can be the problem? can anyone please take a look at the code? Thanks Here are the codes, views. def reply_section(request, comment_id): user = request.user comment = Comment.objects.get(pk=comment_id) comment_replies = Reply.objects.filter(comment=comment).order_by('-id') if request.POST: reply_form = ReplyForm(request.POST or None) if reply_form.is_valid(): reply_content = request.POST.get('content') reply = Reply.objects.create(comment=comment, user=request.user, content=reply_content) reply.save() else: reply_form = ReplyForm() context = { 'reply_form':reply_form, 'comment': comment, 'comment_replies':comment_replies, } if request.is_ajax(): html = render_to_string('posts/comment_section.html', context, request=request) return JsonResponse({'form': html}) template for replies {% for reply in replies %} <blockquote class="blockquote"> <a href="" style="text-decoration: none; color: black;"><h6> {{ reply.user.first_name|capfirst }} {{ reply.user.last_name|capfirst }}</h6></a> <p style="font-size: 8px;">{{ reply.timestamp }}</p> <p style="font-size: 13px;" class="mb-3">{{ reply.content }}</p> </blockquote> {% endfor %} <div class="form-group row"> <form class="reply-form" method="post" action="{% url 'posts:reply_section' comment.id %}">{% csrf_token %} <input type="hidden" name="comment_id" value="{{ comment.id }}"> <div class="form-group"> <textarea class="rounded" name="content" cols="60" rows="2" maxlength="1000" required="" id="id_content"></textarea> </div> <input type="submit" value="submit" class="btn-sm btn-outline-light" style="color: black;"> </form> urls path('<int:comment_id>/reply/', views.reply_section, name='reply_section'), -
"ModelForm has no model class specified."
I've tried to create a form for the django User model, but when i try to open the webpage it gives me error that "ModelForm has no model class specified. Here is my forms.py file: from django import forms from django.contrib.auth.models import User class PersonForm(forms.ModelForm): class meta(): model = User fields='__all__' ' -
How to get selected value in dropdown list html to django views?
views.py def select_value(request): value = request.GET['value'] template = 'apps/selected_value.html' return render(request, template, {'values': value}) <select name="value"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> <p>you have selected value {{values}}</p> i am new to Django and i did lots of searching and for get the selected value from html to django views. i tried with above html and django viwes, still i am getting below. can any one help me on this? thanks in advance. getting MultiValueDictKeyErrorat /value/ 'value'