Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django server 403 (CSRF token missing or incorrect)
I have a basic Django server with an python command line client for posting to this service. I have a login function and a post function. Even though the cookie for CSRF is being set from the login function the server is saying forbidden when I try to access the post_product endpoint after logging in. I've been troubleshooting this for days and haven't had any luck. /api/login/ function: from django.views.decorators.csrf import csrf_exempt from django.contrib.auth import authenticate, login, logout from django.http import HttpResponse @csrf_exempt def handle_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: if user.is_active: login(request, user) if user.is_authenticated: return HttpResponse(author.name + ' is logged in, Welcome!', status=201, content_type='text/plain') return HttpResponse(data) else: return HttpResponse('disabled account', status=400, content_type='text/plain') else: return HttpResponse('invalid login', status=400, content_type='text/plain') else: return HttpResponse('request method invalid ' + request.method, status=400, content_type='text/plain') /api/postproduct/ function: def post_story(request): if request.method == 'POST' and request.user.is_authenticated: # Pull product details from request. # Validate product details. # Create model and save. Python terminal client def run(): url ='http://127.0.0.1:8000' # For debugging logged_in = false with requests.session() as session: while True: command = input("""Enter one of the following commands: login post \n""") … -
Image upload to the rich text field from vue to amazon s3 via django REST framework
I'm experimenting Vue with Django and creating a simple blog. But I'm stuck about usage of uploading images vie CKEditor from vue. uploading images to S3 is working within django-admin. But I couldn't figure out how can I serialize RichTextUploadField and make it work with vue. My model is; class Challenge(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) title = models.CharField(max_length = 240) content = RichTextUploadingField(verbose_name='Code',null=True,blank=True) slug = models.SlugField(max_length=255, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="challenges") image = models.ImageField(upload_to=upload_image_to, editable=True, null=True, blank=True) def __str__(self): return self.title serializers.py; author = serializers.StringRelatedField(read_only=True) created_at = serializers.SerializerMethodField() slug = serializers.SlugField(read_only=True) moments_count = serializers.SerializerMethodField() user_has_momented = serializers.SerializerMethodField() class Meta: model = Challenge exclude = ["updated_at"] def get_created_at(self, instance): return instance.created_at.strftime("%B %d %Y") def get_moments_count(self, instance): return instance.moments.count() def get_user_has_momented(self, instance): request = self.context.get("request") return instance.moments.filter(author=request.user).exists() views.py queryset = Challenge.objects.all().order_by("-created_at") lookup_field = "slug" serializer_class = ChallengeSerializer permission_classes = [IsAuthenticated, IsAuthorOrReadOnly] def perform_create(self, serializer): serializer.save(author=self.request.user) urls.py router.register(r"challenges", cv.ChallengeViewSet) urlpatterns = [ path("", include(router.urls)), path("challenges/<slug:slug>/moments/", cv.ChallengeMomentListAPIView.as_view(), name="answer-list"), path("challenges/<slug:slug>/moment/", cv.MomentCreateAPIView.as_view(), name="moment-create"), path("moments/<int:pk>/", cv.MomentRUDAPIView.as_view(), name="moment-detail"), path("moments/<int:pk>/like/", cv.MomentLikeAPIView.as_view(), name="moment-like"), path('ckeditor/', include('ckeditor_uploader.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) frontend vue.js; return this.loader.file .then( uploadedFile => { return new Promise( ( resolve, reject ) => { const data = new FormData(); data.append( 'upload', uploadedFile … -
Django: overriding predefined method save() using request data
I'm trying to override the save() method on a Django model so that some fields are automatically filled out. This is the model: class Blog(models.Model): title = models.CharField(max_length=200) user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) url = models.CharField(max_length=1500, null=True, blank=True) ip = models.CharField(max_length=200, null=True, blank=True) content = models.TextField(null=True, blank=True) def save(self, * args, ** kwargs): if request.user: self.user = request.user self.url = request.path self.ip = socket.gethostbyname(socket.gethostname()) super().save( * args, ** kwargs) What I'm trying to do is to automatically set the user, URL, and IP fields when I save a record, without having to do that in the view. However, in the current format the request is not "passed" to the model, and I'm not sure how I am supposed to do that. This is what I currently get: name 'request' is not defined -
Fastai attribute error 'PixelShuffle_ICNR' object has no attribute 'do_blur'
I have image processing code using fastai and pytorch embedded in a django view the code is working properly on the production server ( ubuntu machine ) but on my local windows machine it returns this error, I want this code to work on my machine to run the necessary tests so how can I do this? and what's the cause of this error? -
Is it possible to bulk_update a many-to-many relationship in django 2.2?
I have these two simple models: class school(models.Model): name = models.CharField(max_length=128) class teacher(models.Model): schools = models.ManyToManyField(School) user = models.OneToOneField(...) In a view, let's say I wan't to add a school to multiple teachers at the same time. I could do something like this: for teacher in teachers: teacher.add(school) teacher.save() This works, but it is making a lot of queries. Is there a better way to do something like this? I am using django 2.2 (so maybe I could use bulk_update?). -
how to link user of one model class to another user of a foreign class in django views
I've created an app where by a user can create a job and the other user can apply to that specific job, so far creating a job is not a problem but for the other user to apply for that specific job it is quite hard for a beginner like me. I've created tried this way down here but failed and got errors, though for me i think the problem is with my poor views models.py class Application(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='applied_jobs', null=True, on_delete=models.SET_NULL) job = models.ForeignKey(Job, related_name='applications', on_delete=models.CASCADE) career_briefing = models.CharField(max_length=250, null=True) form.py class ApplicationForm(forms.ModelForm): class Meta: model = Application field = ['career_briefing',] views.py class ApplicationCreateView(CreateView): form_class = ApplicationForm template_name = 'jobs/application_form.html' message = _("succesfuly created") def post(self, request, *args, **kwargs): form = ApplicationForm(self.request.POST) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): self.object = self.get_object() form.instance.user = self.request.user form.instance.job = self.kwargs["job_id"] apply = form.save(commit=False): apply.user = self.request.user apply.job = self.object return super().form_valid(form) def get_success_url(self): messages.success(self.request, self.message) return reverse( "jobs:detail", kwargs={"pk": self.kwargs["job_id"]}) urls.py urlpatterns = [ .... url(r'^details/(?P<pk>\d+)/$', JobDetailView.as_view(), name='detail'), url(r'^details/apply/(?P<pk>\d+)/$', ApplicationCreateView.as_view(), name='apply'), .... ] templates.py .... <div> <a class="btn btn-dark" href="{% url 'jobs:apply' job.id %}">{% trans 'apply' %}</a> </div> .... i expect that once the user clicks … -
Uploading a CSV or Excel file along with json data through React html form to Django
I want to submit a form to upload either a csv file or an excel file, and provide additional information provided in the form, e.g. text. For defining the form and sending the request I use React Bootstrap with axios, and for the api I'm using Django 2.2 with rest-framework. request.FILES is always an empty dict, even if I try setting the Content-Type header to multipart/form-data, and then additionally nothing is found in the post data of the request, and printing request.data.get('information') below shows None in the Django log. Please help, any support will be greatly appreciated. See below for code snippets. Form definition in render(): <form onSubmit={this.handleSubmit}> <FormGroup> <Form.Label>Upload file</Form.Label> <Form.Control type="file" onChange={this.handleFile}></Form.Control> </FormGroup> <Button block bssize="large" disabled={!this.validateForm()} type="submit"> Submit </Button> </form> Handling file change: handleFile = event => { event.preventDefault(); const fileToUpload = event.target.files[0] this.setState({ fileToUpload: fileToUpload }) } Sending the request: const payload = { file: this.state.fileToUpload, information: "somedata" } const contentType = "multipart/form-data" let accessToken = token var headers = {"Authorization" : `Bearer ${accessToken}`} headers['Content-Type'] = contentType const response = await axios({ method: "post", data: payload, url: url, headers: headers }); Django endpoint definition: class RegisterData(views.APIView): parser_classes = (parsers.JSONParser, parsers.MultiPartParser) def post(self, request): for file in … -
How to highlight code in an article using RichTextField
I have a RichTextField in the admin panel and I want to add the ability to highlight my code there as in this picture my models.py from djrichtextfield.models import RichTextField class DjangoModel(models.Model): titleDjango = models.CharField(max_length=400, verbose_name='Названия') textDjango = RichTextField() datesDjango = models.DateTimeField(auto_now=True) viewDjango = models.IntegerField(default=0) imgDjango = models.ImageField(upload_to='DjangoLessonsImagae', default="default_value",verbose_name='Каритинка 260х180') django_like = models.IntegerField(default=0) django_dislike = models.IntegerField(default=0) -
How to do complex annotations( and how to think about it!)
I am trying to annotate my Product objects with a total_item_sold field. and I can't seem to get my head around it. So, any explanation as to how I should do this will be greatly appreciated. class Order(models.Model): ... class OrderPayment(models.Model): order = models.ForeignKey(Order) successful = models.BooleanField(default=False) ... class OrderListItem(models.Model): order = models.ForeignKey(Order) list_item = models.ForeignKey(ListItem) ... class Product(models.Model): price = models.IntegerField() ... class List(models.Model): products = models.ManyToManyField(Product, related_name="lists", through="ListItem") .... class ListItem(models.Model): llist = models.ForeignKey(List) product = models.ForeignKey(Product) ... so for each product, I want to find all OrderPayments that have been "succesful" and have that product in them( which is resolved by finding the OrderListItems then ListItems and then products), and then annotate the product with total_items_sold of that product. -
Django REST Framework requires hashed password to login
Django requires me to send a hashed password to get my JWT token. When I send the following request via postman I get a "CustomUser matching query does not exist" error. { "user": { "email": "myuser", "password": "mypassword" } } I can, however, run the code with the hashed password (after looking it up from the admin) and it returns the correct value. How do I send unhashed passwords or hash the passwords before I send them? I am using a custom user model that substitutes email for username. I've tried pointing my code to the header using request.META.get("username") and request.META.get("password") but I receive a 'field required' error. I've also tried to figure out how to hash the password on the app before sending it to my API, but I have failed to find a method that works. I have my view below for handling the request. @csrf_exempt @api_view(["POST"]) @permission_classes((AllowAny,)) def login(request): username = request.data.get('username') password = request.data.get('password') if username is None or password is None: return Response({'error': 'Please provide your username and password'}, status=HTTP_400_BAD_REQUEST) user = authenticate(email=username, password=password) if not user: return Response({'error': 'Invalid Credentials'},status=HTTP_404_NOT_FOUND) token, _ = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=HTTP_200_OK) I expected to get a JWT … -
How to automatically load default pictures when creating a new user in django
Whenever I create a new user and try to log-in that user my default picture wasn't loading and there's no error on my console, but when I click my view profile(profile.html) that's when my default picture will show up on my sidebar. https://ibb.co/bR79XpJ this is the url of my screenshot. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete =models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') update = models.DateTimeField(default = timezone.now) def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile,self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) signals.py @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender = User) def save_profile(sender, instance, **kwargs): instance.profile.save() base.html # My sidebar <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> profile.html # my view profile <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> I expect to automatically show my default picture on my sidebar when I create a new user. -
Django - Adding extra data in admin change_form request
I'm Customizing Django admin , now i have to add some extra fields which are created by javascript code in fieldset.html template . the reason i wrote these code in fieldset.html is that the inputs will be in main form , so they will be in post request data . Sample of fieldset.html: {% for line in fieldset %} {% if field.field.name == 'discount' %} <input type="number" name="product_code"> . . . <script> this script will create more input fields </script> {% endif %} {% endfor %} But in ModelAdmin.saveModel when i check request data , my input data does not exist. class FactorAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): print('request data', request.POST) super(FactorAdmin, self).save_model(request, obj, form, change) is there any other way to include my dynamic html in Django ChangeForm template ? -
how to distinguish authentication status in frontend(vue)
When we use django template to build a website traditionally,django will handle authentication Automatically, but now I trying to build a Front-and-rear-separation website with django-restframework and vue.js, I don't know how frontend distinguish authentication status. I understand how django authentication works, It set sessionid to cookie, when we send request with cookie django server will know is this request is authenticated, but I think frontend should not be able to access cookie, so I would like to set CSRF_COOKIE_HTTPONLY=Truein django, I can sitll send request with cookie the authentication in django server is still work but how frontend tell the authentication status. what I expect is just like normal website, login or not is showing in the top righthand corner of the page. if login, my user name will be display. if not, a link to login page -
Python request.urlretrieve() returns status 500
I'm using Django with Python 3.5 and I'm trying to download a file from a URL, and giving the filename and path where the file should be downloaded. I am using urlretrieve for this operation, but every time am getting 500 error. But when tested in Postman, the API is working fine. Can anyone help me where I'm going wrong? headers = {'content-type': 'application/json'} posts= { "filepath":filepath } password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm() url = 'http://'+API_dns+':'+API_pod+'/api/v1/download-file?filepath='+filepath+'&tid='+tid_selected+'&username='+str(request.user)+'&download_zip_file='+zip_file password_mgr.add_password(None, url, 'admin', 'admin') handler = urllib.request.HTTPBasicAuthHandler(password_mgr) opener = urllib.request.build_opener(handler) urllib.request.install_opener(opener) urllib.request.urlretrieve(url, os.path.join(settings.STATIC_ROOT, "to_download", zip_file)) path = '/static/to_download/'+zip_file context = {'url':path, 'status':200, 'filename':zip_file} return JsonResponse(context) -
Downloading a FileField with a View
I have a table which presents order information - attached to each order is a file. This file's file path displays as a link in the table already, but I am unable to download by clicking it. I would like to be able to click this link and have the proper .docx download. I am referencing: how to download a filefield file in django view but I really don't understand how this solution is working. Is no URL needed? How does the view know which file to pick? I opened a previous question and got marked as a duplicate and pointed to this link, but I really don't understand the solution that was given here. Do I need to somehow pass the pk of the order or something? Any help would be greatly appreciated. Below is my code. models.py class Orders(models.Model): ... order_file = models.FileField(upload_to='web_unit', null=True, blank=True) ... def __str__(self): return self.reference index.html <div class="table-responsive"> <table id="main_table" class="table table-striped table-bordered" cellspacing="0" style="width="100%"> <thead> <tr> .... </thead> <tbody> {% for order in orders %} <tr> <td> <!-- Update book buttons --> <button type="button" class="update-book btn btn-sm btn-primary" style="color: #FFCF8B; border-color: #FFCF8B; background-color: #FFF;" data-id="{% url 'order_update' order.pk %}"> <span class="fa fa-pencil"></span> … -
Django CSRF Verification Failed when using WSGIDaemonProcess with multiple processes
My Django version is 2.2 and I've configured httpd.conf to start a process pool like so: WSGIDaemonProcess my_app processes=6 threads=12 display-name=%{GROUP} home=/tmp maximum-requests=1000 inactivity-timeout=1800 request-timeout=500 python-path=${MY_ENV_VAR} With this setup, I would get Forbidden 403 errors with CSRF verification failed message when I do a POST request. If I keep refreshing the page, when I get lucky, my POST request would succeed. Now I'm guessing this is because the request might have landed onto the Django process that has the "right cache". To test the above theory, if I change the httpd.conf to have only 1 pool process like below, I do not get the 403 error. WSGIDaemonProcess my_app processes=1 threads=12 display-name=%{GROUP} home=/tmp maximum-requests=1000 inactivity-timeout=1800 request-timeout=500 python-path=${MY_ENV_VAR} I have followed the CSRF specific instructions on Django documentation and tried both scenarios when CSRF_USE_SESSIONS is set to True or False What is the recommended approach to configuring Django if I intend to spin up a pool for wsgi processes each of which would run my Django app? -
I am trying to implement the django-simple-referral
I am trying to implement the django-simple-referral. I have written all the necessary required codes according to the documentation provided by django-simple-referral. But after registration is done I am getting the error "'Settings' object has no attribute 'PINAX_REFERRALS_CODE_GENERATOR_CALLBACK'". Please help me with this issue -
Python pip install mysqlclient
So I downloaded Python 32 bits 1st, then I did python -m pip install mysqlclient.I needed Visual C++ 2015, but I had them cuz my text editors is VSCode.I uninstalled VSCode, installed Visual Studio Build Tools, and I am getting this errors whenever I do python -m pip install mysqlclient.One, cl.exe wasnt added to my path, so I did, but it still says error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\bin\\cl.exe' failed with exit status 2 so I downloaded the wheel package for windows, as some other stackoverflow answer said.Whenever I run it, I get I tried downloading Python 64 bits downloading the wheels, adding cl.exe to path. Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/4d/38/c5f8bac9c50f3042c8f05615f84206f77f03db79781db841898fde1bb284/mysqlclient-1.4.4.tar.gz Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'C:\Program Files (x86)\Python\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Patrik\\AppData\\Local\\Temp\\pip-install-0vmm7fdx\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\Patrik\\AppData\\Local\\Temp\\pip-install-0vmm7fdx\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\Patrik\AppData\Local\Temp\pip-wheel-o3ba369p' --python-tag cp37 cwd: C:\Users\Patrik\AppData\Local\Temp\pip-install-0vmm7fdx\mysqlclient\ Complete output (30 lines): running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.7 creating build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.7\MySQLdb … -
Adding multiple instances of a ForeignKey
I have a simple Person class and a Club class that should contain lots of Person instances: from django.db import models class Person(models.Model): name = models.CharField(max_length=200) class Club(models.Model): name = models.CharField(max_length=200) persons = models.ForeignKey(Person, on_delete=models.CASCADE) How do I add more than one Person to the persons attribute? I want to build a database and then save it as follows: club = Club(name='some_club') club.person.add(Person(name='Alex')) club.person.add(Person(name='John')) club.save() # etc. ... -
unable to specify custom Django Model from nested app as AUTH_USER_MODEL
I am unable to specify a custom AUTH_USER_MODEL if that model is in a nested application. Here is some project structure: ├── project │ ├── settings.py │ ├── my_parent_app │ │ ├── __init__.py │ │ ├── apps.py │ │ └── my_child_app │ │ ├── __init__.py │ │ ├── apps.py │ │ └── models.py and here is some code: project/my_parent_app/my_child_app/models.py: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): is_a_nice_user = models.BooleanField(default=False) project/settings.py: INSTALLED_APPS = [ 'my_parent_app', 'my_parent_app.my_child_app', ] AUTH_USER_MODEL = 'my_parent_app.my_child_app.User' When I try to do anything, I get this error: ValueError: Invalid model reference 'my_parent_app.my_child_app.User'. String model references must be of the form 'app_label.ModelName'. This is a very similar to this question. But how can I solve this without resorting to making my_child_app a separate top-level app? -
How to serve static files in Django application running inside Kubernetes
I have a small application built in Django. it serves as a frontend and it's being installed in one of out K8S clusters. I'm using helm to deploy the charts and I fail to serve the static files of Django correctly. Iv'e searched in multiple locations, but I ended up with inability to find one that will fix my problem. That's my ingress file: apiVersion: extensions/v1beta1 kind: Ingress metadata: name: orion-toolbelt namespace: {{ .Values.global.namespace }} annotations: # ingress.kubernetes.io/secure-backends: "false" # nginx.ingress.kubernetes.io/secure-backends: "false" ingress.kubernetes.io/rewrite-target: / nginx.ingress.kubernetes.io/rewrite-target: / ingress.kubernetes.io/force-ssl-redirect: "false" nginx.ingress.kubernetes.io/force-ssl-redirect: "false" ingress.kubernetes.io/ssl-redirect: "false" nginx.ingress.kubernetes.io/ssl-redirect: "false" ingress.kubernetes.io/ingress.allow-http: "true" nginx.ingress.kubernetes.io/ingress.allow-http: "true" nginx.ingress.kubernetes.io/proxy-body-size: 500m spec: rules: - http: paths: - path: /orion-toolbelt backend: serviceName: orion-toolbelt servicePort: {{ .Values.service.port }} the static file location in django is kept default e.g. STATIC_URL = "/static" the user ended up with inability to access the static files that way.. what should I do next? -
How do I close my camera frame after reading/deciding a qr code with pyzbar?
I've been working on this QR code scanner and so far I've gotten everything to work out; The camera works and the frame shows up. pyzbar decodes the QR codes I show it. regex slices the string I need within the decoded data. Text of the data is shown within the frame. Models are updated accordingly. and lastly I update my list for the time the QR was detected The Problem is I actually want the frame to close when a single QR code is detected, decoded and all of the above process is completed. What actually happens is after the frame is open it constantly and after it detects a QR code, it actually logs multiple (around 15) instances of a QR being detected after like 2 seconds. Also the frame is still up and I can still detect Images. The frame closes, only after pressing the waitkey which is 27 or 'Esc' I've tried adding this: for obj in decodedObjects: id = re.findall('/attendees/confirmation/([0-9]+)', str(obj.data)) cv2.putText(frame, str(id[0]), (50, 50), font, 3, (255, 255, 255), 2) attendee = get_object_or_404(Attendee, pk=str(id[0])) attendee.present = True attendee.timestamp = timezone.now() attendee.time_log.append(attendee.timestamp) attendee.save() if id is not None: cv2.destroyAllWindows() break but obviously that won't work … -
How to restrict access to DetailView depending on user permission AND MODEL ATTRIBUTE VALUE?
I'd like to restrict access to some detail article pages that have an attribute is_private=True . They can be displayed in article list, but only users who have a permission view_private_articles must be able to access it. models.py: class Article(models.Model): title = models.CharField( max_length=150, ) is_private = models.BooleanField( default=False, ) views.py: class ArticleListView(LoginRequiredMixin,ListView): model = Article template_name = 'article_list.html' context_object_name = 'article_objects_list' login_url = 'login' class Meta: permissions = [ ("view_private_articles", "Can view private articles"), ] def __str__(self): return self.value class ArticleDetailView( LoginRequiredMixin, PermissionRequiredMixin, DetailView): model = Article context_object_name = 'article_object' template_name = 'detail/article_detail.html' login_url = 'login' permission_required = 'view_private_articles' Problem is, as you could notice, that approach, described here can only restrict users who don't have view_private_articles permission to view ALL ARTICLES (not only with is_private=True attribute). So how to restrict that users to view only articles with attribute is_private=True? -
Display Django TextField in Template (Django 2+)
I am trying to display some content in my database to a template, my model is this below and am trying to access only about inside About_us so as it can be displayed in the template. ''' class About_us(models.Model): welcome_to= models.TextField(max_length=None) about = models.TextField(max_length=None) vision_mission = models.TextField(max_length=None) organization_structure = models.TextField(max_length=None) ''' in my views file this is what i have ''' def about(request): content = About_us._meta.get_field('about').db_column return render(request, 'aboutenos.html', {'content': content}) ''' But the text in the database doesn't show it only shows "None" <p> {{ content.content }} </p> -
Why does the Django Test Client Post Request on a CreateView Fail to Redirect?
My django.test Client returns a response with status code, 200, when I made a post request instead of redirecting with a status code, 302. I am using Django 2.2.4 with Python 3.7.3. No login is required (as addressed by Why does Django Redirect Test Fail?) neither does setting the follow and secure parameters to True (as addressed by Django test client POST command not registering through 301 redirect) I noticed that the same problem affects my update view. It doesn't redirect when I call the Django Test Client with a put method. (I didn't include this code to avoid verbosity). Finally, I noticed that the page redirect works when I python manage.py runserver and then visit the page to create a new Book instance. Here's the test: from django.test import TestCase, Client from django.urls import reverse ... class TestDashboardViews(TestCase): def setUp(self): self.client = Client() self.book_list_url = reverse("dashboard-home") self.book_create_url = reverse("dashboard-upload-book") self.another_demo_book_kwargs = { "title": "Demo Title", "author": "Demo Author", "subject": "Another Demo Subject", "details": "Another Demo Details", "file": "path/to/another/demo/file" } ... def test_book_create_view_using_post_method(self): response = self.client.post(self.book_create_url, self.another_demo_book_kwargs) self.assertRedirects(response, self.book_list_url) ... Here's the affected view: class BookCreateView(CreateView): model = Book fields = ['title', 'author', 'subject', 'details', 'file'] success_url = reverse_lazy("dashboard-home") Here's …