Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
assertRedirect not working. Getting 302 != 201 error
I have two tests: def test_view_exists_at_desired_location(self): note_id = 1 login = self.client.login(username='Name', password='password') response = self.client.get(f'/{ note_id }/edit/') self.assertEqual(response.status_code, 200) def test_view_redirects_if_not_logged_in(self): note_id = 1 response = self.client.get(f'/{ note_id }/edit/') self.assertRedirects(response, f'/accounts/login/?next=/{ note_id }/edit/') in my urls.py I have: urlpatterns = [ ... path('<int:note_id>/edit/', login_required(views.edit), name='edit'), ] The first test, test_view_exists_at_desired_location runs fine, ensuring that a Note with note_id=1 exists. However, the other test fails and tells me: Traceback (most recent call last): File "/home/MyName/Documents/Projects/ProjectName/notes/tests/test_views.py", line 119, in test_view_redirects_if_not_logged_in self.assertEqual(response.status_code, 201) AssertionError: 302 != 201 When I visit /1/edit/ while not logged in on my browser I am redirected to /accounts/login/?next=/1/edit/. I don't think it matters, but here is view.edit: def edit(request, note_id): note = get_object_or_404(Note, pk=note_id) if request.POST: form = NoteForm(request.POST) if form.is_valid(): date = datetime.date.today() title = form.cleaned_data['title'] body = form.cleaned_data['body'] is_private = form.cleaned_data['is_private'] note.title = title note.body = body note.is_private = is_private note.edit_date = date note.save() return HttpResponseRedirect(reverse('notes:mynotes')) # get or any other method. Return create page else: form = NoteForm(instance=note) return render(request, "notes/editor.html", {'form': form, 'note_id': note_id}) -
Django sessions - reliability issues - must keep logging in
I have 2 reliability issue with Django sessions. The goal I am trying to achieve is if I use the account at least once a month, I don't even have to log in. 1. The quantity of sessions I am working on the website, I am the only one using it, and Django keeps creating sessions. I have 30 sessions for just myself today (I cleaned out all the sessions at the start of the day). 2. I have to keep logging in I find every now and then I have to log in again (e.g. come back the next day), or after a reboot. My Current Setup: # Set to 1 months of inactivity SESSION_COOKIE_AGE = 31 * 24 * 3600 # After every request store SESSION_SAVE_EVERY_REQUEST = True SESSION_ENGINE = 'django.contrib.sessions.backends.db' # This is the default I used to use cached DB session engine, but with SESSION_SAVE_EVERY_REQUEST i figure its pointless, as it will be a miss every time. I also thought the default DB session engine maybe more reliable (maybe be more reliable or might just be grasping at straws). For the messages storage I use Session storage. I used to use the default FallbackStorage but figure … -
Consuming JSON API data with Django
From a Django app, I am able to consume data from a separate Restful API, but what about filtering? Below returns all books and its data. But what if I want to grab only books by an author, date, etc.? I want to pass an author's name parameter, e.g. .../authors-name or /?author=name and return only those in the json response. Is this possible? views.py def get_books(request): response = requests.get('http://localhost:8090/book/list/').json() return render(request, 'books.html', {'response':response}) So is there a way to filter like a model object? -
How to POST nested Data that contains a File with Django Rest Framework?
I've been trying to post a nested object with one file and some data via django drf for a few days now. The goal is to create a story together with some images, one of these images being the title image of the story. Basically, I am able to post the story successfully with postman (see picture below). However, when I use my react js frontend for sending, I am not able to create the form data in a way that Django understands it. Django always returns the error story_media field is required. I suppose this is because Django does not understand the incoming data correctly. class Story (models.Model): title = models.CharField(max_length=100,blank=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) class Story_Media (models.Model): story = models.ForeignKey(Story,on_delete=models.CASCADE, null=True, related_name = 'story_media', related_query_name = 'story_media') file = models.FileField(upload_to='story_media/', null=True) isTitlePicture = models.BooleanField(blank=False, null=True) # Story Story Media Serializer class Story_Media_Serializer (serializers.ModelSerializer): class Meta: model = Story_Media fields = ('id','file','isTitlePicture',) # Story Serializer class StoryCreateUpdateSerializer (serializers.ModelSerializer): story_media = Story_Media_Serializer(many=True) class Meta: model = Story fields = ('title','story_media',) def create(self, validated_data): current_user = self.context["request"].user story_media = validated_data.pop('story_media') story_instance = Story.objects.create(author=current_user, **validated_data) for story_media_data in story_media: Story_Media.objects.create(**story_media_data, story=story_instance) # Story Create View Set class StoryCreateUpdateViewSet(viewsets.ModelViewSet): serializer_class = StoryCreateUpdateSerializer … -
Django elasticsearch dsl completion field issue
I am trying to implement search suggestions using django-elasticsearch-dsl-drf for streets. This is documents.py: class StreetDocument(Document): id = fields.IntegerField() name_ru = StringField( fields={ 'raw': KeywordField(), 'suggest': fields.CompletionField(), } ) ... # same for name_uz and name_oz tags_ru = fields.CompletionField() ... # same for tags_uz and tags_oz class Django: model = Street fields = ( 'code', 'street_type' ) in views.py I have this: from django_elasticsearch_dsl_drf.constants import SUGGESTER_COMPLETION from django_elasticsearch_dsl_drf.filter_backends import SuggesterFilterBackend from django_elasticsearch_dsl_drf.viewsets import DocumentViewSet class SuggestionListAPI(DocumentViewSet): document = StreetDocument serializer_class = StreetDocumentSerializer filter_backends = [ CompoundSearchFilterBackend, SuggesterFilterBackend, ] search_fields = ( 'code', 'name_ru', 'name_uz', 'name_oz', 'tags_ru', 'tags_uz', 'tags_oz' ) suggester_fields = { 'name_ru_suggest': { 'field': 'name_ru.suggest', 'suggesters': [ SUGGESTER_COMPLETION, ], }, ... # same for name_uz and name_oz 'tags_ru': { 'field': 'tags_ru', 'suggesters': [ SUGGESTER_COMPLETION, ], }, ... # same for tags_uz and tags_oz } Request to /suggestions?name_ru_suggest__completion=tolstoy does nothing, just receiving all streets unfiltered. Request to /suggestions?search=tolstoy works great, but I need autocompletion. Where did I go wrong? And that will be great if it's possible to use two fields for suggestion at once. Thanks for your time and help. -
I have question about views in django.how i can show several forms in django one by one?
Hi there I do have a problem.in registraion form i wnat to send a code to email of user and make him insert it in next form to sign up. i know i can make a field in user model for the code but i dont wanna do that i want to show the next form in same view and validate the code.is it safe for speed of a website and security? is it a right way to do it if not is another way to do it? thanks for your time i have tried this view but its lots of mess and does not work """ def code_checker(request,email): code=randrange(1000,10000) send_mail("",f"{code}","AH Book Store",[email],fail_silently=False) return(code) def email_register_view(request): if(request.method=="POST"): form=EmailRegisterForm(data=request.POST) if(form.is_valid()): email=form.cleaned_data["email"] code=code_checker(request,email) if(request.method=="POST"): code_form=EmailCodeRegisterForm(data=request.POST) if(code_form.is_valid()): cd=code_form.cleaned_data if(code==cd["code"]): messgaes.success(request,"User Created") else: code_form=EmailCodeRegi.sterForm() return(render(request,"accounts/EmailRegisterForm.html",{"code_form":code_form})) else: form=EmailRegisterForm() return(render(request,"accounts/EmailRegisterForm.html",{"form":form,"code_form":None})) """ -
Two different indexes on Django: One is properly connecting to the CSS but the other one isn't, despite same paths
I'm relatively a beginner in Django and I'm trying to set a website I made to simulate a store. I have two different HTML files: one being a practice store I made (mainly to try out how the cart function worked) and a polished version of the same store. Both are in the same directory. The main issue is one of them isn't changing when I make modifications to the CSS files while the other one is perfectly. Here's a snippet of the code for reference: This is the non-working HTML: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="shortcut icon" type="image/x-icon" href=" {% static 'App/assets/images/favicon.ico' %} "> <meta name="description" content=""> <meta name="author" content=""> <title>Title</title> <script src=" {% static 'App/assets/vendor/home-banner/jquery.min.js' %} "></script> <!-- main css --> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> #### File in question <link rel="stylesheet" href=" {% static 'App/assets/css/home-1.css' %} "> <link rel="stylesheet" href=" {% static 'App/assets/vendor/revolution/vendor/revslider/css/settings.css' %} "> <link rel="stylesheet" href=" {% static 'App/assets/vendor/revolution/responsiveslides.css' %} "> <link rel="stylesheet" href=" {% static 'App/assets/vendor/side-menu/side-menu.css' %} "> <link rel="stylesheet" href=" {% static 'App/assets/vendor/side-menu/jquery.mCustomScrollbar.min.css' %} "> This is the working HTML: {% load static %} <html> <head> … -
Detail views fail to find post url after adding one to many fk relationship from "PostFile" to "Post"
After changing admin.py (previous code commented): # admin.site.register(Post) class PostFileAdmin(admin.StackedInline): model = PostFile @admin.register(Post) class PostAdmin(admin.ModelAdmin): inlines = [PostFileAdmin] @admin.register(PostFile) class PostFileAdmin(admin.ModelAdmin): pass And adding PostFile to models.py: class Post(models.Model): slug = models.SlugField(max_length=200, unique_for_date="date_posted") content = RichTextField() date_posted = models.DateTimeField(default=timezone.now) ... def get_absolute_url(self): return reverse("news:news-detail", args=[self.date_posted.year, self.date_posted.month, self.date_posted.day, self.slug]) class PostFile(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) post_file = models.FileField(upload_to="files/news", null=True, blank=True) Also, views.py: class PostListView(ListView): model = Post template_name = "news/news_home.html" context_object_name = "posts" ordering = ["-pk"] paginate_by = 2 def news_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status="published", date_posted__year=year, date_posted__month=month, date_posted__day=day) return render(request, "news/news_detail.html", {"post": post,}) When I create new post in Django admin, and then try to go to its absolute_url to see detailed view, it raises 404. I checked, using shell, absolute_url is good and all objects are created properly, but for some reason post's URL is broken. Any idea how to solve this? -
How do I use button on card to change a session value?
I am making a menu that goes through a few different steps. Select the grade, then select the textbook, then select the lesson. I want to display the textbooks as cards with buttons that will bring the user to a view of all the lessons associated with that textbook. I've used session to go from the grade to the textbook, but I'm not sure how to go from the textbook to the lessons. I think the way of getting there is to have the button change the session value to that textbook, and bring me to the view that will filter the lessons by that textbook, but I'm not sure how to do that. Any suggestions would be welcome! -
how to import python file from another directory
I am working on a django rest framework and can't import .py files from another directory. I have __init__.py files included in the directory -
invalidImageFormatError Exception The source file does not appear to be an image
So I am using fallback default image to avoid 500 error and it is not successful. I keep getting the same error "InvalidImageFormatError: The source file does not appear to be an image". In my case I try to thumbnail an image that does not exist. But it is assumed that if the image does not exist it should use the one that is in default as fallback. Any ideas? Someone who has happened in the same way and found a solution? In my case this is my code {% oscar_thumbnail child_image.original|default:'image/default.png' "450x450" format="WEBP" padding=True as thumb_child %} I am migrating from sorl-thumbnails which comes by default with django_oscar for easy_thumbnails. The tag OSCAR_THUMBNAIL is used by django_oscar and oscar replaces it with the thumbnailer that is in settings in this case easy_thumbnails. I have debugged the code, and it is entering the easy_thumb classes well ... and the parameters are arriving correctly. The thing is, it doesn't make me fallback when the image it's trying to process doesn't exist. I have a database with products that have associated images, many of these do not exist in my local environment, because in production they are in s3, and I do … -
How to add new pages existing django app through admin page?
I have an existing Django app. What is the best way to add new pages to it through the admin page, without actually coding every time. I want to add static pages, with URLs through the admin page. Add new page with new URLs Add through admin page, not through coding every time. One time code to handle this. Is there a way out? -
Data accessing : Django forms vs request.POST method
Can someone please explain me why is highly recommended to use Django forms to get an html object instead of direct accessing from request.POST or request.GET? -
Django:Widgets not being picked for filter with relation fields
I have the below set up for models program, courses and providers. class Program(models.Model): subtitle = models.TextField( null=True, blank=True) courses = models.ManyToManyField(Course, related_name='course_bundle') class Course(models.Model): provider = provider = models.ForeignKey( Provider, **and more **) Below is my filter for the same where I want the provider to be a multiselect as every program has multiple courses. However, looks like it does not pick the widget defined in the filter but reads directly from Meta and shows. It neither changes the label or style or anything. class ProgramFilter(django_filters.FilterSet): subtitle = django_filters.CharFilter(lookup_expr='icontains', label="Keywords", widget = forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Search for specialities', 'label': 'Keywords', })) courses__provider = forms.ModelMultipleChoiceField(label='Providers',queryset=Provider.objects.all(), to_field_name='courses__provider', required=False, widget=forms.CheckboxSelectMultiple(attrs={ 'class':'form-control', 'label':'Providers' }),) status = django_filters.ChoiceFilter(choices=Program.STATUS,empty_label="All") class Meta: model = Program fields = ['subtitle','cost' ,'duration','popularity','status','courses__provider'] How should we define the widget for filters with relation based properties like courses__provider.It ignores the code outside of meta completely for courses__provider but works for subtitle. -
Django - Filter count data
Does anybody know how can I use count based on selected value using django_filters Error 'UserFilter' object has no attribute 'count' My Reference link views.py def search(request): user_list = Person.objects.all() user_filter = UserFilter(request.GET, queryset=user_list) count = user_filter.count() #this will return an error print(count) return render(request, 'user_list.html', {'filter': user_filter}) filters.py from django.contrib.auth.models import User from .models import Person import django_filters class UserFilter(django_filters.FilterSet): class Meta: model = Person fields = ['category', 'firstname', 'lastname' ] user_list.html {% extends 'base.html' %} {% block content %} <form method="get"> {{filter.form.as_p}} <button type="submit" >Search</button> </form> <table class="table table-bordered"> <thead> <tr> <th>Firstname</th> <th> Lastname</th> <th>Caegory</th> </tr> </thead> <tbody> {% for user in filter.qs %} <tr> <td>{{ user.firstname }}</td> <td>{{ user.lastname }}</td> <td>{{ user.category }}</td> </tr> {% empty %} <tr> <td colspan="5">No data</td> </tr> {% endfor %} </tbody> </table> {% endblock %} I want to count all the list base from data I filtered -
Find django object by .id only (unknown Model)
I have two separate django (version >=2.2) apps: campus and equipment. campus Building Room equipment Camera Display Switcher Source etc. There's a lot of foreign key nesting going on, ex. source -> switcher -> room -> building, and all that works fine. I'm able to do things like source_list = Source.objects.filter(switcher__room_id=room_id) with no issues. I'm creating an API for equipment that will be using raw UDP strings, so I'm a little bit limited in how fancy it can be. My question is, can I somehow figure out what specific object is being referenced by the .id alone? I can narrow the query to the equipment app since I can figure out Building/Room based on the host IP address. In other words, my plan is to send a string from the external device with something like 1356|True|hdmi1|whatever|123|abc|stuff| with 1356 being the .id, and then in django efficiently figure out what equipment object 1356 is referring to. I'm good on the whole transport portion of getting the string into a django view, I just need to identify what 1356 is. Doing something (pseudo code) like this can't be the best way: try: Display.objects.get(id=1356) except: not a display... try: Switcher.objects.get(id=1356) except: not a … -
how to encrypt a file before uploading in django
Im building a project secure file sharing.which encrypts a file before uploading into local computer and decrypts while downloading if the user has the decryption key.I was stuck how to encrypt a file before uploading into my pc I'm following this approach which is mentioned below. https://ruddra.com/documentation-of-django-encrypt-file/#basic-usage but i dont't know how to link with my code. can anyone help me views.py def upload(request): context={} if request.method == 'POST': upload_file= request.FILES["document"] fs=FileSystemStorage() name=fs.save(upload_file.name, upload_file) context['url'] = fs.url(name) return render(request, 'accounts/upload.html',context) upload.html {% include 'accounts/main.html'%} <pre> Upload your files for sharing </pre> {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="document"> <button type="submit">Upload</button> </form> {% if url %} <p> Uploaded file:<a href="{{ url }}">{{ url }}</a></p> {% endif %} {% endblock %} settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL= '/media/' -
Django django.urls.exceptions.NoReverseMatch: Reverse for ' new_topic' not found. ' new_topic' is not a valid view function or pattern name
I'm trying to build a topics section, in where you can create a new topic. This exercise is from the python crash course book. The error I see is the next one: django.urls.exceptions.NoReverseMatch: Reverse for ' new_topic' not found. ' new_topic' is not a valid view function or pattern name. views.py from django.shortcuts import render from .models import Topic, Entry from .forms import TopicForm, EntryForm from django.http import HttpResponseRedirect from django.urls import reverse # Create your views here. def index(request): return render(request, 'learning_logs/index.html') def topics(request): topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render (request, 'learning_logs/topics.html', context) def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) topics = Topic.objects.order_by('date_added') entries = topic.entry_set.order_by('date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topics.html', context) def new_topic(request): if request.method != 'POST': form = TopicForm() else: form = TopicForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form': form} return render(request, 'learning_logs/new_topic.html', context) def new_entry(request, topic_id): topic = Topic.objects.get(id=topic_id) if request.method != 'POST': form = EntryForm() else: form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic_id])) context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) proj/urls.py from django.urls import path from . import views app_name = 'learning_logs' urlpatterns = [path('', views.index, … -
How to call method from tasks.py in Django?
In my cars/models.py I have the following code: from django.contrib.auth import get_user_model from django.utils.timezone import now from django.db import models class Car(models.Model): # Fields # methods In my cars/signals.py I have the following code: from django.dispatch import receiver from django.db.models.signals import post_save from .models import Car from tasks import create_car @receiver(post_save, sender=Car, dispatch_uid="queue_car_create_job") def queue_car_request(sender, instance, created, **kwargs): if not created: return status = create_car.delay(instance.pk) In my cars/apps.py file I have: from django.apps import AppConfig class CarConfig(AppConfig): name = 'provisioners' def ready(self): print("at ready") import cars.signals In my tasks.py I have: from celery import Celery import subprocess import django django.setup() from django.conf import settings from cars.models import Car app = Celery('management', broker=settings.CELERY_BROKER) @app.task(bind=True) def create_car(self, car_pk): if car_pk is None or not isinstance(car_pk,int): return False car_obj = Car.objects.get(pk=car_pk) return True When running Django (without Celery), I get the following error: RuntimeError: populate() isn't reentrant All I want to do is as following: Signal for creating a car. Celery runs an async job to create a car. Previously I had queue_car_request in cars/models.py but I need to import cars/models.py in tasks.py and import tasks.py in cars/models.py which makes a circle (and python does not like it). So I moved it to … -
Django - How can I edit an existing note? (Views)
I'm working on an application which allows users to create, edit, and delete notes for artists and their shows at venues. Currently I have a method for creating new notes and deleting as example, how could I create a method of allowing the user to edit an existing note? Here is what I currently have, I also thrown in repository links as reference to help explain how my application works. Any idea how I can do this? https://github.com/claraj/lmn/blob/master/lmn/urls.py #Note related path('notes/latest/', views_notes.latest_notes, name='latest_notes'), path('notes/detail/<int:note_pk>/', views_notes.note_detail, name='note_detail'), path('notes/for_show/<int:show_pk>/', views_notes.notes_for_show, name='notes_for_show'), path('notes/add/<int:show_pk>/', views_notes.new_note, name='new_note'), path('notes/detail/<int:note_pk>/delete', views_notes.delete_note, name='delete_note'), https://github.com/claraj/lmn/blob/master/lmn/views/views_notes.py @login_required def new_note(request, show_pk): show = get_object_or_404(Show, pk=show_pk) if request.method == 'POST' : form = NewNoteForm(request.POST) if form.is_valid(): note = form.save(commit=False) note.user = request.user note.show = show note.save() return redirect('note_detail', note_pk=note.pk) else : form = NewNoteForm() return render(request, 'lmn/notes/new_note.html' , { 'form': form , 'show': show }) @login_required def delete_note(request, note_pk): # Notes for show note = get_object_or_404(Note, pk=note_pk) if note.user == request.user: note.delete() return redirect('latest_notes') else: return HttpResponseForbidden https://github.com/claraj/lmn/blob/master/lmn/templates/lmn/notes/note_list.html <form action="{% url 'delete_note' note.pk %}" method="POST"> {% csrf_token %} <button type="submit" class="delete">Delete</button> </form> -
Celery or Schedule for django?
So I am working on a project. And it has a small module where when the user is not authenticated he can try to reset the password and I am implementing an OTP based verification for this, where the key for the otp will be stored in the database and when the user tries to reset the password a random number will be created which will be sent to the user through a email and the user can change the password. Now the problem is that I need the random number stored in the database will be changed to null after 10 min of its creation so now do I use the schedule or do use Celery for this project. -
Unable to login because Django saving passwords in plain text but
class UserManager(BaseUserManager): def create_user(self, username, email, password=None): if username is None: raise TypeError('User should have a username') if email is None: raise TypeError('User should have an email') user = self.model( username=username, email=self.normalize_email(email) ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password=None): if password is None: raise TypeError('Password should not be none') user = self.create_user(username, email, password) user.is_superuser = True user.is_staff = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField( max_length = 255, unique = True, db_index = True ) email = models.EmailField( max_length = 255, unique = True, db_index = True ) is_verified = models.BooleanField(default = False) is_staff = models.BooleanField(default = True) is_active = models.BooleanField(default = True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() def __str__(self): return self.email def tokens(self): refresh = RefreshToken.for_user(self) return { 'refresh': str(refresh), 'access': str(refresh.access_token) } class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField( max_length = 255, min_length = 6, write_only = True ) class Meta: model = User fields = ['email', 'username', 'password'] extra_kwargs = {'password': {'write_only': True, 'min_length': 5}} def validate(self, attrs): email = attrs.get('email', '') username = attrs.get('username', '') if not username.isalnum(): raise serializers.ValidationError( "Username should contain only alphanumeric characters" ) return attrs def create(self, validated_data): return User.objects.create_user(**validated_data) class RegisterView(generics.GenericAPIView): permission_classes … -
Is update_or_create safe within atomic transaction?
The title is pretty explicit : can you use an update_or_create command inside an atomic transaction in django ? I don't find the answer in the doc. There is something about race condition, but atomic transaction is about rollback more than race ? -
How to create editable password policy using Flask?
I want to create a Editable password policy using Flask. Admin can tick the any password policy in the menu (Please see admin menu page image). admin menu page Based on the selection password policy need to be updated. How can I Implement it?? -
django one request.is_ajax() check and multiple forms
so i have this code that checks if there is an ajax request and then handle the form stuff if there is, but my problem is it's kind of repetitive to check each time like you will see in the code that i will add, what i want is to check only once and then say if form_1 do some stuff, if form_2 do some stuff here is the code: if request.is_ajax(): Form1 = form_1(request.POST) if form_1.is_valid(): # do some stuff else: # do some stuff) if request.is_ajax(): Form2 = form_2(request.POST) if form_2.is_valid(): # do some stuff else: # do some stuff what i want to do is something like this or an alternative to the following: if request.is_ajax(): if it's form1: # do form1 stuff elif it's form2: # do form2 stuff