Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model ManyToManyField.add is not working
I have a model named TopicRoom and it has a field called creator which is a foreign key to the user model. And a many to many field called members which is a many to many rel to the user model @receiver(post_save, sender=models.TopicRoom) def add_topic_room_creator_as_a_member(instance, created, **kwargs): if created: print("added creator", instance.creator, instance) instance.members.add(instance.creator) print(instance.members.all()) When I create a new instance in the admin panel it prints this added creator bob@gmail.com TopicRoom object (24) <QuerySet [<User: bob@gmail.com>]> but when I view the model in the admin panel it shows that there are no members. And when I retrieve the model from the django manage.py shell, that also shows that there are no members for that object instance >>> TopicRoom.objects.get(id=24).members.all() <QuerySet []> -
How to correctly display static files in Django when debug = False?
what should I do if I used a command python manage.py collectstatic and don’t understand what needs to be done in order for static files to be located and displayed, i get only 404 when i try to load server and my css also dont working my settings.py: DEBUG = False ALLOWED_HOSTS = ['127.0.0.1'] PATH_TO_YOUR_STATIC_FOLDER= 'man/static/' STATICFILES_DIRS = [ BASE_DIR / "man/static", PATH_TO_YOUR_STATIC_FOLDER, ] STATIC_ROOT = BASE_DIR / "staticfiles" # Internationalization # https://docs.djangoproject.com/en/5.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.0/howto/static-files/ STATIC_URL = '/static/' # Default primary key field type # https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' my files structure maybe i need to edit STATICFILES_DIRS? i was trying to change STATICFILES_DIRS in settings, but nothing -
Django access MultilinestringM in Postgis with Geometry(dim=3)
I do have Railway-lines using "Linear Referencing" stored as MultilinestringM in a Postgis-DB (created by FME). So each line has a certain code and along that line assets are placed (km_from, km_to). I do need read access only in order to calculate Linestring from the given from-to values. I try to access that Postgis Information with Django (Geodjango). Does anybody have a clue how to do so? Since in found out Django-Models do not support M-values i thought i try MulitlinestringField with dim=3 and use the z-Dimension which actually would be the m-Dimension. When accessing the DB I only get 2-dimensional Multilinestring even when setting dim=3. geom = models.MultiLineStringField( dim=3, srid=EPSG_CODE, blank=True, null=True, spatial_index=True ) # EPSG:3128=AustriaLambert Does anybody know how I can read in all 3 values from the MultilineStringM stored in Postgis? Many thanks Since in found out Django-Models do not support M-values i thought i try MulitlinestringField with dim=3 and use the z-Dimension which actually would be the m-Dimension. When accessing the DB I only get 2-dimensional Multilinestring even when setting dim=3. -
Difficulty using multiple filters simultaneously in Django view with HTMX
I'm encountering an issue with using multiple filters simultaneously in a Django view while incorporating HTMX for asynchronous updates. Here's a breakdown of the relevant code and the problem I'm facing: Html Requests: <input id="searchInput" class="form-control mb-4" type="search" name="searchInput" placeholder="Procure produtos pelo nome..." hx-get="{% url 'filter_products' %}?searchInput={{ searchInput.value }}" hx-trigger="input changed delay:500ms, search" hx-target="#search-results"> <select name="name_category" class="form-select px-0 py-0" multiple aria-label="multiple select example" hx-get="{% url 'filter_products' %}" hx-trigger="change" hx-target="#search-results"> Filter View: def filter_products(request): category_names = request.GET.getlist('name_category', []) search_query = request.GET.get('searchInput') print(search_query) print(category_names) # Start with all products products = Products.objects.all() # Apply category filter if any category is selected if category_names: category_filters = Q() for category_name in category_names: category_filters |= Q(categoryproducts__category__name_category=category_name) products = products.filter(category_filters) # Apply search filter if a search query is provided if search_query: products = products.filter(title__icontains=search_query) # Render the response using the products found html = render_to_string('products/products_list_partial.html', {'products': products}) return HttpResponse(html) The issue arises when I attempt to use both filters simultaneously. If I select a category while a search query is applied (or vice versa), the other filter gets cleared. For instance, if I have a search query applied and then select a category, the search query disappears, and only the category filter is applied. How … -
django.db.utils.ProgrammingError: column app_table.field does not exist
I have a django app which is already in production. I added some new tables and new fields to existing tables and all went well in the feature branch, but when I merged it with the main branch then i got the following error: django.db.utils.ProgrammingError: column appname_table.field does not exist. I have tried deleting migrations, running fake migrations and a lot of other stuff but it doesn't work out. It might be possible to delete database on local but not in production because already there is user data. -
Django dynamic pages. Why is my code not working?
I am creating a website for the sale of goods, and for each product I create a card based on data from the database. When a new card appears, a dynamic page based on the same database data should be automatically connected to it. The page is created, but the data from the model is not loaded. I watched the Django guide, and it showed this method using DetailView, from where I took the code. Please help me, I don't understand what the problem is. My code: views.py: class car(DetailView): model = inventory template_name = 'main/cars.html' context_object_name = 'inventory' urls.py: urlpatterns = [ path('inventory/<int:pk>', views.car.as_view(), name='cars'), ] cats.html: {% extends 'main/layout.html' %} {% block main %} {% for el in invent %} <div class="main-card "> <img src = '{{ el.img_1 }}' style=""> <h3 style="">{{ el.name }}</h3> <h4 style="">{{ el.rent }}</h4> <button><a href="{% url 'cars' el.id %}">Details</a></button> </div> {% endfor %} {% endblock %} models.py: class inventory(models.Model): name = models.CharField('Name', max_length=100) type = models.CharField('Type of car', max_length=6) img_1 = models.ImageField(upload_to='./sql_imgs') img_2 = models.ImageField(upload_to='./sql_imgs') img_3 = models.ImageField(upload_to='./sql_imgs') img_4 = models.ImageField(upload_to='./sql_imgs') img_5 = models.ImageField(upload_to='./sql_imgs') img_6 = models.ImageField(upload_to='./sql_imgs') img_7 = models.ImageField(upload_to='./sql_imgs') img_8 = models.ImageField(upload_to='./sql_imgs') MSRP = models.CharField('msrp', max_length=40) Purchase = models.CharField('purchase', max_length=40) rent = … -
inside inner class, parameter is not accessed despite being defined inside the class [closed]
I am trying to use an inner class inside an outer class, to make it easier to deal with a large number of parameters. I am currently using Django Rest API. Here is how it looks like now : `class MeasureProcessingContext: def __init__(self, request, cache_metadata, measure_ids, user, paging_id, result,to_include): self.request = request self.cache_metadata = cache_metadata self.measure_ids = measure_ids self.user = user self.size_in_query = 'size' in self.request.query_params self.eval_in_query ='eval' in self.request.query_paramsy self.measure_in_query = 'measure' in self.request.query_params self.page_in_query = 'page' in self.request.query_params self.paging_id = int(self.page_in_query) if self.page_in_query else 0 if self.eval_in_query else -1 self.result = result self.to_include = to_include` The issue is that I get an error as part of the argument, namely paging_id, even though it is being set, I get "paging_id" is not accessedPylance.Even though it is clearly being set as part of the init call. I was expecting to be able to sovle the "paging_id" is not accessedPylance error, such that even argument of the __init___function are defined. I have also tried without using a specific class (in this case MeasureProcessingContext) but due to the number of parameters, this solution ended up being not optimal. -
A Big Issue in django LoginView
there is an issue in Django with the LogoutView. when I try to enter the link 'accounts/logout' django server pops in the cmd: Method Not Allowed (GET): /accounts/logout/ Method Not Allowed: /accounts/logout/ [24/Feb/2024 13:48:11] "GET /accounts/logout/ HTTP/1.1" 405 0 this is the view file content: from django.urls import path, include from django.contrib.auth import views as auth_views from .views import showProfile, logout_user app_name = 'user' urlpatterns = [ path('logout/', auth_views.LogoutView.as_view(template_name='registration/logged_out.html'), name='logout'), path('', include('django.contrib.auth.urls')), ] and this is the 'registration/logged_out.html' file content: {% extends "generic_base.html" %} {% block content %} <form method="post" action="{% url 'user:logout' %}"> {% csrf_token %} <button type="submit">Logout</button> </form> {% endblock content %} the templates file is located in the application 'accounts'. and the app_name = 'user' and this is the generic_base.html template content: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% block title %} <title>Donations</title> {% endblock title %} </head> <body> {% block content %} {% endblock content %} </body> </html> I tried a lot of ways to fix this issue, but none of them worked. I also saw all the provided solutions in Stack Overflow about this problem, but none of them worked. I also tried the solutions in Django built in Logout … -
serving static files in django on pythonanywhere
hello guys i need your help, i followed all the steps to serve my static files for my django application, i ran the collectstatic command, and i can see my files in the static folder in the root directory but i cant access them idk why for example i type https://scheduling.pythonanywhere.com/static/assets/css/style.css i get Not Found The requested resource was not found on this server., eventhough ik that my files are there (venv) 12:25 ~/Scheduling (main)$ ls Mappord appOrd manage.py mydb.sqlite3 requirements.txt static vercel.json -
Can messages sent through django channels be saved
I just created a chat app with Django channels and Daphne server but anytime I refresh a page, all the messages sent on that page disappear. I cant keep the messages after chats I created a model to keep the messages from disappearing but when i refresh , it still disappears -
My EBS healty status is degraded as a result of initial wrong configuration
i initially tried to deploy my Django app with EBS several times and it failed. I then investigated and discovered from the logs that the django.config file in my .ebextensions had the wrong settings instead of ‘‘‘option_settings: aws:elasticbeanstalk:container:python: WSGIPath: myapp.wsgi:application ‘‘‘ I used the one on the documentation which was ‘‘‘option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango.wsgi:application ‘‘‘ Now whenever I try to redeploy again after making this change I still get the 502 Bad Gateway on the browser and in the logs it still says this ‘‘‘ ModuleNotFoundError: No module named 'ebdjango'. ‘‘‘ I deleted my .elasticbeanstalk file and tried to create another application with a different name which shows up in the config.yml in the .elasticbeanstalk, but I still get the 502 error and the logs showing ModuleNotFoundError: No module named 'ebdjango' -
How do i pass the variable from django views.py to my javascript?
Sure, here's a Markdown version of your question for Stack Overflow: Issue with Passing Data from Django Views to JavaScript in Template I'm trying to pass data from my Django view to JavaScript in my template, but I'm encountering an issue where the parameters I'm passing appear to be empty when I inspect the webpage. Views.py def homepage(request): selected_model = request.GET.get('model', '') if selected_model == '1': df = pd.read_csv(os.path.join(settings.BASE_DIR, 'files', 'data', 'preprocessed_price_optimization_dataset.csv')) model_path = os.path.join(settings.BASE_DIR, 'files', 'data', 'price_optimization_model.h5') X = df[['product_id', 'category_id', 'brand_encoded', 'historical_price_scaled']] y = df['historical_price'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) loaded_model = load_model(model_path) predictions = loaded_model.predict(X_test) evaluation = loaded_model.evaluate(X_test, y_test) actual_data = [1, 2, 3, 4, 5] predicted_data = [6, 7, 8, 9, 10] context = { 'actual_data': actual_data, 'predicted_data': predicted_data, } else: print("no actual and predicted data") context = {} return render(request, 'base.html', context) base.html <select id="visualSelector" name="model" onchange="printSelectedValue({{ actual_data|safe }}, {{ predicted_data|safe }})"> <option value="0">---</option> <option value="1">SCATTERPLOT</option> <option value="2">LINEPLOT</option> </select> JavaScript function printSelectedValue(actualData, predictedData) { var selectedValue = document.getElementById('visualSelector').value; var selectedModelValue = document.getElementById('modelSelector').value; if (selectedModelValue === '0') { console.log("No model selected"); return; } var canvas = document.getElementById('plotCanvas'); if (selectedValue === '0') { canvas.style.backgroundColor = 'red'; console.log("value 0:", actualData); } else if (selectedValue … -
How to customize response api schema with drf-spectacular for Django Rest Framework
I have a problem of customizing API schema. Here is my case: I need to return a list of instances in my serializer with it's fields, but also there is supposed to be one common aggregation field, that accumulates those model instances in a list. Here is the example of json structure: { "comments_amount": 2, "comments": [ { "id": 0, "card_id": 0, "user_id": 0, "text": "Comment", "created_at": "2024-02-24T09:07:43.946Z", "updated_at": "2024-02-24T09:07:43.946Z" }, { "id": 1, "card_id": 0, "user_id": 0, "text": "Comment", "created_at": "2024-03-24T09:07:43.946Z", "updated_at": "2024-03-24T09:07:43.946Z" } ] } Here is my code for serializer: class CommentResponseSerializer(serializers.ModelSerializer): parent_id = serializers.IntegerField(help_text=_("ID of parent comment"), min_value=0, required=False) card_id = serializers.IntegerField(help_text=_("Product's card ID"), min_value=0) user_id = serializers.IntegerField(help_text=_("ID of user who created this comment"), required=True) class Meta: model = Comment exclude = ["user", "parent", "card"] And here is for views: @extend_schema(tags=["Product Cards"], summary="API для комментариев карточек продуктов") class CommentView(APIView): @extend_schema( description="API для просмотра комментариев. Доступно всем пользователям.", parameters=[ OpenApiParameter( name="card_id", description="ID карточки продукта", required=True, type=int, location="path" ) ], request=CommentInputSerializer, responses=CommentResponseSerializer, ) def get(self, request, *args, **kwargs): card_id = kwargs["card_id"] comments = Comment.objects.filter(card_id=card_id) serializer = CommentResponseSerializer(comments, many=True) data = { "comments_amount": comments.count(), "comments": serializer.data } return Response(data, status=status.HTTP_200_OK) Here, as you can see, I create dict with … -
Don't insert modules inside a container
I decided to deploy a test project and bought a vps server on ubuntu from reg ru for this purpose. When building containers, an error occurs with pip packages inside the python image: > [backend 5/6] RUN pip install -r requirements.txt: #0 15.76 WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ #0 31.37 WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ #0 47.48 WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ #0 64.58 WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ #0 83.69 WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ #0 98.81 ERROR: Could not find a version that satisfies the requirement asgiref==3.7.2 (from versions: none) #0 98.81 ERROR: No matching distribution found for asgiref==3.7.2 ------ failed to solve: process "/bin/sh -c pip install -r requirements.txt" did not complete successfully: exit code: 1 root@cv3598657:/home/var/www/test_repo# client_loop: send disconnect: Broken pipe the image code itself and … -
Why am I getting WebKitFormBoundary in my post request using the JS Fetch API?
I am trying to send data to my Django server from JS. My code looks like this? let url = play_selected.dataset.url; const csrf_token = getCookie('csrftoken'); let data = JSON.stringify( { selects: arr } ); console.log(data); const response = await fetch(url, { method: 'POST', // Specify the HTTP method body: data, // JSON.stringify(data), // Convert data to JSON string (if object) headers: { 'Content-Type': 'application/json', // Set content type header 'X-CSRFtoken': csrf_token } }); data = await response.json(); console.log(data); The selects arr is just an array of numbers which I will eventually do something in my django back end. Currently all I am doing is printing out the request.POST variable which is always empty. When I print out request.body I get the following: (Pdb) p request.POST <QueryDict: {}> (Pdb) p request.body b'{"selects":["29"]}' (Pdb) I would imagine that request.POST should display something similar to what is in request.body. Why is request.POST empty? -
How to read PDF file from Django?
I need to create an app in Django that scrape data from a PDF file, how can I do this? I really don't have any clue all I know is that python has a few libraries to read PDF files like for example PYPDF2 but I don't know how to integrate all of this in DJANGO. I tried PYPDF2 in a python shell but it didn't work for me all it prints is blank line -
Django CORS issue
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://url/. (Reason: header ‘authorization’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response). The api is made using djangorestframework and i have configured corsheader in the settings.py,error pop up when im trying to put authorization in headers in the fetch request -
Lots of issues using openAI in Python only on Ubuntu
I have a project utilising openAI One of the changes required me to run openai migrate, it says "You can run openai migrate to automatically upgrade your codebase to use the 1.0.0 interface. " I did that on windows and had no issues. I can't remember how I did it. I think I just opened up powershell or terminal and wrote openai migrate (which doesn't really make sense to me, is it scanning my entire system and makes changes to update the code? Whatever, I digress). Anyway, I'm moving to linux and ran my program (Django). It says the exact same thing as before - that you need to run openai migrate. So I open a terminal on my desktop, 'openai migrate' and viola..nothing. OpenAI not found. I know that openai is installed in ./local after trying to follow another debugging step. It seems I have 2 options 1 - manually refactor my code to comply with the new API or 2 - run the openAI migrate command which I believe does that already for you?? Anyway, I'm going with option #2 but I cannot even run open ai migrate. I'm not a linux expert (yet..) and don't know about … -
Is the structure of the project correct?
Here is the structure of my project: ├─── applications │ ├─── about │ │ ├─── admin.py │ │ ├─── api │ │ │ │ └─── __init__.py │ │ │ ├─── apps.py │ │ ├──── __init__.py │ │ ├─── libs │ │ │ │ └─── __init__.py │ │ │ ├─── migrations │ │ │ │ └─── __init__.py │ │ ├─── models.py │ │ │ ├─── services │ │ │ │ └─── __init__.py │ │ ├─── templates │ │ ├─── tests.py │ │ │ └─── views.py │ ├─── account │ │ │ ├─── admin.py │ │ ├─── api │ │ │ │ └─── __init__.py │ │ │ ├─── apps.py │ │ ├──── __init__.py │ │ ├─── libs │ │ │ │ └─── __init__.py │ │ │ ├─── migrations │ │ │ │ └─── __init__.py │ │ ├─── models.py │ │ │ ├─── services │ │ │ │ └─── __init__.py │ │ ├─── templates │ │ ├─── tests.py │ │ │ └─── views.py │ ├─── blog │ │ │ ├─── admin.py │ │ ├─── api │ │ │ │ └─── __init__.py │ │ │ ├─── apps.py │ │ ├──── __init__.py │ │ ├─── libs │ │ │ │ └─── __init__.py │ │ │ … -
how can i fix my ui in django jinja template everything is messed up?
i was adding image sharing functionality to my project but now i messed up its ui and i am unable to fix it!! <div class="room__message"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> {{ message_form.body }} </div> <div class="mb-3"> {{ message_form.image }} </div> <input type="submit" class="btn btn-primary" value="Send Message"> </form> </div> the above code has "message_form.body" has a text area without id so it a name="body" and the code "message_form.image" is the image upload button. i don't know what went wrong but the text area and button are hard stuck and send message button is expanded. i attached the image or the ui pls help. i just want to adjust text area and the upload and send message button this is my site at 100% scale this is at 33% scale the website is working properly just the UI is messed up need help to fix it -
Add two time values and display in template
I am having trouble on how to correctly display the addition of two time values in a template. Here is my code. models.py class UserTimesheet(models.Model): employee = models.ForeignKey(Employee, models.SET_NULL, blank=True, null=True) date = models.DateField() monday_start_time = models.TimeField(_(u"Start Time"), null=True, blank=True) monday_end_time = models.TimeField(_(u"End Time"), null=True, blank=True, ) @property def get_monday_total(self): if self.monday_start_time is not None and self.monday_end_time is not None: return self.monday_end_time - self.monday_start_time I have tried using: {{ get_monday_total }} {{ UserTimesheet.get_monday_total }} And a lot of different other things, but I cannot, for the life of me, figure out how to display this logic within a template. Any ideas? Any and all help is grateful. -
Deplying django and vue don't load the site
Im trying to deploy django with the dist folder generated from the npm run build command, I tested the site with the serve npm package and works just fine, but when I copy that folder into the django project directory and run python manage.py runserver the page renders blank and the browser console tells these errors. The resource from “http://localhost:8000/assets/index-422b98df.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). and Loading module from “http://localhost:8000/assets/index-4435c3df.js” was blocked because of a disallowed MIME type (“text/html”). I just wrote the simplest view to render the index.html. def index(request): return render(request, 'dist/index.html') Any help will be useful, thanks in advance. -
Django display crossed tables
I have an event signup page where the participant insert's details upon signing up. Then in a view I am trying to display a listing of their name, title, and details. I am stuck trying to get the details field to display if there were any for the participant. Thank you. ######## Model - Events ######## class Event(models.Model): Event_ID = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) Event_Description = RichTextField(null=True, blank=True) Event_Category = models.ForeignKey(EventCategories, default=1, on_delete=models.CASCADE) Event_participants = models.ManyToManyField(User, blank=True, related_name='events') def __str__(self): return self.Event_Name ######## Model - Events ######## class Submission(models.Model): participant = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="submissions") event = models.ForeignKey(Event, on_delete=models.SET_NULL, null=True) details = models.TextField(null=True, blank=False) id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True, editable=False) def __str__(self): return str(self.event) + ' --- ' + str(self.participant) ######## View ######## def single_event(request, pk): try: event = Event.objects.get(Event_ID=pk) submitted = Submission.objects.filter(event=event) submitted = list(submitted.values('participant','details')) except: return render(request, 'events/single-event.html', {"success":True,}, status=200) context = {'events':Event.objects.filter(Event_ID=pk), 'event':event, 'submitted':submitted} return render(request, 'events/single-event.html', context) ######## Template - single-event.html ######## {% for event in events %} {% for user in event.Event_participants.all %} <tr> <td>{{ user.profile.title }}</td> <td>{{ user.first_name }} {{ user.last_name }}</td> <td>{{ ??????????? }}</td> #This is where i need help. I would like to display 'details' from the Submission model here </tr> {% endfor … -
Django-allauth Third-Party Login Failure
I've got an instance of an application where I'm trying to authenticate users using Google/Github. All the configuration is as documented, the callbacks are as required by the docs, the client ID and secrets are alright. Yet, when receiving the callback, I get shown the following page The callback url i am getting is (with no error msg): http://localhost:8000/accounts/github/login/callback/?code=1216195be45faf4d04af&state=jYUTOFAXVKeiqzpk I do not know what code and state in uri is referring to. The page I am getting redirected to after login attempt I was using version 0.61.1 Downgrading to 0.54.0 and removing allauth.account.middleware.AccountMiddleware middleware solved the problem. But now I can not use LinkedIn Open ID Connect authentication as it is not supported in version 0.54.0. Looking for the solution so that i can use google,github, and linkedin social auth in version 0.61.1 -
Rendering a form with Django using crispy forms
I am rendering a review form on a product page, however the basic rendering is not working. I know I have crispy forms installed correctly as I have used it elsewhere without problem. Can anyone see where I am going wrong? models.py from django.db import models class Review(models.Model): """ Model for review form. Assistance with the positive integer field came from: https://www.geeksforgeeks.org/positiveintegerfield-django-models/ """ stars = models.PositiveIntegerField(choices=( (1, '1 star'), (2, '2 stars'), (3, '3 stars'), (4, '4 stars'), (5, '5 stars'))) body = models.TextField(blank=False) created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ["created_on"] def __str__(self): return f"Review {self.body}" forms.py from django import forms from .models import Review class ReviewForm(forms.ModelForm): """ Review form set up """ class Meta: model = Review fields = ('stars', 'body') views.py from django.shortcuts import render from .models import Review from .forms import ReviewForm from django.contrib import messages def review(request): """ A view to return review """ # reviews = Review.objects.order_by('-created_on').all() # if request.method == 'POST': # review_form = ReviewForm(request.POST) # if review_form.is_valid(): # review_form.instance.name = request.user.username # review_form.save() # review_form = ReviewForm() # messages.add_message(request, messages.SUCCESS, # 'Your review has been successfully posted!') # else: review_form = ReviewForm() context = { 'review_form': review_form, } return render(request, 'product/product_detail.html', context) …