Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to resize django ckeditor inside the form model
I need to use django-ckeditor in various part of my project, so for each part need to resize it. But I know that I can resize it by adding this definitions in settings as below: INSTALLED_APPS = [ 'ckeditor', ] CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Basic', 'height': 70, 'width': 430, }, } however, as I mentioned above, I am using several editor in different parts, so need to resize them differently. How to reside in different form.fields? class proForm(forms.ModelForm): description = forms.CharField(widget=CKEditorWidget()) class Meta: fields = ('__all__') -
Why is custom serializer save() method not called from view?
I have a view like this: class MyViewSet(ModelViewSet): # Other functions in ModelViewset @action(methods=['post'], url_path='publish', url_name='publish', detail=False) def publish_data(self, request, *args, **kwargs): new_data = util_to_filter_data(request.data) serializer = self.serializer_class(data=new_data, many=True) serializer.is_valid(raise_exception=True) serializer.save() # This is calling django's save() method, not the one defined by me return Response(serializer.data) And my serializer: class SomeSerializer(ModelSerializer): # fields def create(self, validated_data): print("in create") return super().create(validated_data) def save(self, **kwargs): print("in save") my_nested_field = self.validated_data.pop('my_nested_field', '') # Do some operations on this field, and other nested fields obj = None with transaction.atomic(): obj = super().save(kwargs) # Save nested fields return obj When I'm calling my serializer's save() method from my view (see the comment in view code), the save() method of django is called instead of the one defined by me, due to which I'm having issues that were handled in my save() method. This is the traceback: File "/home/ubuntu18/Public/BWell/path_to_view/views.py", line 803, in publish_data serializer.save() File "/home/ubuntu18/Envs/bp_env/lib/python3.7/site-packages/rest_framework/serializers.py", line 720, in save self.instance = self.create(validated_data) I wanted to perform some actions in save() before calling create(), but my flow is not reaching the save() method. What am I doing wrong here? P.S.: This is happening only when I am providing many=True in serializer constructor. -
Unique token using uuid is generating same codes
im using uuid token to activate users account , so every client created have their own code in the Client model , but when i create new client it generate always the same Token as others , i have used the uuid 4 , is their anyother ways to generate unique client code to activate their account or some other method then uuid , or just im missing a point on how to generate uuid on models , their is my model and client creation codes : Model.py : def generateUUID(): return str(uuid4()) class client(models.Model): name = models.CharField(max_length=45, unique=True) email = models.EmailField(max_length=85) date_of_birth = models.DateField(null=True, blank=True) height = models.IntegerField(null=True, blank=True) weight = models.IntegerField(null=True , blank=True) created_at = models.DateTimeField(auto_now_add=True) picture = models.URLField(null=True ,blank=True) affiliation = models.ForeignKey(User, on_delete=models.CASCADE, related_name="client_coach") reference = models.OneToOneField(User, on_delete=models.CASCADE, null=True , blank=True) is_active = models.BooleanField(default=False) token = models.CharField( max_length=85, default=generateUUID()) def __str__(self): return self.name def getname(self): return self.coach.name view.py: if request.method == 'POST' and request.POST['action'] == 'client': form = ClientForm(request.POST) print(form) name = request.POST.get('name') email = request.POST.get('email') #client_code = code.objects.create() new_client = client.objects.create(name = name, email = email, affiliation = request.user) new_client.save() return JsonResponse({'client': model_to_dict(new_client)}, status=200) -
JSON Exception Handling Syntax unclear to me -- JSONDecodeError
I am using JSON to get some data from an API and if the entered URL is wrong(which is very possible) the JSON file returns: "Unknown symbol" The error message is as follows : (don't be scared a lot of it is just relevant information, scroll down to the bottom I have highlighted the main error.) Environment: Request Method: POST Request URL: http://127.0.0.1:8000/buy/ Django Version: 3.1.2 Python Version: 3.7.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 353, in raw_decode obj, end = self.scan_once(s, idx) During handling of the above exception (0), another exception occurred: File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\VARDHAN\Desktop\python websites\trading_website\accounts\views.py", line 116, in buy json_data = requests.get(url).json() File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\models.py", line 900, in json return complexjson.loads(self.text, **kwargs) File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\json_init_.py", line 348, in loads return _default_decoder.decode(s) File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None Exception Type: JSONDecodeError at /buy/ … -
Online result search aplication first html page should render the form and second page will show the data. Help Appricated?
Django, I have two HTML pages first is index.html which shows the home page along with the search field and the second HTML form is the result which shows the desired result which is search by the user. I have already written code that is working fine on only one page but I want to redirect the home page once the user fillup the details it should go to the next page called result.html. modles.py from django.db import models from django.utils.encoding import smart_text from multiselectfield import MultiSelectField # Create your models here. class ResultQuery(models.Model): os_choice = ( ('Windows 10', 'Windows 10'), ('Windows 8', 'Windows 8'), ('Linux', 'Linux'), ) operating_system = models.CharField(max_length=30, blank=True, null=True, choices=os_choice) level = models.CharField(max_length=30) program = models.CharField(max_length=30) semester = models.CharField(max_length=20) exam_year = models.IntegerField() institute = models.CharField(max_length=4) reg_no = models.CharField(max_length=50) symbol_num = models.IntegerField() student_name = models.CharField(max_length=50) dob = models.DateField() sgpa = models.TextField() result = models.CharField(max_length=40) name = models.CharField(max_length=30) subject1_code=models.CharField(max_length=40) subject1_title=models.CharField(max_length=40) subject1_credit_hour=models.TextField() subject1_grade_point=models.TextField() subject1_grade=models.TextField() subject1_remarks=models.CharField(max_length=20, null=True, blank=True) subject2_code = models.CharField(max_length=40) subject2_title = models.CharField(max_length=40) subject2_credit_hour = models.TextField() subject2_grade_point = models.TextField() subject2_grade = models.TextField() subject2_remarks = models.CharField(max_length=20, null=True, blank=True) subject3_code = models.CharField(max_length=40) subject3_title = models.CharField(max_length=40) subject3_credit_hour = models.TextField() subject3_grade_point = models.TextField() subject3_grade = models.TextField() subject3_remarks = models.CharField(max_length=20, null=True, blank=True) subject4_code = … -
Django - Validation Errors not displayed using Ajax
I have a contact form and i'm using Ajax to submit the form. However i have a problem i cannot figure out how to display error messages, to notify user that has entered wrong data. For example name field accepts only letters, also i'm using PhoneNumberField to check phone. <p id="error_1_id_name" class="invalid-feedback"><strong>Wrong First Name, use only letters</strong></p> Enter a valid phone number (e.g. +12125552368). When submitting the form with invalid data for example enter name with numbers i'm getting When entering correct data everything works as expected. Any help is appreciated. views.py def contact(request): form = ContactForm(request.POST or None) data = {} if request.is_ajax(): if form.is_valid(): form.save() data['name'] = form.cleaned_data.get('name') data['status'] = 'ok' return JsonResponse(data) context = { 'form': form, } return render(request, 'pages/contact.html', context) main.js const alertBox = document.getElementById('alert-box') const form = document.getElementById('contact') const name = document.getElementById('id_name') const email = document.getElementById('id_email') const phone = document.getElementById('id_phone') const subject = document.getElementById('id_subject') const budget_range = document.getElementById('id_budget_range') const message = document.getElementById('id_message') const csrf = document.getElementsByName('csrfmiddlewaretoken') console.log(csrf) const url = "" const handleAlerts = (type, text) =>{ alertBox.innerHTML = `<div class="alert alert-${type}" role="alert"> ${text} </div>` } form.addEventListener('submit', e=>{ e.preventDefault() const fd = new FormData() fd.append('csrfmiddlewaretoken', csrf[0].value) fd.append('name', name.value) fd.append('email', email.value) fd.append('phone', phone.value) fd.append('subject', subject.value) … -
Python correlation in DJango
I am making a website on Django with Python. Index.html page has a form with 10 rows each row has six inputs which are price, review, rating, voucher, first review(date input) & shipping. User will input data in HTML from there I am converting that data in Pandas data frame. In Pandas dataframe there are two additional columns "current date" and "days". These two new columns are meant to calculate number of days between first review and current date. Based on the dataframe columns when I run Python correlation function .corr() It is only showing two columns with NaN values. Can someone help me to show complete correlation values in powershell? NOTE: THE CODE RUNS FINE WITH JUPYTER NOTEBOOK My views.py code is as follows Views.py def index(request): if request.method == "POST": qsPrice1 = request.POST.get('price1') qsPrice2 = request.POST.get('price2') qsPrice3 = request.POST.get('price3') qsPrice4 = request.POST.get('price4') qsPrice5 = request.POST.get('price5') qsPrice6 = request.POST.get('price6') qsPrice7 = request.POST.get('price7') qsPrice8 = request.POST.get('price8') qsPrice9 = request.POST.get('price9') qsPrice10 = request.POST.get('price10') qsReview1 = request.POST.get('review1') qsReview2 = request.POST.get('review2') qsReview3 = request.POST.get('review3') qsReview4 = request.POST.get('review4') qsReview5 = request.POST.get('review5') qsReview6 = request.POST.get('review6') qsReview7 = request.POST.get('review7') qsReview8 = request.POST.get('review8') qsReview9 = request.POST.get('review9') qsReview10 = request.POST.get('review10') qsRating1 = request.POST.get('rating1') qsRating2 = request.POST.get('rating2') qsRating3 = … -
Change Page owner in Wagtail admin
We have a Wagtail site where various people contribute to a news item before its published and the person who creates the page is not necessarily the main author. I'm looking for way to edit the Page.owner in the Wagtail admin. In the model class I've added: content_panels = Page.content_panels + [ ... FieldPanel('owner') ] Which shows all the site's users in a dropdown but this doesn't get saved. I was wondering if there was a more 'Wagtail' way of doing this, aside from overriding the save() definition. -
How to turn off a django model field validation?
I have a model as below: from cities.models import City class Post(models.Model): location = models.ForeignKey(City, default='', blank=True, null=True, on_delete=models.CASCADE) and in the template: <form id="dropdownForm" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ wizard.form.media }} {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %} {% else %} <div class="content-section-idea-detail-1stpage mt-4 text-center"> <label for="selectorlocation" class=""><h4><b>Select your location:</b></h4></label><br> {{ wizard.form.location }} </div> {% endif %} <input id="id_sub_post_details" class="btn btn-sm btn-primary ml-2" type="submit" value="{% trans 'submit' %}"/> </form> But the problem is that, I am not able to leave location field empty as it verifies the field before submit. However, I expect blank=True disables the validation. Do you know where is the problem happening? -
How does Python import packages and files with the same name?
I have a Django project and the directory is as follows. There are a Python file named permissions.py and a module name permissions.I want to import permissions.helpers but it raises ImportError and the error message is cannot import name helpers. The first element in sys.path is the project directory(the parent directory of myapp) as I expected.I thought Python Interpreter should try to find modules or files from sys.path but it seems to search in the current module first.Am i wrong and how can i import permissions.helpers without using absolute_import? -
Full text mysql database search in Django
We have been using a MYSQL database for our project and Django as the backend framework. We want to support a full text search on a particular table and return the Queryset in Django. We know that Django supports full text search on a Postgres database but we can't move to another database now. From what we have gathered till now - Using inbuilt search functionality - Here we check on every field if the value exists and then take an OR to combine the results. Similar to the link (Django Search query within multiple fields in same data table). This approach however straight forward may be inefficient for us because we have huge amounts of data. Using a library or package - From what we have read Django haystack is something a lot of people are talking about when it comes to full text search. Django Haystack - https://django-haystack.readthedocs.io/en/master/tutorial.html#installation We haven't checked the library completely yet because we are trying to avoid using any library for this purpose. Let us know if you people have worked with this and have any views. Any help is appreciated. Thanks. -
In my selenium file, I want to add printed data i.e. odr_id of terminal to database using model.py or any alternative option?
odr_id = pay.find_element_by_id('deep-dtyp-order-details-section') sleep(3) print(odr_id.text) #views.py def odr(request): name = odr_id.GET(request) return [Amazon.order_detail, name] pass -
reportlab in django, return a string instead of a pdf
I am working in an application in which I need to create pdf file from response which I am getting from server. I am using reportlab with django 1.8 and the response looks like this: %PDF-1.3 %���� ReportLab Generated PDF document http://www.reportlab.com 1 0 obj << /F1 2 0 R >> endobj 2 0 obj << /BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font >> endobj 3 0 obj << /BitsPerComponent 8 /ColorSpace /DeviceRGB /Filter [ /ASCII85Decode /DCTDecode ] /Height 1250 /Length 1206832 /Subtype /Image /Type /XObject /Width 1667 >> stream [...] here is my code : def generate_pdf(request,course_id): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"' # Create the PDF object, using the response object as its "file." p = canvas.Canvas(response) # # change the page size p.setPageSize((500,500)) # # Draw the image at x, y. I positioned the x,y to be where i like here p.drawImage('fond.jpg', 0, 0, width=500,height=500) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(100, 100, "Hello world.") # Close the PDF object cleanly, and we're done. p.showPage() p.save() … -
Is there a way to start/stop a celery task from django views?
I just finished my celery task for my django app, but I'm looking a way now for how to start/stop it through a toggle button on my frontend UI. I know it can do on django-admin(built in). but I want to make it for the app. like from a typical django view and restapi, you create a function like this: def start_task and def stop_task and call it through api(URL) to execute it. How can I do it? Thanks! -
unable to save files to django model through rest api serializers
I am trying to use djangrest api to upload multiple files to a single model, while trying to do so, though I can pass my files through serializer but couldnt save those on my model. Here is my models.py from django.db import models # Create your models here. class UploadedImage(models.Model): img = models.ImageField('Uploaded Image', upload_to='images') # stores uploaded image # dt_created = models.DateTimeField(auto_now_add=True, blank= True, null= True, verbose_name='Created') my admin.py from django.contrib import admin from .models import UploadedImage # Register your models here. admin.site.register(UploadedImage) My viewsets.py from django.shortcuts import render from rest_framework import viewsets from imageUpload.serializers import UploadedImageSerializer from imageUpload.models import UploadedImage from rest_framework.response import Response from rest_framework import parsers from rest_framework import status # Create your views here. class UploadImageViewset(viewsets.ModelViewSet): queryset = UploadedImage.objects.all() serializer_class = UploadedImageSerializer def create(self, request): serializer_class = UploadedImageSerializer(data=request.data) if 'img' not in request.FILES or not serializer_class.is_valid(): return Response(status=status.HTTP_400_BAD_REQUEST) else: # Single File # handle_uploaded_file(request.FILES['file']) # Multiple Files files = request.FILES.getlist('img') for f in files: handle_uploaded_file(f) serializer_class.save() return Response(status=status.HTTP_201_CREATED) def handle_uploaded_file(f): with open(f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) Here is my serializers.py from rest_framework import serializers from .models import UploadedImage class UploadedImageSerializer(serializers.ModelSerializer): img = serializers.FileField(max_length=None, allow_empty_file=False) class Meta: model = UploadedImage fields = … -
Django - how to cache template for all url prefix
I have a Django app which renders html template and loads data into html via ajax from front end(based on url's dynamic id). For eg., this is my site's dynamic url pattern "www.mysite.com/order/< some dynamic id>", I want django to cache & return all the requests to this url prefix r"^**www.mysite.com/order/**" to render the html without hitting my views function. Currently, each dynamic id in the url pattern ("/order/100","/order/101","/order/102..etc")is coming to my views and rendering the same template for each. I'm expecting, anyone visits with prefix "/order/" the html template needs to be rendered automatically without hitting my views. I'm currently using redislite for caching, Please help me with a solution. -
Django : Media Files not displayed in templates
I am trying to create a blog and to display image for each post. i am trying to display user-uploaded images on a webpage. When I upload the image files using the Django admin interface (I made a model for Post images with an ImageField), the image is stored in /media/images correctly. But I can't display the image on my webpage. However, when I inspect my template with GoogleChrome, the path of my files are ok but there is a 500 error (about-us-2.jpg:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error). Media Settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'core/static'), ) Project urls.py: from django.conf.urls import include, url from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin' , admin.site.urls), path("", include("authentication.urls")), path("", include("app.urls")), ]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) App urls.py: from django.urls import path, re_path from django.conf.urls import include, url from app import views from . import views urlpatterns = [ path('', views.index, name='home'), url(r'^blog$', views.blog_view, name ='blog'), url(r'^blog/(?P<id>[0-9]+)$', views.post_view, name ='blog_post'), re_path(r'^.*\.*', views.pages, name='pages'), ] Views.py … -
How to show suggestions of existing child record in TabularInline in django admin?
I want to show suggestion of existing child record while adding child record to parent. class IndustryInline(admin.TabularInline): model = Industry class ParentIndustriesAdmin(admin.ModelAdmin): list_display = ('id', 'name') search_fields = ['id', 'name', ] ordering = ['-date_modified'] inlines = [ IndustryInline, ] def save_model(self, request, obj, form, change): obj.modified_by = request.user obj.save() admin.site.register(ParentIndustry, ParentIndustriesAdmin) How to get suggestion for existing records like we get in case of ManytoMany relationship. -
Django view doesn't properly redirect
When view function - index is called with post request it doesn't redirect. Print inside the function executes. Can't find reason. I changed return redirect('/result') to return HttpResponse("some text") and it does not work either. My code: data = {"number" : 0} @csrf_exempt def result(request): global data response = "solution: " + str(data['number']) return HttpResponse(response) @csrf_exempt def index(request): global data if request.method == 'POST': uploadFile1 = request.FILES['file1'] uploadFile2 = request.FILES['file2'] text1 = '' text2 = '' with open('file1', 'wb+') as file1: text1 = uploadFile1.read() with open('file1', 'wb+') as file2: text2 = uploadFile2.read() data = calcpy.views.getNumber(str(text1), str(text2)) print('test') #this executes return redirect("/result") template = loader.get_template('main.html') context = {'solution' : 0} return HttpResponse(template.render(context)) My urls.py code: from django.conf.urls import patterns, include, url from . import views import version.models web_srv_prefix = version.models.getWebSrvPrefix() urlpatterns = patterns('', url(r'^' + web_srv_prefix + '/ajax/(?P<module>\w+)/(?P<function>\w+)/', views.ajax, name='ajax'), url(r'^$', views.index, name='index'), url(r'^result/$', views.result, name='result') ) -
Django - TypeError - Field 'id' expected a number but got <WSGIRequest: GET '/marketplace/add_to_cart/5/'>
I'm pretty new to Django and face a problem trying to implement a cart for my e-shopping website. As I call my "add_to_cart" function, I want to be sure if either a cart exists for this session, and if there is already a reference for the selected item in this cart. Here is my models.py : CART_ID = 'CART-ID' class Cart(models.Model): creation_datetime = models.DateTimeField(auto_now_add=True) update_datetime = models.DateTimeField(auto_now=True) checked_out = models.BooleanField(default=False) user = models.ForeignKey(User,on_delete=models.DO_NOTHING, null=True, blank=True) @classmethod def create(cls): cart_id = request.session.get(CART_ID) if cart_id: cart = models.Cart.objects.filter(id=cart_id, checked_out=False).first() if cart is None: cart = cls() request.session[CART_ID] = cart.id else: cart = cls() request.session[CART_ID] = cart.id return cart def add(self, article, prix_unitaire, quantite=1): item = Item.objects.filter(cart_id=self.id, article=article).first() if item: item.prix_unitaire = prix_unitaire item.quantite += int(quantite) item.save() else: Item.objects.create(cart_id=self.id, article=article, prix_unitaire=prix_unitaire, quantite=quantite) class Item(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) article = models.ForeignKey(Article, on_delete=models.CASCADE) quantite = models.PositiveIntegerField() prix_unitaire = models.PositiveIntegerField() def prix_total(self): return self.quantite * self.prix_unitaire prix_total = property(prix_total) in my views.py, I defined my "add_to_cart" function : def add_to_cart(request, pk, quantite=1): article = Article.objects.get(pk=pk) cart = Cart(request) cart.add(article, article.prix_unitaire, quantite) and my urls.py urlpatterns = [ ... path('add_to_cart/<int:pk>/', add_to_cart, name='add_to_cart'), As I call the function, I get this error : TypeError at /marketplace/add_to_cart/5/ Field … -
Is there any way to save data into third(join) table? django
I have 2 main tables which I join them with many to many. I have some checks and I need to save the data into this join table. I made a research but can't really find how to save data in this kind of table. for patient in patients: patientDatabase, created = Patient.objects.get_or_create( coreapi_id=patient["ID"], defaults=dict( first_name=patient["first_name"], last_name=patient["last_name"], email=patient["email"], ), ) # Get the last saved record from DB lastPatient = (Patient.objects.latest('coreapi_id')) roles_DB = list(Role.objects.values()) for role in patient['Roles']: if role['name'] == roles_DB[0]['role_name']: Save the result(data) into role_role_id this is what my model looks like: class Patient(models.Model): coreapi_id = models.CharField(max_length=100) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(max_length=100) language = models.CharField(max_length=20) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email class Role(models.Model): role_id = models.ManyToManyField(Patient) role_name = models.CharField(max_length=100) -
notification to say "please make your screen landscape" in phone screen with django
how can i make notification to say "please make your screen lanscape" when phone screen is horizontal? -
Django How to display error if the query results are empty
I am building a simple app which enables the users to search quotes from db by entering keywords using a form. I would like to return an error if "no matching quotes are found for the entered keywords" . Kindly guide me. Heres the search form: <form action="{% url 'search_results' %}" method="get"> <input name="q" type="text" placeholder="Search By Keywords" id="q" required /> <button onClick="{% url 'search_results' %}" class="btn btn-success">Search Quotes</button> </form> -- Heres the views.py {% for quotes in object_list %} <div class="shadow card"> <div class="card-body"> <h6 class="card-title">{{ quotes.by }}</h6> <p>{{ quotes.quotation }}</p> </div> </div> {% endfor %} -
getting 'str' object has no attribute 'get' when using django template tags
template {{ show_details.message|get_value:"data_errors"}} template_tags.py @register.filter def get_value(dictionary, key): print("DICTIONARY",dictionary,"KEYYY",key) #output for this is ('DICTIONARY','','KEYYY',u'data_errors') return dictionary.get('key') AttributeError: 'str' object has no attribute 'get' -
django rest api framework "list" obj has no attribute values
I trying to pass some files through djangorest framework and while trying to do so, I am facing error 'list' object has no attribute 'name' my views.py from django.shortcuts import render from rest_framework import serializers from rest_framework import viewsets from rest_framework import status from rest_framework.response import Response from restfilesupload.serializers import FileSerializer class FileUploadViewSet(viewsets.ViewSet): def create(self, request): serializer_class = FileSerializer(data=request.data) if request.method == 'POST': if 'file' not in request.FILES or not serializer_class.is_valid(): return Response(status=status.HTTP_400_BAD_REQUEST) else: handle_uploaded_file(request.FILES.getlist("file")) return Response(status=status.HTTP_201_CREATED) def handle_uploaded_file(f): with open(f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) class Meta: fields = ['pk' , 'file'] my serializers.py from rest_framework import serializers class FileSerializer(serializers.Serializer): file = serializers.FileField(max_length=None, allow_empty_file=False)