Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the best practice for retrieving data from backend and using them in frontend form using REST API? [closed]
I am developing a REST API for an application in Django. It's frontend is being created in AngularJS. In create forms, there are fields that are related fields. For example, if a Car model is related to Manufacturer model, I want to send the list of manufacturers from the backend while creating Car. But, the issue is there might be multiple relationships in Car model like MadeInCountry, Distributers, etc. Also, based on logged in users and other criteria, I want to send filtered objects to be displayed in the form. How do I accomplish this using REST APIs? I have come to two conclusions for achieving this: Send data to be populated in form using GET method of the Create API and ask frontend to call that API. Ask frontend to call list API of every related field and send filtered data to be used in the form. Which method should I use? Or, are there any more efficient and best practice for this? -
how to return json response from views.py instead of .html file in django
I am working on django project that is returning a template in its views.py with context as: return render_to_response('page.html', context) here context is a dictionary that is having keys and values from multiple model classes I need to just return the json response instead of html page. please help me out. -
Django: Receive data from form once
I don't know exactly how to name this question, but this is my problem. I have a calendar which behavior depends on get parameters. I have 2 basics GET params: month and year so it renders calendar for specific year and month. My problem: I need option to change month to next / previous. I can easily do that with JS using ajax, but now I want it to work for non-JS users as well. I tried: next_month / prev_moth GET param so I render calendar depending on that params, but here's the problem with this approach: if user refresh page, wrong calendar is rendered because refreshing is just repeating request so params will be saved so if user refresh page 10 times he will get calendar from 10 months before (if there is prev_month get param). I can't remove get params because QueryDict is immutable. -
How to pass image url to line_items.images field in Stripe API in django
In my project i'm trying to buy products and uses Stripe api for payment.So during payment time i would like to display product.name,product.price and product.image in the session. product.name and product.price works fine but instead of product.image alt section of the image (alt='product') is displaying. class in views.py class CreateCheckoutSessionView(View): def post(self, request, *args, **kwargs): product_id = self.kwargs['id'] product = cake_list.objects.get(id = product_id) YOUR_DOMAIN = 'http://127.0.0.1:8000' checkout_session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': 'usd', 'unit_amount': product.price*100, 'product_data': { 'name': product.name , 'images': [YOUR_DOMAIN +'/media/'+ str(product.image)], }, }, 'quantity': 1, }, ], mode='payment', success_url=YOUR_DOMAIN + '/myorders/', cancel_url=YOUR_DOMAIN + '/payment-cancelled/', ) return JsonResponse({ 'id' : checkout_session.id }) While printing product.image in console it displays the correct ImageField data which is images/filename.png. 'images' is the file which images are upload_to -
Problem locating media file using Django's static function in template
I am using Django 3.2 I am trying to integrate a blog app that has a slightly convoluted directory structure for its static assets. Here is the relevant part of the tree: Blog app static assets directory structure blog/static/blog/ ├── css │ ├── bona │ │ ├── comment.css │ │ ├── detail-page.css │ │ ├── prism.css │ │ ├── responsive.css │ │ ├── styles │ │ └── styles.css │ ├── common-css │ │ ├── bootstrap.css │ │ ├── fontawesome-free │ │ ├── ionicons.css │ │ ├── ionicons.min.css │ │ └── swiper.css │ └── tinymce │ ├── github.css │ └── tomorrow-night-blue.css ├── font │ ├── fontello.eot │ ├── fontello.svg │ ├── fontello.ttf │ ├── fontello.woff │ └── fontello.woff2 ├── fonts │ ├── Aileron │ │ ├── Aileron-Black.otf │ │ ├── Aileron-Bold.otf │ │ ├── Aileron-Heavy.otf │ │ ├── Aileron-Italic.otf │ │ ├── Aileron-Light.otf │ │ ├── Aileron-Regular.otf │ │ ├── Aileron-SemiBold.otf │ │ ├── Aileron-Thin.otf │ │ ├── Aileron-UltraLight.otf │ │ └── Gidole-Regular.ttf │ ├── Colaborate │ │ ├── ColabBol.otf │ │ ├── ColabLig.otf │ │ ├── ColabMed.otf │ │ ├── ColabReg.otf │ │ └── ColabThi.otf │ ├── ionicons.eot │ ├── ionicons.svg │ ├── ionicons.ttf │ ├── ionicons.woff │ ├── linea-basic-10.eot … -
filter ChoiceField dynamically based on another field
I have a Model Form that must be filled in by the user. in the form there are 3 drop-down menus (foreignkey in the model) which depend on each other. that is, when the user selects a value in the first field the results in the second must dynamically depend on that. i know i have to use ajax but i never used it and i don't know where to start I know that to filter I have to set the queryset e.g. form.fields['stabilimento'].queryset = Stabilimento.objects.filter(), but I don't know how to do it using ajax model.py class Ticket(models.Model): stabilimento = models.ForeignKey(Stabilimento, on_delete = models.RESTRICT) linea = models.ForeignKey(Linea, on_delete = models.RESTRICT) macchina = models.ForeignKey(Macchina, on_delete = models.RESTRICT) form.py class NewTicketForm(forms.ModelForm): class Meta: model = Ticket fields = '__all__' -
How to send iframe via Django email?
I have a HTML template of my e-mail message with embded google map, via iframe. How can I send email with iframe integration in django? -
How can a fill table with database query
Hello I want that when I select a div with certain data it is filled by taking the date of the data of the div. I hide select if is not selected but i do with js you can see the picture here: image I want to get this value before load a template for q in qs: rec_sistrade = q.rec_sistrade emp = request.user.user_sistrade ## sentencia = "exec [Empresa].[dbo].[PT_GET_ORDENES]" + str(rec_sistrade) + "," + emp cursor.execute(sentencia) results = namedtuplefetchall(cursor) order= "'FSAFSF'" (replace getting selected order) sentencia2 ="exec [Empresa].[dbo].[PT_GET_ORDENES_EVENTOS]" + str(rec_sistrade) + "," + emp + "," + op ## html <select id="select" class="form-control" name="select"> <option readonly selected>SELECCIONA UNA OPCI&Oacute;N</option> <option value="div1">{{ results.1.op_ser_codigo }}{{ results.1.op_num_codigo }} / ({{ results.1.data_ini }} - {{ results.1.data_fim }})</option> <option value="div2">{{ results.2.op_ser_codigo }}{{ results.2.op_num_codigo }} / ({{ results.2.data_ini }} - {{ results.2.data_fim }})</option> </select> <div id="div1"> <b><p class="black">ORDEN: </b><input type="text" class="sinborde date_tr" name="orden1" value="{{ results.1.orden }}" readonly/> </p> <b><p class="black">OP: </b><input type="text" class="sinborde" name="op1" value="{{ results.1.op_ser_codigo }}{{results.1.op_num_codigo}}" readonly/> </p> <b><p class="black">FECHA INICIO: </b><input type="text" class="sinborde date_tr" name="fecha_ini_1" value="{{ results.1.data_ini }}" readonly/> </p> <b><p class="black">FECHA FINAL: </b> <input type="text" class="sinborde date_tr" name="fecha_fin_1" value="{{ results.1.data_fim }}" readonly/> </p> <b><p class="black">CLIENTE: </b></p> <b><p class="black">ART&Iacute;CULO: </b><input type="text" class="sinborde date_tr" name="articulo1" … -
How to call model in Django
I'm writing a project with Django that can manage citizens with their passports. But today when I created an HTML page to represent the database, I have encountered an error. My purpose of this webpage is show to user the info includes (citizen name, citizen sex, the birthday of citizen, passport type, passport number, and valid time of citizen's passport). All of citizen information, I have put in Citizen table. With passport of citizen, I have put in Passport table. The HTML page have represented all the information of Citizen table, but cannot represent informations in Passport table and I don't know why. I don't know what I have wrong. Here is my code: models.py class Passport(models.Model): Number = models.CharField(max_length=8, default=1) pType = models.CharField(max_length=1) validTime = models.DateField() pLocation = models.ForeignKey(Manager, on_delete=models.CASCADE, null=True, default=None, related_name="passport", ) def __str__(self): return f"{self.Number} ({self.pType})" class Citizen(models.Model): sID = models.OneToOneField( Passport, on_delete=models.CASCADE, default=1, ) name = models.CharField(max_length=64) sex = models.CharField(max_length=1) year = models.DateField() code = models.BigAutoField(primary_key=True, default=None) def __str__(self): return f"{self.name} ({self.sex})" urls.py from django.urls import path from . import views app_name = 'citizens' urlpatterns = [ path("", views.index, name="index", ), path("<int:citizen_id>", views.citizen, name="citizen"), path("<int:citizen_id>/passport", views.passport, name="passport") ] views.py from django.shortcuts import render from django.http … -
view count increase in DRF
I need to increase the view count with 1 on each refresh. I'm not sure about the method since I'm new to DRF. Thanks in advance. models.py class Module(models.Model): name = models.CharField(max_length=250, default="") view_count = models.IntegerField(default=0) serializers.py class ModuleSerializer(serializers.ModelSerializer): class Meta: model = Module fields = "__all__" views.py class ModuleView(generics.ListAPIView): queryset = Module.objects.all() serializer_class = ModuleSerializer def get(self, request): obj = self.get_object print(obj) obj.view_count = obj.view_count + 1 obj.save(view_count="view_count") return super().get(request) -
How to search models Django
Given: the id of the contract (eg 32812) get from the objects of the credit application model (!!!) unique id manufacturers of all goods that are associated with this contract in the performance of try to minimize the reference to the database class Credit(models.Model): """ Кредитная заявка. Только один контракт но несколько товаров """ name_credit = models.TextField(max_length=200, verbose_name='name_credit',null=True) contract = models.ForeignKey('Contract', verbose_name='contract', related_name='contract', on_delete=models.CASCADE) # product = models.ForeignKey('Product', # verbose_name='product', # related_name='product', # on_delete=models.CASCADE) date = models.DateField(verbose_name='date', blank=True, null=True) def __str__(self): return "%s" % self.name_credit class Meta: verbose_name = 'Кредитная заявка ' verbose_name_plural = 'Кредитные заявки' class Contract(models.Model): """ Контракт связан с кредитной заявкой """ #product = models.ForeignKey('Product', on_delete=models.CASCADE, related_name='product', null=True) contracts = models.TextField(max_length=200, verbose_name='contracts') date = models.DateField(verbose_name='date', blank=True, null=True) credit = models.ForeignKey(Credit, on_delete=models.CASCADE, null=True, blank=True,related_name='credit') manufacturer = models.ForeignKey('Manufacturer', on_delete=models.CASCADE, null=True) def __str__(self): return "%s" % self.contracts class Meta: verbose_name = 'Контракт ' verbose_name_plural = 'Контракты' class Product(models.Model): """ Товар имеет только одного производителя """ credit = models.ForeignKey(Credit, on_delete=models.CASCADE, null=True, blank=True) products = models.TextField(max_length=100, verbose_name='products') manufacturer = models.ForeignKey('Manufacturer', on_delete=models.CASCADE, related_name='manufacturer', null=True, blank=True) def __str__(self): return "%s" % self.products class Meta: verbose_name = 'Товар' verbose_name_plural = 'Товары' class Manufacturer(models.Model): """ Производитель производит только один продукт """ name = models.TextField(max_length=200, verbose_name='name') #product … -
Print subprocess stdout line by line in real time in Django StreamHttpResponse
I wrote an API in Django. It runs a shell script in the server and prints some logs. When the clients calls the API in the browser, I want the browser to print the logs line by line. So far, the snippet is like: from django.http import StreamingHttpResponse import subprocess import shlex def test(request): cmd = 'bash test.sh' args = shlex.split(cmd) proc = subprocess.Popen( args, cwd='/foo/bar', shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) return StreamingHttpResponse( (line for line in iter(proc.stdout.readline, '')), content_type="text/plain", ) And test.sh is like #!/bin/bash echo hello sleep 1 echo world sleep 1 echo love sleep 1 echo and sleep 1 echo peace sleep 1 The logs are not printed until bash test.sh is finished. How can I make it print the logs as if test.sh is run in the client? I'm using Python 2.7 and Django 1.11.29. I know they are old, but I still have to use them now. Thanks for help. -
How to change the value of a boolean in a model after a certain period of time in django?
I'm building a rental application in Django which has a boolean field rental_status. rental_status = models.BooleanField(default = False) rental_status describes if the product is already rented or is available to rent. the default value is true i.e is available for rent. Consider a situation where a person rents out the product for x amount of time and we change the rental_status to false. So, My question is how can we change rental_status to true after x time so that it can be rented again. (I understand if my way of implementation is not good or ideal but it is just for a project. Please suggest if there are any other better implementations) -
Why set value on select option from django form not work?
I have codes in django template like this <label for="exampleFormControlInput1" class="form-label text-primary">Jenis Kelamin</label> <div class="input-group mb-3"> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="jenis_kelamin_radio" id="inlineRadio1" value="laki-laki"> <label class="form-check-label" for="inlineRadio1">Laki-Laki</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="jenis_kelamin_radio" id="inlineRadio2" value="perempuan"> <label class="form-check-label" for="inlineRadio2">Perempuan</label> </div> </div> call django form which widget is select {{ peserta_form.jenis_kelamin }} and Jquery code like this <script> $(document).ready(function(){ $('input:radio[name="jenis_kelamin_radio"]').change(function(){ if($(this).val() == 'laki-laki'){ $('#jenis_kelamin').val("Laki-Laki").change(); } else if($(this).val() == 'perempuan'){ $('#jenis_kelamin').val("Perempuan").change(); } }); }); </script> but not work, please help. thanks -
Django Rest framework how to create Family and assign members to that family while assigning roles to each member
I have my parishioner model like below (Only pasting relevant CODE) class Parishioner(models.Model): family = models.ForeignKey(Family, null=True, on_delete=models.PROTECT, related_name='members') role = models.ForeignKey(FamilyRole, null=True, blank=True, on_delete=models.PROTECT, related_name='role') Parishioner can have one Family and One role in that family So I'm trying to achieve this in my Family Serializer. class FamilySerializer(serializers.ModelSerializer): members = serializers.PrimaryKeyRelatedField( many=True, queryset=Parishioner.objects.all(), allow_null=True, required=False ) class Meta: model = Family fields = ('id', 'name', 'address', 'monthly_contribution', 'members', 'enabled') read_only_fields = ('id',) depth = 1 As you can see above I can clearly assign members to that Family. But I want to assign roles to Each family member as well. How can I do that in Django ? Examples for FamilyRole: Father, Mother, son, daughter My front end will be similar to this in my Create Family page (and I expect to send only one request to server to achieve this by using api/family/ endpoint) Simply I want to, Create a Family, Assign Members(Parishioners) to that Family, Assign Role to each of those Member(Parishioner), Through api/family/ endpoint. What is the best way to achieve above ? -
Get Local vars in Django
is there a way to print the Local Vars of the view in the template, like the one shown in the error page of django? I need it to be able to quickly see the contents of the variables during the debug and test phases like this -
Creating two different profiles in one application
I am building a BlogApp App and I have two different sections, One is Blog Section and another is Article Section. AND i am trying to create two different profiles for them. When a user register or signup then a Profile is successfully creating for Blog Section ( NOT Article section ). BUT i am trying to do :- When user click on Article section after signup then there will be option of creating another Profile for Article Section and both will be different profile. ( AND there will be no relation between Blog Profile and Article Profile BUT user will same ) Blog Profile is successfully creating BUT I am trying to make Article Profile. models.py class ArticleProfile(models.Model): user = models.ForeignKey(User,default='',null=True,on_delete=models.CASCADE) full_name = models.CharField(max_length=30,default='') views.py def create_profile(request): if request.method == 'POST': form = ArticleProfileForm(request.POST,request.FILES,instance=request.user) if form.is_valid(): custom_form = form.save(False) custom_form.save() messages.success(request, "Article Profile is Created") return redirect('dating:DatingSection') else: form = ArticleProfileForm(instance=request.user) context = {'form':form} return render(request, 'dating/create_profile.html', context) BUT when i create profile using this form then it is not saving in Admin. Any help would be Appreciated. Thank You in Advance. -
Django real time applications
is there a way to make real time applications in Django other than channels? I can't understand it and even copying the code isn't enough to make it work, is it possible to use react js to make chat app and integrate it into Django project? I really need to learn building real time applications but I can't find a tutorial -
Why is Docker not picking up code changes, despite 'prune all', 'build no cache' and then 'up force recreate'?
I'm dockerising a django app (webapp). However, when I make code changes they do not seem to be reflected when the container is rebuilt. I'm trying to test that I can hit 'app' but the name has changed to 'newapp'. testcase.py from django.test import TestCase import requests class TestServerUp(TestCase): def testhitendpoint(self): r = requests.get(host='app', port=1234) self.assertEquals(r.status_code, 200) Running the command sudo docker exec -it webapp python manage.py test tests.testcase fails because host should be 'newapp' requests.exceptions.ConnectionError: HTTPConnectionPool(host='app', port=1234): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fd97d430550>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')) I change the test case to: from django.test import TestCase import requests class TestServerUp(TestCase): def testhitendpoint(self): r = requests.get(host='newapp', port=1234) self.assertEquals(r.status_code, 200) I bring the containers down: sudo docker-compose -f ./deploy/docker-compose.yaml down I remove the containers from docker: sudo docker system prune --all --volumes -f, then sudo docker rm -f $(sudo docker ps -aq) just to be sure. I rebuild the containers: sudo docker-compose -f ./deploy/docker-compose.yaml build --no-cache I then spin the containers up: sudo docker-compose -f ./deploy/docker-compose.yaml up --force-recreate -d I run the tests again: sudo docker exec -it webapp python manage.py test tests.testcase (or sudo … -
Django forms difference, one works, the second one doesn't
I've got a kind strange problem. I've got two different (but almost the same forms and validation). The validation in first one works, in the second one doesn't. Can someone tell me why? 1) class SignUpForm1(forms.Form): test_value = forms.CharField( label='Your name', max_length=100, widget=forms.TextInput(attrs={'class': "input"}) ) def clean_test_value(self): data = self.cleaned_data.get('test_value') if data != "abc": raise forms.ValidationError("Error") return data class SignUpForm2(forms.Form): name = forms.CharField( label='name', max_length=100, widget=forms.TextInput(attrs={'class': "input"}) ) def clean_name_value(self): data = self.cleaned_data.get('name') if data != "abc": raise forms.ValidationError("Error") return data -
Django Models: Accessing Parent Object Attribute Within a Related Object Using OneToOneField
I am trying to access the username attribute of a Django User object from a Profile object that is related by a OneToOneField. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) username = models.TextField(default=user.username, primary_key=True) image = models.ImageField(upload_to='images/profile') header = models.CharField(max_length=64) slug = AutoSlugField(populate_from='x') bio = models.CharField(max_length=300, blank=True) The intent of this is to be able to get a Profile object using a ReactJS frontend by passing the username provided at login back to a profile detail endpoint in a Django API, where the username is the primary key for the endpoint. path('<pk>/profile/', ShowProfilePageView.as_view(), name='show_profile_page'), I've tried many different things for the default argument passed to the Profile username attribute, but nothing is working so far. Is this even possible? -
Request always returns unauthorized sent from React-Native to Django
i am trying to send a get request from my react-native app to a django api but i always get the error {"detail":"Authentication credentials were not provided."}. but when i try this same request on postman everything works, i tried getting the code from postman itself and copied it to my react-native app but its the same unauthorized error this is the code generated from the above postman request and i copy and pasted directly to my react-native app and it throws the above unauthorized message. also tried the generated code from postman for curl and it works, Please let me know what i am missing here var myHeaders = new Headers(); //you can assume the token is correct myHeaders.append("Authorization", "Token f38be1f33dbb5d6004108990a0a76"); var requestOptions = { method: 'GET', headers: myHeaders, redirect: 'follow' }; fetch("https://base_url/api/v1/endpoint", requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); -
Django incorrect padding
so when I was creating my site and finished the frontend I wanted to open the admin dashboard and tada Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 3.0.14 Python Version: 3.6.8 Installed Applications: ['jazzmin', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main'] Installed 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'] Traceback (most recent call last): File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\sessions\backends\base.py", line 199, in _get_session return self._session_cache During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred: File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\sites.py", line 249, in wrapper return self.admin_view(view, cacheable)(*args, **kwargs) File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\sites.py", line 220, in inner if not self.has_permission(request): File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\sites.py", line 194, in has_permission return request.user.is_active and request.user.is_staff File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 224, in inner self._setup() File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 360, in _setup self._wrapped = self._setupfunc() File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\middleware.py", line 24, in <lambda> request.user = SimpleLazyObject(lambda: get_user(request)) File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\middleware.py", line 12, in get_user request._cached_user = auth.get_user(request) File "C:\Users\mohamd\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\__init__.py", line 173, … -
Django IntegrityError UNIQUE constraint failed: plans_customer.user_id
I have a problem with my checkout view. After I added user verification via email, I am geting integrity error. I would like to know how to solve this issue. I have alredy checked some of the solutions from the internet but none of them works for me. Some basic info: Request Method: POST Request URL: http://127.0.0.1:8000/checkout Django Version: 2.2.3 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: plans_customer.user_id Here is my checkout view: @login_required def checkout(request): try: if request.user.customer.membership: return redirect('settings') except Customer.DoesNotExist: pass coupons = {'bank':25, 'city':25} if request.method == 'POST': stripe_customer = stripe.Customer.create(email=request.user.email, source=request.POST['stripeToken']) plan = 'price_1IC3TwL0fAQS9DO5lqZSmcew' if request.POST['plan'] == 'yearly': plan = 'price_1IC3TwL0fAQS9DO5IKzHz5ZI' if request.POST['coupon'] in coupons: percentage = coupons[request.POST['coupon'].lower()] try: coupon = stripe.Coupon.create(duration='once', id=request.POST['coupon'].lower(), percent_off=percentage) except: pass subscription = stripe.Subscription.create(customer=stripe_customer.id, items=[{'plan':plan}], coupon=request.POST['coupon'].lower()) else: subscription = stripe.Subscription.create(customer=stripe_customer.id, items=[{'plan':plan}]) customer = Customer() customer.user = request.user customer.stripeid = stripe_customer.id customer.membership = True customer.cancel_at_period_end = False customer.stripe_subscription_id = subscription.id customer.save() msg_plain = render_to_string('mails/email.txt') msg_html = render_to_string('mails/email.html') subject = 'Welcome to J & M Traders' recepient = str(request.user.email) send_mail(subject, msg_plain, EMAIL_HOST_USER, [recepient], html_message=msg_html) return redirect('home') else: coupon = 'none' plan = 'monthly' price = 9999 og_dollar = 99.99 coupon_dollar = 0 final_dollar = 99.99 if request.method == 'GET' and 'plan' … -
Unexpected aguments when saving a form in Django
I am trying to save form data using Django. My app is a very basic car maintenance app I am creating to learn Django. Here is my Views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.http import HttpResponse from service.models import Service from service.forms import oil_change # Create your views here. @login_required(login_url='/login/') def service(request): obj = User obj = Service.objects.filter(user=request.user) temp = list(Service.objects.all()) print("here") if temp: result = temp[0] return render(request, 'serviceT/service.html', {'object': obj, 'result': result}) return render(request, 'serviceT/service.html', {'object': obj}) @login_required(login_url='/login/') def update_miles(request): obj = User obj = Service.objects.filter(user=request.user) context = {'object': obj} if (request.method == 'POST'): Service.objects.all().delete() form = oil_change(request.POST) if (form.is_valid()): miles = form.cleaned_data["miles"] last_change = form.cleaned_data["last_change"] reminder = form.cleaned_data["reminder"] next_change = reminder + miles oil_change(user=request.user, miles=miles, last_change=last_change, reminder=next_change).save() return render(request, 'serviceT/service.html', context) else: form = oil_change() return render(request, 'serviceT/miles.html', {'form': form}) The issue in on the line where I try to save the form. oil_change(user=request.user....) Here is my forms.py and models.py from django import forms from django.core import validators from django.forms import ModelForm from service.models import Service class oil_change(forms.ModelForm): class Meta: model = Service fields = ['miles', 'last_change', 'reminder'] widgets = { 'miles': forms.NumberInput(), 'last_change': forms.NumberInput(), 'reminder': forms.NumberInput() } from …