Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django; How to organize common functions or similar templates
I'm a beginner. I've been working on Django project. Now I'm trying to create notification part and I get the count of notifications. The notification part is on like mypage. There are list menu on mypage and the part is common. Now I want to show up the count on the mypage but I'm wondering if I have to get common context. there is a common part on pages that are belong to my page. inbox.html, my_profile.html etc. <div class="list-group"> <a href="#"> My page top </a> <a href="#"> Inbox <span class="badge badge-primary badge-pill">{{ this is the count of notifications }}</span> </a> The function to get the count of notifications is like this def get_number_of_notifications(self): notifications = Message.objects.filter(message_to=request.user, is_read=False).count() return notifications and in views.py is like def mypage_top(request): ... def my_profile(request): ... def inbox(request): ... My question is basically do I have to write down the process to call the function on each view? I'm wondering if there's a better way. -
When I should check if request is is_ajax()?
I am a little bit confusing with docs. I can't understand real use case when I should check request to is_ajax()? -
CKEDITOR: Make Lollipops Great Again
I'm not really sure, what that little bastard is called, but Lord knows, he has to be exorcised. Upon editing text within the ckeditor, I'd like to use the native, builtin quick-editing tool (the one that came with the device, which works on most applications) rather than the one offered by ckeditor; is this possible, please, mr Master Coder Man? I'd upload an image of the culprit to further communication, alas I'm told that you have to "have money to gain money" on here: Not having ample points, I cannot upload images. Sigh! -
To create set of subset in RPY2 from Django queryset
I have in my views: from django.shortcuts import render import rpy2 import rpy2.robjects as robjects from rpy2.robjects.packages import importr kst = importr('kst') def nodes(request): r = robjects.r kst = importr('kst') r.sets_options('quote', False) edges = Edge.objects.all() n = Node.objects.all() i = 0 set = {} # making dictionary of individual state_nodes in set variable for node in n: set[i] = ','.join(str(i.tag) for i in node.state_node.all()) i = i+1 for key, value in set.items(): if key==0: a = r.set(value) continue b = r.set(value) a = r.set(a, b) # making the knowledge space from above set of strings ks = kst.kstructure(a) ksp = kst.kspace(ks) lp = kst.lpath(ks) list = kst.lpath_is_gradation(lp) learning_path(lp) context = { 'q': n, 'e': edges, 'lp': lp, 'ksp': ksp } return render(request, 'states/states.html', context) The variable a (should contain set of subsets to pass it in kst function) and n ( django queryset) are <QuerySet [<Node: 2-JTJ2ME>, <Node: 1-8VAZPI>, <Node: 2-L5TTC3>, <Node: 2-JTJ2ME,2-L5TTC3>, <Node: 2-JTJ2ME,1-8VAZPI>]> {{}, {2-JTJ2ME,1-8VAZPI}, {2-JTJ2ME,1-8VAZPI, ("2-JTJ2ME,2-L5TTC3"), (("2-L5TTC3"), (("1-8VAZPI"), ("2-JTJ2ME")))}} {{2-JTJ2ME,1-8VAZPI}, {{2-JTJ2ME,2-L5TTC3}, {{2-L5TTC3}, {{1-8VAZPI}, {2-JTJ2ME}}}}} I want to convert this queryset in the set of subsets but from above way, the error is encountered. Curly braces are improperly coming. I want 'a' variable should contain this: set( set('2-JTJ2ME'), … -
Django + Vue.js importing modules
How can I import modules for VueJS app in a template, rendered by Django. I'm trying to import module CKEditor. This is my situation: template.html: <div id="app"> <form> <vue-ckeditor v-model="formField" /> </form> </div> <script src="https://unpkg.com/vue-ckeditor2"></script> <script> Vue.component('vue-ckeditor', VueCkeditor.VueCkeditor) var app = new Vue({ delimiters: ['[[', ']]'], el: '#app', data: function() { return { formField: "", } }, </script> On Github it requires import VueCkeditor from 'vue-ckeditor2';. Is there a way to do that in Django template? Thank you! -
Django Image resizing script
Hi I have a project that the images upload and save in a sub folder in the media and never set an image size so now the images save 4mb and ended up totalling to 40GB in size. I know how to write a script if the images were in a single folder but could someone guide me to do this to check all images in a folder and resize it ? Even if its in a sub folder and another sub folder. Using Django and python -
Django Rest Framework - Serializing data of reverse related table which depends on another reverse relation
class Admin(models.Model): username = models.CharField(max_length=189) password = models.CharField(max_length=189) class Page(models.Model): name = models.CharField(max_length=189) class AdminPage(models.Model): user = models.OnetoOneField(User, related_name="connected_page", on_delete=models.CASCADE) page = models.ForeignKey(Page, related_name="connected_users", on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Message(models.Model): user = models.ForeignKey(User, related_name="messages", on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) Here, I want to serialize a list of pages which will contain a list of connected users. e.g. { "pages": [ { "name": "XXX", "users": [ { "username": "Sad User", "status": "active", }, { "username": "Sleepy User", "status": "idle", } ] } ] } Here, each user can only be connected to one page at the same time. The status of a connected user will be active if the AdminPage connection was created within 30 minutes, and will become inactive if the user has no messages in the last 30 minutes. (A user connected to a page an hour ago but a message 2 minutes ago will be active). I want to solve this problem using Django and the DjangoRestFrameowrk (DRF) with the least number of queries. Currently I am using a serializermethodfield to do this, but this created an additional query on each user which I want to avoid. Is there any way I can accomplish this? Any thoughts are appreciated! … -
wrong url to admin django after adding profile
i had a login page that i would change it to another login page and i follow this instruction: enter link description here and I add this code to it and when i want to login to my user admin that i before added it sends me to to wrong url http://localhost:8050/admin/login/?next=/admin/ and it sends : RelatedObjectDoesNotExist at /admin/login/ User has no profile. -
How to change url key parameter while filtering
Now I'm querying the DB via url as /api/album/?id=123. How can I change the key ('id') to album without affecting the result? That is, how to change /api/album/?id=123 to /api/album/?album=123 ? I'm using DjangoRestFramework and django-filter packages for my API # model.py from django.db import models class Album(models.Model): artist = models.ForeignKey(Musician, on_delete=models.CASCADE) name = models.CharField(max_length=100) # serializer.py from rest_framework import serializers class AlbumSerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = Album # filter.py from django_filters import rest_framework as filters class AlbumFilter(filters.FilterSet): class Meta: model = Album fields = '__all__' # views.py from rest_framework.viewsets import ModelViewSet class AlbumViewset(ModelViewSet): serializer_class = AlbumSerializer queryset = Album.objects.all() filter_backends = (filters.DjangoFilterBackend,) filter_class = AlbumFilter -
why my django form is invalid?
I create my form ROLE is radio button, TEAMS is checkbox class OrganizationMemberForm(forms.ModelForm): ROLES = (('member','member'), ('admin','admin'),('manager','manager'),('owner','owner')) role = forms.TypedChoiceField( choices=ROLES, widget=forms.RadioSelect, ) teams = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple, ) class Meta: model = OrganizationMember fields = ['role'] and in my view,I add teams field because I need choicesvalue def get_form(self, form_class=None): form_class = super(OrganizationMembersDetailView, self).get_form(form_class=None) TEAMS = [(team.id, team.id) for team in Team.objects.filter( organization=self.model.objects.get(id=self.kwargs.get('pk')).organization)] form_class.fields['teams'] = forms.MultipleChoiceField( choices=tuple(TEAMS), widget=forms.CheckboxSelectMultiple, ) return form_class when i test using my hand the self.request.POSTis <QueryDict: {'csrfmiddlewaretoken': ['IMkErNAgdNHHcqeisIQclkHvfqwIbR0ycW6ztlvvZ9cufvulmPOlRKQd8PPr4JFe'], 'role': ['admin'], 'teams': ['1', '3']}> So, I want unit test class OrganizationMemberTest(UserAccountLoginMixin): def test_change_member_role(self): response = self.client.post( reverse( 'organization-member-detail', kwargs={'slug': self.organization_obj.name, 'pk': self.user_obj.id} ), {'role':'admin', 'teams':'["1","3"]'} ) self.assertEqual(response.status_code, 200) def test_organization_member_form(self): form_data = {'role':'admin', 'teams':"['1', '3']"} form = OrganizationMemberForm(data=form_data) self.assertTrue(form.is_valid()) but test was failed, because form is invalid. i change teams data // str -> list data = {'role':'admin', 'teams':['1','3']} but form is invalid too.. why my form is invalid? thank you :) -
Django Ckeditor save iframe to database
I have a trouble , iam developing CMS using Django and Django Ckeditor for text editor , i use youtube plugin for ckeditor for add iframe youtube and i have a trouble. When add iframe in ckditor, i query in database , iframe change to: <iframe width="640" frameborder="0" src="//www.youtube.com/embed/ht2ERtFfFPw" height="360" allowfullscreen=""></iframe> <--p-->&lt Iframe tag strip to &lt . Config: ckeditor in django : 'extraAllowedContent': 'iframe[*]', 'allowedContent': True, When website not render iframe , it render string text -
Using PubNub to publish message in Django view
I'm looking into using PubNub to publish a message from a Django view. I'm running my web app on pythonanywhere. It seems to work fine at first, but if I refresh the view a few times I'm catching a RuntimeError exception with the message "can't start new thread". Here's the code for my view: def my_view(request): try: pnconfig = PNConfiguration() pnconfig.subscribe_key = '<sub key>' pnconfig.publish_key = '<pub key>' pnconfig.ssl = False pubnub = PubNub(pnconfig) pubnub.publish().channel('My Demo Channel').message({"text": "Message from my_view()"}) except: logger.error(sys.exc_info()[0]) logger.error(sys.exc_info()[1]) context = {'val_1': 1, 'val_2': 2} return render( request, 'my_app/my_view.html', context) The exception is thrown on the line where I call pubnub.publish(). Am I doing something incorrectly? -
How to map a directory to a group of urls to a group of templates in Django
I'm building an application that will have a blog. The frontend of the application is built in Vue, the backend uses Django. I'm wanting to build the blog with Vuepress (not important if you don't know what that is--basically it generates static HTML pages from Markdown). My blog, which is separate from the rest of the app, has its own dist folder: dist/ ├── blog.html ├── first-post.html └── second-post.html The rest of the Vue application (excluding the blog) is an SPA. In urls.py in the backend, I serve this SPA using a catch-all: urlpatterns = [ re_path(r'^(.*)$', TemplateView.as_view(template_name='index.html')), ] What I can't quite figure out is how to serve all of the Vuepress blog pages without having to specify the template for each one. Otherwise, I'll have to do this: urlpatterns = [ path('blog', TemplateView.as_view(template_name='blog.html')), path('blog/first-post', TemplateView.as_view(template_name='first-post.html')), path('blog/second-post', TemplateView.as_view(template_name='second-post.html')), re_path(r'^(.*)$', TemplateView.as_view(template_name='index.html')), ] Alternatively, if there is a way to integrate the Vuepress blog into vue-router for the rest of the application, this would also solve my problem. -
React native IOS authorization header with Django rest framework
has anyone encountered in DRF that the request from a react native app IOS Simulator is always been denied because of the Authorization header, Basically, it doesn't accept my authorization header even if its correct and it is working fine on an android simulator and Insomnia. I'm using a specific RetrieveAPIView for that, and the weird thing is I also have a ListAPIView that needs Authorization but that one is working fine on request from IOS simulator, Hoping that someone could help me here. The solution I've made so far is: Enabling all server on my accepted Django CORS setting. Editing Info.plist file that allows the app to run or request even in local domains. Pointing to my domain which has a valid SSL certificate. But none of the above is working. thank you. -
Flask to Django
I following some nice flasks tutorials and trying to apply some of the code to a Django projects but keep getting hung up on the following: def redeem(self): """ Update the redeem stats for this coupon. :return: Result of saving the record """ self.times_redeemed += 1 if self.max_redemptions: if self.times_redeemed >= self.max_redemptions: self.valid = False return db.session.commit() I'm getting hung up on the db.session.commit() at multiple spots. I'm working in Django but appears it is flask only. -
Django + Apache, The requested URL /admin/ was not found on this server
I am working on Django project and try to host on Apache, however it occur "The requested URL /admin/ was not found on this server.", I read this tutorial for the vhost & wsgi configuration: The server environment: CentOS 7.5, Apache 2.4, Python 3.6, Django 1.11.15 and run with Virtual Environment. The project is work fine when I activate the virtualenv and use the built-in server. python manage.py runserver 192.168.99.70:8080 I found out a error is generated on Apache error log: [wsgi:error] Target WSGI script not found or unable to stat: /root/psbookingproject/psbooking/psbooking But I can't figure out how to correct the path issue. My project folder structure: Apache vhost.conf Listen 8080 <VirtualHost 192.168.99.70:8080> # This is name based virtual hosting. So place an appropriate server name # here. Example: django.devsrv.local ServerName psbooking.com ServerAdmin admin@sample.com # This alias makes serving static files possible. # Please note, that this is geared to our settings/common.py # In production environment, you will propably adjust this! Alias /static/ /root/psbookingproject/static/ # This alias makes serving media files possible. # Please note, that this is geared to our settings/common.py # In production environment, you will propably adjust this! Alias /media/ /root/psbookingproject/media/ # Insert the full path to … -
Set value of an unknown Django Model Field
I am implementing a function that gets a model class as a parameter, and should get a dictionary from the same model, set model fields to namesake keys in such dictionary, and save the model to the database. This is the code of the function: def populate_model(self, model_to_populate): model_to_populate_instance = model_to_populate() if hasattr(model_to_populate_instance, 'populate_data'): populate_data = getattr(model_to_populate, 'populate_data') for key, value in populate_data.items(): field = getattr(model_to_populate_instance, key) field = value model_to_populate_instance.save() Something is wrong because I don't get values from the dictionary in the database, but objects GeneralApp.models.CustomCharField>. I guess I am not succeeding to set the value of the model instance field to the value in the dictionary. O would appreciate your help. -
Nested Python Packages/Django Application Packaging
I have a library that I am creating for use across multiple applications. It consists of a set of abstract base classes that are in the "main" package, and a series of reusable Django applications. Files in mylib-core: mylib/__init__.py mylib/models.py mylib/serializers.py mylib/viewsets.py Files in mylib-auth: mylib/auth/__init__.py mylib/auth/models.py mylib/auth/serializers.py mylib/auth/viewsets.py These are two libraries that are to be packaged separately, where mylib-auth depends on mylib-core and the classes in mylib-auth are derived from those in mylib-core The issue that I am having is that when running the test runner for mylib-auth the files for mylib-core are not found. I have installed the the mylib-core package into the virtualenv for mylib-auth. I think this has to do with my nested package structure - where I have a mylib folder in both packages. It seems python is only looking for files in the parent mylib directory that contains the auth subfolder and is ignoring the files in the venv/lib/.../mylib directory. This results in the following errors: When I attempt to run my test suite for mylib-auth I get an error that the application mylib.auth cannot be found because mylib has no property auth - despite having installed the mylib-core into my virtualenv. Adding … -
django-recaptcha returning "Error: Missing required parameters: sitekey"
I followed the django-recaptcha directions to add a field to my contact form. When it renders (in my local test), it has a field that says "Captcha:" but no actual captcha rendered. The dev console in chrome says Uncaught Error: Missing required parameters: sitekey in https://www.gstatic.com/recaptcha/api2/v1531759913576/recaptcha__en.js This answer says to add render=explicit to the javascript, but a) I'm not sure that's even the problem, b) I would think the Django package would handle it. Django 1.11.8, Django recaptcha 1.4.0. Django form is class ContactForm(forms.Form): contacter = forms.EmailField(required=True, label=_('Your Email (optional)'), widget=forms.widgets.TextInput( attrs={'size': '50'})) contact_text = forms.CharField(required=True, widget=forms.widgets.Textarea( attrs={'rows': '10', 'cols': '70', 'class': 'defaultText', 'title': _('Type a message here')})) captcha = ReCaptchaField() The rendered Django form is below. <form action="/contact/" method="post" id="new-contact"> <input type='hidden' name='csrfmiddlewaretoken' value='...' /> <fieldset id="contact"> <legend>Contact Us</legend> <tr><th><label for="id_contacter">Your Email (optional):</label></th><td><input type="text" name="contacter" required id="id_contacter" size="50" /></td></tr> <tr><th><label for="id_contact_text">Contact text:</label></th><td><textarea name="contact_text" rows="10" title="Type a message here" id="id_contact_text" required cols="70" class="defaultText"> </textarea></td></tr> <tr><th><label for="id_captcha">Captcha:</label></th><td><script src="https://www.google.com/recaptcha/api.js?hl=en"></script> <div class="g-recaptcha" data-sitekey="" data-required="True" data-id="id_captcha" ></div> <noscript> <div style="width: 302px; height: 352px;"> <div style="width: 302px; height: 352px; position: relative;"> <div style="width: 302px; height: 352px; position: absolute;"> <iframe src="https://www.google.com/recaptcha/api/fallback?k=" frameborder="0" scrolling="no" style="width: 302px; height:352px; border-style: none;"> </iframe> </div> <div style="width: 250px; height: 80px; position: … -
React Django - Social Auth Login - Can't send axios.get request but href works
I'm trying to use django-rest-framework-social-oauth2 to login with Patreon and currently I can login using Patreon if I have an <a href="http://localhost:8000/auth/login/patreon/"> tag that I can click on in React. However, if I try and do const response = await axios.get('http://localhost:8000/auth/login/patreon/', { headers: { 'Content-Type': 'application/x-www-form-urlencoded', crossdomain: true } } ) in an onClick function I get Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/auth/login/patreon/. (Reason: missing token ‘crossdomain’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel). Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/auth/login/patreon/. (Reason: CORS request did not succeed). I've tried removing crossdomain and tried adding {'Access-Control-Allow-Origin': *} with no luck as well. What's the difference between an href tag and an axios.get? -
What is the function of the name parameter in django.urls.path?
When creating a path inside a urls.py file, one often does this: urlpatterns = [ path('foo/',views.FooView,name='bar'*), ] I'm a beginner to Django, but I am yet to see the function of the name parameter inside django.urls. What is this parameter for, and how can one use it effectively inside a Django-powered website? In short, what does this parameter do, and why is it important to include when creating a path? Thanks! -
Django can't upload multiple files and request.FILES seems empty
I'm using django 2.0 and python 3.6, I've tried almost everything to get the values from request.FILES but nothing seems to work, I think that I'm missing something very simple but I can't find it. models.py class Imagen(models.Model): imagen = models.FileField(max_length=200, blank=True, upload_to='%Y/%m/%d/') views.py if request.method == 'POST': for filename in request.FILES.iteritems(): name = request.FILES[filename].name print('name =' + name) ## <-- not printing anything print('file = ' + file)## <-- not printing anything print('filename = ' + filename)## <-- not printing anything HTML template <form method='post' action='' enctype="multipart/form-data"> <input name='imagen' type="file" multiple/> <button type='submit' class="btn waves-effect">Agregar</button> </form> that views.py is the one that I have right now but so far I've tried all the following variants: **1** if request.method == 'POST': for f in request.FILES.getlist('imagen'): filename = f.name print(filename) ## <-- not printing anything **2** if request.method== 'POST': form = FileUploadForm(request.POST, request.FILES) ## form imported from forms.py if form.is_valid(): print('form is valid!') ## <-- not printing anything else: print('form not valid ') ## <-- not printing anything either!! IDK WHY -
Django - DRF (django-rest-framework-social-oauth2) and React creating a user
I'm using the DRF and ReactJS and I am trying to login with Patreon using django-rest-framework-social-oauth2. In React, I send a request to the back-end auth/login/patreon/ and I reach the Patreon OAuth screen where I say I want to login with PAtreon. Patreon then returns with a request to the back-end at accounts/profile. At this point a python-social-oauth user has also been created. At this point I'm confused. How do I make a request to Patreon to login, create a user in the back-end, and return the session information to the react front-end so that I can include the session information in all following requests from the front-end? I don't want the returned request to be at the backend/accounts/profile, do I? -
django - Passing varying values through URL
I'm new to django and I have to develop a REST API with it. I have datas on mysql db and I want to update one of them on demand. I use PyMySQL and each data has 5 fields (petId, name, species, gender, birthday). For example, urls can be .../api/pets/3/update?name=fluffy,age=4 or .../api/pets/3/update?age=5 or .../api/pets/3/update?age=2,gender=f,name=fluffy In each case this should update the pet with id of 3 with given parameters. As you can see parameters, their positions and their number can vary. In my views.py I have this method def update_a_pet(requested_pet_id, **data): pet = get_a_pet(requested_pet_id) pet_id = data.get('petId', pet[petId]) pet_name = data.get('name', pet[name]) pet_species = data.get('species', pet[species]) pet_gender = data.get('gender', pet[gender]) pet_birthday = data.get('birthday', pet[birthday]) try: with create_connection().cursor() as cursor: sql = "UPDATE `%s` SET `%s` = `%d`, `%s` = `%s`, `%s` = `%s`, `%s` = `%s`, `%s` = `%s` WHERE `%s` = `%d`" cursor.execute(sql, (table_name, petId, pet_id, name, pet_name, species, pet_species, gender, pet_gender, birthday, pet_birthday, petId, requested_pet_id)) create_connection().commit() I planned to get the id with requested_pet_id variable and all other parameters as **data. In urls.py I have the following line for this task. But I can't figure it out how to pass varying number and type of parameters. url('api/pets/(?P<requested_pet_id>[0-9]+)/update/$', views.update_a_pet), … -
Some Images is not shown when upload by mobile in django application but work always perfectly when upload throw laptop?
I am stuck in the very serious problem without any solution. This is my models.py file class Report_item(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL) title = models.CharField(max_length=255, help_text='*Title for the post e.g. item identity') item_type = models.CharField(default="", max_length=100, help_text='*Enter the item name you found e.g. Marksheet,key,wallet') location = models.CharField(max_length=60, help_text='*Enter the address/street where you find this item') city = models.CharField(max_length=60, help_text='*Enter the city name') date = models.DateTimeField(default=timezone.now) Description = models.TextField(blank=True,null=True,help_text='*Enter full description about item') publish = models.BooleanField(default=False) image = models.FileField(default="add Item image", help_text='*Please uplocad a item image to identify by the owner') def __str__(self): return self.title + " " + str(self.publish) def get_absolute_url(self): return reverse('feed:detail', kwargs={'pk': self.pk}) class Meta: ordering = ["-date"] When I upload an image from my laptop then it is uploaded successfully and also shown in the feed. But when I uploaded using a mobile phone then it always uploads but does not show in feed or profile page. Although the image with the same name is available in admin panel but when I try to open it then it shows the 404 not found an error.