Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can axios get the status code in .catch()?
In the Axios document: axios.get('/user/12345') .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); }); we know we can catch the error in the .catch() method. But when I use the Django-Rest-Framework as the backend API provider. it only provide the data, there is no status in it: You see the error: {username: ["A user with that username already exists."]} but in the browser, we can know the status code: Before asking this question, I have read How can I get the status code from an http error in Axios? this post. But the post seems different with mine. EDIT-1 In my Django-Rest-Framework project: the view: class UserCreateAPIView(CreateAPIView): serializer_class = UserCreateSerializer permission_classes = [AllowAny] queryset = User.objects.all() the serializer: class UserCreateSerializer(ModelSerializer): """ user register """ … -
django tastypie bundle.object returns F('value')
posmenu = POSMenuResource() request_bundle = posmenu.build_bundle(request=request, data = m_new) bundle_data = posmenu.obj_create(request_bundle) Here if i print bundle_data.obj.id it gets the latest value But if i print bundle_data.obj.version it gives F('version') + 1 as result (which is how it is defined in obj_create of the same resource) How to get the exact value instead of function value -
React, react-router, django
I have a SPA-application on React with Redux. React talk with Django only with rest api. Otherwise, frontend and backend - different parts. Also, I know that have another way - standart Django scheme (render to template, when in template - connect with React). Which way is more good? Different parts or Django-way? Sorry, if this question is a strange. Thanks a lot. -
How do i display multiple images uploaded via a formset on my template?
I'm trying to create a site that displays a list of construction projects carried out by my company whereby i want each project on the list to have a gallery of images related to it which i will later loop over in my project details template, i have tried to use formsets but i cant figure out how to loop over the images in the formset to show in the template?can anyone please help me or give me a better approach to my problem? i'm using this approach on this question currently -
in doesnt work for queryset
I have tried to use the built in Groups system in Django to pass through whether a user is part of a group or not to the template: def is_contributor(request): group = Group.objects.get_or_create(name='contributor') return { 'is_contributor': True if group in request.user.groups.all() else False } The following will pass through False even if the user is part of the group. Specifically, if I pass through the following: request.user.groups.all() I get: <QuerySet [<Group: contributor>]> Which leads me to believe that the 'in' in this case is not working over the queryset. Are there limitations to using in over a queryset? Is there a better approach? -
Can't compare string in Django template
Here's my template: <p>{{ instance.video_source }}</p> #"youtube" {% if instance.video_source == "youtube" %} <h1>YOUTUBE</h1> #doesn't print "YOUTUBE" {% endif %} Any idea why the if statement doesn't fire? I've also tried {% if instance.video_source == youtube|stringify %} which is this template tag here: def stringify(obj): return str(obj) and the if statement still doesn't fire. And this also doesn't work {% if instance.video_source == youtube|stringformat:"s" %} <h1>YOUTUBE</h1> {% endif %} Here's the origin of instance.video_source: @property def video_source(self): return "youtube" Any idea why the if statement isn't working? -
Django - Sorting boolean using annotate
Let's imagine I have this model and I would like to sort them by logical operation n1 != n2: class Thing(Model): n1 = IntegerField() n2 = IntegerField() ... def is_different(self): return self.n1 != self.n2 If I sort them by sorted built-in function, I found that it does not return a Queryset, but a list: things = Thing.objects.all() sorted_things = sorted(things, key=lambda x: x.is_different()) Now, if I use annotate sorted_things = things.annotate(diff=(F('n1') != F('n2'))).order_by('diff') it raises the following error: AttributeError: 'bool' object has no attribute 'resolve_expression'. I found a solution using extra queryset: sorted_things = things.extra(select={'diff': 'n1!=n2'}).order_by('diff') but following Django docs (https://docs.djangoproject.com/en/2.0/ref/models/querysets/#extra): Use this method as a last resort This is an old API that we aim to deprecate at some point in the future. Use it only if you cannot express your query using other queryset methods. If you do need to use it, please file a ticket using the QuerySet.extra keyword with your use case (please check the list of existing tickets first) so that we can enhance the QuerySet API to allow removing extra(). We are no longer improving or fixing bugs for this method. Then, what is the optimal way to do it? Thanks! -
Django-material frontend widget override
I'm using material frontend, i'm trying to override widgets as I do that in an admin form, although it seems overridden in my IDE. I cannot get it to work in the frontend. The goal is to replace certain field's widget with a custom one i.e I want range instead of text input. Anyone with experience with Django material that can show me a way to bypass the original rendering of the widgets. -
UPSERT with Django. Many rows
I try to do UPSERT with Django 2.0, Postgres 9.5. My table: \d+ candle Table "public.candle" Column | Type | Modifiers | Storage | Stats target | Description -------------------+--------------------------+-----------------------------------------------------+---------+--------------+------------- id | integer | not null default nextval('candle_id_seq'::regclass) | plain | | mts | timestamp with time zone | not null | plain | | open | numeric(200,40) | not null | main | | close | numeric(200,40) | not null | main | | high | numeric(200,40) | not null | main | | low | numeric(200,40) | not null | main | | volume | numeric(200,40) | not null | main | | pair_timeframe_id | integer | not null | plain | | Indexes: "candle_pkey" PRIMARY KEY, btree (id) "candle_mts_84b62390_uniq" UNIQUE CONSTRAINT, btree (mts) "candle_pair_timeframe_id_3f7b76ce" btree (pair_timeframe_id) Foreign-key constraints: "candle_pair_timeframe_id_3f7b76ce_fk_pair_timeframe_id" FOREIGN KEY (pair_timeframe_id) REFERENCES pair_timeframe(id) DEFERRABLE INITIALLY DEFERRED Implemented it like this: with connection.cursor() as cursor: g = ''' INSERT INTO candle ( pair_timeframe_id, mts, open, close, high, low, volume ) VALUES %s ON CONFLICT (mts) DO UPDATE SET open = EXCLUDED.open, close = EXCLUDED.close, high = EXCLUDED.high, low = EXCLUDED.low, volume = EXCLUDED.volume WHERE candle.pair_timeframe_id = %s; ''' % (data, str(pairs_timeframes_id)) Values might be me many, but in … -
TemplateDoesNotExist at / (home.html)
I'm working on an example Placeholder Image Server. This uses a single file approach, so urls, views, settings, are all in just one file called placeholder.py. Each time I try visiting http://localhost:8000 (the homepage), I get TemplateDoesNotExist at / thrown at me. I can't figure out what's wrong. Below is the project structure: /placeholder placeholder.py /templates home.html /static style.css Here's the content of each file: placeholder.py import hashlib import os import sys from io import BytesIO from PIL import Image, ImageDraw from django.conf import settings from django import forms from django.urls import path, reverse from django.core.cache import cache from django.core.wsgi import get_wsgi_application from django.http import HttpResponse, HttpResponseBadRequest from django.shortcuts import render from django.views.decorators.http import etag from django.core.management import execute_from_command_line # settings likely to change between environments DEBUG = os.environ.get('DEBUG', 'on') == 'on' SECRET_KEY = os.environ.get('SECRET_KEY', 'soj-4^4nho$ifsxsoi1+a8&6o&dya)tcivwcg9g_82&8sg*q^9') ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', 'localhost').split(',') BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # settings settings.configure( DEBUG=DEBUG, SECRET_KEY=SECRET_KEY, ALLOWED_HOSTS=ALLOWED_HOSTS, ROOT_URLCONF=__name__, MIDDLEWARE_CLASSES=( 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ), INSTALLED_APPS=( 'django.contrib.staticfiles', ), TEMPLATES=[ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': os.path.join(BASE_DIR, 'templates'), } ], STATICFILES_DIRS=( os.path.join(BASE_DIR, 'static'), ), STATIC_URL='/static/', ) # simple form to validate the height and width of an image class ImageForm(forms.Form): '''form to validate requested placeholder image''' width = forms.IntegerField(min_value=1, max_value=2000) height = forms.IntegerField(min_value=1, … -
Django send_mail returns 1, but email not received
I am trying to send email via Amazon SES but it does not seem to work for me despite doing all the configuration. I have also tried to setup a local SMTP server but still the same, If I don't specify any email backend / SMTP host, I still get the same response. It seems like Django is not picking up my email backend. How can I debug this? Am I missing something? Django 2.0.3 Python 3.6.2 "boto": { "version": "==2.48.0" }, "boto3": { "version": "==1.6.8" }, "botocore": { "version": "==1.9.8"} My config: EMAIL_BACKEND = 'django_ses.SESBackend' AWS_SES_REGION_NAME = 'us-west-2' AWS_SES_REGION_ENDPOINT = 'email.us-west-2.amazonaws.com' AWS_SES_ACCESS_KEY_ID = "<access key>" AWS_SES_SECRET_ACCESS_KEY = "<secret key>" DEFAULT_FROM_EMAIL = "notify@domain.com" I tried to do this and It just returns 1 but the mail is not received. from django.core.mail import send_mail send_mail( 'Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False, ) However, when I send emails using smtp lib, it goes through. import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def send_email(): mail_subject, mail_body = generate_mail_body("John Doe", 2867) from_name = "Notifications <notifications@domain.com>" from_address = "notifications@domain.com" to_address = "user@domain.com" # Setup Message message = MIMEMultipart() message['From'] = from_name message['To'] = to_address message['Subject'] = mail_subject # Record … -
Failed to load resource: Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin
I have a Vue.js frontend project, which start at the 8080 port. I access the site by: http://localhost:8080/register and I use the Python/Django write the backend site. using Django-Rest-Framework provide the APIs. My backend APIs server is start as: http://0.0.0.0:8001/ But when I register( access the api ), I get bellow Access-Control-Allow-Origin error: Failed to load resource: Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin. In my Python backend project settings.py code are: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '8cyiv%(rkpv33s_(n8x_5&+6-9&s!ddc!0)98la3=9(y8=k$4u' DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_docs', # API docs 'rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth.registration', 'wx_numbers', 'users_management', ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', # corsheaders 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = ( 'XMLHttpRequest', 'X_FILENAME', 'accept-encoding', 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ) CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ( 'http://localhost:8080', 'http://localhost:8081', 'http://localhost', 'http://localhost:8888', ) ROOT_URLCONF = 'wx_backup.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'wx_backup.wsgi.application' AUTH_USER_MODEL = … -
how to impliment Haystacksearch fetched autocomplete
I want implement fetching in autocomplete, here is my autocomplete function def autocomplete(request): fetch_field = request.GET.get('fetch_field') sqs = SearchQuerySet().autocomplete( content_auto=request.GET.get( 'query', ''))[ :5] s = [] for result in sqs: d = {"value": result.title, "data": result.object.slug} s.append(d) output = {'suggestions': s} print('hihi' ,output) return JsonResponse(output) Now I can get fetch fields but I don't know how to fetch with SearchQuerySet. -
Bootstrap-table How to make height adjust to shown data
I am using bootstrap-table to create my table, and it functions perfectly, but it looks a bit strange because the height seems to just be fixed, regardless of how much data is in it. So if I only have 6 records, there is just this awkward empty space underneath. Here is my html: <table class="table" data-toggle="table" data-page-size="10" data-pagination="true" data-search="true"> <thead> <tr> <th data-sortable="true">Username</th> <th data-sortable="true">Full Name</th> <th data-sortable="true">Points</th> {% for subject in subjects %} <th data-sortable="true">{{ subject }}</th> {% endfor %} </tr> </thead> <tbody> {% for user in users %} <tr> <td> <a href="{% url 'profile' username=user.username %}">{{ user.username }}</a> </td> <td>{{ user.first_name }} {{ user.last_name }}</td> {% for item in user.profile.points %} <td>{{ item.1 }}</td> {% endfor %} </tr> {% endfor %} </tbody> And here is a screenshot of my page: Any ideas on how to fix this? -
Hashes of static files collected with CachedFilesMixin as STATICFILES_STORAGE don't match between the collecstatic phase and the serve phase?
I'm trying to setup static file versioning in my django app that uses django-pipeline as a compressor. The documentation says that django-pipeline doesn't directly support versioning because django-storages supports cache-busting natively. So I simply did the following: STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' However, when I do collectstatic, my files are generated with a certain hash, e.g. /media/static/css/mycss.12345678.css, and when I subsequently serve my files, I get a different hash, e.g. /media/static/css/mycss.87654321.css. And that results in a 404. What might I be missing? -
How to use AWS Cognito in Django Application
How to replace Django Authentication with AWS Cognito. And also how to sync my Django users with AWS. Thanks in advance. -
Display User Profile getting ERROR: 'AnonymousUser' object has no attribute '_meta'
I have a simple view that is suppose to check if there is post data, if so update the user data using UserChangeForm. Else get the form data of user and display. Issue: AttributeError at /profile/edit 'AnonymousUser' object has no attribute '_meta' I think it might be this line in the edit_profile view # Handles the get request - if no post info is submitted then get the form and display it on the edit profile page. else: form = UserChangeForm(instance=request.user) args = {'form': form} return render(request, 'accounts/profile_edit.html', args) Not sure what. Here is the view.py edit_profile def edit_profile(request): # Handle post request - if the user submits a form change form details and pass the intance user if request.method == 'POST': form = UserChangeForm(request.POST, intance=request.user) if form.is_valid(): form.save() return redirect('accounts/profile') # Handles the get request - if no post info is submitted then get the form and display it on the edit profile page. else: form = UserChangeForm(instance=request.user) args = {'form': form} return render(request, 'accounts/profile_edit.html', args) profile_edit.html {% extends 'base.html' %} {% block head %} <title>Profile</title> {% endblock %} {% block body %} <div class="container"> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Save Changes</button> </form> </div> {% … -
How to style registration form in django using bootstrap
So I have set up a user registration portal for my website. It is in form of plain HTML text. I have downloaded a bootstrap file for registration portal but it simply does not work. from django import forms class UserRegistrationForm(forms.Form): username = forms.CharField( required=True, max_length=30, label='User Name', ) name = forms.CharField( required=True, max_length=30, label='Full Name', ) last = forms.CharField( required=True, max_length=30, label='Last Name', ), email = forms.CharField( required=True, max_length=30, label='Email', ) password = forms.CharField( required=True, max_length=30, label='Password', widget=forms.PasswordInput(), ) Below is my bootstrap. Can you tell me the error here. It simply does not work <body> <form method="POST" class = "signup"> {% csrf_token %} {{ form.as_p }} <div class="loginBox"> <img src="user.png" class="user"> <h2>Resgister Here</h2> <p>Email</p> <input type="text" name="email" placeholder=""> {{ form.email }} <p>Username</p> <input type="text" name="username" placeholder=""> {{ form.username }} <p>Name</p> <input type="text" name="name" placeholder=""> {{ form.name }} <p>Password</p> <input type="password" name="password" placeholder="••••••"> {{ form.password }} <input type="submit" name="" value="register"> </div> </form> </body> </html> -
Application's pages should not get open on pasting the url in a different browser in django
I have faced an issue like applcation pages should not get open on pasting the url in a different browser in django -
What is the best way to test drf serializer validate
I think two way how can i test drf serializer validate following is my serializer validate code def validate_md5(self, md5): if len(md5) != 40: raise serializers.ValidationError("Wrong md5") return md5 and it is test code 1) def test_wrong_validate_md5_2(self): url = reverse('apk-list') response = self.client.post(url, {'md5':'test'}, format='json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) 2) def test_wrong_validate_md5(self): serializer = ApkSerializer(data=self.apk) if len(self.apk.get('md5')) != 40: self.assertEqual(serializer.is_valid(), False) else: self.assertEqual(serializer.is_valid(), True) what is better than another? or is there best solution? and ... I practice test-driven coding. is it necessary to write test code as above -
django / vue - receive and open dynamically generated PDF
I've been trying most of the related solutions that were posted here in SO, but none of them worked for me basically because as stated here, new versions of Chrome, Firefox, etc, don't accept loading data from URLs in the top frame anymore, meaning that it's no longer possible to open a pdf using window.open('data:application/pdf;base64,' + response.body) or similar approachs. The system I'm developing sends post requests from a Vue 2 front end (using Vue Resource to a Django backend that dynamically generates and returns the requested PDF. When testing the backend using postman, everything works fine; after sending the request the pdf is automatically downloaded. This is how the postman request looks like: This is part of the backend: pdf = generate_pdf(pdf_type, customer_id) response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename='test.pdf' return response However, when I make the post request from Vue, which looks like this (symplified): return Vue.http.post(url, request) .then((response) => { var fileURL = URL.createObjectURL(response.data) window.open(fileURL) }) The displayed PDF is blank. Inspecting the response.data, the pdf string is exactly the same as postman gets. Any idea on how to download / open in a new tab this response? -
certbot nginx doesn't finish
question regarding letsencrypt.org certbot. Whenever I run the certbot --nginx command, it never finishes the process. Full output (running as root): $ certbot --nginx --agree-tos --redirect --uir --hsts --staple-ocsp --must-staple -d <DOMAINS> --email <EMAIL> Saving debug log to /var/log/letsencrypt/letsencrypt.log Plugins selected: Authenticator nginx, Installer nginx Starting new HTTPS connection (1): acme-v01.api.letsencrypt.org Obtaining a new certificate Performing the following challenges: http-01 challenge for <DOMAIN> http-01 challenge for <DOMAIN> nginx: [emerg] duplicate listen options for [::]:80 in /etc/nginx/sites-enabled/django:50 Cleaning up challenges nginx restart failed: b'' b'' Running certbot certificates: $ certbot certificates Saving debug log to /var/log/letsencrypt/letsencrypt.log ------------------------------------------------------------------------------- No certs found. ------------------------------------------------------------------------------- The only thing where I messed up was not properly configuring my DNS before running certbot the first time (messed up my A record, et al; I'm new at this :P), however I don't know what to do moving forward; this is my first web-server so I'm still in a bit of a learning curve. I'm not sure if this is a configuration error, or something else. For info, I'm running a DigitalOcean Django/Ubuntu 16.04 droplet (only edited /etc/nginx/sites-available/default, to change server_name). Will update below for any additional info needed; thanks in advance. ^_^ -
In Django, is a superuser also a mendatory active member or not?
In Django, a superuser is also a mendatory active member or not ? -
How can I submit and save all forms with one button
I am new to django and still learning so forgive me if I did everything completely wrong. I am trying to make a single page with multiple forms on it all submitted with one button and I successfully did do that but I am now trying to make it more dynamic by adding an "add more" button but when I did the form no longer submitted all of the formsets it only submits one formset how do I make it so I can add as many forms as i want and it will still save them? Do I need to use a queryset like update queryset or something? Any help or guidance would be greatly appreciated. Views.py class ScanCreateView(CreateView, LoginRequiredMixin): template_name = 'scanset.html' model = Scan_Info form_class = ScanForms success_url = 'success/' def get(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) Scan_form = ScanInlineFormSet() PostScan_form = PostScanFormSet() return self.render_to_response( self.get_context_data(form=form, Scan_form=Scan_form, PostScan_form=PostScan_form)) def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) Scan_form = ScanInlineFormSet(self.request.POST) PostScan_form = PostScanFormSet(self.request.POST) if (form.is_valid() and Scan_form.is_valid() and PostScan_form.is_valid()): return self.form_valid(form, Scan_form, PostScan_form) else: return self.form_invalid(form, Scan_form, PostScan_form) def form_valid(self, form, Scan_form, PostScan_form): self.object = form.save() … -
How to combine few mutations in the if\else logic in order to get 'GetOrCreateUser'?
I use VueJS and Django + django-graphql-jwt (which returns tokens). I want to use email\password fields for registration and for login. On a server I want to check if provided email already exists -> use django-graphql-jwt's mutation token_auth = graphql_jwt.ObtainJSONWebToken.Field() to return token, else -> create a new user with provided email and password and return a text like "User is Created" in order to inform VueJS that this is a new user. For now I have: # schema.py import graphene import graphql_jwt from django.contrib.auth import get_user_model from graphene_django import DjangoObjectType class UserType(DjangoObjectType): class Meta: model = get_user_model() class CreateUser(graphene.Mutation): user = graphene.Field(UserType) class Arguments: password = graphene.String(required=True) email = graphene.String(required=True) def mutate(self, info, password, email): user = get_user_model()( username=email.split('@')[0], email=email, ) user.set_password(password) user.save() return CreateUser(user=user) # Want to combine two mutations here class GetOrCreateUser(graphene.Mutation): user = graphene.Field(UserType) class Arguments: password = graphene.String(required=True) email = graphene.String(required=True) def mutate(self, info, password, email): # Return token if get_user_model().objects.filter(email=email).exists(): return {'token': graphql_jwt.ObtainJSONWebToken.Field(), 'msg': 'Token Generated'} # Create new user else: CreateUser(???) return {'token': '', 'msg': 'User is Created'} class Mutation(graphene.ObjectType): create_user = CreateUser.Field() get_or_create_user = GetOrCreateUser.Field() I tried different variants, but it seems I do not understand fully graph's workflow or\and what magic …