Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Type-error - django python
from django.conf.urls import * from django.contrib import admin from payments import views admin.autodiscover() urlpatterns = [ # Examples: # url(r'^$', 'ecommerce_project.views.home', name='home'), # url(r'^ecommerce_project/', include('ecommerce_project.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), url(r'^$', 'main.views.index', name='home'), url(r'^pages/', include('django.contrib.flatpages.urls')), url(r'^contact/', 'contact.views.contact', name='contact'), url(r'^sign_in$', views.sign_in, name='sign_in'), url(r'^sign_out$', views.sign_out, name='sign_out'), url(r'^register$', views.register, name='register'), url(r'^edit$', views.edit, name='edit')] Issue in this code - type error - view must be callable I do not understand what is wrong with my urls.py file, here is a copy of it: Type error -
inline form with django crispy form
I'm sorry but I just don't get it, the docs here are pretty awesome, and I'm using practically the same example, I just have two fields, that I want do display inline, but it's just does not work, My form: from django import forms from crispy_forms.helper import FormHelper from crispy_forms import layout, bootstrap from crispy_forms.bootstrap import InlineField, FormActions, StrictButton from crispy_forms.layout import Layout from ..models import EmployeeModel class EmployeeCreateForm(forms.ModelForm): """ TODO: Extend CompanyModel into Form :returns: TODO """ def __init__(self, *args, **kwargs): super(EmployeeCreateForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.method = "POST" self.helper.form_class = 'form-inline' self.helper.field_template = 'bootstrap3/layout/inline_field.html' self.helper.form_action = "company:create-employee" self.helper.layout = Layout( 'first_name', 'last_name', StrictButton('Add', css_class='btn-default'), ) class Meta: model = EmployeeModel fields = ["first_name", "last_name"] and my template: {% extends "base.html" %} {% load i18n static %} {% load crispy_forms_tags %} {% block content %} <nav class="navbar fixed-top navbar-light bg-faded"> <ul class="nav justify-content-center"> <li class="nav-item"> <a class="nav-link" href="{% url 'why' %}">WHY SCREEN?</a> </li> <li class="nav-item"> <a class="nav-link" href="#">BLOG</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'faq' %}">FAQ</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'about' %}">ABOUT</a> </li> </ul> </nav> <div class="container"> <div class="row"> <p style="padding:60px;"></p> </div> </div> <div class="container"> <div class="row"> <div class="col-sm-4 col-sm-offset-2"> <form … -
Django: cannot decode unicode characters from StreamingHttpResponse streaming_content
I'm trying to test a django admin action method streaming a large CSV file . I'm using StreamingHttpResponse object since I'm dealing with a large number of rows as suggested by official documentation. The only difference from the implementation above is that my csv output may contain unicode strings. Export function is working fine since is streaming huge numbers of rows in seconds. Here's how I'm formatting every single line before sending them to writerow function [u'{}'.format(field_1), u'{}'.format(field_2)] I'm having a very hard time to test StreamingHttpResponse object on python 2. Say my_streaming_http_response is the StreamingHttpResponse object I want to test, here's my test: reader = csv.reader( [i.decode('utf-8') for i in my_streaming_http_response.streaming_content] ) self.assertEqual( list(reader), [ ['Row-1-col-1', 'Row-1-col-2'], ['Row-2-col-1', 'Row-2-col-2'], ] ) this works with python2 and python3 when no unicode strings are provided python3 when containing unicode When I try to run this test on python 2 I get this error UnicodeEncodeError: 'ascii' codec can't encode character [UNICODE CODE] in position [POSITION]: ordinal not in range(128) and I just cannot figure out how to test this on python2, any suggestion? Thanx in advance! -
How to "group by" in django serializers for same model
I am new to Django-Python and learning to build serializers. I understand the basic implementation of Serializers but stuck with this following particular requirement. This is my Customer Events model - class CustomerEvents(models.Model): account_number = models.BigIntegerField(blank=False) event_type = models.CharField(max_length=255, blank=False, null=False) Sample records in CustomerEvents: Account Number Event Type A12345 Billing Issues A12345 Video Services A12345 Sales I want to create a CustomerEventsSerializer which will return values as below: { "account_number" : A12345, "event_types" : ['Billing Issues', 'Video Services', 'Sales'] } -
How to add an OrderingFilter to existing filters and render them as links
I'm using django-filter for filtering posts of a Django wagtail index page via the django-filter's LinkWidget. That works fine, just like in the django admin interface with list_filter. Now I would like to expose the functionality to sort/order the queryset by some criteria. Django-filter does provide an OrderingFilter (ref) - but I do not know how to implement this filter and achieve a LinkWidget-like rendering. My current approach: # filters.py class PostFilter(django_filters.FilterSet): categories = PatchedAllValuesFilter( name="categories__slug", label="Categories", widget=LinkWidget(), choice_name="categories__name", ) ordering = django_filters.OrderingFilter( widget=LinkWidget, fields=( ('title', 'title') ) ) class Meta: model = PostPage fields = ['categories'] # views.py from .models import PostPage from .filters import PostFilter filter = PostFilter(request.GET, queryset=all_posts) filter_ordering = PostFilter(request.GET, queryset=all_posts).filters['ordering'] context = self.get_context(request) context['filter'] = filter context['filter_ordering'] = filter_ordering return render(request, self.template, context, *args, **kwargs) # template.html <ul> {% for choice in filter_ordering.field.choices %} <li>{{ choice }}</li> {% endfor %} </ul> ... but this does not work. I do get something from my OrderingFilter: ('', '---------') ('title', <django.utils.functional.lazy.<locals>.__proxy__ object at 0x7f0d3e021cc0>) ('-title', 'Title (descending)') ... and how to render this as links in my template? Grateful for any help -
Django one to one filed with User in form
I try to update number_of tokens and amount, but it doesn't work, can some one tell me what's the problem models.py class ConfiTCL(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) number_of_tokens = models.IntegerField(blank=True, null=True) amount = models.IntegerField(blank=True, null=True) forms.py class ConfigPCLForm(forms.ModelForm): """This class represents the Config PCL form""" class Meta: model = ConfiTCL fields = ('number_of_tokens', 'amount',) widgets = { 'number_of_tokens': forms.TextInput(attrs={'class': 'form-control'}), 'amount': forms.TextInput(attrs={'class': 'form-control'}), } views.py class UpdateAdminView(TemplateView): template_name = "admin.html" @method_decorator(user_passes_test(lambda u: u.is_superuser)) @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def post(self, request): form = ConfigPCLForm(request.POST, instance=request.user) if form.is_valid(): form.save() return TemplateResponse(request, self.template_name, {'form': form,'user':self.request.user}) def get(self, request, *args, **kwargs): user = User.objects.get(username=request.user) form=ConfigPCLForm(instance=user) context = {'form': form,'user':self.request.user} return TemplateResponse(request, self.template_name, context) -
Django: FormView not execute the form_valid() method
I am using Braintree as a Payment solution (Sandbox). When I use a fill the form it redirect me to the same page. My error is that the Form doesn't get process. On the FormView only the get_context_data() were execute but not form_valid() html <script src="https://js.braintreegateway.com/web/dropin/1.6.1/js/dropin.min.js"></script> <form action="{% url 'checkout_braintree' %}" method="POST" id="payment-form"> {% csrf_token %} <h3>Method of Payment</h3> <p>378282246310005</p> <input type="hidden" id="nonce" name="payment_method_nonce" /> <div class="bt-drop-in-wrapper"> <div id="bt-dropin"></div> </div> <button class="button" type="submit" id="submit-button"><span>Test Transaction</span></button> </form> var form = document.querySelector('#payment-form'); braintree.dropin.create({ authorization: '{{ client_token }}', container: '#bt-dropin', paypal: { flow: 'vault' } }, function (createErr, instance) { form.addEventListener('submit', function (event) { event.preventDefault(); instance.requestPaymentMethod(function (err, payload) { if (err) { console.log('Error', err); return; } // Add the nonce to the form and submit document.querySelector('#nonce').value = payload.nonce; form.submit(); }); }); }); urls.py url(r'^checkout/$', BraintreePaymentProcessFormView.as_view(), name='checkout_braintree'), views.py class BraintreePaymentProcessFormView(FormView): template_name = 'startupconfort/cart.html' success_url = '/' form_class = BraintreeSaleForm http_method_names = ['post'] def get_context_data(self, **kwargs): # import ipdb; ipdb.set_trace() context = super().get_context_data(**kwargs) context['client_token'] = get_braintree_client_token() return context def form_valid(self, form): # import ipdb; ipdb.set_trace() user = self.request.user nonce = form.cleaned_data['payment_method_nonce'] result = braintree.Transaction.sale({ "amount": get_total_price_of_the_shipping_cart(user), "payment_method_nonce": nonce, "options": { "submit_for_settlement": True } }) # import ipdb; ipdb.set_trace() if result.is_success or result.transaction: print(result.transaction) messages.success(self.request, 'Payment … -
Django - How to save user activity log to log table
I've searched many times through Google. because I can't find my question answer and I'm ask for help. I am not familiar with Django, i should not use third-party module For example, django-user-activity-log. i need help with the principle and method configuring and recording log tables to log user activity logs in log table. to sum up, First, I need to count users who have completed membership and those who have not. Next, I need to configure and record the table to record the user activity log. log table is content who, when, what, how do. form is to string. because if i have a problem with my customer, i should use the log to respond. Ultimately, i need to count member, non-member, analyzing user activity. For example, Google Analytics. i ask help in other world developers. How can I log user activity logs into a log table in string format? -
Using a User uploaded file as an email template in django
I have the following Python code within a Django model to send emails to the 'owner' of the model. I want admin to be able to upload files which will be used (if uploaded) or the default template files will be used if it has not be loaded. This is the code: def send_invitation(self): ''' sends an invitation from admin to accept a listing ''' try: if self.user or not self.email : return False except : try: email_body_template = Parameter.objects.get(name='send_invitation_email.txt').f except: email_body_template = 'listing_cms_integration/email/send_invitation_email.txt' try: email_subject_template = Parameter.objects.get(name='send_invitation_email_subject.txt').f except: email_subject_template = 'listing_cms_integration/email/send_invitation_email_subject.txt' context = Context() context['listing'] = self context['site'] = Site.objects.get_current().domain subject = render_to_string(email_subject_template, context) message = render_to_string(email_body_template, context) email = EmailMessage(subject, message, to=[self.email]) email.send() return True If I do not have a Parameter named 'send_invitation_email.txt' then it works fine. When picking up Parameter as specified I get the following error. coercing to Unicode: need string or buffer, FieldFile found How do I convert my user uploaded file into one I can use as an email template? -
django: Setting environment variables in /etc/apache2/envvar is not working
I have a Django (v1.11.6) app on my Ubuntu server having Python 3.5 (not using virtualenv). However, I want to set environment variables in mod_wsgi for Django. Since I'm not using virtualenv I set then in /etc/apache2/envvar. But apache2 service can't get them. In settings.py I have SECRET_KEY = get_env_variable("GA_SECRET_KEY") but apache raises the following error: [Mon Oct 23 14:03:29.180611 2017] [wsgi:error] [pid 30062] [client 194.42.16.145:13576] SECRET_KEY = os.environ("GA_SECRET_KEY") [Mon Oct 23 14:03:29.180630 2017] [wsgi:error] [pid 30062] [client 194.42.16.145:13576] TypeError: '_Environ' object is not callable Do you know how to fix this? -
AttributeError at /accounts/upload_save/ 'WSGIRequest' object has no attribute 'cleaned_data'
I got an error,AttributeError at /accounts/upload_save/ 'WSGIRequest' object has no attribute 'cleaned_data' .I am making file upload system.It is that if i select file and put "SEND" button,selected image is sent to model.But now,when i select images and put "SEND" button,the error happens. I wrote in views.py @login_required @csrf_exempt def upload_save(request): form = UserImageForm(request.POST, request.FILES) if request.method == "POST" and form.is_valid(): data = form.save(commit=False) data.user = request.user data.image = request.cleaned_data['image'] data.save() return render(request, 'photo.html') else: form = UserImageForm() return render(request, 'profile.html', {'form': form}) in index.html <main> <div class="detailimg col-xs-8"> <div class="relative_ele"> <div class="container" id="photoform"> {% if form.errors %} <div class="alert alert-danger" role="alert"> <p>At least 1 picture should be selected</p> </div> {% endif %} <form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="input-group"> <label class="input-group-btn" style="width: 80px;"> <span class="file_select btn-lg"> File Select1 <input type="file" name="image"> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="input-group"> <label class="input-group-btn" style="width: 80px;"> <span class="btn-lg file_select"> File Select2 <input type="file" name="image2"> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="form-group"> <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control"> </div> <div class="col-xs-offset-2"> <div class="form-group"> <input type="submit" value="SEND" class="form-control"> </div> </div> </form> </div> </div> </div> </main> I really cannot understand why this error happens.I reworte in views.py like @login_required … -
Pillow Resizing images (thumbnail) on Amazon S3 - Django
I am try resize an image when this is saved. Specifically, my images are stored on Amazon S3, then I use the django-storages and boto3 third party applications When a image is saved, this is stored in my Amazon S3 bucket, having a acces url such as follow: https://s3-sa-east-1.amazonaws.com/ihost-project/media/studyoffer_images/algoritmos-para-ensenanza/15061122523583.jpg The code to save and resize the image is this: class UploadStudyOffer(models.Model): study_offer = models.ForeignKey(StudiesOffert, related_name='uploadsstudyoffer') image = models.ImageField(upload_to=get_image_path) # images folder per object def save(self, *args, **kwargs): super(UploadStudyOffer, self).save(*args, **kwargs) # We first check to make sure an image exists if self.image: # Open image and check their size image = Image.open(self.image) i_width, i_height = image.size max_size = (100,100) # We resize the image if it's too large if i_width > 1000: image.thumbnail(max_size, Image.ANTIALIAS) image.save(self.image.path) When I upload an image, I get this message: Exception Type: NotImplementedError at /host/study-offer/algoritmos-para-ensenanza/edit/images/ Exception Value: This backend doesn't support absolute paths. And I am not sure, if the error is manage at storages or boto backends or in Pillow. Then at level of Pillow I found the following options in the moment of save the image, such as follow: I change the section code: image.save(self.image.path) to: image.save(self.image.name) And I get this error: File "/home/bgarcial/workspace/hostayni_platform/hosts/models.py" … -
django app on server: No module named 'django.urls'
I have a Django (v1.11.6) app on my Ubuntu server and was using Python v2.7. I am now using Python 3.5 (not using virtualenv), however when I run sudo service apache2 restart I get the following error in my browser: ImportError at / No module named 'django.urls' Request Method: GET Request URL: https://dev.ga.coach/ Django Version: 1.8.7 Exception Type: ImportError Exception Value: No module named 'django.urls' When I run python3 manage.py runserver I get no error. -
Django: Null Query
I'm using chain method for querying the database something like, objects = chain(Data.objects.filter(q_obj)..... ) In template, {% for obj in objects %} ... {% endfor %} But, if objects returns No data then how can I print out "Nothing found". I tried all of these, {% if objects == " " %} {% for obj in objects %} ... {% endfor %} {% else %} Nothing found {% endif %} Also I tried, if objects == None if objects is null if objects|default_if_none:"" if not objects if objects|length > 0 But couldn't make that happen. -
Django redirect to a view with GET arguments set
I'm having a hard time understanding the Django System of views and templates. All I want to do is inform the user of the status of his request- he pushes a button and gets a infobox with a message. The button in the Dashboard is at the root of the URL and sends a POST request to the Django Web App at book/. In the view bound to this URL I check if the booking is valid and want to inform the user (without use of javascript) about the result. I wanted to send back a HTTP redirect to /?response=success or /?response=failed. I've tried to give the view of the dashboard arguments and changed the URL regex but this did not lead where I want it to go. Currently its just return redirect('dashboard') and the URL conf is: ... url(r'^$', app.views.dashboard, name='dashboard'), url(r'^book/$', app.views.book, name='book'), ... I really like django - its really easy to use. But in simple cases like this it just drives me crazy. I would appreciate any kind of help. Kind regards Eric -
django app on server: I moved from python 2.7 to 3.5 and apache2 can't find django
I have a Django app on my ubuntu server. Up to now, I was using python 2.7. My Django version is 1.11.6. From now on, I'm using python 3.5. But when I run sudo service apache2 restart I get the following error: [Mon Oct 23 12:50:22.001339 2017] [wsgi:error] [pid 28871] [client 194.42.16.145:28999] from django.core.wsgi import get_wsgi_application [Mon Oct 23 12:50:22.001360 2017] [wsgi:error] [pid 28871] [client 194.42.16.145:28999] ImportError: No module named 'django' It's important to note that when I run python3 manage.py runserver I get no error. I'm not using virtualenv. -
Open Graph metatags - "Missing Properties" and "Inferred Property" [Facebook Share using Django]
I am trying to create a Facebook Share button to share a page with a custom topic, description, and image. But according to: developers.facebook.com/tools/debug/sharing (please forgive me the format, I cannot post more than 2 links) I have some problems with missing and inferred properties. Sharing Debugger Warnings - Screenshot First and last metatag are loaded as raw metatags. I wonder why tags in between aren't? Sharing Debugger All Raw Tags - Screenshot base.html: <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- My og metatags --> <meta property="fb:app_id" content="{ myId }" /> <meta property="og:url" content="{ myUrl }" /> <meta property="og:type" content="website" /> <meta property="og:title" content="{ myTitle }" /> <meta property="og:description" content="{ myDescription }" /> <meta property="og:image" content="{% static 'accounts/img/share_image.png' %}" /> <meta name="turbolinks-cache-control" content="no-preview"> </head> <body> {% block body %} <h1>Base</h1> {% endblock %} <script> (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.10&"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> </body> </html> template.html: {% extends 'base.html' %} {% load static %} {% block body %} <div class="fb-share-button" data-href="{ myPageToShare }" data-layout="button_count"> </div> {% endblock %} -
Django logout not working throw WSGI
I have a login and a logout view on my application. It's perfectly working with the development server. But when I use WSGI in production, logout is ignored. There is the redirection but user is still connected (especially if I logout from an other page the one I loggued in). Below my code: LoginView: class LoginView(FormView): def get(self, request, **kwargs): # some code # def post(self, request, **kwargs): form = LoginForm(request.POST or None) if request.POST and form.is_valid(): user = form.login() if user is not None: login(request, user) response = redirect(request.POST["next"] if request.POST["next"] != "" else "/") return response # some code # LogoutView: class LogoutView(View): def get(self, request): logout(request) return redirect("/") The problem seems to be the csrf token. If I delete it before logout, the logout always succeed. So add this line just after logout call in the LogoutView: csrf.rotate_token(request) It seems to work well now, but... it's not a very good code, is it a better manner to get it working? Thanks in advance for your help -
django app on server: apache runs with python 2.7 instead of python 3.5
I have a django app in my ubuntu server. Up to now I was using python 2.7. My django version is 1.11.6. From now on, I want to use python 3.5. But when I run sudo service apache2 restart I get errors containing python 2.7: [Mon Oct 23 12:40:53.500064 2017] [wsgi:error] [pid 28615] [client 194.42.16.145:23434] mod_wsgi (pid=28615): Target WSGI script '/home/zinonas/guardianangel/GuardianAngel/wsgi.py' cannot be loaded as Python module. [Mon Oct 23 12:40:53.500102 2017] [wsgi:error] [pid 28615] [client 194.42.16.145:23434] mod_wsgi (pid=28615): Exception occurred processing WSGI script '/home/zinonas/guardianangel/GuardianAngel/wsgi.py'. [Mon Oct 23 12:40:53.500125 2017] [wsgi:error] [pid 28615] [client 194.42.16.145:23434] Traceback (most recent call last): [Mon Oct 23 12:40:53.500144 2017] [wsgi:error] [pid 28615] [client 194.42.16.145:23434] File "/home/zinonas/guardianangel/GuardianAngel/wsgi.py", line 15, in <module> [Mon Oct 23 12:40:53.500203 2017] [wsgi:error] [pid 28615] [client 194.42.16.145:23434] application = get_wsgi_application() [Mon Oct 23 12:40:53.500213 2017] [wsgi:error] [pid 28615] [client 194.42.16.145:23434] File "/usr/local/lib/python2.7/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application [Mon Oct 23 12:40:53.500240 2017] [wsgi:error] [pid 28615] [client 194.42.16.145:23434] django.setup(set_prefix=False) [Mon Oct 23 12:40:53.500250 2017] [wsgi:error] [pid 28615] [client 194.42.16.145:23434] File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 22, in setup [Mon Oct 23 12:40:53.500281 2017] [wsgi:error] [pid 28615] [client 194.42.16.145:23434] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Mon Oct 23 12:40:53.500308 2017] [wsgi:error] [pid 28615] [client 194.42.16.145:23434] File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 56, in __getattr__ … -
Django Migrations ValueError: [...] was declared with a lazy reference to [...]
I have quite a complex project architecture which involves several applications whose models contains cross references. For example, I have a billing.Premium model - which belongs to the billing app - that is referenced by another model whose name is payments.PaymentJob through a one to one field: ('premium', models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, to='billing.Premium', verbose_name='premium')) (This code comes from one of payment's migrations) But I have come to some point when I need to rename billing.Premium to billing.PremiumInstallment and this is when the funny part comes: after having refactored my code to replace the model name, I try to django-admin makemigrations, it leads to the following error: ValueError: The field payments.PaymentJob.premium was declared with a lazy reference to 'billing.premium', but app 'billing' doesn't provide model 'premium'. It appears like my migration has been broken since I have renamed the model of an external application. I do not know how to fix this in a fancy way, I mean generating some migration without error and that would be applied when I run django-admin migrate. Any idea? -
404 Page not found in Django, even though regular expression is correct
I have the following URL in my Django project: url(r'^result/edit/(?P<pk>\d+)/$', views.edit_result, name='edit_result') Unfortunately, even when I manually input http://127.0.0.1:8000/result/edit/2/, it gives back a "page not found", and the view function is not called. The view function can be seen below: def edit_result(request, pk): result = get_object_or_404(Result, pk=pk) group = Group.objects.filter(pk=pk) results = Result.objects.filter(group=group) context = { 'pending_results': results, 'groups': group } return render(request, 'resultregistration/editresult.html', context) Strangely, it works perfectly fine with: http://127.0.0.1:8000/result/edit/1/ (so with 1), but not with 2, even though both objects with primary keys are present in the database. Does anyone know why the view function is not called, even though the regular expression is (I assume) correct? Thank you! -
Paginate results from django_filter
I am very new at this technology and I want to paginate a table containing results using django_filter(In my case I want to filter results from Book Model which are displayed in a html Table). I tried every documentation and forum post but don't know what I am doing wrong or if I am doing something correct. Here is my code: models class Book(models.Model): name = models.CharField(max_length=350) author = models.CharField(max_length=350) category = models.CharField(max_length=200) def __str__(self): return self.name filters class BookFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') author = django_filters.CharFilter(lookup_expr='icontains') category = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Book ields = ['name', 'author', 'category',] views class SearchBooksView(ListView): template_name = "booksearch.html" book_list = Book.objects.all() context_object_name = 'book_list' paginate_by = 3 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) book_filter = BookFilter(self.request.GET) paginator = Paginator(book_filter, self.paginate_by) page = self.request.GET.get('page') try: book_list = paginator.page(page) except PageNotAnInteger: book_list = paginator.page(1) except EmptyPage: book_list = paginator.page(paginator.num_pages) context['book_list'] = book_list return context ** html ** <h1 class="h1"> Search Books </h1> <form method="get"> {{ book_filter.form.as_p }} <button type="submit">Search</button> </form> <div class="container"> <table> <thead> <tr> <th>Name</th> <th>Author</th> <th>Category</th> </tr> </thead> <tbody> {% for book in book_list %} <tr> <td>{{ book.name }}</td> <td>{{ book.author }}</td> <td>{{ book.category }}</td> </tr> {% endfor %} </tbody> </table> {% if … -
Error message is not shown
Error message is not shown.I wrote in index.html <main> <div class="detailimg col-xs-8"> <div class="relative_ele"> <div class="container" id="photoform"> {% if form.errors %} <div class="alert alert-danger" role="alert"> <p>At least 1 picture should be selected</p> </div> {% endif %} <form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="input-group"> <label class="input-group-btn" style="width: 80px;"> <span class="file_select btn-lg"> File Select1 <input type="file" name="image"> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="input-group"> <label class="input-group-btn" style="width: 80px;"> <span class="btn-lg file_select"> File Select2 <input type="file" name="image2"> </span> </label> <input type="text" class="form-control" readonly=""> </div> <div class="form-group"> <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control"> </div> <div class="col-xs-offset-2"> <div class="form-group"> <input type="submit" value="SEND" class="form-control"> </div> </div> </form> </div> </div> </main> in views.py @login_required @csrf_exempt def upload_save(request): if request.method == "POST": form = UserImageForm(request.POST, request.FILES) if form.is_valid(): data = form.save(commit=False) data.user = request.user data.image = request.cleaned_data['image'] data.save() else: print(form.errors) else: form = UserImageForm() return render(request, 'registration/photo.html', {'form': form}) In my current code,when I select no image and put "SEND" button & I select 1~2 image and put "SEND" button,photo.html is shown.I wanna show error message {% if form.errors %} <div class="alert alert-danger" role="alert"> <p>At least 1 picture should be selected</p> </div> {% endif %} when I select no image,but now my system … -
mezzanine url shows modelname in search
When I use the default search and added in my model, the url shows search/?q=new+york&type=app.modelname how do I remove it? I tried updating the urls.py from mezzanine.core.views import search url(r'search/$', search, name="my_search"), -
Can't create registration form with image uploading in Django application
I have a problem related to registrations form. I tried to implement One To One field, but it didn't bring any results. My problems: I can not add to the User model ImageField and some other fields(I'm not sure about it) and when I fill image field in the registration form I can not get the image back in Profile page. The only thing I want is to create registration form with some specific additional fields and image uploading. You can also suggest other ways of realizing this. Models.py from django.db import models from django import forms from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) picture = models.ImageField(upload_to='profile-photos') profile_sphere = models.CharField(null=True,max_length=1000,blank=True,verbose_name='Сфера деятельности', choices=(['it','Информационные технологии'],['wood','Деревообработка'])) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() forms.py from django import forms from .models import Profile from django.contrib.auth.forms import UserCreationForm , UserChangeForm from django.contrib.auth.models import User from django.core.validators import EmailValidator class SignUp(UserCreationForm): email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username','first_name','last_name', 'email','password1',) class NewForm(forms.ModelForm): class Meta: model = Profile fields = ('profile_sphere','bio','picture',) views.py (def register and def profile) def register(request): …