Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku Django-AuthException at /complete/vk-oauth2/
''' Please help me, I'm new to programming. I need to enter in social net and I have an error(.Please help me how to change the version of the social network in contact in Heroku?AuthException at /complete/vk-oauth2/ Invalid request: versions below 5.81 are deprecated. Version param should be passed as "v". "version" param is invalid and not supported. For more information go to https://vk.com/dev/constant_version_updates ''' -
Can not get comment id with AJAX in django
I'm fighting with this problem during several days and can not find the solution for my case. I'm trying to make system of likes without refreshing the page. In synchronous mode system of likes and dislikes works fine, but when I'm trying to add AJAX, I'm getting 405 and only one last comment is working for one click, I understand problem that Ajax doesn't understand django urls with id or pk like my variant {% url 'store:like' comment.pk %} , but how it can be solved? There is this part from the template: {% for comment in comments %} <h6 class="card-header"> {{ comment.author }}<small> добавлен {{ comment.created_at|date:'M d, Y H:i' }} </small> </h6> <div class="card-body"> <h4>{{ comment }}</h4> <form id="like" method="POST" data-url="{% url 'store:like' comment.pk %}"> {% csrf_token %} <input type="hidden" value="{{comment.pk}}" name="id"> <input type="hidden" name="next" value="{{ request.path }}"> <button style="background-color: transparent; border: none; box-shadow: none;" type="submit"> <a class="btn btn-success" id="like"> Likes {{ comment.likes.all.count }}</a> </button> </form> </div> {% empty %} <p>Для данного товара ещё нет комментариев.</p> {% endfor %} my ajax call in the same template: <script type="text/javascript"> $(document).ready(function(){ var endpoint = $("#like").attr("data-url") $('#like').submit(function(e){ e.preventDefault(); var serializedData = $(this).serialize(); $.ajax({ type: 'POST', url: endpoint, data: serializedData, success: function(response) { … -
Django error trying to run server after installing cors-headers
So I'm trying to make a Django back-end for my project. It's my first time doing something like this, so when I got a CORS error (CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.) I Googled what to do. After doing the steps following the documentation, I've got the following error when trying to run 'python manage.py runserver'. C:\Users\Bence\Documents\Programozás-tanulás\web50\final project\benefactum>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\Bence\AppData\Roaming\Python\Python310\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Bence\AppData\Roaming\Python\Python310\site-packages\django\core\management\commands\runserver.py", line 115, in inner_run autoreload.raise_last_exception() File "C:\Users\Bence\AppData\Roaming\Python\Python310\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Bence\AppData\Roaming\Python\Python310\site-packages\django\core\management\__init__.py", line 381, in execute autoreload.check_errors(django.setup)() File "C:\Users\Bence\AppData\Roaming\Python\Python310\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Bence\AppData\Roaming\Python\Python310\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Bence\AppData\Roaming\Python\Python310\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\Bence\AppData\Roaming\Python\Python310\site-packages\django\apps\config.py", line 300, in import_models self.models_module = import_module(models_module_name) File "C:\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load … -
Specific Django models relationships
Good day! I'm coding an educational portal on Django and here are the models: class UserRanking(models.Model): user_id = models.ForeignKey(UserCourses, on_delete=models.CASCADE) i_xp = models.IntegerField(default=1) class UserCourses(models.Model): i_subscription_type = models.ForeignKey(SubscriptionType, on_delete=models.CASCADE) i_course_id = models.ForeignKey(CourseInfo, on_delete=models.CASCADE) i_user_id = models.ForeignKey(UserProfile, on_delete=models.CASCADE) dt_subscription_start = models.DateTimeField() dt_subscription_end = models.DateTimeField() class UserProfile(models.Model): i_user_id = models.ForeignKey(UserAuth, on_delete=models.CASCADE) ch_name = models.CharField(max_length=100) ch_surname = models.CharField(max_length=100) url_photo = models.URLField(max_length=250) # the path to the database dt_register_date = models.DateTimeField() dt_total_time_on_the_website = models.FloatField() I need to get such relationships database diagram Can you help me, please? -
How to gracefully restart django gunicorn?
I made a django application using docker. Currently I send hup signal to gunicorn master process to restart. If I simply send a hup signal, the workers are likely to restart without fully completing what they were doing. Does gunicorn support graceful restart just by sending a hup signal to the master process? If not, how can I gracefully restart the Gunicorn? -
How to encrypt data in django
As we know that we had an id in Django for each item in models by using which we can access that item. Now I want to encrypt that while sending to the frontend so that the user can't enter random id in URL to access any note. So how can I encrypt that here is what i want url should look thsi = notes.com/ldsfjalja3424wer0ew8r0 not like this = notes.com/45 class Note(models.Model): title = models.char id = model.primary def create_encryptkey(): And can be decoded in views if needed for any purpose for example to get exact id Thanks! -
passing variable value from django to another python script
I want to run an external python file the Django.view code is as follows: def generate(request): a=int(request.POST["status"]) b=int(request.POST["level"]) run(['python', 'water.py',a,b]) I have imported this water.py file from my app I want to pass these a and b values to my water.py file so that the water.py file can run in the background and can create a CSV file but I don't know how to pass these value my water.py code is as follows from time import time import sys from __main__ import* # trying to pass those values here x,current_level=sys.argv[1],sys.argv[2] but when I try to pass the value in this way I get error list index out of range is there any better way to tackle with this problem please suggest it would be very helpful -
Django ajax upvote downvote function
I'm very new to ajax, need help with implementing ajax to a django upvote-downvote utils function. I have tried doing it on my own but couldn't pull it off, any help will be much appreciated thanks. Here are the code snippets: in my model: models.py class Questions(models.Model): title = models.CharField(max_length=long_len) ques_content = models.TextField() tags = models.ManyToManyField(Tags) upvotes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='user_upvote') downvotes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='user_downvote') answers = models.ManyToManyField('main.Answer', related_name='answers') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=False) views = models.IntegerField(default=0) is_answered = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) votes = models.IntegerField(default=0) has_accepted_answer = models.BooleanField(default=False) in my utils: utils.py def performUpDownVote(user,isQuestion,id,action_type): id = int(id) flag = False if isQuestion == 'True': print('------> isQ') q = Questions.objects.get(pk = id) if q.author == user: return False else: print('------> isNotQ') flag=True q = Answer.objects.get(pk = id) if q.answered_by == user: return False existsInUpvote = True if user in q.upvotes.all() else False existsDownUpvote = True if user in q.downvotes.all() else False if existsInUpvote: if action_type == 'downvote': q.upvotes.remove(user) q.downvotes.add(user) reputation(flag,-20, q) q.votes = q.votes - 1 elif existsDownUpvote: if action_type == 'upvote': q.downvotes.remove(user) q.upvotes.add(user) reputation(flag,20, q) q.votes = q.votes + 1 else: if action_type == 'downvote': q.downvotes.add(user) reputation(flag,-10, q) q.votes = q.votes - 1 if action_type == 'upvote': … -
Reverse for 'google_login' not found. 'google_login' is not a valid view function or pattern name
I Have a project and I want to use Google authentication for signup on my website. This is my signup.html code: {% load socialaccount %} <form class="site-form" action="{% url 'authentication:signup' %}" method="post"> {{ form }} {% csrf_token %} <label> <a href="{% provider_login_url "google" %}">Login With Google</a> <input type="submit" value="submit"> </label> </form> and this is my urls.py file: path('signup/', views.signup_view, name='signup'), path('google-login/', include('allauth.urls')), but when I want to use from singup.html, this error raised: Reverse for 'google_login' not found. 'google_login' is not a valid view function or pattern name. and when I want to use from google-login, 404 not found displayed: Using the URLconf defined in project.urls, Django tried these URL patterns, in this order: admin/ auth/ login/ [name='login'] auth/ logout/ [name='logout'] auth/ signup/ [name='signup'] auth/ google-login/ signup/ [name='account_signup'] auth/ google-login/ login/ [name='account_login'] auth/ google-login/ logout/ [name='account_logout'] auth/ google-login/ password/change/ [name='account_change_password'] auth/ google-login/ password/set/ [name='account_set_password'] auth/ google-login/ inactive/ [name='account_inactive'] auth/ google-login/ email/ [name='account_email'] auth/ google-login/ confirm-email/ [name='account_email_verification_sent'] auth/ google-login/ ^confirm-email/(?P<key>[-:\w]+)/$ [name='account_confirm_email'] auth/ google-login/ password/reset/ [name='account_reset_password'] auth/ google-login/ password/reset/done/ [name='account_reset_password_done'] auth/ google-login/ ^password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)/$ [name='account_reset_password_from_key'] auth/ google-login/ password/reset/key/done/ [name='account_reset_password_from_key_done'] auth/ google-login/ social/ auth/ google-login/ google/ auth/ google-signup/ auth/ ^static/(?P<path>.*)$ The current path, auth/google-login/, didn’t match any of these. Thanks for your help. -
How to manage a redirect after a Ajax call + django
I'm managing my payments using braintree drop in and i'm using django. when the payment is success it should redirect to the payment success page and when it's unsuccess it should redirect to the payment failed page. I define the redirects in my views.py but i don't know how should i handle the redirect in ajax in this code after payment nothing happens and redirect is not working. what should i add to my ajax to handle the redirect? Braintree drop in Javascript code: <script> var braintree_client_token = "{{ client_token}}"; var button = document.querySelector('#submit-button'); braintree.dropin.create({ authorization: "{{client_token}}", container: '#braintree-dropin', card: { cardholderName: { required: false } } }, function (createErr, instance) { button.addEventListener('click', function () { instance.requestPaymentMethod(function (err, payload) { $.ajax({ type: 'POST', url: '{% url "payment:process" %}', data: { 'paymentMethodNonce': payload.nonce, 'csrfmiddlewaretoken': '{{ csrf_token }}' } }).done(function (result) { }); }); }); }); </script> Views.py @login_required def payment_process(request): order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) total_cost = order.get_total_cost() if request.method == 'POST': # retrive nonce nonce = request.POST.get('paymentMethodNonce', None) # create and submit transaction result = gateway.transaction.sale({ 'amount': f'{total_cost:.2f}', 'payment_method_nonce': nonce, 'options': { 'submit_for_settlement': True } }) if result.is_success: # mark the order as paid order.paid = True # … -
ProgrammingError: Cursor closed while using Django ORM raw
There is a a repeating error ProgrammingError: Cursor closed when using a raw query using Django ORM MyModel.objects.raw(<raw_sql_query>) The database being used is MySQL, and the cursor object is not being accessed in any application code. All references found online refer to problems when dealing with the cursor object. There are other instances of error: Programming Error (2014, Commands out of sync; you can't run this command now) in some celery tasks, which are running on separate hosts. Can anyone help me with clues to debug this problem ? Or any areas I might have not explored which is leading to this error. Environment: Python 3.6+, Django 2+, Mysql 5.7+ -
Django REST API connecting to existing database MySQL shows empty [] in http://127.0.0.1:8000/api/overview
I want to connect my Django REST API to MYSQL which i have done in my settings sucessfully, however it shows emppty [] in http://127.0.0.1:8000/api/overview/. I would appreciate if you could help to understand how to get my figures to show in http://127.0.0.1:8000/api/overview/. in my app/models.py : from django import forms from .models import Overview class OverviewForm(forms.ModelForm): class Meta: model=Overview fields=["__all__"] in app/forms.py: from django.conf import settings from django.db import models class OverviewQuerySet(models.QuerySet): pass class OverviewManager(models.Manager): def get_queryset(self): return OverviewQuerySet(self.model,using=self._db) class Overview(models.Model): symbol=models.CharField(settings.AUTH_USER_MODEL,max_length=200) typename=models.CharField(max_length=500) sector=models.CharField(max_length=500) objects = OverviewManager() class Meta: managed=False db_table='overviews' def __str__(self): return '{}'.format(self.symbol) class Meta: verbose_name = 'Overview' verbose_name_plural = 'Overviews' in my app/api/serializers.py: from rest_framework import serializers from app.models import Overview class OverviewSerializer(serializers.ModelSerializer): class Meta: model=Overview fields=["__all__"] in my app/api/views.py: from rest_framework import generics, mixins, permissions from rest_framework.views import APIView from rest_framework.response import Response import json from cfs.models import Overview from .serializers import OverviewSerializer class OverviewSearchAPIView(APIView): permission_classes = [] authentication_classes= [] serializer_class = OverviewSerializer def get(self,request,format=None): qs = Overview.objects.all() serializer = OverviewSerializer(qs,many=True) return Response(serializer.data) in my app/api/urls.py: from django.urls import path from .views import OverviewSearchAPIView urlpatterns = [ path('', OverviewSearchAPIView.as_view()), ] in my app/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ … -
Django pagination is not working properly when using POST method in Search form
I am trying to search an item in a form using POST method and I got the results. But when I use Django pagination, I got the results in the first page. When I click the next or 2 button in Django paginator I got an error like this. The view profiles.views.individual_home didn't return an HttpResponse object. It returned None instead. Here search form is in one html page and results shown in another html page. views.py def individual_home(request): if request.method == 'POST': keyword = request.POST.get('keywords') print(keyword) location = request.POST.get('location') print(location) ind = IndividualProfile.objects.get(user_id=request.user.id) details = companyjob.objects.filter( Q(job_title=keyword) | Q(qualification=keyword) | Q(skills_required=keyword) | Q(job_location=location) & Q(closing_date__gte=datetime.date.today())) if details: print(details) count = details.count() paginator = Paginator(details, 3) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, "individual_home.html", {'jobs': page_obj,'count': count, 'ind': ind}) else: return redirect("individual_homes") individual_home.html: <div class="container mt-5"> <div class="row mt-5"> <div class="col-lg-10 mx-auto"> <div class="career-search mb-60"> <form method="POST" action="{% url 'individual_home' %}" class="career-form mb-60" style="background-color:#6351ce;"> {% csrf_token %} <div class="row"> <div class="col-md-6 col-lg-4 my-3"> <div class="input-group position-relative"> <input type="text" class="form-control" placeholder="Enter Your Keywords" id="keywords" name="keywords"> </div> </div> <div class="col-md-6 col-lg-4 my-3"> <input type="text" class="form-control" placeholder="Location" id="location" name="location"> <div class="col-md-6 col-lg-4 my-3"> <button type="submit" class="btn btn-lg btn-block btn-light btn-custom" id="contact-submit"> Search … -
How to pass multiple integers to ManyToMany Field present in the list in Django
I want add this product to both category, how to do it class Category(models.Model): name = models.CharField(max_length=500) image = models.ImageField(upload_to='categories', default='default.png') class Products(models.Model): name = models.CharField(max_length=500) category_id = models.ManyToManyField(Category, default='') category_id = [4, 6] product, created = Products.objects.get_or_create(name =data['Casual Red Shirt'], product.category_id.add() -
how to deploy django project on aws?I already tried with nginx,gunicorn but it was not working.Need some help in this
While using aws to deploy django project with nginx,gunicorn but it was not working so how deploy it in properly.need some help. -
How to use django annotate to compare current date with other date in models
I want to get the days between the current time and another date. Here is the command what I used: employees = Employee.objects.annotate( duration=ExpressionWrapper(datetime.now().date() - F('start_working_date'), output_field=DurationField()) ) But the result I got( employee.duration) is 0. for employee in employees: employee.duration And here is my models: class Employee(models.Model): name = models.CharField(max_length=30) start_working_date = models.DateField() -
How to get uploaded file name from django id
I simply wanted the file exact file name which i have been uploaded so that i can read the whole file and show content on HTML page... class newcodes(models.Model): user_id = models.AutoField fullname = models.CharField(max_length=200) codefile = models.FileField(upload_to ='programs/')//her is my codefile location in models Here is my function for reading text but i cant get name of uploaded file so i can't read the file def showcode(request,id): programs=newcodes.objects.filter(id=id) print(programs) # f=open('media/') return render(request,"Codes.html") -
Django Modelviewset Filtering
I have two models Category & Post. In Post model there is foreign key of category. Based on category I want to filter the data to show the post category wise. Here's my code. models.py class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField() parent = models.ForeignKey('self',blank=True, null=True ,related_name='news', on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "Category" def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) class Post(models.Model): NEWS_TYPE = (('Images','Images'),('Multi-Images','Multi-Images'),('Image-Text','Image-Text'), ('Audio-Video','Audio-Video'),('Audio-Video-Text','Audio-Video-Text'),('Audio','Audio'), ('Audio-Text','Audio-Text')) POST_STATUS = (('Pending','Pending'),('Verified','Verified'),('Un-Verified','Un-Verified'), ('Published','Published'),('Mint','Mint')) category = models.ForeignKey(Category, related_name='Category', on_delete=models.CASCADE) post_type = models.CharField(max_length=100, verbose_name='Post Type', choices=NEWS_TYPE) title = models.TextField(verbose_name='News Title') content = models.TextField(verbose_name='News Content') hash_tags = models.CharField(max_length=255, verbose_name='Hash Tags') source = models.CharField(max_length=255, verbose_name='News Source') author = models.ForeignKey(User, related_name='Post', on_delete=models.CASCADE) views = models.ManyToManyField(User,related_name='Views', blank=True) likes = models.ManyToManyField(User, related_name='Likes', blank=True) dislikes = models.ManyToManyField(User, related_name='Dislikes', blank=True) status = models.CharField(max_length=20, verbose_name='Status', choices=POST_STATUS, default='Pending') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return (self.post_type)+ '-' +self.title serializers.py class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class PostSerializer(serializers.ModelSerializer): category = serializers.SerializerMethodField() class Meta: model = Post fields = ('category','post_type','title','content','hash_tags','source','author','views', 'likes','dislikes','status') views.py class CategoryAPI(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer class PostAPI(viewsets.ModelViewSet): serializer_class = PostSerializer def get_queryset(self): news_post = Post.objects.all() … -
Why is it going to anaconda how do I fix i
enter image description here I'm new so you have to press on the link. Pls help -
How get selected value in bootstrap V5 select with python
I am using Class Based Views in django... Then my model is: class Survey(Base): description = models.CharField('Description', max_length=50, unique=True) item1 = models.CharField('Item1', max_length=50) item2 = models.CharField('Item2', max_length=50) ... class Meta: verbose_name = 'Survey' def __str__(self): return self.description Now I am reading database data for fill in select and works fine. How I get this select item for fill table fields? info.html <div class="col-12"> <div class="card card-chart"> <div class="card-header "> <div class="row"> <div class="col-sm-4 text-left"> <h2 class="card-title">Informations</h2> <option selected>choose a option</option> {% for s in survey %} <option>{{s.description}}</option> {% endfor %} </select> </div> <!-- of course, in this moment variable [s] not exist --> <div class="col-sm-8 text-right"> <table class="table"> <tbody> <tr> <td>item 1</td> <td>item 2</td> </tr> <tr> <!-- want fill this fields with select item above--> <td>{{s.item1}}</td> <td>{{s.item2}}</td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> -
How to send mail to the post author when got new comment in django rest framework through serializer?
I am trying to build an API where students will ask questions and the teacher will answer that question. For asking questions and answering I am using the blog post way. Now, my problem is I am trying to send mail from the serializer. But when I want to detect the post author I am unable to do that. I can send selected users but not from the model. If anyone can help me with that it will be so helpful. Thanks a lot. these are the add_question model and answer the question model --- class add_question(models.Model): title = models.CharField(max_length=250, blank=False) description = models.TextField(blank=True, null=True) is_answered = models.BooleanField(default=False) is_deleted = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE) STATUS = ( ('Published', 'Published'), ('Suspended', 'Suspended'), ('Unpublished', 'Unpublished'), ) status = models.CharField(choices=STATUS, default='Published', max_length=100) RESOLUTION = ( ('Resolved', 'Resolved'), ('Unresolved', 'Unresolved'), ) resolution = models.CharField(choices=RESOLUTION, default='Published', max_length=100) def __str__(self): return self.title class add_questionFile(models.Model): question = models.ForeignKey(add_question, on_delete=models.CASCADE, related_name='files') file = models.FileField('files', upload_to=path_and_rename, max_length=500, null=True, blank=True) class submit_answer(models.Model): description = models.TextField(blank=False, null=False) is_deleted = models.BooleanField(default=False) rating = models.FloatField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) question_id = models.ForeignKey(add_question, blank=False, on_delete=models.CASCADE) created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE) class submit_answerFile(models.Model): answer … -
Django generic create view . Can we add conditions to save data from the form?
This is what my code looks like and I want to add some condition to the Borrower create view like if the stock method of book returns 0 then don't list that book in field while creating a new borrower or if it isn't possible at least throw some error while adding borrower to that book. models.py: class Book(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200) author = models.CharField(max_length=100) summary = models.TextField( max_length=1000, help_text="Enter a brief description of the book") isbn = models.CharField('ISBN', max_length=13, help_text='13 Character https://www.isbn-international.org/content/what-isbn') genre = models.ManyToManyField( Genre, help_text="Select a genre for this book") language = models.ForeignKey( 'Language', on_delete=models.SET_NULL, null=True) total_copies = models.IntegerField() pic = models.ImageField(blank=True, null=True, upload_to='books') def stock(self): total_copies = self.total_copies available_copies = total_copies - \ Borrower.objects.filter(book=self).count() if available_copies > 0: return available_copies else: return 0 def __str__(self): return self.title class Borrower(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) student = models.ForeignKey('Account', on_delete=models.CASCADE) book = models.ForeignKey('Book', on_delete=models.CASCADE) issue_date = models.DateField( null=True, blank=True, help_text='YYYY-MM-DD', default=date.today) return_date = models.DateField( null=True, blank=True, help_text='YYYY-MM-DD') def __str__(self): return self.student.name.title()+" borrowed "+self.book.title.title() def fine(self): today = date.today() fine = 0 if self.return_date <= today: fine += 5 * (today - self.return_date).days return fine views.py: class BorrowerView(LoginRequiredMixin, ListView): model=Borrower context_object_name='borrowers' template_name … -
How to insert raw html into form when creating a page using django
I want to include things like hyperlinks, quoting, italicized text, etc. into my pages I post on the site I wrote with django but it seems to escape my code. What can I do to add this feature? Has someone else already done something I could just use? -
Error: Has No Attribute "Getlist" Error When Making Request in Django
When I run the tests to make requests to the webpage on Django, the tests run fine and have expected behavior. However, when the same code is run when I'm making a request outside of the testing environment in Django, running: request.data.getlist("insert_key_here") where "insert_key_here" is a key from a key-value pair where the value is a list, I get this error: 'dict' object has no attribute 'getlist' When I try to run this instead request.data["insert_key_here"] I get an error that a string's indices must be an int. Does this mean that the request.data is somehow a string? If it was just grabbing the first value in the list like how it would if you used .get() instead of .getlist(), I don't know that I'd be getting this error just from trying to fetch the value. To give some context, this is an example of the format of the request: { "insert_key_here" : [ "list_item1", "list_item2" ] } I'm not sure why it would work perfectly in the testing environment, but, then, when I run it outside the testing environment, I get that error on that specific line. -
I couldn't able to save my data in to admin. it just redirect me to Home page
This is my View.py code. hear it redirect me to home page and doesn't save my data in to admin panel. **if i indent back else condition Blockquote else: form = OrderForm() return redirect('home') Blockquote it gives me error - ValueError at /orders/place_order/ The view orders.views.place_order didn't return an HttpResponse object. It returned None instead.** def place_order(request, total=0, quantity=0,): current_user = request.user # if cart count is less then 0 or equel to 0, then redirect to shop cart_items = CartItem.objects.filter(user=current_user) cart_count = cart_items.count() if cart_count <= 0: return redirect('store') grand_total = 0 tax = 0 for cart_item in cart_items: total += (cart_item.product.price*cart_item.quantity) quantity += cart_item.quantity tax = (12 * total)/100 grand_total = total + tax if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): # store all the information inside belling table data = Order() data.user = current_user data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.phone = form.cleaned_data['phone'] data.email = form.cleaned_data['email'] data.address_line_1 = form.cleaned_data['address_line_1'] data.address_line_2 = form.cleaned_data['address_line_2'] data.country = form.cleaned_data['country'] data.provence = form.cleaned_data['provence'] data.zone = form.cleaned_data['zone'] data.district = form.cleaned_data['district'] data.order_note = form.cleaned_data['order_note'] data.order_total = grand_total data.tax = tax data.ip = request.META.get('REMOTE_ADDR') data.save() # genarate order no yr = int(datetime.date.today().strftime('%y')) dt = int(datetime.date.today().strftime('%d')) mt = int(datetime.date.today().strftime('%m')) d = datetime.date(yr,mt,dt) current_date = …