Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
File not found error when using python to execute shell command to generate PDF
I am using PhantomJS to generate a PDF from an HTML file Django Templates generate an HTML file The html file is stored in a temp folder The phantomjs command is executed via os.system() or subprocess.call() command and is expected to generate a PDF file. The phantomjs command is working fine in two conditions: When run directly on the shell. When run via an API call However the requirement is to make it run via a cron job and that is where it throws the following error: Traceback (most recent call last): File "/home/ubuntu/reniso/reniso_django/inspections/cron.py", line 105, in do if ZInspectorReportGenerator(inspection_id).generate_inspection_report(): File "/home/ubuntu/reniso/reniso_django/inspections/inspection_report.py", line 213, in generate_inspection_report s3_config_type='inspection_reports').generate_pdf() File "/home/ubuntu/reniso/reniso_django/django_fiblabs/html_to_pdf/transform.py", line 24, in generate_pdf html_path_name=html_path_name) File "/home/ubuntu/reniso/reniso_django/django_fiblabs/html_to_pdf/transform.py", line 93, in convert_html_to_pdf result = subprocess.check_output(conversion_command) File "/usr/lib/python3.6/subprocess.py", line 336, in check_output **kwargs).stdout File "/usr/lib/python3.6/subprocess.py", line 403, in run with Popen(*popenargs, **kwargs) as process: File "/usr/lib/python3.6/subprocess.py", line 709, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.6/subprocess.py", line 1344, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: 'phantomjs html_to_pdf.js rp1001151_24_08_2018_inspection.html rp1001151_24_08_2018_inspection.pdf': 'phantomjs html_to_pdf.js rp1001151_24_08_2018_inspection.html rp1001151_24_08_2018_inspection.pdf' The exact same command is working via the shell, it is working via an API call as well but not through the cron job. I … -
Django Page not found error event if path is correct
I'm new to Django framework using 2.1 version, I have trouble using optional parameters in urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('myapp/', include('myapp.urls')), path('myblog/', include('myblog.urls')), path('admin/', admin.site.urls), ] Appname : myblog urls.py from django.urls import include, path, re_path from django.contrib import admin from . import views app_name = 'myblog' #FOR NAMESPACE ISSUE THIS IS REQUIRED urlpatterns = [ re_path(r'^test_view/<mode>/(?:blog-(?P<blog_id>\d+)/)?$', views.test_view) ] myblog view.py def test_view(request, mode, blog_id): return HttpResponse('ss') myblog template <button type="button" class="btn-xs btn-primary" onclick="location.href='{% url 'myblog:test_view' 'create' 1 %}'">Create New Blog</button> ERROR IN TEMPLATE : NoReverseMatch at /myblog/ Reverse for 'test_view' not found. 'test_view' is not a valid view function or pattern name. ADD WHILE ACCESSING URL DIRECTLY http://127.0.0.1:8000/myblog/test_view/create/1/ I GET PAGE NOT FOUND IT IS TO BE NOTED THAT AS PER THE DOCUMENTATION GIVEN IN DJANGO DOCUMENTATION I HAD MAKE SAME CHANGES BUT STILL I GET THAT ERROR THANKS IN ADVANCE. -
Django; Images cannot be shown up suddenly
I've been working on Django project. I'm working on local environment. The images cannot be shown up at all suddenly even though I didn't change code at all since last time I worked on. (yesterday) I have no idea what is happening. On the page, all the images are like this. On command line, every status is 200 as usual. And even jquery and bootstrap cannot work well sometimes today. How can I handle with this kind of thing? The images are shown up now. But I didn't change code at all. I just run server again and again. What is the problem of this kind of thing and how can I prevent this? -
how to issue invoice automatically to the user in razorpay if payment is completed
I am using razorpay as the payment gateway for my django application.When a payment is completed,I want to create invoice automatically with invoice number and GST details and send invoice to the customer through email.Here I found only manual method to create invoice.Is there any possible way to create invoice automatically? -
Is there a better way to implmenet custom feildsets in django admin
We are adding customized feildsets in admin form to display and save video credits. here is where we are adding feildsets. def get_fieldsets(self, request, obj=None): fieldsets = super(CreditsAdminMixin, self).get_fieldsets(request, obj=None) for category in CreditCategory.objects.all().order_by('name'): fields = [] for field in category.fields.all().order_by('name'): field_name = "credit_%s_%s" % (slugify(category.name), slugify(field.name)) fields.append(field_name) self.exclude += (field_name, ) fieldsets.append((category.name, {'fields': fields})) return fieldsets CreditCategory is the category for each credit. feilds are the names of every feild in it to which user enters a value. example: here is the code to render the form above way: def __init__(self, *args, **kwargs): super(CreditsFormMixin, self).__init__(*args, **kwargs) self.helper_credits = FormHelper() self.helper_credits.form_tag = False fieldsets = [] for category in CreditCategory.objects.all(): fields = [] for field in category.fields.all(): field_name = "credit_%s_%s" % (slugify(category.name), slugify(field.name)) self.credits_keys.append({"key":field_name,"value":field}) initial = None if self.instance.pk: try: initial = str(self.instance.credits.get(field=field)) except Credit.DoesNotExist: pass except Credit.MultipleObjectsReturned: pass self.fields[field_name] = forms.CharField(label=field.name, initial=initial,max_length=255, required=False, validators=[validate_credit_field]) fields.append(Field(field_name)) fieldsets.append(CollapsibleFieldset(category.name, ColumnFields(*fields))) self.helper_credits.layout = Layout(*fieldsets) And here where we save credits: def save_credits(self): instance = self.instance for field in CreditField.objects.all(): name = self.cleaned_data["credit_%s_%s" % (slugify(field.category.name), slugify(field.name))] if name: credit = instance.credits.filter(field=field).first() if credit: credit.name = name credit.save() else: credit = instance.credits.create(field=field, name=name) else: instance.credits.filter(field=field).delete() This works fine up until few weeks ago. But, Now, … -
How to set fields in Forms Django?
I want filter a choice in a form according FK ou User_logged. Here is my models. #models.py class Store(models.Model): name = models.CharField(max_length=64, unique=True) description = models.TextField(null=True, blank=True) class StoreManager(models.Model): store = models.ForeignKey(Store, related_name='store', on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) class StoreLogo(models.Model): store = models.ForeignKey(Store, related_name='store', on_delete=models.CASCADE, verbose_name='Store') image = photo = models.FileField() For example, I'm in View ListStore, seeing informations about Store - Clothes, and there is a Forms for StoreLogo. In the forms I want the field store get Store - Clotes, because I'm in View Store in object Store - Clothes. I'm using CBV now TemplateView(for a personalized form) or CreateView(default Forms). Anyone can help me? -
Cannot get Django ModelAdmin.get_urls() to work
I am trying to create custom views for my models in Django admin site. I created ModelAdmin for my model named Document like this: from django.http import HttpResponse from django.urls import path from django.contrib import admin from my_app.models import Document @admin.register(Document) class DocumentAdmin(admin.ModelAdmin): def get_urls(self): urls = super().get_urls() custom_urls = [ path('my-view/', self.admin_site.admin_view(self.my_view)) ] return urls + custom_urls def my_view(self, request): return HttpResponse('test') According to the docs I should be able to access my_view with /admin/my_app/document/my-view but when I try to visit this URL django redirects me to admin homepage with the following warning: Document with ID "my-view" doesn't exist. Perhaps it was deleted? So it looks like django cannot see my custom url. What am I missing? How can I get this to work? -
Auto-update the models fields in django
models.py STATUS_CHOICES = (('0', 'Rejected'),('1', 'Accepted'),) class Orders(models.Model): customer_id = models.CharField(max_length = 20) name = models.CharField(max_length = 20) user = models.ForeignKey(User, on_delete = models.CASCADE, null =True) status = models.CharField(max_length = 15, choices = STATUS_CHOICES) quantity = models.IntegerField() quantity_left = models.IntegerField(default=10, blank=True, null=True) I'm working on customer - seller project, where a customer orders and seller either accepts or rejects the order. In the above model, the quantity left should be equal to quantity_left - quantity upon accepting the order. This field quantity_left should auto update(decrease) by quantity each time the customer orders with a particular quantity. forms.py class OrderForm(ModelForm): class Meta: fields = ("customer_id", "name", "status", "quantity") -
Receiving 404 Error in Heroku with Django-Tenants with Wildcard CNAME
Posting code momentarily I have a really weird situation I cannot seem to figure out. I have not touched my implementation of this package since the beginning of the year and now the functionality ceases to exist on my live heroku server. I currently have a Create Account form on my public tenant which generates a tenant/domain just as the docs do and django-tenants does its auto schema generation. This works correctly on my localhost and have zero problems. However on my live server, I proceed to get a 404 error... Not Found...The requested URL / was not found on this server. I have a CNAME record on DNSimple which points to a wildcard domain that appears to be working, because I have already have a tenant I made awhile ago that is still completely functional (ie. some-customer.mydomain.com). I have looked into my PSQL db attached to heroku and everything is there as it should be, as well as the migrations occurring in the logs when I create an account which generates a tenant. I was hoping that there might be some enlightenment as to what I am doing/have done wrong to make this issue occur. It just … -
How add a stripe form to a existing Django model form
I have a verification model, where a user has to fill in some details and pay a charge to get verified. I need to add a stripe payment form to this, such that unless the user pays the form does not submit. How do I achieve this Below are my models.py class Verification(models.Model): user = models.ForeignKey(User, related_name='verified') dob = models.Datefield() government_id = models.ImageField() verify = models.BooleanField(default=False) deny = models.BooleanField(default=False) agree_terms = forms.BooleanField(required=True) Below is my model form class VerificationForm(forms.ModelForm): agree_terms = forms.BooleanField(required=True) class Meta: model = Verification fields = ('dob', 'government_id', 'agree_terms') Below is the template of my django form <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" value="Send" class="btn btn-success btn-sm" /> </form> Below is the stripe form <form action="" method="POST"> {% csrf_token %} <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="{{ data_key }}" data-amount="Some amount" data-name="Samir Tendulkar data-description="Verufication charge" data-image="{% static 'images/logo.png' %}" data-locale="auto" data-email="{{request.user.email}}" data-currency="usd" data-billing-address="true" data-zip-code="true"> </script> </form> How do I make it such that unless the user pays the form does not submit and finally my views.py class CreateApplication(LoginRequiredMixin, CreateView): model = Verification form_class = VerificationForm def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return redirect('verification:thanks') -
Django-comments-xtd returning error upon posting comment as authenticated user
I have django-comments-xtd installed as part of my django site to allow comments. At the moment, I just have it setup as per the documentation, and have not begun customizing. Making a comment as a guest works fine, however making a comment as an authenticated user generates an error (although the comment posts). The HTTP error is a 404 error, with the django error message being: "post page objects don't have a get_absolute_url() method" I'm not sure where to begin to troubleshoot that error. I can replicated the error clicking on the 'permananant link' for a comment, which I guess is what django-comments-xtd tries to redirect to. I am using django 1.11.13, python 3.6 and django-comments-xtd 2.1.0 -
Get scrapy result inside a Django view
I'm scrapping a page successfully that returns me an unique item. I don't want neither to save the scrapped item in the database nor to a file. I need to get it inside a Django view. My view is as follows: def start_crawl(process_number, court): """ Starts the crawler. Args: process_number (str): Process number to be found. court (str): Court of the process. """ runner = CrawlerRunner(get_project_settings()) results = list() def crawler_results(sender, parse_result, **kwargs): results.append(parse_result) dispatcher.connect(crawler_results, signal=signals.item_passed) process_info = runner.crawl(MySpider, process_number=process_number, court=court) return results I followed this solution but results list is always empty. Thanks! -
Get Django filter to acknowledge custom class
Suppose I have a DateTimeField in a model: class MyModel(Model): when = models.DateTimeField() I can do lookups against this field in the Django ORM using either strings or datetime.datetime instances: models.MyModel.objects.filter(when__gt='2018-09-02 19:00:00') # Works start = datetime.datetime(2018, 9, 2, 19, 0) models.MyModel.objects.filter(when__gt=start) # Also works I'd love to be able to have this type conversion "just work" for a custom DateTime class: class DateTime: def __init__(self, ...): # Init here start = DateTime(2018, 9, 2, 0, 0) models.MyModel.objects.filter(when__gt=start) # Throws a TypeError Is this possible? If so, what needs to be done? My custom class has a __repr__ and __str__ method defined, so I'm not sure what I'm missing. -
How to use bootstrap modal-dialog in django?
I am having a problem in using bootstrap modal-dialog in my Django template. When a user submits the form then the modal-dialog appear only for 2 seconds and redirect to the index.html file. This is my views.py file class RequestItem(generic.CreateView): model = UserNotification fields = ['Name', 'Mobile_No', 'Proof'] def get_form(self, form_class=None): if form_class is None: form_class = self.get_form_class() form = super().get_form(form_class) form.fields['Name'].widget = TextInput(attrs={'placeholder': '*Enter your name'}) form.fields['Mobile_No'].widget = TextInput( attrs={'placeholder': "*Enter your's mobile number to get a call back from angel"}) form.fields['Proof'].widget = TextInput(attrs={'placeholder': '*enter proof you have for your lost item'}) return form def form_valid(self, form): print(self.kwargs) self.object = form.save(commit=False) qs = Report_item.objects.filter(id=self.kwargs.get("pk")) self.object.user = qs[0].owner self.object.save() query_list = Report_item.objects.filter(publish=True) return render(self.request,"feed/index.html",{"object_list":query_list}) This is my form with the modal-dialog: <div class="thumbnail" style="padding-right:5%;"> <div class="thumbnail-center"> <font size="6"> <p>Please fill this form</p> </font> </div> <form class="form-herizontal" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% if form.errors %} <p>{{ form.errors }}</p> {% endif %} {% include 'feed/form_template.html'%} <br> <div class="row"> <div class="col-md-5"></div> <div class="col-md-7"> {% if user.is_authenticated %} <button type="submit" class="login-btn btn btn-success" data-toggle="modal" data-target="#myModal">Request to return</button> {% else %} <button type="submit" class="login-btn btn btn-success" disabled>Request to return</button> <p style="color:red;">*Please <a href="{% url 'login' %}">login</a>to request yout item</p> {% endif %} </div> … -
Cryptic Django CMS install error - what might be causing this error?
(env) Name-MacBook-Pro-2:site_cms name$ djangocms -f -p . site_cms Creating the project Please wait while I install dependencies If I am stuck for a long time, please check for connectivity / PyPi issues Dependencies installed Creating the project The installation has failed. ***************************************************************** Check documentation at https://djangocms-installer.readthedocs.io ***************************************************************** Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/bin/djangocms", line 11, in <module> sys.exit(execute()) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/djangocms_installer/main.py", line 44, in execute django.setup_database(config_data) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/djangocms_installer/django/__init__.py", line 407, in setup_database command, env=env, stderr=subprocess.STDOUT File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/subprocess.py", line 376, in check_output **kwargs).stdout File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/subprocess.py", line 468, in run output=stdout, stderr=stderr) subprocess.CalledProcessError: Command '['/Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7', '-W', 'ignore', 'manage.py', 'migrate']' returned non-zero exit status 1. I am following the instructions on this page: http://docs.django-cms.org/en/develop/introduction/01-install.html However I am unsure why it is not installing. Is there anyway to get more verbose data on the error? I'm trying to google each of these lines and nothing is consistent with the issue I am having. Could it be due to Python version? This is on OSX - High Sierra. Do I possibly need to do something to let Django CMS connect to my database? -
Django Rest Framework how to extend User table
I would like to extend User table using OneToOne relation. I did everything like in tutorials but I can't save properly data into database. Basic User data are ok (except password - it is not encrypted) but profile data is null. models.py from django.db import models from django.contrib.auth.models import User from apps.group.models import CommissionGroup from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(max_length=20) nick = models.CharField(max_length=50) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() serializers.py from rest_framework import serializers from .models import * class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('password', 'is_superuser', 'username', 'first_name', 'last_name', 'email') read_only_fields = ('id', ) class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('user', 'phone', 'nick') views.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.renderers import TemplateHTMLRenderer from rest_framework import status from django.shortcuts import redirect from .serializers import * from .models import * class UserForm(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'user/add.html' def get(self, request): group = CommissionGroup.objects.all() return Response({'all_groups': group}) def post(self, request): user_serializer = UserSerializer(data=request.user) profile_serializer = ProfileSerializer(data=request.user.profile) if user_serializer.is_valid() and profile_serializer.is_valid(): user_serializer.save() profile_serializer.save() return redirect('/user/add') return Response(status=status.HTTP_400_BAD_REQUEST) example fields in add.html … -
Django 2.0 save data from form to db (i see blank page)
When i fill form from http://127.0.0.1:8000/cockpit/professions/add_proffession the object it is not saved to the database and i am redirect to http://127.0.0.1:8000/cockpit/professions/ and i see blank page... when I come in directly to http://127.0.0.1:8000/cockpit/professions/, I see a list of everything what i add before from admin page... views @login_required def ProfessionsAddListView(request): if request.method == "POST": form = ProfessionsAddForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user_profile = request.user post.save() return redirect('cockpit') else: form = ProfessionsAddForm() return render(request, 'app/categories/announcementAdd.html', {'form': form}) @method_decorator(login_required, name='dispatch') class ProfessionsListView(ListView): model = Announcement template_name = 'app/cockpit/professions.html' def get_queryset(self): return Announcement.objects.filter(user_profile_id = self.request.user.profile) forms class ProfessionsAddForm(forms.ModelForm): class Meta: model = Announcement fields = ('title', 'price', 'description', 'subcategory', 'gpsLat', 'gpsLon') urls path('cockpit/professions/', app.views.ProfessionsListView.as_view(), name='professions'), path('cockpit/professions/add', app.views.ProfessionsAddListView, name='professions_add'), -
TypeError: super(type, obj): obj must be an instance or subtype of type?
Why am I getting this error? TypeError: super(type, obj): obj must be an instance or subtype of type This is my models.py file class UserNotification(models.Model): Name = models.CharField(max_length=250) Mobile_No = models.CharField(max_length=10, validators=[RegexValidator(r'^\d{1,10}$')]) Proof = models.TextField() viewed = models.BooleanField(default=False) user = models.ForeignKey(User) date = models.DateTimeField(default=timezone.now) def __str__(self): return self.Name class Meta: ordering = ["-date"] This is my views.py file class RequestItem(generic.CreateView): model = UserNotification fields = ['Name', 'Mobile_No', 'Proof'] def get_form(self, form_class=None): if form_class is None: form_class = self.get_form_class() form = super(UserNotification, self).get_form(form_class) form.fields['Name'].widget = TextInput(attrs={'placeholder': '*Enter your name'}) form.fields['Mobile_No'].widget = TextInput( attrs={'placeholder': "*Enter your's mobile number to get a call back from angel"}) form.fields['Proof'].widget = TextInput(attrs={'placeholder': '*enter proof you have for your lost item'}) return form def form_valid(self, form): print(self.kwargs) self.object = form.save(commit=False) qs = Report_item.objects.filter(id=self.kwargs.get("pk")) self.object.user = qs[0].owner self.object.save() return HttpResponse("<h1>Your request has been processed</h1>") I am using django 1.11. There was no error and code working properly until I add the placeholder function. After adding the placeholder I am getting this error. Please help me to resolve it. -
How do I filter Choice FK in Forms?
I want filter a choice in a form according user_logged. Here is my models. #models.py class Store(models.Model): name = models.CharField(max_length=64, unique=True) description = models.TextField(null=True, blank=True) class StoreManager(models.Model): store = models.ForeignKey(Store, related_name='productarea', on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) class StoreLogo(models.Model): store = models.ForeignKey(Store, related_name='store', on_delete=models.CASCADE, verbose_name='Store') image = photo = models.FileField() First I created a Store, after that I Associate a StoreManager to a Store, and then I want in a forms add a ImageLogo, so in that forms, in field Store, I want list only a Store what user has associated. Store = (SuperMarket Store), (ClothesStore) StoreManager = John(SuperMarket Store), Julian(ClothesStore) StoreLogo = John (can only view SuperMarket Sotre) StoreLogo = Julian(can only view ClothesStore) I'm using CBV(generic.CreateView). There is my views. #views.py class AddPhotoOnEstablishment(LoginRequiredMixin, generic.CreateView): model = StoreLogo fields = ['store', 'image'] success_url = reverse_lazy('register:establishment_list') context_object_name = 'object_name' I want, if John has associated to Store and logged in the system, when he add a Image logo, the field Store only appear the Store he has associated. Anyone can help-me? Thanks a lot friends. -
Django: python manage.py migrate --noinput
I am considering to add the command release: python manage.py migrate --no-input to my deployment, so Heroku is automatically migrating, once I push my repository. I now wonder if --no-input is a 'good' idea? One more specific question: If migrate normally asks me 'Did you rename this field'. With --no-input, will it answer automatically yes? I couldn't find much detailed information in the official Django documentation. -
Ovveride UserCreationForm errors message in django
Hi i extend UserCreationForm form and my new form is like: class create_user_form(UserCreationForm): email=forms.EmailField(label='ایمیل',widget=forms.EmailInput(attrs={'class':'form-control','placeholder':'user@mail.com',})) # username=forms.CharField(error_messages={'username': 'Please let us know what to call you!'},label='نام کاربری',widget=forms.TextInput(attrs={'class':'form-control','placeholder':'مثال : Mohammad',})) first_name=forms.CharField(label='نام',widget=forms.TextInput(attrs={'class':'form-control','placeholder':'نام واقعی',})) last_name=forms.CharField(label='فامیلی',widget=forms.TextInput(attrs={'class':'form-control','placeholder':'فامیلی واقعی',})) class Meta: model=User fields=['username','email','first_name','last_name'] def __init__(self,*args,**kwargs): super(UserCreationForm,self).__init__(*args,**kwargs) self.fields['username'].widget.attrs['class']='form-control' self.fields['username'].label='نام کاربری' self.fields['username'].help_text='' self.fields['password1'].widget.attrs['class']='form-control' self.fields['password2'].widget.attrs['class']='form-control' self.fields['password1'].label='رمز عبور' self.fields['password2'].label='تایید پسورد' self.fields['password1'].help_text='' self.fields['password2'].help_text='' So i ovveride labels and help_text of form inputs to my own language But i can't find a way to ovveride error message that occur when submitting form Also i have tried username=forms.CharField(error_messages={'username': 'Please let us know what to call you!'},label='نام کاربری',widget=forms.TextInput(attrs={'class':'form-control','placeholder':'مثال : Mohammad',})) But it dosen't work Can you help me to change error messages of form? -
Django Add Two Numbers
I am new to Django. I am having a hard time finishing this application. Overall, I am trying to have one form that accepts two different numbers and then adds those numbers together. This is what I have so far, but I know there must be errors somewhere. Also, I do not know what I need to return exactly. Any help would be greatly appreciated. Also, it would be nice to display the output on a new page. I assume I would accomplish this by adding another html file. However, could you please provide how this would be accomplished as well. forms.py: from django import forms class InputForm(forms.Form): x = forms.IntegerField(label='Enter first number: ') y = forms.IntegerField(label='Enter second number: ') views.py: from django.shortcuts import render from django.http import HttpResponse from .forms import InputForm def add(request): form = InputForm(request.POST or None) if request.method == 'POST': form = InputForm(request.POST or None) if form.is_valid(): cd = form.cleaned_data input1 = cd['x'] input2 = cd['y'] output = input1 + input2 return ??? else: form = InputForm() return render(request, 'addition/home.html') urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.add, name='addition-home'), ] home.html: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Home</title> … -
Django form submitted with ajax redirects to form action instead of calling success
I have simple form class TimeForm(forms.Form): time = forms.TimeField() date = forms.DateField() def clean_date(self): time = self.cleaned_data['time'] date = self.cleaned_data['date'] date_time = datetime.combine(date, time) if datetime.now() > date_time: raise ValidationError("datetime error") return start_date with class based view class TimeView(View): @staticmethod def post(request): form = TimeForm(request.POST) if form.is_valid(): # do something json_data = json.dumps({'some_record': value}) else: json_data = json.dumps({'errors': form.errors}) return HttpResponse(json_data, content_type='application/json') In html I have standard form with submit connected do ajax <form action="/time_url/" method="POST" id="time_form"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> <script> $('#time_form').submit(function(event) { event.preventDefault(); $.ajax({ type: "POST", url: '/time_url/', dataType: 'json', data: $(this).serialize(), success: function(data, textStatus, jqXHR){ alert('yay'); } }) }); </script> and I'd like to be able to submit this form without page reload. Everything seems to work perfectly but success function of ajax is not triggered, instead page is redirected to /time_url/ with json data. It doesn't matter wheter form is valid nor not, it's always redirected. I've tried also with return JsonResponse(form.errors.get_json_data()) instead of return HttpResponse(json_data, ...) as suggested here Django form submit with ajax but without success. I'm new to javascript but for me it looks like problem with ajax, since proper data is served by server. Thanks for … -
Representing the other side of a one-to-one relationship in a serializer
I have a one-to-one relationship set up between a User model, and a UserProfile model. The UserProfile model contains additional information about the user, and is created immediately after a User model saves. The OneToOne field is set on the UserProfile. The serialized User data appears fine when I access any of the views concering the UserProfile, but I would also like the UserProfile data to appear on User views, and I was wondering how to specify this in the UserSerializer. serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ( "id", "username", "email", "first_name", "last_name", "groups" ) class UserProfileSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = UserProfile fields = ( "user", "current_city", "current_country" ) -
Django: Select multiple field values and add them in database
I am working on a django-project where i have to create exam paper and add questions to them.. I need help in creating a view in which for a particular exam i first select the subject and chapter and after submitting it i get all the questions related to them as checkboxes to select multiple values and enter marks for each question. I have created a dependent dropdown list using SimpleIsBetterThanComplex but that lets me add only question at a time which is i don't like.. Please anyone give the solution or hint on how i could implement this. Thanks in advance.