Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-rest-framework + Django-oauth-toolkit permission of scopes for different applications
Good afternoon! I am trying to build an API with DRF + Django-OAuth-Toolkit and having a problem with understanding if it is possible to restrict some scopes for different applications/users. If user makes token request with scopes defined, how can I filter scopes for him working with custom scopes and not read/write+? Or what is the best way to restrict some functionality for user? Thank you in advance. -
for loop in python to get nth element in a query set
Please can you check my python code below if it okay to do this for a queryset : gp_id= [0,1,2] for gp in gp_id: specail_list = Special.objects.filter(promotion=False, start__lte=date_instance, minimum_stay__lte=nights, object_id=room_filter.id, end__gte=date_instance, is_active=True, member_deal=False)[gp] print specail_list -
How can you dynamically embed one app into another in Django 2.1?
Consider a site built using DJango (2.1) with 2 separate apps - a forum app and a poll app. How can I dynamically include the rendering of a poll app within the forum app (say as part of a forum post). For instance, as a user, I would write my post and click an "embed poll" button. The modelform for the poll app would pop up, I would enter my info and save the poll. All of this make sense. The part I'm having trouble with is being able to store the information of that poll as part of the forum.. i.e. when I go to view that post, I should see the poll associated with it. The problem with including a poll as part of the forum app is that a poll could exist in other places (say a blog entry or on a simple front page). What process(es) would be used to accomplish this? -
Correct way to store duration in django
I have a mysql field that has a value of 32:52:00 -- 32 hours, 52 minutes, 00 seconds. However, when I try storing it in django like so: runtime = models.TimeField(blank=True, null=True) I get the following error: ValueError: hour must be in 0..23 How should I store this value, as it seems like django is expecting the time to be less than 24 hours? -
How to humanize time in Django only if date is no later than a week?
If, for example, post was created 2018 Nov 27 and now is 2018 Dec 04, date will not be humanized. -
I am looking to create a search form to search by the name of the file
I have a model that looks like this, for convenience I have added the whole models.py here - def randomizer(instance, filename): basefilename, file_extension= os.path.splitext(filename) chars= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890' randomstr= ''.join((random.choice(chars)) for x in range(10)) basefilename = basefilename[:10] return '{basename}_{randomstring}{ext}'.format(basename= basefilename, randomstring= randomstr, ext= file_extension) class Document(models.Model): uploaded_at = models.DateTimeField(auto_now_add=True) upload = models.FileField(upload_to=randomizer, null=True) I want to create a search form by the name of the file and create the corrosponding view. I looked around but I cant find a convincing way to query by the name of the filefield. Any help would be appreciated. -
Using Django on Laravel?
I recently started on a project using Laravel and I'm curious to know that if I can consume Django web services on Laravel. I tried searching google but all that came up were comparisons on it. I want to know if there are any struggles or issues when integrating a python api for php. (ps. I'm clueless to a lot of these stuffs so am sorry if somethings aren't clear to me) -
column "user_id" of relation "checkout_order" does not exist
I am trying to attribute orders to particular user accounts which I have already created.I have gone through the process I did on a previous app but it is not working and keeps throwing up the following error. I think it is something to do with the placement of the user foreignkey but I cant figure it out or find any other posts on here related to it. My model.py file is as follows. from django.db import models from babysitters.models import Babysitter from django.contrib.auth.models import User class Order(models.Model): user = models.ForeignKey(User) def __str__(self): return "{0}".format(self.date) class OrderLineItem(models.Model): order = models.ForeignKey(Order, null=False) babysitter = models.ForeignKey(Babysitter, null=False) quantity = models.IntegerField(blank=False) price = models.IntegerField(blank=False) def __str__(self): return "{0} {1} {2} @ {3}".format(self.quantity, self.babysitter.firstName, self.babysitter.quantity, self.babysitter.price) My forms.py is from django import forms from .models import Order class MakePaymentForm(forms.Form): MONTH_CHOICES = [(i, i,) for i in range(1, 13)] YEAR_CHOICES = [(i, i,) for i in range(2018, 2036)] credit_card_number = forms.CharField(widget=forms.TextInput(attrs= {'placeholder':'Credit card number'}), max_length=16, label='Credit card number', required=True) expiry_month = forms.ChoiceField(label="Month", choices=MONTH_CHOICES) expiry_year = forms.ChoiceField(label="Year", choices=YEAR_CHOICES) cvv = forms.CharField(widget=forms.TextInput(attrs= {'placeholder':'cvv'}), max_length=3, label='Security code (CVV)', required=True) stripe_id = forms.CharField(widget=forms.HiddenInput) class OrderForm(forms.ModelForm): class Meta: model = Order fields = ('user',) and views.py is from django.contrib import … -
Django REST ModelSerializer --- General Question
I am working through a tutorial that includes the building of an articles app. I have an Article model that I am serializing and I am curious about why I need to explicitly set certain fields when using a ModelSerializer. Her is my model: from django.db import models from core.models import TimestampedModel class Article(TimestampedModel): slug = models.SlugField(db_index=True, max_length=255, unique=True) title = models.CharField(db_index=True, max_length=255) description = models.TextField() body = models.TextField() author = models.ForeignKey('profiles.Profile', on_delete=models.CASCADE, related_name='articles') def __str__(self): return self.title Pretty standard stuff. Next step is to serialize the model data in my serializers.py file: class ArticleSerializer(serializers.ModelSerializer): author = ProfileSerializer(read_only=True) # Three fields from the Profile app description = serializers.CharField(required=False) slug = serializers.SlugField(required=False) class Meta: model = Article fields = ( 'author', 'body', 'createdAt', 'description', 'slug', 'title', 'updatedAt', ) Specifically, why do I need to explicitly state the author, description, and slug fields if I am using serializers.ModelSerializer and pulling those fields in from my model in my class Meta: below? Thanks! -
Forward Based On Domain Name With Elastic Beanstalk
I have two domains - example.com example2.com I want to redirect any traffic from example.com to example2.com. I was forwarding using DNS records, but if anyone goes to https://example.com, it won't forward any traffic. Is it possible to set a configuration within ebextensions to accomplish this? -
How to link tags to search results in a Django Blog?
I am building a blog in django and am using django-taggit. I'm trying to figure out how to tie the link of a tag to the search result page that shows all of the posts using that tag. I already have the search page created, I know how to filter queries to the page to bring the correct results, and know how to link to the page itself {% url 'search' %}. But how would I pass queries to the page from the template? For instance, if I have a post tagged "dog" I want users to be able to click on the tag "dog" and be taken to the search page that only has results for posts also tagged "dog". The django documentation does not have examples of this. And every tutorial resource so far has been focused on the filtering and displaying of the search page itself rather than linking to it with desired queries in an <a> tag instead of a <form>. -
Django: Save JSON to database using Fetch/Post
In a Django app, I want to save JSON to the database using the fetch/post API, and I'm having CSRF verification troubles. I have a model "Job" with a field that should hold JSON. class Job(models.Model): job_id = models.IntegerField() setup_json = models.CharField(max_length=100000, blank=True, null=True) The JSON is generated thru user interactions on a page. When the press a "save" button I want to write the JSON to the setup_json field of the proper job. I don't want to use a form, because the JSON is stored in JavaScript and not written anywhere on the page. So I get the CSRF token from the template to use directly: {% csrf_token %} <script type="text/javascript"> const csrftoken = document.getElementsByName("csrfmiddlewaretoken")[0].value; </script> (Note: in my "settings.py" file I added the line CSRF_USE_SESSIONS = True in order to use this technique.) Then I have my save button call a function like this: function onPressSave() { fetch(`webapp/api/save-json/${jobId}`, { method: "POST", headers: { "X-Requested-With": "XMLHttpRequest", "X-CSRF-Token": csrftoken, "Content-Type": "application/json; charset=utf-8", Accept: "application/json" }, credentials: "same-origin", body: JSON.stringify("test json") }); } I get a "POST 403 (Forbidden)" error in the console. Any help would be greatly appreciated! -
Cache large a Queryset in Django rest framework
i faced with problem. I have endpoint, which gives all objects, about(600). When first request I get all elements, but if after request create new a records, created record will not receive. But why? After reload server, created records is receive and missing pagination for this endpoint. Thanks -
Debug Django application in VSCode
I'm trying to debug a Django app within Visual Studio Code and the breakpoints are not being hit and I have the following error: pydev debugger: warning: trying to add breakpoint to file that does not exist: c:\projects\code\testapp_env\testapp\polls\views.py (will have no effect) The launch.Json has the following format: { "name": "Python: Django", "type": "python", "request": "launch", "stopOnEntry": false, "program": "${workspaceFolder}/testapp/manage.py", "console": "integratedTerminal", "args": [ "runserver" ], "django": true, "env": {}, "envFile": "${workspaceFolder}/.env" }, Thank you in advance -
Experience with Django or other frameworks?
**hi, what are your experiences with django? I want to start developing apps and web development. If you use other frameworks which ones would you suggest? I really want to create apps and write programs. I even think of quitting university because of this. ** -
Ignore any redirect when POSTing from Python Requests module?
I use this script to access my Django server and retrieve a CSRF token which then simply attempts to POST data to a view: #!/usr/bin/env python2.7 import sys, time import requests username = 'root' password = 'pass' fileName, userFolder, uploadFolder = sys.argv URL = 'http://127.0.0.1:8000/admin/login/' client = requests.session() # Retrieve the CSRF token first client.get(URL) # sets cookie if 'csrftoken' in client.cookies: csrftoken = client.cookies['csrftoken'] login_data = dict(username=username, password=password, csrfmiddlewaretoken=csrftoken, next='') r = client.post(URL, data=login_data, headers=dict(Referer=URL)) But in my Django development server's access log I see: [03/Dec/2018 17:44:17] "GET /admin/login/ HTTP/1.1" 200 1637 [03/Dec/2018 17:44:17] "POST /admin/login/ HTTP/1.1" 302 0 Not Found: /accounts/profile/ [03/Dec/2018 17:44:17] "GET /accounts/profile/ HTTP/1.1" 404 9904 What I don't understand is why I keep getting an additional Get and 404? Is it possible to configure my Python request to ignore any kind of redirect signal regardless it be for a get or post or session.get? I have tried adding allow_redirects=False to client.get(URL, allow_redirects=False) but that did not help. My POSTs are working fine, I'm simply trying to eliminate the additional GET request as it's unnecessary clutter. Thanks. -
Javascript correctly scoped in nested include template in Django
How do I get the level 3 template to have the same scope as level 1/base? base.html <html> <head> {% block inline-scripts %}{% endblock inline-scripts %} </head> <body> {% block content %} Default Content{% endblock content %} <body> </html> level1.html {% extends "base.html" %} {% block inline-scripts %} {% this will get loaded %} <script src='some/file.js'></script> {% endblock inline-scripts %} {% block content %} Level 1 Content {% include 'level2.html' with whatever=variables %} {% endblock content %} level2.html Level 2 HTML {% include 'level3.html' with whatever=variables %} level3.html Level 3 HTML - How do I get the JS here to have the scope of the level 1/base {% block inline-scripts %} {% this will NOT get loaded %} $(document).ready(function() { //Current error //Uncaught ReferenceError: $ is not defined //Do some stuff }) {% endblock inline-scripts %} <script> manuallyEnteringJS.doesntWorkEither </script> -
Django: Programmatically asociate a user instance with a group, on save
After a user is saved, I need to make sure that its instance is associated with a group by default. I have found two ways to achieve that: Overriding the model's save() method models.py: from django.contrib.auth.models import AbstractUser, Group class Person(AbstractUser): def save(self, *args, **kwargs): super().save(*args, **kwargs) to_add = Group.objects.get(id=1) # get_or_create is a better option instance.groups.add(to_add) Capturing a post_save signal: signals.py: from django.conf import settings from django.contrib.auth.models import Group from django.db.models.signals import post_save from django.dispatch import receiver @receiver( post_save, sender=settings.AUTH_USER_MODEL, ) def save_the_group(instance, raw, **kwargs): if not raw: to_add = Group.objects.get(id=1) # get_or_create is a better option instance.groups.add(to_add) Are these methods equal in achieving their goal? Is there a better one in Django terms of "Good Practice"? -
Sort a python Django query with zero always first, then positives, then negatives
I have Django objects set up like: class Example(models.Model): count = models.CharField(default="0") So if I have some objects ex1, ex2, ex3, ex4 that have count of -1, 0, 5, -6 respectively. I want to be able to query the objects and sort them into the order [0, 5, -6, -1] where any zeros come first, then positives, then negatives while also going in ascending order for each section. I was thinking about using something like Example.objects.order_by('count') but did not find a way to do that with a custom function like Ordering a Django queryset by the returned results of a method The other route I was looking at was something like below: objs = Example.objects.all() sorted_objs = sorted(objs, key = lambda o: int(o.count)) Is there a way to use the sorted method to sort the zeros first? I was unable to find one. The final way I am using is: objs = Example.objects.all() zero_objs = [] positive_objs = [] negative_objs = [] for obj in objs: if obj.count == 0: zero_objs.append(obj) elif obj.count < 0: negative_objs.append(obj) else: postitive_objs.append(obj) sorted_objs = zero_objs + sorted(postitive_objs) + sorted(negative_objs) This works but seems like it's not the best way to do this, so any … -
Django: Model object created with form returning DeferredAttribute on Object.stock_level
I have model called Item class Item(models.Model): item_name = models.CharField(max_length=200) item_price = models.DecimalField(max_digits=100, decimal_places=2) item_description = models.CharField(max_length=300) item_bought_price = models.DecimalField(max_digits=100, decimal_places=2) stock_level = models.IntegerField() restock_level = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) I also have a form for website admin to add new item object from the website without going to /admin url forms.py class ItemForm(forms.Form): item_name = forms.CharField(label='Item name', max_length=200) item_price = forms.IntegerField(label='Price') item_description = forms.CharField(label='Item Description', max_length=500) item_bought_price = forms.IntegerField(label='Item bought price') stock_level = forms.IntegerField(label='Stock Level') restock_level = forms.IntegerField(label='Restock Level') def clean(self): cleaned_data = super().clean() item_name = cleaned_data.get('item_name') item_price = cleaned_data.get('item_price') item_description = cleaned_data.get('item_description') item_bought_price = cleaned_data.get('item_bought_price') stock_level = cleaned_data.get('stock_level') restock_level = cleaned_data.get('restock_level') views.py def add_item(request): if request.user.is_superuser: if request.method == "POST": form = ItemForm(request.POST) if form.is_valid(): item_name = form.cleaned_data['item_name'] item_price = form.cleaned_data['item_price'] item_description = form.cleaned_data['item_description'] item_bought_price = form.cleaned_data['item_bought_price'] stock_level = form.cleaned_data['stock_level'] restock_level = form.cleaned_data['restock_level'] item = Item.objects.create( item_name=item_name, item_price=item_price, item_description=item_description, item_bought_price=item_bought_price, stock_level=stock_level, restock_level=restock_level, ) item.save() return redirect('items:item_list') else: messages.error(request, 'Invalid form.') return redirect('site_admin:add_item') else: form = ItemForm() return render(request, 'Admin/add_item.html', {'form':form,}) else: return HttpResponse('Whoopsie!') I have one more function, where when item is ordered, quantity of items bought is subtracted from stock_level, It works fine with Item instances created through /admin, but with item instances created through form, when … -
What are the Django requirements to become a full stack dev.
To fully use Django would I need to know: HTML CSS3 JS JSON if yes, what else would i need to be comfortable using to fully be a full stack web dev? Thank you. -
Django OAuth Toolkit giving me "Authentication credentials were not provided" error
I've been trying for a while to get django Oauth toolkit to work but no matter what I get a 401 error and when I check the details it's the error in the title. Even though I'm obviously passing credentials views.py: class PostCarFax(viewsets.ModelViewSet): #authentication_classes = [authentication.TokenAuthentication, authentication.SessionAuthentication, authentication.BaseAuthentication] permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] queryset = CarFax.objects.all() serializer_class = CarFaxSerializer serializers.py: class CarFaxSerializer(serializers.ModelSerializer): class Meta: model = CarFax fields = ('vin', 'structural_damage', 'total_loss', 'accident', 'airbags', 'odometer', 'recalls', 'last_updated', 'origin_country') def create(self, validated_data): return CarFax.objects.create(**validated_data) settings.py import os import django_heroku from django.conf import settings settings.configure() # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ts_0a3(d9$$g4h&_w#k$op7a)lg3@vrk!^fs!m-zv=))rw$=xi' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] '''import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", __file__) import django django.setup()''' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'oauth2_provider', 'rest_framework', 'rest_framework.authtoken', ] 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', 'oauth2_provider.middleware.OAuth2TokenMiddleware', ] ROOT_URLCONF = 'django_api.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ … -
How to add Tags in a django blog using taggit
am trying to add some tags in my post_list function i have installed taggit and tested it in shell it is working fine and am able to display the tags in the html template blog.html but the problem is that trying to add the url for a particular tag shows errors .NoReverseMatch at /blog/ Reverse for 'post_list' with arguments '('python',)' not found. 1 pattern(s) tried: ['blog\/$'] I have a blog category called python here are my works so far views.py def post_list(request,tag_slug=None): object_list=Post.objects.filter(status='Published').order_by("-created") recent_post=object_list[:6] categories = Category.objects.all().annotate(post_count=Count('post')) for category in categories: print(category.post_count) if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) object_list = object_list.filter(tags__in=[tag]) page = request.GET.get('page', 1) paginator = Paginator(object_list, 3) try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) context={ 'items':items, 'recent_post':recent_post, 'categories':categories, } return render(request,"blog.html",context) blog.html <div class="widget"> <h3 class="badge">TAGS</h3> <div class="tagcloud"> {% for obj in items %} {% for tag in obj.tags.all %} <a href="{% url 'post_list' tag.slug %} ">{{ tag.name }}</a> {% if not forloop.last %}, {% endif %} {% endfor %} {% endfor %} </div> </div> help please -
Token matching query does not exist
I am trying to set up a way to add friends on a social media type site, but something is wrong and I don't know what is going on. Here is my model: class Friend(models.Model): #static variables for friend_status attribute FORMER_FRIENDS = 0 FRIENDS = 1 A_REQUESTS_B = 2 B_REQUESTS_A = 3 friend_A = models.ForeignKey(User, related_name='friend_A') friend_B = models.ForeignKey(User, related_name='friend_B') friend_status = models.IntegerField def __str__(self): return '%s and %s friendship' % (self.friend_A, self.friend_B) class Meta: unique_together = (('friend_A', 'friend_B'),) Here is my URL: url(r'^friend_request/(?P<username>[\w.@+-]+)', AddFriend.as_view(), name = 'add_friend'), Here is my class-based view: class AddFriend(APIView): def get(self, request, username): user = Token.objects.get(key='token string').user friend = User.objects.get(username=username) #check for friendship instance new_friend, created = Friend.get_or_create(friend_A=user, friend_B=friend) When I try to access the endpoint I get the following output: DoesNotExist at /friend_request/brian Token matching query does not exist. Setting up friend relationships is proving more difficult than I expected. Please advise. -
Python Django Multi Level Join Query
Task Details I am working on creating a custom API to fetch data from three tables, based on provided key info. Background To elaborate, I've three data tables - Client, Account and Client_accounts and their structure looks like this: Client ID (Integer) Primary Key display_name (varchar) Accounts ID (Integer) Primary Key nickname (varchar) Client_Accounts Client_ID (Integer) Foreign Key -> ID from client table Account_ID (Integer) Foreign Key -> ID from accounts table In intend to pass a client ID to my API and want to fetch all the accounts (and accounts names) owned by that client. The SQL query that I am trying to replicate looks like this: select cl.id as client_id, cl.display_name, ac.id as account_id, ac.nickname as account_name from datahub_clients cl join datahub_client_accounts cl_ac on cl.id=cl_ac.client_id join datahub_accounts ac on cl_ac.account_id=ac.id where cl.id=15 ; Done so far This is what I used to fetch the client's name API, by passing the client_id: ##### For endpoint - get_client_name @api_view(['GET', 'POST']) @permission_classes((AllowAny,)) def get_client_name(request): try: if request.method == 'GET': list_of_account_ids = Client_Accounts.objects.filter(client_id=request.GET['id']).values_list('account') needed_accounts = Accounts.objects.filter(id__in=list_of_account_ids).values('id','nickname') return Response({'requested client id':request.GET['id'],'identified client name': 'detailed info to go here'}, status=status.HTTP_200_OK) else: return Response({'status':'error','message': 'Facepalm moment!'}, status=status.HTTP_403_FORBIDDEN) Problem Statement 1) In the code above, I …