Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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): … -
Django Pillow error name has attr no defined, possible WSGI issue
I have no problems working with Pillow in my development environment - and have not had any issues with it either on a public server where I have implemented mod_wsgi. However, today, when attempting to upload an image in the admin, I get this error message File "/home/<username>/virtualenvs/<sampleenv>/lib/python3.6/site-packages/PIL/Image.py", line 585, in __del__ NameError: name 'hasattr' is not defined It must relate to mod_wsgi since this is the only difference between my development and production environment. Why this has suddenly happened is a mystery. This is my /etc/apache2/mods-available/wsgi.load file: LoadModule wsgi_module /home/<username>/virtualenvs/<sampleenv>/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so WSGISocketPrefix /var/run/apache2/wsgi WSGIPythonHome /home/<username>/virtualenvs/<sampleenv> I have not attempted to copy the mod_wsgi module into the Apache installation - perhaps this is the problem but I'm not sure how to do this. I hope I've managed to explain the problem clearly - any help would be great! -
Django "AttributeError: 'function' object has no attribute 'as_view'"
when i use user_passes_test decorators an error display : "AttributeError: 'function' object has no attribute 'as_view'" this is my code : urls.py : url(r'^user/admin/$', UpdateAdminView.as_view(), name='admin'), views.py : @user_passes_test(lambda u: u.is_superuser) @method_decorator(login_required, name='dispatch') class UpdateAdminView(TemplateView): template_name = "admin.html" -
Can't access the value of the `to` form field
I'm creating a blog using Django and there's this feature I implemented that allows users to share posts via email. Here's the form from django import forms from .models import Post class EmailPostForm(forms.Form): name = forms.CharField(max_length=100, required=True, widget=forms.TextInput( attrs={'placeholder' : 'your name'} )) email = forms.EmailField(max_length=200, required=True, widget=forms.TextInput( attrs={'placeholder' : 'your email'} )) to = forms.EmailField(max_length=200, required=True, widget=forms.TextInput( attrs={'placeholder' : 'recipient\'s email'} )) comments = forms.CharField(max_length=500, required=False, widget=forms.Textarea( attrs={'rows' : 5, 'placeholder' : 'Tell recipient what you think about this post (optional)'} ), help_text='The maximum length of the text is 4000') Here's the view def post_share(request, post_id): # Retrieve the post by id post = get_object_or_404(Post, id=post_id, status='published') sent = False if request.method == 'POST': # Form was submitted form = EmailPostForm(request.POST) if form.is_valid(): # Form fields passed validation cd = form.cleaned_data post_url = request.build_absolute_uri(post.get_absolute_url()) presubject = '{} ({}) recommends you reading "{}"' subject = presubject.format(cd['name'], cd['email'], post.title) premessage = 'Read "{}" at {}\n\n{}\'s comments: {}' message = premessage.format(post.title, post_url, cd['name'], cd['comments']) send_mail(subject, message, 'admin@sayc.com', [cd['to']]) sent = True else: form = EmailPostForm() return render(request, 'post_share.html', {'post' : post, 'form' : form, 'sent' : sent}) Here's the url urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^(?P<post_id>\d+)/share/$', views.post_share, name='post_share'), ] And here's the … -
Can we fill the fields I don't need in Serializer fields?
I have a User Model, and it has many fields in it: class User(models.Model): openstackcloud_id = models.CharField(max_length=32, null=True) # username = models.CharField(max_length=16) password = models.CharField(max_length=40) # sha1加密 real_name = models.CharField(max_length=12, null=True,blank=True) phone = models.CharField( max_length=11) # 手机号码 email = models.EmailField(blank=True, null=True ) qq = models.CharField(max_length=10, null=True, blank=True) address = models.CharField(max_length=64, blank=True, null=True) # 地址 id_card = models.CharField(blank=True, null=True, max_length=18, validators=[RegexValidator(regex='^.{18}$', message='身份证长度必须为18', code='nomatch')]) id_card_img_front = models.CharField(max_length=256, blank=True, null=True) id_card_img_back = models.CharField(max_length=256, blank=True, null=True) nickname = models.CharField(max_length=16, blank=True, null=True) profile = models.CharField(max_length=256, blank=True, null=True, default='我爱旗云') # 个人简介 usertype = models.ForeignKey(to='UserType', default=1, blank=True) # 默认是:1.普通用户 user_c_type = models.CharField(max_length=4, null=True) # 用户类型(个人 or 企业) fixed_phone = models.CharField(max_length=16, null=True) # 固定电话 fax = models.CharField(max_length=16, null=True) # 传真 main_bussiness = models.CharField(max_length=16, null=True) # 主营业务 main_industry = models.CharField(max_length=16, null=True) # 所属行业 company_name = models.CharField(max_length=32, null=True) # 公司名称 company_address = models.CharField(max_length=32, null=True) # 公司地址 province = models.CharField(max_length=32, null=True, default="--省--") # 省市县 town = models.CharField(max_length=32, null=True, default="--市--") # 省市县 country_level = models.CharField(max_length=32, null=True, default="--县--") # 省市县 ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) # 更新时间 status = models.CharField(max_length=1, null=True, default=1) # 1.存活 2.禁用 3.注销 You see, there is many fields in User model. But I am using rest framework, like: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', … -
Unable in getting data from list containing many objects
I am trying request.data.get('student_name') but it says that list has no attribute get. I just want to get the name of all students before passing to the serializer. I am sending the POST request data in the form of [ {"student_name": "jack", "last_name": "cale", "fathers_name":"carlos"}, {"student_name": "alex", "last_name": "magasa", "fathers_name":"greg"}, {"student_name": "sia", "last_name": "gunns", "fathers_name":"brett"}, {"student_name": "jacob", "last_name": "woods", "fathers_name":"john"} ] my views.py @api_view(['POST']) def add_students(request): student_name = request.data.get('student_name') fathers_name = request.data.get('fathers_name') serializer = StudentsSerializer(data=request.data, many=True) if serializer.is_valid(): serializer.save() return Response("success") else: return Response(serializer.errors) my serializers.py class StudentsSerializer(serializers.ModelSerializer): class Meta: model = Students fields = ('student_name', 'last_name', 'fathers_name') my models.py class Students(models.Model): student_name = models.CharField(max_length=100, null=True) last_name = models.CharField(max_length=100, null=True) fathers_name = models.CharField(max_length=100, null=True) -
Timing issue with image upload on Heroku + Django Rest Framework + s3
ok this is a mix of architecture design and code question.. I've had this problem on a couple of applications and I'm not sure how to handle this. The problem is fairly basic, an app which allows users to attach files/images to an object. Let's say I have the following Django models: Document and Attachment. class Document(models.Model): body = models.TextField(blank=True, help_text='Plain text.') class Attachment(models.Model): document = models.ForeignKey(Document, on_delete=models.CASCADE, related_name='attachments') attachment = models.FileField(upload_to=get_attachment_path, max_length=255, null=False) filesize = models.IntegerField(default=0) filetype = models.CharField(blank=True, max_length=100) orientation = models.IntegerField(default=0) The get_attachment_path callable simply builds a path based on the document pk and the user. When a user creates a document, he can attach files to it. As it's a modern world, you want to be able to upload the files before creating the document, so I have a TempUpload object and a direct connection from the web application to S3 (using pre-signed URL). When the user clicks save on the document form, I get an array of all the TempUpload objects that I need to attach to the new document. Now here's the problem... within the heroku 30s timeout constraint, I need to: create the document (quite fast) iterate the array of TempUpload objects, and … -
HTML pages loading problems and buffer
Hi have a project that use Django/Python to create a web app, my problem is that on some page that rely heavely on Jquery Dialog and forms it takes up to 20 seconds to load the page. When the page load, it does like a buffer and for a few seconds display everything on the page on top of each other (like jquery tabs and dialog poping on top of the page) so i wanted to add a loading buffer and hide everything until the page is load. i just added divs in the body <div class="loader"></div> <div id="body" style="display:none;"> and this in the document.ready $('#body').show(); But my problem is that the page buffer for a few seconds, display nothing (not even the loader) then the loader pop for not even 3 seconds and the page end up fully loaded. What i don't understand is that if my page take so long to load why isn't the loading buffer image staying during the whole loading phase ? -
not able to host django app it on Heroku
So i created a new Django app with static files,its running perfectly in localhost,i saw Heroku is a good place to publish my app,but after following all the proceedures,i'm not able to get any output from it,it successfully deploys without any errors,but if i open the app it says Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. I'm not sure what to do at this point,the log says nothing any help would be appreciated -
Django force redirect to home page
this is easiest to explain with an example. I have an HTML button, when it is clicked it is supposed to change a status-field in the database. After the status-field is changed, the user is supposed to be redirected back to home. Below is the HTML-button that calls a Javascript function: {% for group in groups %} <button id="approve-btn" onclick="approvePendingGroup({{ group.pk }})">Approve</button> {% endfor %} Here is the Javascript-function: function approvePendingGroup(id) { window.location.href = "/result/approve/" + id; } The Javascript-function calls the following URL, which calls a method in views. urlpatterns = [ url(r'^result/approve/(?P<pk>\d+)/$', views.approve_group, name ='approve_group'), ] Here is the views-method that is supposed to redirect back to home: @csrf_exempt def approve_group(request, pk): group = Group.objects.get(pk=pk) group.status = Status.approved group.save() return reverse('home') Unfortunately, this does not lead to the http://127.0.0.1:8000/home page It takes me to the: http://127.0.0.1:8000/result/approve/1/home page instead. It just appends "home" to the previous URL. How can I force this method to redirect directly to home, and not just append it at the end of http://127.0.0.1:8000/result/approve/1/? Thank you for your time! -
Django class based view and template with some div section
I have my Django class based view in which in the get method I am rendering a template with 4 div section(when one div section is being displayed, other three are hided, just for information). Each div section in the template displays a different set of data from a model. The logic of the extraction of data that I want to display is mixed and code is such a mess. Now my code is like this: class MyClass(View): def post(...): .... def get(self, request): # about 50 lines of code in which I am extracting data from models # but is too messy ... # in context I put extracted data context={'proposte_richieste': proposte_richieste, 'proposte_richiedibili': proposte_richiedibili, 'offerte_richiedibili': offerte_richiedibili, 'offerte_richieste': offerte_richieste, 'richiesteapprovate': richiesteapprovate, 'richiesteOapprovate': richiesteOapprovate, 'studente': studente, } return render(request,'myapp/mytemplate',context) I want something like this: class MyClass(View): def post(...): .... def get(self, request): def functionForDiv1(): ...#code for extract data for div1 def functionForDiv2(): ...#code for extract data for div2 -
paypal IPN is in json format body , how to append verify cmd?
def paypalNotify( tag, request ) : logger.info( "get notify from " + tag + "Paypal:" ) logger.info( "QueryDict: ") logger.info( request.POST ) logger.info( "body: " ) logger.info( request.body ) logger.info( "content_type : " ) logger.info( request.content_type ) notify = json.loads( str( request.body, "utf8") ) verify_cmd = "?cmd=_notify-validate" ok = False if tag == "sandbox" : resp = requests.post( SANDBOX_PAYPAL_VERIFY_IPN + verify_cmd , data = request.body ) elif tag == "live": resp = requests.post( LIVE_PAYPAL_VERIFY_IPN + verify_cmd , data = request.body ) logger.info( resp ) if resp.ok and resp.text == "VERIFIED": logger.info( "verify paypal notify success " ) ok = True elif resp.ok and resp.text == "INVALID" : logger.info( "verify paypal notify failed " ) ok = False return HttpResponse(); else: logger.info( "verify paypal notify failed " ) ok = False return HttpResponse() I get following log: get notify from sandboxPaypal: QueryDict: body: b'{"id":"WH-60T842431C033902E-45C96888PP9193402","event_version":"1.0","create_time":"2017-10-23T09:26:04.086Z","resource_type":"sale","event_type":"PAYMENT.SALE.COMPLETED","summary":"Payment completed for $ 2.0 USD","resource":{"id":"9C282227JW286135M","state":"completed","amount":{"total":"2.00","currency":"USD","details":{"subtotal":"2.00"}},"payment_mode":"INSTANT_TRANSFER","protection_eligibility":"ELIGIBLE","protection_eligibility_type":"ITEM_NOT_RECEIVED_ELIGIBLE,UNAUTHORIZED_PAYMENT_ELIGIBLE","transaction_fee":{"value":"0.37","currency":"USD"},"invoice_number":"","custom":"[\"xxxxxeg@qq.com\", \"primary\", \"1\"]","parent_payment":"PAY-12T27562BA472264LLHW3K4Y","create_time":"2017-10-23T09:25:30Z","update_time":"2017-10-23T09:25:30Z","links":[{"href":".....sandbox.paypal.com/v1/payments/sale/9C282227JW286135M","rel":"self","method":"GET"},{"href":".....sandbox.paypal.com/v1/payments/sale/9C282227JW286135M/refund","rel":"refund","method":"POST"},{"href":"....sandbox.paypal.com/v1/payments/payment/PAY-12T27562BA472264LLHW3K4Y","rel":"parent_payment","method":"GET"}]},"links":[{"href":".....sandbox.paypal.com/v1/notifications/webhooks-events/WH-60T842431C033902E-45C96888PP9193402","rel":"self","method":"GET"},{"href":"......sandbox.paypal.com/v1/notifications/webhooks-events/WH-60T842431C033902E-45C96888PP9193402/resend","rel":"resend","method":"POST"}]}' How can I verify the IPN with JSON body ? the suck document said I need append " cmd=_notify-validate ", I tried to append the verify cmd to response body, it doesn't work.