Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'input' is an invalid keyword argument for print()
I am using graphene-django for an api. I am trying to create a mutation for creating a brand which has foreign key of company. When i mutate, I get the following error "'input' is an invalid keyword argument for print()". I could not figure out, why this error is thrown. Here is my mutation class BrandInput(graphene.InputObjectType): company = graphene.List(CompanyInput) name = graphene.String() website = graphene.String() description = graphene.String() country = graphene.String() city = graphene.String() address = graphene.String() class CreateBrand(graphene.Mutation): class Arguments: input = BrandInput(description="These fields are required", required=True) class Meta: description = "Create Brand Mutation" errors = graphene.String() brand = graphene.Field(BrandNode) @staticmethod def mutate(root, info, **args): print('args', args, **args) if not info.context.user.is_authenticated: return CreateBrand(errors=json.dumps('Please Login to list your brand')) try: company = models.Company.objects.get(slug=args.get('input')['company']) if company: brand = models.Brand.objects.create( company=company, name=args.get('input')['name'], slug = args.get('input')['slug'], website = args.get('input')['website'], description = args.get('input')['description'], country = args.get('input')['country'], city = args.get('input')['city'], address = args.get('input')['address'], ) return CreateBrand(brand=brand, errors=null) except models.Company.DoesNotExist: return CreateBrand(errors=json.dumps('Company should be required')) I felt doubt in company = graphene.List(CompanyInput) so i changed it to company = graphene.String() and provided the slug of the company so i can find the company instance when mutating the brand. But i get the same error. The query … -
read uploaded text file into text widget (django forms)
I have a file upload that takes a text file, and reads the input (contentOfFile). The file upload, and reading of the data works fine (I've tested it), but I'm having issues trying to populate my text area widget with this data. views.py uploaded1 = request.FILES['uploaded'] contentOfFile = uploaded1.read() textInput1.innerHTML = contentOfFile forms.py class HomeForm(forms.Form): textInput1 = forms.CharField(required=False, widget=forms.Textarea( attrs={ 'class': 'form-control', } )) class Meta: fields = {'textInput1',} template.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.textInput1 }} <button type="submit" name="compare" class="btn btn-primary mb-2">Compare</button> </form> -
django admin cache Admin.method results
This Model admin list view with 300 records, if I run it as is it's fast, but if I add a method to change a value it would take a long time to finish. class ModelAdmin(admin.ModelAdmin): list_per_page = 300 list_display=('data_rif', 'get_created', ) def get_created(self, obj): return User.objects.get(username=self.cod_operatore).first_name It would make 300 duplicates query. Is there a way to cache the results for get_created? -
Django Custom Tables Creation
I have a project where i have to create a command table for the customers to command on the site. What I am trying to achieve is to give the possibility of selecting multiple products to the customer. The foreign key is ok for one product, but when we have to select multiple ones, is not ok. Even when clicking the "+"add button, you are not allowed to add more, but django makes you add a new product in the DB :D. How can i achieve my target of adding multiple products to the cart? Thank you in advance! My models; from django.db import models from django.conf import settings from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ from datetime import datetime, timedelta, time today = datetime.now().date() class ClientManager(models.Manager): def active(self, *args, **kwargs): return super(ClientManager, self).filter(timestamp__lte=datetime.now()) class Client(models.Model): TYPE_CLIENT = ( ('PF', 'Persoana Fizica'), ('PJ', 'Persoana Juridica'),) MODEL_CLIENT = ( ('O', 'On-line'), ('S', 'Showroom'), ('D', 'Distribuitor')) user = models.ForeignKey(settings.AUTH_USER_MODEL,blank=True, null=True, default=1, on_delete=True) model_client = models.CharField(max_length=3, blank=True, default="PF", null=True, choices=MODEL_CLIENT, help_text='Selecteaza de unde vine clientul') tip_client = models.CharField(max_length=3, blank=True, default="PF", null=True, choices=TYPE_CLIENT, help_text='Selecteaza tipul de client') nume_client = models.CharField(max_length=30, blank=True, default="", null=True, help_text='Insereaza Numele si Prenumele Clientului') adresa_client = models.CharField(max_length=50, … -
Djagno: Getting objects from ManyToMany through model in a single database query
Given these models: class Places(models.Model): #... class Tour(models.Model): places = ManyToManyField(A, through='TourPlaces') class TourPlaces(models.Model): tour = ForeignKey(Tour, on_delete=models.CASCADE) place = ForeignKey(Place, on_delete=models.CASCADE) #... How can I build a Queryset so that I can get the Tours a Places belongs to on the SQL side without hitting the database repeatedly? Pseudo example: for place in Places.objects.(some kind of annotation maybe?): print(place.tours[0]) Instead of for place in Places.objects.all(): print(TourPlaces.objects.get(place=place).tour[0]) Context: My REST Framework ModelSerializer for Places, using the code above in a SerializerMethodField, is too slow. -
How Can I Fake A MultiPolygon Field?
I am creating a Django factory for a model that contains a MultiPolygonField. It is throwing an error when I run the test. Detail below. I have created a special provider to fake this field. The code is taken from the Django docs: from django.contrib.gis.geos import ( Polygon, MultiPolygon, ) import factory from faker import Faker from faker.providers import BaseProvider fake = Faker() class Provider(BaseProvider): def mpoly(self): p1 = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) ) p2 = Polygon( ((1, 1), (1, 2), (2, 2), (1, 1)) ) mpoly = MultiPolygon(p1, p2) return mpoly fake.add_provider(Provider) class GeographyFactory(factory.DjangoModelFactory): """ A Factory to generate mock GeographyFactory objects to be used in tests. """ class Meta: model = 'location.Geography' name = factory.Faker('name') mpoly = fake.mpoly The error I get when I run the tests, however, has stumped me. TypeError: Cannot set Geography SpatialProxy (MULTIPOLYGON) with value of type: <class 'method'> It seems to suggest that I am not returning the right type, but I can't figure out what it wants instead of the MultiPolygon object I am returning. Why does it think I am returning <class 'method'>? Any suggestions would be most welcome! -
Django rest framework generic view set custom headers
I am new to Django-rest-framework. I'm learning about generic-view [Generic-view]. I want to know how to set some custom headers in the response. I am returning csv response using django-restframework-csv library. I am using ListModelMixin in my view class. My code look like from rest_framework.mixins import ListModelMixin from rest_framework_csv.renderers import CSVRenderer Class SnippetList(ListModelMixin): serializer_class = SnippetSerializer renderer_classes = (CSVRenderer, ) def get(self, request, format=None, *args, **kwargs): return self.list(request, *args, **kwargs) I want to set this header in response. headers = { 'Content-Disposition': 'attachment; filename=snippet_log.csv', } Actually, I want to set the filename of csv. I didn't find a way to set the headesr in case of ListModelMixin. Any help would be appreciated. Thanks. -
uuid as keyword argument <pk> in django urls.py
I am using a uuid4 as id in some django models. Thats why I cannot use <int:pk> in the urls.py because it wont match. Is there another prefix I can use to match these uuids like a2182835-4518-cb95-8eaf-0d5a34105cb2 ? -
How do I create a ComboField in Django forms (which accepts CharField and ChoiceField inputs)?
I have to create a ComboField in Django forms which accepts CharField and ChoiceField inputs. Is there a way to do it in forms.py? Or should I use javascript /html to do it? -
Celery Beat Elastic Beanstalk
I am trying to setup celery beat on Elastic Beanstalk. The normal tasks are working perfectly fine, but the beat scheduler seems to have some issues. It is a permission issue and seeing that I am new to EB I have no idea how to get this to work. When I SSH into the app and enter: celery -A project beat -l info I get the following error: PermissionError: [Errno 13] Permission denied: '/var/run/celery/celery-beat.pid' Help would be much appreciated. -
How to implement a multiple model search in Django Rest Framework?
I am to build an application that has multiple models - related and unrelated. I also have to implement a search field that searches all the specified fields of all these models. User: name, education, xxx, UnrelatedDocument: title, xxx, UserDocument: User(F), title, xxx, Of the above three models UnrelatedDocument is not related with any other model. I was wondering how to implement a common search field for all these models on specific fields? -
Am I using distinct() right?
I'm trying to create a simple app to display a list of database records. Said data is loaded in bulk from a csv by means of csvimport. The csv file I'm loading has several thousands of records, but for this test theres one column (citie) which has the same value for all of them. In an index view I'm using for tests, I want to display the number of (different) cities loaded, and then a list of said cities. This is in my views.py def index(request): num_municipios = DireccionEnCobertura.objects.values_list('municipio').distinct().count() municipios = DireccionEnCobertura.objects.values('municipio').distinct() return (render (request, 'index.html', context={'num_municipios':num_municipios, 'municipios':municipios})) this is in my index.html <ul> <li><strong>Municipios:</strong> {{ num_municipios }}</li> </ul> <table> <thead> <td>Municipios Incluidos</td> </thead> <tbody> {% for municipio in municipios.distinct() %} <tr> <td>{{ municipio.municipio }}</td> </tr> {% endfor %} </tbody> </table> and this is the model class DireccionEnCobertura(models.Model): gescal17 = models.CharField(max_length=17, help_text="") municipio = models.CharField(max_length=50, help_text="") tipo_via = models.CharField(max_length=50, help_text="") nombre_via = models.CharField(max_length=200, help_text="") numero = models.CharField( max_length=5, help_text="", null=True) cod_postal = models.CharField( max_length=5, help_text="") uuii = models.CharField( max_length=5, help_text="", null=True) class Meta: ordering = ["tipo_via", "nombre_via", "numero"] def __str__(self): return self.municipio + " " + self.tipo_via + " " + self.nombre_via + " " + str( self.numero ) def … -
Django && PayPal Webhook
I'm trying to setup a webhook using PayPal and Django. Everything seems to be set up correctly, but when I test the webhook, I get: RuntimeError: You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to myapi/summary/v2/paypalwebhook/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. I've done all manner of combinations trying to get it to work -- I've removed the slash in urls.py, removed and readded the slash in the webhook simulator, changed APPEND_SLASH to false and true and back to true. It never works. Either I get a 'not found' with no trailing slash (whether or not I have a trailing slash in the paypal simulator) or I get the above error. -
Update a Profile picture
so i'm working on little django application where users can view and modify there profile ,but i didn't know how to provide a button under the profile picture that allows the user to choose a new one and when he chooses it redirect him to the same page with the new profile picture ,any help or ideas will be usefull , tnks !! here's what i tried : forms.py class picture_form(forms.ModelForm): class Meta: model=Profile fields=('image',) views.py def profile(request): if request.method == 'POST': form = picture_form(request.POST, request.FILES) if form.is_valid(): profile = Profile.objects.get(user=request.user) profile.image = form.cleaned_data['image'] profile.save() return redirect(reverse('profile')) else: for usr in User.objects.all(): if request.user.get_full_name() == usr.get_full_name(): prf = Profile.objects.filter(user=usr) form = picture_form() return render(request, 'store/profile.html', {'profile': prf, 'form': form}) template {% if prf.image %} <div class="profile-img"> <img src="{{ prf.image.url }}" id="prf_img" alt=""/> </div> {% else %} <div class="profile-img"> <img src="{% static 'img/empty-profile-picture.png' %}" id="prf_img" alt=""/> </div> {% endif %} <!--<a href="{% url 'upload_picture' %}"> <div class="file btn btn-lg " > Change Photo <input type="file" name="file"/> </div></a> --> <form method="post" action="{% url 'profile' %}" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="btn btn-outline-success" value="upload"> </form> </div> -
Pass user as parametr
I have field in view: <h1>{{article.author}}</h1> And I want pass author to UR: <p><a href="{% url 'subscribe' user=article.author %}">Подписаться на пользователя {{article.author}}</a> </p> URL: path('<user:user>',views.sunscribe, name="subscribe") But I have error: "URL route '%s' uses invalid converter %s." % (original_route, e) django.core.exceptions.ImproperlyConfigured: URL route '' uses invalid converter 'user'. -
Translate SQLite to Django
I want to get the all albums with the average voting. SELECT a.*, avg(v._mark) AS voting from musicwebapp_album AS a LEFT JOIN musicwebapp_vote AS v ON v.album_id = a.id GROUP BY a.id; I actually don't know how to how to do it with django. -
Django Reverse for 'test' with no arguments not found. 1 pattern(s) tried: ['db\\/test\\/(?P<items>[0-9]+)\\/$']
This is a common question, but I've been combing through SO for awhile and I still can't solve it. I keep getting this error when attempting to pass the primary key to a model view via an tag from another page Here is the template trying to render the hyperlink. <div class="main"> <table id = "results_table" class = "results_table"> {% if header %} <tr> {% for h in header %} <th>{{h}}</th> {% endfor %} </tr> {% endif %} {% if values %} {% for value in values %} <tr> {% for v in value %} <td>{{v}}</td> {% for items in archive %} <a href = "{% url 'db:test' items.pk %}"> Modify </a> {% endfor %} {% endfor %} </tr> {% endfor %} {% else %} <p>No results.</p> {% endif %} </table> Here is urls.py from django.urls import path from . import views app_name = 'db' urlpatterns = [ #path('', views.index, name='index'), path('index/', views.index, name='index'), path('search/', views.search, name='search'), path('upload/', views.upload, name='upload'), path('result/', views.search_result, name='result'), path('test/<int:items>/', views.test, name='test'), path('login/', views.login_user, name='login'), path('upload/scanfile/', views.upload, name='scanfile'), path('logout/', views.logout, name='logout'), path('drag_n_drop_test/', views.drag_n_drop_test, name='drag_n_drop_test'), ] path('test//', views.test, name='test') is the line that I've been trying to alter And here is views.py @login_required def search_result(request): primary_keys = … -
Django - queryset - annotate - Sum() with a Case-When and a filter()
I have basically two models - Product and Stock as given below (omitted some ForeignKey fields). class Product(models.Model): opening_stock=models.PositiveIntegerField(default=0) and TRANSACTION_TYPE=(('I','Stock In'),('O','Stock Out')) class Stock(models.Model): product=models.ForeignKey('product.Product', blank=False,null=False) date=models.DateField(blank=False, null=False,) quantity=models.PositiveIntegerField(blank=False, null=False) ttype=models.CharField(max_length=1,verbose_name="Transaction type",choices=TRANSACTION_TYPE, blank=False, db_index=True) I already have a ListView to list all products along with their current stock balance (opening_stock+sum(quantity when ttype=I) - sum(quantity when ttype=O)), as given below. class ProductList(ListView): paginate_by = 20 model=Product def get_queryset(self): queryset = super(ProductList, self).get_queryset() queryset = queryset.annotate( stock_in_sum = Sum(Case(When(stock__ttype='I', then=F('stock__quantity')), output_field=DecimalField(), default=0)), stock_out_sum = Sum(Case(When(stock__ttype='O', then=F('stock__quantity')), output_field=DecimalField(), default=0)) ) queryset = queryset.annotate( balance_stock = ExpressionWrapper(F('opening_stock') + F('stock_in_sum') - F('stock_out_sum'), output_field=DecimalField()) ) Now, I want to make another view to list of all products along with the available stock up to a specific date. I've created a form with DatePicker and my current view and form are as given below. class StockByDate(ListView): paginate_by = 20 model=Product template_name="product/stock_by_date.html" form_class=StockByDateForm def get_queryset(self): date= self.request.GET.get('date') if date: queryset = super(StockByDate, self).get_queryset() queryset = queryset.annotate( stock_in_sum = Sum(Case(When(stock__ttype='I', then=F('stock__quantity')), output_field=DecimalField(), default=0), filter=Q(stock__date__lte=date)), stock_out_sum = Sum(Case(When(stock__ttype='O', then=F('stock__quantity')), output_field=DecimalField(), default=0), filter=Q(stock__date__lte=date)), ) queryset = queryset.annotate( balance_stock = ExpressionWrapper(F('opening_stock') + F('stock_in_sum') - F('stock_out_sum'), output_field=DecimalField()) ) and class StockByDateForm(forms.Form): date = forms.DateField(required=True, input_formats=['%Y-%m-%d',], widget=forms.DateInput(attrs={'class': 'datepicker'})) class Meta: fields = ['date'] … -
Django authentication issues
I run an ecommerce website on Django 2.1.0 I have some user session issues. My checkout process is like so : - Cart - Delivery Info - Summary - Leaving the site for the bank for payment - "Notification" Bank send a post resquest with payement informations - If everything ok we redirect user to /confirmation Problem is I noticed that users are no more logged in in "Notification" step. On this step I have the decorator @login_required. So it redirects user to /my-account/login?next=/notification By the time user get redirected, he is logged in again. So is redirected back to /my-account/ and never visit /confirmation page. The question is, why my user is disconnected on notification. This setup use to work well for months. I suspect django update from 1x to 2x ? Is there known issue with session ? -
Nginx doesn't serve media files
I've deployed Django project using Nginx web server, but on the website, only static files are displaying correctly. When I try to access a particular media file using website.com/media/file_name it throws an error Not found. The requested URL /media/dress.png was not found on this server. Here's my settings.py file import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') KEY_DIR = os.path.join(BASE_DIR, 'etc') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ with open(os.path.join(KEY_DIR, 'secret_key.txt')) as f: SECRET_KEY = f.read().strip() # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [ '*', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks', 'endless_pagination', 'catalog', 'like', ] 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', ] ROOT_URLCONF = 'bride.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR, ], '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', 'like.context_processors.like', ], }, }, ] WSGI_APPLICATION = 'app_name.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'bride_db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, … -
using moto s3 with django test client to test a http redirect to an s3 presigned url
I'm trying to provide a redirect to an s3 presigned url generated via boto3, it looks like it should work but I want to write a testcase for it. I've checked with something similar to what's below. The test_redirect_to_presigned_url() fails with a test_bucket/testfile.png not found. While the test_motos3_presigned_url works as expected. from django.test import TestCase from django.test import Client class MotoS3TestCase(TestCase): def setUp(self): self.mock = mock_s3() self.mock.start() self.bucket_name = 'test_bucket' self.conn = boto3.resource('s3') self.conn.create_bucket(Bucket=self.bucket_name) self.s3 = boto3.client('s3') def tearDown(self): self.mock.stop() def test_redirect_to_presigned_url(self): client = Client() response = client.get('/url/to/view/', follow=True) self.assertTrue(response.status_code == 200, f'response: {response}, response.content: {response.content}') def test_motos3_presigned_url(self): keyname = 'testfile.png' self.s3.upload_fileobj(io.BytesIO(b'somefile content'), self.bucket_name, keyname) params = { 'Bucket': self.bucket_name, 'Key': keyname, } presigned_url = self.s3.generate_presigned_url( ClientMethod='get_object', Params=params, ExpiresIn=3600, HttpMethod='GET' ) import requests response = requests.get(presigned_url) self.assertTrue(response.status_code == 200, f'response: {response}, response.content: {response.content}') views.py import boto3 from django.http import HttpResponseRedirect def redirect_to_presigned_url(request): s3 = boto3.client('s3') keyname = 'testfile.png' self.s3.upload_fileobj(io.BytesIO(b'somefile content'), self.bucket_name, keyname) params = { 'Bucket': self.bucket_name, 'Key': keyname, } presigned_url = self.s3.generate_presigned_url( ClientMethod='get_object', Params=params, ExpiresIn=3600, HttpMethod='GET' ) return HttpResponseRedirect(redirect_to=presigned_url) It appears that moto doesn't integrate well with the django test client. Is there a good why I can create a testcase to check this redirect? -
Celery is not auto-discovering shared tasks in other modules
I am trying to use celery w/ Django and not getting very far. I am also using django-celery-beat. I don't seem to be discovering the shared tasks in other modules. Here is some code: proj/proj/settings.py: INSTALLED_APPS = [ "django_celery_beat", "proj", "myapp", ] CELERY_BROKER_URL = "amqp://user:password@localhost:5672/vhost" proj/proj/__init__.py: from proj.celery import app as celery_app __all__ = ('celery_app',) proj/proj/celery.py: import os from celery import Celery from django.conf import settings if not settings.configured: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') proj/app/tasks.py: from celery import shared_task @shared_task def add(x, y): return x + y When I look at the admin interface for django-beat I only see the "proj.celery.debug_task" and not "myapp.tasks.add" Any ideas why? -
Retrieve Django hidden MultipleChoice form field value
I have a ModelForm like this: class MyForm(forms.ModelForm): many_keys = forms.ModelMultipleChoiceField(OtherModel.objects.all(), required=False, widget=forms.HiddenInput) # i set this input as hidden class Meta: model = MyModel fields = '__all__' def clean(self): cleaned_data = super().clean() print(self.data.getlist('many_keys')) # ['[1411, 1412, 1413..'] When i use this form to update the model, the many_keys is already populated with previous value, but unlike the non hidden field, getlist return the value as a list of 1 string, instead of returning a list of primary keys. In fact, in the HTML, the hidden field is represented like this, wich may be the source of the problem <input type="hidden" name="many_keys" value="[1411, 1412, 1413, 1414, 1415, 1416, 1417, 1418, 1419, 1420]" id="id_many_keys" /> If i remove widget=forms.HiddenInput, all is fine and i get a proper list of primary keys. I found this behavior to be quite inconsistent, and i am searching a clean way to retrieve this value, if the field is hidden or not. -
Why does a Contact Form fail to work with jinja tags?
I can successfully create a contact form with Django (2.1). When I put the form tags inside with {% csrf_token %} inside a {% block content %}{% endblock %} in a html template, I cannot get the "success" page to "fire". Why would this happen when I use the jinja tags? Any advice appreciated! Middleware: 'django.middleware.csrf.CsrfViewMiddleware', urls.py from django.conf.urls import url, include from django.urls import path from . import views # from django.contrib.auth.views import login urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^$', views.about, name='about'), url(r'^$', views.howitworks, name='services'), url(r'^$', views.showroom, name='showroom'), url(r'^privacy/', views.privacy, name='privacy'), url(r'^terms-of-service/', views.tos, name='terms-of-service'), url(r'^contact/', views.emailView, name='contact'), # path('email/', views.emailView, name='email'), path('success/', views.successView, name='success'), ] views.py from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from django.core.mail import send_mail, BadHeaderError from .forms import ContactForm def index(request): return render(request, 'home/landing.html') def about(request): return render(request, 'home/landing#about.html') def howitworks(request): return render(request, 'home/landing#services.html') def showroom(request): return render(request, 'home/landing#portfolio.html') def privacy(request): return render(request, 'home/privacy.html') def tos(request): return render(request, 'home/terms-of-service.html') # def contact(request): # return render(request, 'home/contact.html') # def login(request): # return render(request, 'auth/account/login.html') # def signup(request): # return render(request, 'auth/account/signup.html')4 def emailView(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] subject … -
Query parameters in PUT call of APIClient
I have an API endpoint to which I want to make a PUT call which needs both a body and query parameters. I use Django's test client to call my endpoint in a test case (docs). I read in the documentation that for a GET call, query parameters are introduced using the argument data. I also read that for a PUT call, the argument data represents the body. I miss documentation how to add query parameters in a PUT call. In particular, this test case fails: data = ['image_1', 'image_2'] url = reverse('images') response = self.client.put(url, data=data, content_type='application/json', params={'width': 100, 'height': 200}) And this test case passes: data = ['image_1', 'image_2'] url = reverse('images') + '?width=100&height=200' response = self.client.put(url, data=data, content_type='application/json') In other words: is this manually URL building really necessary?