Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
generate form fields from vocabulary (RDFS)
I have a vocabulary described with RDFS, consider for example the "Friend of a Friend" (FOAF). Now I want to populate my database, so I want to insert the classes (the Person classes) and their relations (the friendship). I want to do that with a web page with the appropriate form field connected to a back-end server. My ontology is more complicated than the FOAF (but it is based on it), so I am searching for a tool that automatically creates the web forms. Presently I am not linked to a particular technology, but I would like to stay with RDF since I am also using rdflib, in particular for querying. Django seems to be a solution, but I am not sure how it interacts with RDF. -
PIP INSTALL CROSSBAR gives error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools":
I have been trying to pip install crossbar on my virtual environment in Windows 10 but I keep getting: error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools I have installed the requirement and have restarted my system severally but still getting the same error. Pip has been upgraded too. Here is the list of programs install from my Control Panel: And here is the Command Prompt error (again) I have equally installed Microsoft Visual C++ 2017 Redistributable, both (x86) and (x64) but still did not work. -
Is there any way to change view of Django-rest-auth of login?
I've created rest APIs using Django-rest-auth, in login, it's returning key and some user info, But I need to add some status like success and message and some other things. Is there any way to override view of django-rest-auth for login? class TokenSerializer(serializers.ModelSerializer): user = UserSerializer(many=False, read_only=True) # this is add by myself. device = DeviceSerializer(many=True, read_only=True) class Meta: model = TokenModel fields = ('key', 'user', 'device',) -
Django web server starts but does not request anything
So here is how problem started. I had Python 3.6.4 installed on my windows machine like for 4 month. Everthing was normal. Yesterday I decided to update to Python 3.7.0. I asked around and knew that there is no way but uninstalling old version and installing again. So I did it. But since I have done that, I run my django server, it starts, tells me it runs on 127.0.0.1:8000 but it does not request anything, I mean website is not loading. I look at terminal, no requests or anything. I wondered if there is problem with project, and copied it run it on manjaro on virtualbox. It worked perfectly. How do I solve this problem? It does not gives me any error. Thanks in Advance! -
Django: Attached image in email loses CSS if referenced more than once
email.css: .share-image { width: 1em !important; height: 1em !important; vertical-align: text-bottom !important; padding-right: 0.1em !important; color: #31B2C9 !important; border-radius: 3px; } relevant .py file where I'm attaching the image: context['img_ref'] = 'cid:image.png' msg_html = render_to_string('new_notification.html', context) msg = EmailMultiAlternatives(subject=msg_subject, body=msg_html, from_email=msg_reply_to, to=[job.profile.user.email], reply_to=[msg_reply_to]) # important to attach images and set related msg.content_subtype = 'html' msg.mixed_subtype = 'related' # configure images twitter_image = MIMEImage(open(staticfiles_storage.path('img/image.png'), 'rb').read(), _subtype='png') twitter_image.add_header('Content-ID', '<{}>'.format('image.png')) If I use the image once in the template, like so: <img src="{{ img_ref }}" class="share-image"> Then CSS is applied correctly. However, if I include it twice: <img src="{{ img_ref }}" class="share-image"> <img src="{{ img_ref }}" class="share-image"> the second instance of the image is shown in full size, without any of the CSS applied. -
how to print/return loop in custom way? (python/Django)
I have a html template. it's search results design shows the results in this way like result1 result2 result3 result4 result5 result6 so on with load more button now i have data in models.py in my django project i want to print the data in such way on my html page. i have tried for loop. but it gives the result like: result1 result2 result3 result4 result5 result6 result7 Please suggest any solution to get the result like the following way: result1 result2 result3 result4 result5 result6 so on with load more button -
django ManyToManyField save
There's form with many fields (Date, Char, Text, Image, URL...) and they works fine. I mean values are submitted to DB as they must. But when I added ManyToManyField, it didn't save the value of this MultipleChoice form to DB. Any ideas why? models.py: class EventTag(models.Model): tags = models.CharField(max_length=300) def __str__(self): return self.tags class Article(models.Model): source = models.CharField(max_length=100) source_img = models.ImageField(default='default.png', blank=True) #other fields event_tags = models.ManyToManyField(EventTag, blank=True) forms.py: class CreateArticle(forms.ModelForm): class Meta: model = models.Article fields = ['source', 'source_img', 'event_tags', ] views.py: def article_create(request): if request.method == 'POST': form = forms.CreateArticle(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() return redirect('articles:list') else: form = forms.CreateArticle() return render(request, 'articles/article_create.html', { 'form': form }) -
Generating choiceField of user groups for creating and updating user
While creating user, I am letting the form attach permission Groups. Generally User and Group are tied in ManyToMany relationship. Thus it is generating MultipleChoiceField. But, instead of MultipleChoiceField, I want a single choice can be selected only for the groups field. Which I have already figured out for the create User form. But for update User form, how can i call the initial value for the groups field (Or how to automatically select the saved value). Also, is there a better efficient way than the code below? Create User form: class UserForm(forms.ModelForm): email = forms.EmailField(required=True) groups = forms.ChoiceField(required=False) class Meta: model = User fields = ('username', 'email', 'groups') def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) choices = [[obj.pk, obj.name] for obj in Group.objects.all()] choices.insert(0, ['', '--------']) self.fields["groups"].choices = choices Update user form: class UserUpdateForm(forms.ModelForm): email = forms.EmailField(required=True) groups = forms.ChoiceField(required=False) class Meta: model = User fields = ('email', 'first_name', 'last_name', 'is_active', 'groups') def __init__(self, *args, **kwargs): super(UserUpdateForm, self).__init__(*args, **kwargs) choices = [[obj.pk, obj.name] for obj in Group.objects.all()] choices.insert(0, ['', '--------']) self.fields["groups"].choices = choices # My goal here is to call the initial value for the groups field which # is ManyToManyField -
Django get data from get method and pass to post method
I am trying to pass the data from get method to post method, so I can update my database data through a form. In below code, specifically I tried to use a class level variable "saved_objectID" to pass the editObjectID from get method to post method. But I always get blank values/no value. Is there a way to implement this? Thank you in advance for the help class EditDataView(ListView): model =TemporaryModel form_class = TemporaryForm template_name = 'frontend/editData.html' dict = { "EditData":"Edit Data Below"} saved_objectID = '' def get(self, request, *args, **kwargs): editObjectId = request.GET.get('editObjectId') editObjects = TemporaryModel.objects.get(pk=editObjectId) saved_objectID = editObjectId form = TemporaryForm(instance=editObjects) return render(request, 'frontend/editData.html', {'form': form,"dict":dict}) def post(self, request, *args, **kwargs): form = TemporaryForm(request.POST, instance=TemporaryModel.objects.get(pk=self.saved_objectID)) if form.is_valid(): form.save() return render(request, 'frontend/editData.html', {'form': form,"dict":dict}) -
Django - a migrations was detected, but saying no migrations to apply
I added a new field slug = models.SlugField(unique=True, null=True) to a model. A new migration was successfully detected. (venv) 192-168-1-201:shop jinx$ python manage.py makemigrations book Migrations for 'book': book/migrations/0014_book_slug.py - Add field slug to book But when I tried to apply the migration, it said: (venv) 192-168-1-201:shop jinx$ python manage.py migrate book Operations to perform: Apply all migrations: book Running migrations: No migrations to apply. Clearly, the table is not updating. And --fake doesn't help as well. (venv) 192-168-1-201:shop jinx$ python manage.py migrate --fake book Operations to perform: Apply all migrations: book Running migrations: No migrations to apply. I have been facing this problem for serval times, but each time I fixed it somehow. Now I want to know what causes this issue? -
Django: SQL way (i.e using annotation, aggregate, subquery, when, case, window etc) vs python way
Sql way means using using annotation, aggregate, subquery, when, case, window etc. i.e get all the extra calculation columns from sql Till now if I want to get some addition information from the data of each row like calculate something etc, I used to get the table in queryset and loop over each object and then store the desired result in a list of dicts and pass it to the template. Ofcourse i was using prefetch so that i can avoid N+1 queries. But since django 1.11 we can do the same thing in more expressive way using sql (i.e using annotation, aggregate, subquery, when, case, window etc) and no python. Disadvantage: One disadvantage i found using sql way rather than python way is debugging. I have to do complex calculations on the data of each queryset object. So that i can check step by step. If i do it in the sql way i can only see the final result but not be able to track the steps. Advantage: I didnt tried, but heard from The Dramatic Benefits of Django Subqueries and Annotations that its quite fast. Presently most of my sql takes less than 100 ms and most … -
Django Model Versioning with 2 copies of data
We have a fully functional django app based on the django-rest-framework. The initial data required for this app was supplied to us in Excel and was imported using django commands. Since then it has been modified and used by the end-user. We now have a new requirement to supply an integration API which will be used to progressively send updates to us from the Master Data Centre. This data needs to be stored separately from the current app data till a point in time when the user chooses to update his copy of the data from the master data or decline it. So my question is what would be the best possible efficient way to implement this? Currently I have come up with a simple POST API that will accept flat data structures for every model and store it separately. For example class AppCustomer(models.Model): #initial App Model in use name = models.CharField(max_length=10) title = models.CharField(max_lentgh=10) .... .... class APICustomer(models.Model): #new copy of AppCustomer Model name = models.CharField(max_length=10) title = models.CharField(max_lentgh=10) .... .... class APICustomerUpdateView(views.APIView): permission_classes = (IsAuthenticated,) parser_classes = (CustomerJSONParser,) def post(self, request, format=None): logger.info("Request Data %s", request.data) customer, _ = models.APICustomer.objects.get_or_create(name=request.data.get('name')) customer.title = request.data.get('title') ..... ..... customer.save() return Response(status=204) … -
Adding foreign key data to serializer?
I'm trying to use the Django Rest-Framework to produce some JSON that shows all the user's posts, but also shows the images for that post. Image is a foreign key to Post. Here are the models: models.py class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField(max_length=200) class Image(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) img = models.CharField(max_length=120) views_count = models.IntegerField(default=0) views.py class GetPosts(ListAPIView): serializer_class = PostSerializer def get_queryset(self): requested_user = get_requested_user(self) return Post.objects.filter(user=requested_user).order_by('-created_at') def get_requested_user(self): filter_kwargs = {'username': self.kwargs['username']} return get_object_or_404(User.objects.all(), **filter_kwargs) serializers.py class PostSerializer(serializers.ModelSerializer): image_img = serializers.RelatedField(source='Image', read_only=True) class Meta: model = Post fields = ('status', 'image_img ') In the serializers.py, I'd like to show all of the fields for Image (img, views_count) What I get with my current code is this: { "count": 1, "next": null, "previous": null, "results": [ { "status": "I am number 1" } ] } Which contains the user's posts, but not the user's posts and each post's images. Note: Query url looks like this: /api/posts/user/ -
Can I have two edit profile forms in django One is the main edit Profile form and 1 for just 2 fields
I have a profile model which has too many fields. Two of the fields are lat and lon I use the django form to edit all the fields below class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=100) state = models.CharField(max_length=100, blank=True, null=True) country = models.CharField(max_length=100) street_address = models.CharField(max_length=500, null=True, blank=True) zip_code = models.CharField(max_length=10, default='') phone_number = models.CharField(max_length=17, blank=True, null=True) age = models.DateField(blank=True, null=True) member_since = models.DateTimeField(auto_now_add=True) profile_image = models.ImageField(default='', blank=True, null=True) bio = models.TextField(default='', blank=True) bio_images = models.ImageField(default='', blank=True, null=True) activities_i_do = models.TextField(default='', blank=True, null=True) activities_i_love = models.TextField(default='', blank=True, null=True) is_verified = models.BooleanField(default=False) lat = models.FloatField(blank=True, null=True) lon = models.FloatField(blank=True, null=True) Below is the view to edit the attrubutes @login_required def edit_profile(request): if request.method == 'POST': user_form = UserEditForm(data=request.POST or None, instance=request.user) profile_form = ProfileEditForm(data=request.POST or None, instance=request.user.profile, files=request.FILES) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() return redirect('accounts:profile', username=request.user.username) else: user_form = UserEditForm(instance=request.user) profile_form = ProfileEditForm(instance=request.user.profile) context = {'user_form': user_form, 'profile_form': profile_form} return render(request, 'accounts/profile_edit.html', context) Now the question is Can I use another form to just edit the lat lon fields of the above model example something like below <form method="post" action="{{ ??????????? }}"> <input id="jsLat" type="text" placeholder="latittude" > <input id="jsLon" type="text" placeholder="longitude"> <button type="submit" id="submit">Submit</button> </form> I have … -
HeaderParseError in django email form
When testing my email app, I get the following error: HeaderParseError at /contact/ Expected 'atom' or 'quoted-string' but found '@' I've been able to track the error down to the multiple variables containing just a '@', including 'recipients', but am having a hard time finding a fix. I suspect it comes from the sanitized data, but even using just the POST object returned the same error. Thanks in advance! Here's the code: def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] from_email = form.cleaned_data['email'] recipient_list = list(str('xxxxx@gmail.com')) # recipient_list.append(from_email) ''' Begin reCAPTCHA validation ''' recaptcha_response = request.POST.get('g-recaptcha-response') data = { 'secret': settings.RECAPTCHA_PRIVATE_KEY, 'response': recaptcha_response } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) result = r.json() ''' End reCAPTCHA validation ''' email = EmailMessage(subject, message, str(from_email), recipient_list) email.send() if result['success']: messages.success(request, 'New comment added with success!') else: messages.error(request, 'Invalid reCAPTCHA. Please try again.') return HttpResponseRedirect('/contact') else: data = form.cleaned_data form = ContactForm(data, initial=data) messages.error(request, 'Please correct the errors on the form below.') else: form = ContactForm() return render(request, 'contact.html', {'form': form}) -
Django connection mysql error, showing the target computer actively refused
Problem Description: I am using django to connect to mysql. After clicking and executing, I am telling me that the error is that the target computer actively refuses. I would like to ask what caused this. I checked a lot of information. Basically, the service is not open, but My current mysql on my local computer is turned on. Error message: Unhandled exception in thread started by .wrapper at 0x000001C834726840> Traceback (most recent call last): File "E:\python\env\webnev\lib\site-packages\pymysql\connections.py", line 582, in connect **kwargs) File "e:\python\pytho3.6\Lib\socket.py", line 724, in create_connection raise err File "e:\python\pytho3.6\Lib\socket.py", line 713, in create_connection sock.connect(sa) ConnectionRefusedError: [WinError 10061] Unable to connect because the target computer actively refused. During handling of the above exception, another exception occurred: I am not sure if it is related to the version of the module, but as long as I remove the code to add the linked database, this project will run normally. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test', 'USER': 'root', 'PASSWORD': '123456', 'HOST': '127.0.0.1', 'POST': '3307', }, } enter image description here -
Pymongo error: "Unrecognized pipeline stage name: '$count'" coming from djongo - MongoDB 4.0
I have a Django (2.1) application that connects to MongoDB (4.0.2) using djongo (1.2.29) running on a Ubuntu 16.04 LTS. It sits on a virtualenv configured for Python 3.6.6 with the following packages: biopython==1.72 dataclasses==0.6 Django==2.1 djongo==1.2.29 mod-wsgi==4.6.4 numpy==1.15.1 pymongo==3.7.1 pytz==2018.5 sqlparse==0.2.4 I'm getting an error when the application starts, and I've been able to reproduce it by doing: (venv) giovanni@triptofano:~/inovatoxin$ python manage.py shell Python 3.6.6 (default, Jun 28 2018, 04:42:43) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from Proteins.models import Protein >>> Protein.objects.get(id='2') <Protein: Calpain clp-1> >>> Protein.objects.count() Traceback (most recent call last): File "/home/giovanni/inovatoxin/venv/lib/python3.6/site- packages/djongo/sql2mongo/query.py", line 725, in __iter__ yield from iter(self._query) File "/home/giovanni/inovatoxin/venv/lib/python3.6/site- packages/djongo/sql2mongo/query.py", line 159, in __iter__ self._cursor = self._get_cursor() File "/home/giovanni/inovatoxin/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 258, in _get_cursor cur = self.db_ref[self.left_table].aggregate(pipeline) File "/home/giovanni/inovatoxin/venv/lib/python3.6/site-packages/pymongo/collection.py", line 2397, in aggregate **kwargs) File "/home/giovanni/inovatoxin/venv/lib/python3.6/site-packages/pymongo/collection.py", line 2304, in _aggregate client=self.__database.client) File "/home/giovanni/inovatoxin/venv/lib/python3.6/site- packages/pymongo/pool.py", line 579, in command unacknowledged=unacknowledged) File "/home/giovanni/inovatoxin/venv/lib/python3.6/site- packages/pymongo/network.py", line 150, in command parse_write_concern_error=parse_write_concern_error) File "/home/giovanni/inovatoxin/venv/lib/python3.6/site-packages/pymongo/helpers.py", line 155, in _check_command_response raise OperationFailure(msg % errmsg, code, response) pymongo.errors.OperationFailure: Unrecognized pipeline stage name: '$count' The above exception was the direct cause of the following exception: ... loads of error messages ... File "/home/giovanni/inovatoxin/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line … -
How to create Tests in Django with login and Group Permissions?
I have a problem, I need create tests my Django Project for my forms and my views. I have my groups created in django-admin, and I have a json file exported with groups permissions. In my tests, I want a valid login, and after that, test if the user logged (created in test setUp) has permission for access that view. How to create a user, login user, and add user in some group loaded by json file with group informations? I searched by this, and dont founded some thing with really help me. Basic, the above things, I think put in the def setUp(self):, and in test I will compare with login is valid, and then compare with AssertEqual(response.status_code, 200) or AssertEqual(response.status_code, 403) With someone can help me, I going to thanks very much. -
Django model Slug field unique_for_month not working
I'm using django v. 1.11.3. Here is my model field declaraion. class Post(models.Model): slug = models.SlugField(max_length=80, unique_for_month='pub_date') pub_date = models.DateField('date published', auto_now_add=True) ... def get_absolute_url(self): return reverse('blog_post_detail', kwargs={'year': self.pub_date.year, 'month': self.pub_date.month, 'slug': self.slug,}) I use ModelForms to create the user forms as follows. class PostForm(forms.ModelForm): class Meta: model = Post fields = '__all__' def clean_slug(self): return self.cleaned_data['slug'].lower() However, when I try to enter duplicated slug and redirect to the newly created post it is created in the db and get method call fails due to multiple object return. Here is the URL config and FBV for the detail page. url(r'^(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<slug>[\w\-]+)/$', post_detail, name='blog_post_detail'), def post_detail(request, year, month, slug): post = get_object_or_404(Post, pub_date__year=year, pub_date__month=month, slug=slug) return render(request, 'blog/post_detail.html', {'post': post}) Finally, this is the error show in debug data. MultipleObjectsReturned at /blog/2018/8/python-3-programming/ get() returned more than one Post -- it returned 2! ~/workspace/django_unleashed/src/blog/views.py in post_detail post = get_object_or_404(Post, pub_date__year=year, pub_date__month=month, slug=slug) I checked with the db and I see two entries for the same slug in the same month. What is wrong here? -
django tags spanning multiple lines
I was following a django tutorial and I noticed the string text kept having \ in it. I thought that simulated \n in django... Then for some reason tags wouldn't render correctly. Context: sending an email through sendgrid from a generated template For example: {% load i18n %}{% autoescape off %} {% trans "Hi" %} {{ user.get_username }}, {% trans "We've received a request to reset your password. If you didn't make\ this request, you can safely ignore this email. Otherwise, click the button\ below to reset your password." %} {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid \ token=token %} {% endblock reset_link %} {% endautoescape %} got this in the email: {% trans "We've received a request to reset your password. If you didn't make\ this request, you can safely ignore this email. Otherwise, click the button\ below to reset your password." %} http://127.0.0.1:8000{% url 'password_reset_confirm' uidb64=uid\ token=token %} but this rendered the email correctly: {% load i18n %}{% autoescape off %} {% trans "Hi" %} {{ user.get_username }}, {% trans "We've received a request to reset your password. If you didn't make this request, you can safely ignore this email. Otherwise, click the … -
Is there any recommend (or fast) python web server framework
I currently building an online judge system. I use django and django-rest to build to restful api backend, and use it to handle submission CRUD something like that. After the django received a submission, it will pass it to Celery, and in the Celery task, it will make a request to my judge server. And my problem is which python web framework should I choose to implement this judge server. <client> → <django rest> → <Celery> → <!!! judge server !!!> → <judger sandbox> Because I have a sandbox library which can be import in python like this import _judger _judger.run( bash command or something like that here ) And it will be multiprocess inside each requeste, because each submission has multiple test case to execute. And I need a reliable and fast (less overhead on networking) framework to build a server to wrap the sandbox, is there any good suggestion? Thanks a lot. -
Django - FileNotFoundError Error while running collectstatic with Bower
I tried to run collectstatic by pointing to development settings. python3 manage.py collectstatic --settings=socialmkt.settings.dev Now collectstatic does not find the bower_components folder because "static" was inserted in the path. FileNotFoundError: [Errno 2] No such file or directory: '/home/user/Projects/socialmkt/socialmkt/settings/static_dev/bower_components' How do I remove this "static" from the path for it to find the folder? /home/user/Projects/socialmkt/socialmkt/static_dev/bower_components Thanks! -
MultipleChoiceField django python, impossible display datas in the template
I have big problem, I use MultipleChoic Field into django for "input multiselect", a user at the possibility of make many choices via the "input select multiple" I explain to you : I use this Package : https://pypi.org/project/django-multiselectfield/ this is my model : class Profil(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,) skill = MultiSelectField(max_length=500, null=True, blank=True, choices=Skillz) board = MultiSelectField(max_length=500, null=True, blank=True, choices=Boardz) this is my form : class ProfilForm(forms.ModelForm): skill = forms.MultipleChoiceField(required=False, widget=forms.SelectMultiple, choices=Skillz) board = forms.MultipleChoiceField(required=False, widget=forms.SelectMultiple, choices=Boardz) this is my datas of the choices (used in models Profil and form ProfilForm): Boardz = ( ('Reddit', 'reddit.com'), ('Discord', 'discord.com'), ('Twitter', 'twitter.com'), ) Skillz = ( ('Python', 'PythonDjango'), ('Rust', 'RustRocket'), ('Ruby', 'RubyOnRails'), ) Now the concern problem is views.py and my template.html <!-- this is what I want with my datas --> <select multiple class="form-control" id="id_board"> <option>reddit.com</option> <option>discord.com</option> <option>twitter.com</option> </select> <select multiple class="form-control" id="id_skillz"> <option>PythonDjango</option> <option>RustRocket</option> <option>RubyOnRails</option> </select> <input type="submit" value="Save"> Into the views.py (which is surely wrong) : def GetDatasForRegisterForm(request): form = ProfilForm() return render_response(request, "registration/register.html",{'form': form}) template.html : I'm totally lost for display my data choices in select multiple for the user, please guys, how make ? -
SuspiciousOperation when loading image in django
I'm deploying a web application in django and there is one page that loads some images from my static files that is returning the following error: SuspiciousOperation at /wallet Attempted access to '/coins/' denied. I've been reading that it is because the media file but I don't understand it because all the other static files load correctly. I'm using s3 from aws. This is my s3 configuration file: import datetime import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) AWS_ACCESS_KEY_ID = "whatever" AWS_SECRET_ACCESS_KEY = "whatever" AWS_STORAGE_BUCKET_NAME = 'xxx' AWS_S3_CUSTOM_DOMAIN = '%s.s3.us-east-2.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, '../static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' MEDIA_URL = '' MEDIA_ROOT = '' and the whole error in debug mode is the following one: Environment: Request Method: GET Request URL: http://ip/wallet Django Version: 2.0.5 Python Version: 3.6.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'profiles', 'portfolios', 'django_extensions', 'rest_framework', 'corsheaders', 'storages'] 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', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware'] Template error: In template /home/ubuntu/chimpy/templates/base.html, error at line 54 Attempted access to '/coins/' denied. 44 : <div class="sidebar-user"> 45 : {% load static %} 46 : {# <div class="sbuser-pic"><a href="/user"><img src="{% static … -
How do I raise PermissionDenied Redirect to another page using CBV?
I have a model with my permissions, and in my view using CBV(generic.CreateView) or (generic.DetailView), if a user logged has permissions, he can access the view, if hasn't access, the page Forbidden 403 shows. But, if a user dont have permission for that view, I want raise exception PermissionDenied, and redirect to a specific page for this error. My view: class AddJob(LoginRequiredMixin, PermissionRequiredMixin, generic.CreateView) permission required = 'can_create_job' model = Job fields = ['name', 'description', 'salary'] success_url = reversy_lazy('job_list) context_object_name = 'object_name' Can anyone help me? Thanks