Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sorting models in Django Template
I have two models one is a Lease model that has fields like address, prefix, start_time etc. The second is a Sub model that has fields such as range, subnet, prefix. What I need is to sort the leases into the Subs they belong in based on the Sub's range field. I have added fields to both for comparison. These fields are addr_cut, addr_end for Lease and range_low_cut, range_low_end, and range_high_end for Sub. What I am trying to do that is failing is this: {%for lease in leases%} {%for sub in subs%} {%if lease.addr_cut in sub.range_low_cut%} {%if lease.addr_end >= sub.range_low_end%} {%if lease.addr_end <= sub.range_high_end% Now if I display the contents of lease.addr_cut and sub.range_low_cut: 2606:7400:201:3: 2606:7400:201:3: Looks like the first 'if' should get the green light right? Wrong. It fails for every check regardless of whether the contents are the same. I am new and I know that I am probably trying to introduce too much logic into the template but it seems like this is display based so it belongs here. So my question. If it is a matter of too much logic in the template where and how should I implement this logic to sort my leases into … -
how to update fields of one model depending upon the value of a field in an other model in a django app?
I am new to programming , and stuck in a problem. I have created two classes in django models, 1) Accounts 2) data entry . i am inserting a record in Data entry like against a specific account debit this amount . I want this entry to be sum in a field in Accounts, everytime a data entry is occured . Please help me to the right way .. how i will achieve this -
I have one login temaplate and I want to pass "Invalid credetials" message with that template in django. I wrote following code but it is not working.
I am using following code for rendering "login.html" with "context" message but it is not working. context = messages.warning(request, 'Wrong Credentials.') return HttpResponseRedirect(reverse('login',context) ) -
Website intermittent load failure - something wrong with DNS?
Quick overview: Developed web app with Python and Django; developed and tested locally; adjusted settings to harden for deployment Deployed app to Heroku for simple hosting platform; tested and worked successfully Purchased hobby hosting on Heroku so deployed app would not sleep; I can still verify this to be true, the app loads instantly at myappname.herokuapp.com Purchased domain name on GoDaddy Used a free CloudFlare account to manage DNS Entire chain of operation works successfully sometimes, but sometimes I get a website coming soon page: So when I go to bed last night, everything works. I can load the app from the purchased domain name on all my computers and mobile devices. I wake up this morning, and I'm once again getting the coming soon page. No matter how many times I refresh, and with cache disabled in Chrome so I know it's not my browser. Everything is working perfectly on the Heroku side, since I can load the app there every single time. Once I told GoDaddy to use Cloudflare's nameservers I think there can't be an issue on GoDaddy's side. There has to be something with Cloudflare. The DNS settings on Cloudflare are super simple: CNAME for my.url … -
django set template url from view
Is it possible to set a template url from a view in Django? i.e. I have form with a cancel button and I want to use that form on multiple views but the cancel url will be different depending on what view the form is used in. view: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['app'] = 'sites' context['view'] = 'site_list' context['cancel_id'] = 'this may or may not be set' return context template: {% if cancel_id %} <a href="{% url 'app:view' cancel_id %}" class="btn btn-primary">Cancel</a> {% else %} <a href="{% url 'app:view' %}" class="btn btn-primary">Cancel</a> {% endif %} -
Add custom oauth2 provider to django allauth
I am having problems creating a new custom provider for oauth2 using Django. I have built the oauth2 server and it is working(tested on another consumer) however I am having trouble to create a provider on Django. I am using the Django allauth library (https://github.com/pennersr/django-allauth). There are examples of other providers there and I have build mine following the same convention. A new app was created and inside it, I have placed my files. These are the contents of my files. provider.py from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class MPAccount(ProviderAccount): # def get_profile_url(self): # return self.account.extra_data.get('display_name') # # def get_avatar_url(self): # return self.account.extra_data.get('display_name') # # def to_str(self): # dflt = super(MPAccount, self).to_str() # return self.account.extra_data.get('display_name', dflt) class MPProvider(OAuth2Provider): id = 'testclient' name = 'Testclient' account_class = MPAccount def extract_uid(self, data): return str(data['id']) def extract_common_fields(self, data): return dict(email=data.get('display_name'), name=data.get('display_name')) provider_classes = [MPProvider] url.py from allauth.socialaccount.providers.oauth2.urls import default_urlpatterns from .provider import MPProvider urlpatterns = default_urlpatterns(MPProvider) views.py import requests from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from .provider import MPProvider class MPOAuth2Adapter(OAuth2Adapter): provider_id = MPProvider.id access_token_url = 'removedForQuestion' authorize_url = 'removedForQuestion' profile_url = 'removedForQuestion' supports_state = False def complete_login(self, request, app, token, **kwargs): resp = requests.get(self.profile_url, params={'access_token': token.token}) extra_data = … -
Reverse for 'post_share' with arguments '('',)' not found. 2 pattern(s) tried: ['blog\\/(?P<post_id>[0-9]+)\\/share\\/$', 'blog\\/post_share\\/$']
Before, you guys give me that "use the search tools" kind of speech. Yeah, I already did it, and to no avail. Anyways, I have been scratching my head for the last two days trying to figure out why I keep getting this error" Reverse for 'post_share' with arguments '('',)' not found. 2 pattern(s) tried: ['blog\/(?P[0-9]+)\/share\/$', 'blog\/post_share\/$']" I am using Django 2 and I am reading the book Code for Django by Example book by Antonio Mele. Forms.py class EmailPostForm(forms.Form): name = forms.CharField(max_length = 30) email = forms.EmailField() to = forms.EmailField() comments = forms.CharField(required = False, widget = forms.Textarea) Views.py def post_share(request, post_id): post = get_object_or_404(Post, id = post_id, status = 'published') sent = False if request.method == 'POST': form = EmailPostForm(request, POST) if form.is_valid(): cd = form.cleaned_data post_url = request.build_absolute_uri(post.get_absolute_url()) subject = '{} ({}) recommends you reading "{}"'.format(cd['name'], cd['email'], post.title) message = 'Read "{}" at {}\n\n{}\'s comments: {}'.format(post.title, post_url, cd['name'], cd['comments']) send_mail(subject, message, 'sample@gmail.com', [cd['to']]) sent = True else: form = EmailPostForm() return render(request, 'blogg/shared.html', { 'post': post, 'form': form, 'sent':sent }) urls.py app_name = 'blog' urlpatterns = [ path('post_list', views.post_list, name = 'post_list'), path('post_detail/<int:year>/<int:month>/<int:day>/<str:post>', views.post_detail, name = 'post_detail'), path('post_share/', views.post_share, name = 'post_share'), # re_path(r'^(?P<post_id>\d+)/share/$', views.post_share, name='post_share'), path('<int:post_id>/share/', … -
Using django filter in multiple relation fields
I have three models with a simple relation as below: models.py class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) class PersonSession(models.Model): start_time = models.DateTimeField(auto_now_add=True) end_time = models.DateTimeField(null=True, blank=True) class Billing(models.Model): DEBT = 'DE' BALANCED = 'BA' CREDIT = 'CR' session = models.ForeignKey(PersonSession, blank=False, null=False) STATUS = ((BALANCED, 'Balanced'), (DEBT, 'Debt'), (CREDIT, 'Credit')) status = models.CharField(max_length=2, choices=STATUS, blank=False, default=BALANCED ) views.py class PersonFilter(django_filters.FilterSet): start_time = django_filters.DateFromToRangeFilter(name='branch_sessions__start_time', distinct=True) billing_status = django_filters.ChoiceFilter(name='branch_sessions__billing__status', choices=Billing.STATUS, distinct=True) class Meta: model = Person fields = ('first_name', 'last_name') class PersonList(generics.ListCreateAPIView): queryset = Person.objects.all() serializer_class = PersonSerializer filter_backends = (django_filters.rest_framework.DjangoFilterBackend) filter_class = PersonFilter I want to get billings from person endpoint which have DE status in billing and are between a period of time: api/persons?start_time_0=2018-03-20&start_time_1=2018-03-23&billing_status=DE But the result is not what I were looking for, this returns all persons has a session in that period and has a billing with the DE status, whether that billing is on the period or not. In other words, it seems use or operation between two filter fields, I think this post is related to this issue but currently I could not find a way to get the result I want. I am using djang 1.10.3. -
How to create an associative entity with extra fields in django
I am facing the following problem. I have to entities,Proposal and User, a user can vote up or down several proposals and a proposal can have several votes from several users. This relation between Proposal and User is Many to Many, the thing is that here I want to add an extra field to indicate if the Vote is positive or negative. Is there are a way to do this in Django using ManyToManyField?, or the only way to do this is creating the model entity of Vote by hand like this: class Vote(models.Model): user = models.ForeignKey(User,related_name='voter',null=False) proposal = models.ForeignKey(Proposal,related_name='vote_to',null=False) opinion = models.BooleanField(blank=False,null=False) And in case I have to do it by hand, how I can do for saying to Django that the primary key is the composition of the others Foreign keys -
How to manage groups and permission using my own template?
Actually, I'm beginner in Django and I'm working on a project where I need to create a custom template to manage groups and permissions to not be obliged to use the Django's one. I am looking for any tutorial or documentation to help me to do this Thank you in advance for your help -
beautifulsoup4 doesn´t work
I´ve already installed beautifulsoup4 but it doesn´t work. This is the second time I try to install: (k36) C:\GROWTHTECH\Projetos\blockchain>python -m pip install beautifulsoup4 Requirement already satisfied: beautifulsoup4 in c:\users\patff\appdata\local\conda\conda\envs\k36\lib\site-packages\beautifulsoup4-4.6.0-py3.6.egg You are using pip version 9.0.1, however version 10.0.1 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. When I made a test: >>> import beautifulsoup4 Traceback (most recent call last): File "<console>", line 1, in <module> ModuleNotFoundError: No module named 'beautifulsoup4' >>> from BeautifulSoup import BeautifulSoup Traceback (most recent call last): File "<console>", line 1, in <module> ModuleNotFoundError: No module named 'BeautifulSoup' >>> exit() -
ModuleNotFoundError: No module named 'django.db.migrations.migration'
I got this error ModuleNotFoundError: No module named 'django.db.migrations.migration' after i tried these below steps for the error column “video_url” of relation “resources_home” does not exist python3 manage.py migrate --fake resources zero(resources is my app name) find . -path "/migrations/.py" -not -name "init.py" -delete find . -path "/migrations/.pyc" -delete python3 manage.py showmigrations -
I am trying to upload a file to Django server using angularjs 1.6.5. I am not able to upload file using $http.patch method
Using Angularjs 1.6.5 I am trying to upload a file to the Django server. When I try to upload the file I am not sure what type of 'Content-Type' header should be passed with the $http.patch method. Here is the following my Angular apps config:- var app = angular.module("edit_modules", []); app.config(function($httpProvider) { $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; $httpProvider.defaults.headers.common['Content-Type'] = 'application/json; charset=utf-8'; $httpProvider.defaults.useXDomain = true; $httpProvider.defaults.headers.common['Accept'] = 'application/json, text/javascript'; }); And this is my patch method:- $http.patch(url, data, { headers: {'Content-Type': 'application/json; charset=utf-8' } }).then(successCallback, errorCallback); function successCallback(response){ console.log("Success"); console.log(response); }; function errorCallback(error){ alert("Error Uploading!"); console.log(error); }; When I pass {'Content-Type': 'application/json; charset=utf-8' } through the Header I get the following error:- "The submitted data was not a file. Check the encoding type on the form." Status :- 400 Since its content-type is file I used the following header {'Content-Type': 'multipart/form-data; charset=utf-8'} . But then I got this error:- Multipart form parse error - Invalid boundary in multipart: None Status :- 400 As suggested in the link here I tried the following header as well {'Content-Type': undefined} But this as well did not resolve my problem and I got the following error:- Unsupported media type "text/plain;charset=UTF-8" in … -
Getting enum value by name returns different enum value
So this is something that has been messing with my head for past 30 minutes and I really do not know what to do anymore. This is the enum: class Field(Enum): API_VERSION = '^[v]{1}\d{1,}$' TOKEN = '^[A-Za-z0-9]*$' APPLICATION = '^[0-9]*$' SUCCESS = '^[01]{1}$' IM1 = '^[0-9]{0,16}$' IM2 = '^[0-9]{0,16}$' When I try to get a value of some enum, it sometimes gives the correct value, for example API version and token is working properly. But when I try to get IM1: print(Field.IM1.name + " - " + Field.IM1.value) It returns this: APPLICATION = '^[0-9]*$' Which is a totally different enum field. What could be the problem here? -
Django form don't use default primary key
I use Integer field in Answer form for getting id of question page. But Integer field get not id page, that get title of this page. I thought it because primary key is title, but not, i tried to set id = models.AutoField(primary_key=True) in Question and Answer models, but situation the same. That's my form class: class AddAnswerForm(forms.Form): text = forms.CharField(widget=forms.Textarea) question = forms.IntegerField() def clean_question(self): question_id = self.cleaned_data['question'] try: question = Question.objects.get(id=question_id) except Question.DoesNotExist: question = None return question def clean(self): pass def save(self): answer = Answer(**self.cleaned_data) answer.save() return answer That's my models: class Question(models.Model): title = models.CharField(default='', max_length=255) text = models.TextField(default='') added_at = models.DateTimeField(blank=True, auto_now_add=True) rating = models.IntegerField(default=0) author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='question_user') likes = models.ManyToManyField(User, related_name='question_like_user') def __str__(self): return self.title def get_url(self): return '/question/{}/'.format(self.id) class Answer(models.Model): text = models.TextField(default='') added_at = models.DateField(blank=True, auto_now_add=True) question = models.ForeignKey(Question, on_delete=models.SET_NULL, null=True, related_name='answer_question') author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='answer_user') def __str__(self): return self.text And that's my view: def question(request, pk): try: q = Question.objects.get(id=pk) except Question.DoesNotExist: raise Http404 a = Answer.objects.all() u = User.objects.all() if request.method == 'POST': form = AddAnswerForm(request.POST) if form.is_valid(): _ = form.save() url = q.get_url() return HttpResponseRedirect(url) else: form = AddAnswerForm(initial={ 'question': q, 'answer': a, 'user': … -
Getting the location of uploaded file in django
I have uploaded two files in django.After uploaded I want to take the uploaded file location. view.py from __future__ import unicode_literals from django.shortcuts import render from django.conf import settings from django.core.files.storage import FileSystemStorage from django.conf.urls import url from django.http import HttpResponseRedirect from django.urls import reverse def upload(request): if request.method == 'POST':# and request.FILES['myfile'] and request.FILES["myfile2"]: #request.FILES['myfile'] and request.FILES["myfile1"]: myfile=request.FILES['myfile'] myfile2=request.FILES["myfile2"] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) filename2=fs.save(myfile2.name, myfile2) uploaded_file_url = fs.url(filename) uploaded_file_url2 = fs.url(filename2) #json_data=open('uploaded_file_url','r') return HttpResponseRedirect(reverse('myapp:compare'), { 'uploaded_file_url': uploaded_file_url,'uploaded_file_url2': uploaded_file_url2 }) #upload_file = request.FILES['upload_file'] return render(request, 'myapp/upload.html') def compare(request): #filename = fs.save(myfile.name, myfile) #filename2=fs.save(myfile2.name, myfile2) return render(request,'myapp/home.html',{}) Here I need the location of two uploaded files at compare.How can I do that? -
Getting the pk from url in Django
here is my URL structure that I use to get the item pk in the link : urls.py path('categories/<int:item_category>/', views.item_category, name="item_category"), views.py def item_category(request, pk): item_category = get_object_or_404(Categories, pk=pk) ids = [self.kwargs.get('pk')] cat_id = Categories.objects.get(pk=ids) return render(request, 'items_modal.html', {'item_category': item_category, 'cat_id': cat_id }) Now i want to use the pk to get the result on the new link here is my html <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">{{ cat_id }}</h5> -
DJANGO oauth2 grant_type client_credentials
I have implemented oauth2 using client_credentials gran_type. While generating access token(using o/token/ api) user id is not linked with access_token model PFA for the same, user field is null. so I'm not able to access any other api's using access token getting 403 forbidden error. Any suggestion and help would be appreciable. . -
Django custom middlware routing
I have a Django project which uses django's contrib library for session management using cookies (for both Admin panel and User authentication). Now I'm migrating to JWT token based authentication system. I do not want to re-build an admin portal. My current settings.py looks like this MIDDLEWARE_CLASSES = ( 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'MyJwtMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) Right now all my APIs fail because the requests should pass through both middlwares (Token based and cookie based) What I want to achieve: Django's Admin portal (urls starting with /admin/) should use cookie based authentication system and uses all the midddlwares (meaning it should not use the JwtMiddlware) All other urls should use token based authentication (meaning it should not use the contrib middlewares). Is there any way I can split the middleware wrt urls? -
How is CACHE being populated for django static files?
I see this, not tracked by git: » tree myapp/deploy_static/CACHE/ myapp/deploy_static/CACHE/ ├── css │ ├── 9845305ef067.css │ └── e1296b6ea873.css └── js ├── 31da978add15.js └── aa5d5b818ac3.js 2 directories, 4 files I have several questions: What is this CACHE? It seems to be a collection of all JS / CSS needed by the django application. Who is responsible for generating this? I am not doing anything special in my development workflow to generate this, but I see it appear. Where is this documented? I haven't been able to find references to it in the django documentation Should I commit this to version control? -
Django Admin aditional custom field is hidden
I want to show the image src, as a field tag in Django Admin and I have: class AImageAdmin(AdminFilteringFK, AdminListImageModel, admin.ModelAdmin): model = AImage list_display = ('image_tag', 'a', 'filename', 'file_type') fields = ('a', 'image', 'image_tag', 'filename', 'file_type') readonly_fields = ('filename', 'file_type', 'image_tag') def image_tag(self, obj): src = obj.image.url return mark_safe( '<img src="{url}" />'.format(url=src)) The new field is created correctly, but for some reasons (that I don't get Django is hiding the field, by adding "display: none") <img src="/media/a/28/image/at_2_zxkm.gif" style="display: none !important;" width="70;/"> -
How to check Django permissions in Vue JS template
I would like to v-show a label based on a Django permission, like so: <label for="input" class="ui right floated icon button" :class="color" v-show="(!is_existing) && {{perms.auth.has_permission}}"> <i class="file text icon"></i> 'Upload' </label> However, Vue JS complains because Property or method "False" is not defined on the instance but referenced during render.. Is there a way to access the permission inside v-show? -
How to add a template in another template django angular app?
<div class="home_top_section"> <!-- <div ng-include="'/partials/landing-page-header.html'"></div> --> <ng-include src="'{% static '/partials/landing-page-header.html' %}'"></ng-include> <searchbox class="home_search" searchresult="searchresult"></searchbox> </div> The above code includes a header to the current template. This is working fine when i add the following code to the django views (but it's difficult to add this same login if the app is big), if page_url == 'partials': # Checks whether the url contains partials page = '%s.html' % '/'.join(request.path.split('/')[1:]) Is there any workaround to do that? If yes please help me fix this issue. Thanks in advance... -
Django - Combining Multiple Variables
I'm working on a blog. On it's first page I wants to show 4 random blog posts & 6 latest blog posts! Here's what I did, # 4 random posts data1 = sorted(Blog.objects.all(), key=lambda x: random.random())[:4] # 6 latest posts (excluding the random ones) data2 = Blog.objects.exclude(id__in=data1).order_by('-id')[:6] # all blogs results = list(chain(data1, data2)) But, the above code is raising an error, int() argument must be a string, a bytes-like object or a number, not 'Blog'. When I remove .exclude(id__in=data1) from data2 everything starts working fine, but I need it in order to prevent duplicates. How can we fix that? Thank You! -
Django admin screenshot does not appear in my app
I have run some basic stuff with Django,created superuser (my_env) mm@6830s:~/mysite$ python manage.py createsuperuser Username (leave blank to use 'mm'): Email address: *******@yahoo.co.uk Password: Password (again): Superuser created successfully. When I start the server python manage.py runserver Performing system checks... Output System check identified no issues (0 silenced). April 24, 2018 - 10:50:12 Django version 2.0.4, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [24/Apr/2018 10:50:23] "GET / HTTP/1.1" 200 16348 [24/Apr/2018 10:50:23] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [24/Apr/2018 10:50:50] "GET / HTTP/1.1" 200 16348 [24/Apr/2018 10:50:50] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [24/Apr/2018 10:50:50] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 80304 [24/Apr/2018 10:50:50] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 82564 [24/Apr/2018 10:50:50] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 81348 [24/Apr/2018 10:51:07] "GET / HTTP/1.1" 200 16348 [24/Apr/2018 10:51:07] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [24/Apr/2018 10:51:07] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 80304 [24/Apr/2018 10:51:08] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 82564 [24/Apr/2018 10:51:08] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 81348 [24/Apr/2018 10:51:17] "GET / HTTP/1.1" 200 16348 [24/Apr/2018 10:51:18] "GET /static/admin/css/fonts.css HTTP/1.1" 304 0 [24/Apr/2018 10:51:18] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 304 0 [24/Apr/2018 10:51:18] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 304 0 Anyway,I do not have screenshot with username and password as I expected.May be something is wrong with file hierarchy …