Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
queryset use 'values' for join ,,... template variables is too long name.. can i change it?
queryset use values and LEFT join auth_user the template variable name is too long Can I change the template name to a shorter one? queryset = Post.objects.values('id','subject','created_by_id','created_by__first_name') I have to use template variable name like this "post.created_by__first_name" It's too long... can i change it? -
Django uploaded file process throws expected str, bytes or os.PathLike object, not TemporaryUploadedFile
I am trying to resize/convert uploaded image before saving: def resize_convert(image_file, size, file_full_name): os.chdir(BASE_DIR + '/convert/') file_name = os.path.splitext(os.path.basename(file_full_name))[0] file_ext = os.path.splitext(os.path.basename(image_file))[1] files = {} for i in size: cmd = ['convert', image_file, '-resize', i, file_name + i + file_ext] subprocess.check_call(cmd, shell=False) webp_cmd = ["cwebp", "-q", "100", file_name + i + file_ext, "-o", file_name + '_' + i + '.webp'] subprocess.check_call(webp_cmd) files[i] = os.getcwd() + '/' + file_name + '_' + i + '.webp' return files so from view I passed all necessary params like this : for pro in product_files: resize_convert(pro.file.name, ["308x412"], pro) then it throws this error expected str, bytes or os.PathLike object, not TemporaryUploadedFile -
How to use use a django variable in html <script> tag?
Like the python variable has a list of values and I want to equate a variable, say var list= python variable inside tag. -
Django Factory Boy Create vs create_batch
I am learning django test and i found django factory boy library very helpfull for writing testcase but one thing i am not getting.. forexample my one of Factory name is BlogFactory so i notice, most of the people use this like this: BlogFactory.create() and some people use it like this.. BlogFactory.create_batch() I am not getting difference between it.. What is different between create and create_batch ? -
Send data from django views to multiple pages
I have a function in my views.py and i want to return the value to multiple pages This is my views.py ```python def index(request): if request.method == 'POST': text = request.POST['input_text'] ResA, ResB = main.main(text) content = {'ResA': ResA, 'ResB': ResB} return render(request, 'index.html', content) return render(request, 'index.html') ``` i want send content from index function to index and example pages and This is my urls.py ```python urlpatterns = [ path('', views.index), path('example', views.index), ] ``` Thanks -
Django render template from model variables
I have a model: class DocumentoPaziente(models.Model): nome = models.CharField(null=True, blank=True, max_length=50) cognome = models.CharField(null=True, blank=True, max_length=50) contenuto = models.CharField(null=True, blank=True, max_length=100000) Variale content: Il Paziente <font color="#000000"><font face="Arial, serif"><font size="3" style="font-size: 12pt"><span lang="zxx"><b>{{ member.cognome }} {{ member.nome }}</b></span></font><font color="#000000"><font face="Arial, serif"><font size="3" style="font-size: 12pt"><span lang="zxx"> abitante [...] In template: {% autoescape off %} {{ member.contenuto }} {% endautoescape %} It render Il Paziente {{ member.cognome }} {{ member.nome }} abitante [...] Expected: Il Paziente Smith John abitante [...] Ty -
how to create a task scheduler in django
I'm working in on school project, I'm supposed to do a task scheduler but i don't know how to start. In fact, we are supposed to take reservations for activities in an institution an with that scheduler set the periods of reservation for one week or month for example at the end of this period, analyse reservation to make a board of activities in institution and make possible a reservation for another week it's not possible to make reservation of the week that the periods of reservation has been pass. Now I have a script to analyse the reservation but I don't know how to make scheduler to run the analyse script. thanks in advance. -
Raising an ValidationError on a specific field within a clean function in django
I have a Django model and I would like to make validation which involved several of the fields. However I would like to show the validation error on a specific field in the admin page and not globally. When raising a validationError in the clean function, it always shows the error in the top portion of the admin page see an example: I though about using Field validators but because my validations are on the model level and not on the field level it isn't helpful (I only get access to the value of the field and no the whole model instance) -
I am trying to implement blog app with django.I created registration form with profile pic upload.But its not submitting data?
I am trying to implement blog app with django.I created registration form with profile pic upload.But after i enter data and choose image and click on submit its not submitting data.Its returns same registration page.Instead of submitting data . #models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(default='default.jpg',upload_to='pics') #views.py def register(request): if request.method == "POST": form = Register(request.POST,request.FILES) if form.is_valid(): profile = Profile() email = form.cleaned_data['Email'] User_name=form.cleaned_data['Username'] Password=form.cleaned_data['Password'] Confirm_Password=form.cleaned_data['Confirm_Password'] firstname=form.cleaned_data['Firstname'] user=User.objects.create_user(username=User_name, password=Password,email=email,first_name=firstname) user.save(); profile.image = form.cleaned_data["Image"] profile.save(); return redirect('/') else: form = Register() return render(request,'register.html',{'form': form}) #forms.py class Register(forms.Form): Email = forms.EmailField(widget=forms.TextInput(attrs= {"class":"inputvalues"})) Username = forms.CharField(widget=forms.TextInput(attrs= {"class":"inputvalues"})) Password = forms.CharField(widget=forms.PasswordInput(attrs= ({"class":"inputvalues"}))) Firstname = forms.CharField(widget=forms.TextInput(attrs= {"class":"inputvalues"}),max_length=30) Lastname = forms.CharField(widget=forms.TextInput(attrs= {"class":"inputvalues"}),max_length=40) Confirm_Password = forms.CharField (widget=forms.PasswordInput(attrs=({"class":"inputvalues"}))) Image = forms.ImageField() def clean_Email(self): if validate_email(self.cleaned_data['Email']): raise forms.ValidationError("Email is not in correct format!") elif User.objects.filter(email = self.cleaned_data['Email']) .exists(): raise forms.ValidationError("Email aready exist!") return self.cleaned_data['Email'] def clean_Username(self): if User.objects.filter(username = self.cleaned_data['Username']).exists(): raise forms.ValidationError("Username already exist!") return self.cleaned_data['Username'] def clean_Confirm_Password(self): pas=self.cleaned_data['Password'] cpas = self.cleaned_data['Confirm_Password'] if pas != cpas: raise forms.ValidationError("Password and Confirm Password are not matching!") else: if len(pas) < 8: raise forms.ValidationError("Password should have atleast 8 character") if pas.isdigit(): raise forms.ValidationError("Password should not all numeric") <!-------register.html> {% extends 'layout.html' %} {% block content %} <div class="box"> <h2> … -
"TypeError: 'int' object is not callable" when deleting in Django
I'm stumped... I get "TypeError: 'int' object is not callable" when the view attempts to delete an instance." The exception is thrown on the line "form.instance.delete()" Here's the code: view.py def decorate_letter(request, slug, template_name='letters/letter/decorate_letter.html'): active_flair = Flair.objects.filter(status='active') active_flair_count = active_flair.count() flair_formset_factory = modelformset_factory(LetterFlair, fields=('letter', 'flair', 'x', 'y', 'r', 'placed', 'delete'), form=LetterFlairModelForm, extra=0) # get user & topic user = request.user topic = Topic.objects.get(slug=slug) letter = get_object_or_404(Letter, author_id=user.id, topic_id=topic.id) if request.POST: flair_formset = flair_formset_factory(request.POST or None) for form in flair_formset.forms: if form.has_changed(): if form.is_valid(): form.instance.delete() if form.cleaned_data['delete'] == 1: form.instance.delete() elif form not in flair_formset.deleted_forms: form.save() models.py class Flair(models.Model): STATUS_CHOICES = ( ('inactive', 'Inactive'), ('active', 'Active') ) type = models.CharField(unique=True, max_length=250, default="default") image = models.ImageField(upload_to="flair") title = models.CharField(max_length=250) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='inactive') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) publish = models.DateTimeField(auto_now=True) class LetterFlair(models.Model): letter = models.ForeignKey(Letter, on_delete=models.CASCADE) flair = models.ForeignKey(Flair, on_delete=models.CASCADE, default=1) x = models.DecimalField(decimal_places=2, max_digits=5, null=True, default=0) y = models.DecimalField(decimal_places=2, max_digits=5, null=True, default=0) r = models.DecimalField(decimal_places=2, max_digits=5, null=True, default=0) placed = models.CharField(default='false', max_length=250) delete = models.IntegerField(default=0) forms.py class LetterFlairModelForm(forms.ModelForm): class Meta: model = LetterFlair fields = ['letter', 'flair', 'x', 'y', 'r', 'placed', 'delete'] What could be causing the exception? -
Why is this condition not working? - if in template
I am trying to prescribe a condition if selected kind of product. I'm trying to prescribe a condition if in template. But I'm doing something wrong. Helps me, please. views.py def product_list(request, category=None, subcategory=None, kind=None): if category: categories = Category.objects.all() category = Category.objects.get(slug=category) subcategories = Subcategory.objects.filter(category=category) products = Product.objects.filter(category=category, available=True) products_quantity = len(Product.objects.filter(category=category, available=True)) kinds = None if subcategory: subcategory = Subcategory.objects.get(slug=subcategory) kinds = Kind.objects.filter(kind=subcategory) products = Product.objects.filter(category=category, subcategory=subcategory, available=True) if kind: kind = Kind.objects.filter(slug=kind) products = Product.objects.filter(category=category, subcategory=subcategory, kind__in=kind, available=True) if products: paginator = Paginator(products, 8) page = request.GET.get('page') products = paginator.get_page(page) context = { 'categories':categories, 'category':category, 'subcategories':subcategories, 'subcategory':subcategory, 'products':products, 'products_quantity':products_quantity, 'kinds':kinds } return render(request, 'shop/product/product_list.html', context) product_list.html # Not works {% if kind %} Hello {% endif %} But if I prescribe such a condition. This work fine {% if category %} Hello {% endif %} How do i set conditions for kind? Thanks! -
Django unable to load model into views
I am trying to import my models into views.py but I am unable to do so. However I am able to register them on the admin site but when I use the same code I used in admin.py to import the models into views.py, I get an error. I am using djongo so I am not sure if that changes anything about how to import them and I cannot seem to find the documentation for it. models.py from djongo import models class Round(models.Model): round_num = models.IntegerField(default=0) admin.py from django.contrib import admin from .models import Round admin.site.register(Round) views.py from .models import Round When I try and run my views.py file I get the following error: ModuleNotFoundError: No module named 'main.models'; 'main' is not a package Also my views, admin, and models file are all in the same directory. I have made the migrations and I can see my Round model in MongoDB. The only thing I cannot do is import it to the view -
How to fix 'Manager isn't available; 'auth.User' has been swapped'
I am setting up a CustomUser to use email as username (eliminating the username). This is the guide I have been following. https://wsvincent.com/django-referencing-the-user-model/ I have been trying to use the get_user_model including AUTH_USER_MODEL = 'core_app.CustomUser' in settings. When i try to register using the registrationcompany function i get an error. settings.py AUTH_USER_MODEL = 'core_app.CustomUser' INSTALLED_APPS = [ 'accounts', 'core_app.apps.CoreAppConfig', ] core_app/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.utils.translation import gettext_lazy as _ from .managers import CustomUserManager class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, null=True) USERNAME_FIELD = 'email' objects = CustomUserManager() class Meta: verbose_name = _('user') verbose_name_plural = _('users') core_app/managers.py from django.contrib.auth.models import BaseUserManager class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): if not email: raise ValueError('Email field is required') email = self.normalize_email(email) user = self.model(email=email, **kwargs) user.set_password(password) user.save() return user accounts/views.py def registercompany(request): if request.method =='POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() new_user = form.save() new_user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'], ) login(request, new_user) return redirect(reverse('nonprofits:filterview')) else: form = RegistrationForm() args = {'form': form} return render(request, 'accounts/reg_form_company.html', args) accounts/models.py from django.db import models from django.contrib.auth import get_user_model class UserProfile(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) organisation_name = models.CharField(blank=True, default='', objects = models.Manager() def __str__(self): return self.user.username def create_profile(sender, **kwargs): … -
Are queries using related_name more performant in Django?
Lets say I have the following models set up: class Shop(models.Model): ... class Product(models.Model): shop = models.ForeignKey(Shop, related_name='products') Now lets say we want to query all the products from the shop with label 'demo' whose prices are below $100. There are two ways to do this: shop = Shop.objects.get(label='demo') products = shop.products.filter(price__lte=100) Or shop = Shop.objects.get(label='demo') products = Products.objects.filter(shop=shop, price__lte=100) Is there a difference between these two queries? The first one is using the related_name property. I know foreign keys are indexed, so searching using them should be faster, but is this applicable in our first situation? -
How to combine two filters from two models?
How to combine two filters from two models? Must be work as AND (&) Credit.objects.filter(id__in=Condition.objects.filter(security='Deposit - deposit').values('credit__id').distinct(), bank__id=1)) Credit.objects.filter(id__in=Condition.objects.filter(purpose=3).values('credit__id').distinct(), bank__id=1)) -
<Post: mi post>” needs to have a value for field “id” before this many-to-many relationship can be used
I'm trying to save data in a model that has a m2m relation from django admin, but when I save that error, try changing the relation to foreignkey but it's not what I need, any ideas? models.py class Post(models.Model): titulo = models.CharField(verbose_name="titulo del post", max_length=50) posting = HTMLField(verbose_name="posting",blank=True,null=True) categoria = models.ManyToManyField("posts.Categoria", verbose_name="categorias del post") slug = models.SlugField(verbose_name="slug del post", help_text="identificador unico del post", unique=True) admin.py @admin.register(Post) class PostAdmin(admin.ModelAdmin): readonly_fields = ('slug',) def save_model(self,request,obj,form,change): if change: formato = "%d%S" es = " " if obj.titulo.find(es) >= 1: obj.slug = obj.titulo.replace(es, "-").lower() + "-" + obj.fecha_creacion.strftime(formato) else: obj.slug = obj.titulo.lower() + "-" + obj.fecha_creacion.strftime(formato) obj.save() -
How to visit a git branch of Django project on Nginx/uWSGI server?
I have successfully built several web sites hosted on an Nginx server using Django, uWSGI and virtualenv. I had never used version control but now I am starting to use Git. I understand how to create, commit and push branches. My question is: how to make different Git branches visible at the web address of the site I'm working on? Do I change the Nginx config file to point somewhere different? I just updated the dev branch of my project, and of course the site does not reflect the changes. How can I tell the server to serve the dev branch or the master branch of the project? I would prefer to avoid a complicated system with different subdomains for different branches — I really just want the simplest thing that will work. -
Update a Model in Django right before the backend select
Before my Model in Django gets hydrated and filled with data, I want to update (alter) my model, save it back to the database and then go on the normal way. My approach (not working) as now is this: from django.db import models from MyApp import models as m class CustomManager(models.Manager): def get_queryset(self): # This is not evaluated to true although it should from my assumption: if (isinstance(self.model, m.MyObject)): # Here I want to take the internal key of # MyObject (maybe from the URL?), # Simply accessing self.model.internal_key does not work. # Then make an API call to an external server, # update my local object, save it back to db and proceed print(self.model) # Prints <class 'MyApp.models.MyObject'> Can someone point me to the right direction if this is the correct approach and how I go on? -
Why the form is invalid at FormView?
All fields are filled. But for some reason does not go into the form_valid method, but it goes into form_invalid. Why form is invalid? forms.py class CreditFilterForm(forms.Form): CURRENCY_CHOICES = ( ('KZT', _('KZT')), ('USD', _('USD')), ) PERIOD_CHOICES = ( ('1', _('One year')), ('2', _('Two')), ('3', _('Three')) ) sum = forms.CharField(widget=forms.NumberInput(attrs={'id': "sum", 'class':"forminput-text"})) currency = forms.ChoiceField(choices = CURRENCY_CHOICES, widget=forms.Select(attrs={'name': "minbeds", 'id':"currency"})) term = forms.ChoiceField(choices = PERIOD_CHOICES, widget=forms.Select(attrs={'id':"term", 'name': "minbeds"})) views.py class CreditsList(ListView): model = Credit template_name = 'credits/credit_listing.html' def get(self, request, *args, **kwargs): self.object_list = self.get_queryset() little_form = CreditFilterForm(self.request.GET or None, prefix="little") ... class LittleForm(FormView): form_class = CreditFilterForm template <form action="{% url 'little_form' %}" method="post"> {% csrf_token %} {{ little_form.as_p }} <input type="submit" name="{{ little_form.prefix }}" value="Submit"> </form> -
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'project.routing'
i have installed django channels i have added routing.py in project root folder and added the line ASGI_APPLICATION = 'project.routing.application' but whenever i tried to run the server i get raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'scrapshut.routing' downgrading channels version to 1.5 works but i want to figure out whats the issue with channels 2 async-timeout==3.0.1 attrs==19.1.0 autobahn==19.6.2 Automat==0.7.0 certifi==2019.6.16 cffi==1.12.3 channels==2.2.0 channels-redis==2.3.3 chardet==3.0.4 constantly==15.1.0 cryptography==2.7 daphne==2.3.0 defusedxml==0.6.0 dj-database-url==0.5.0 Django==2.2.2 django-heroku==0.3.1 django-widget-tweaks==1.4.5 gunicorn==19.9.0 hiredis==1.0.0 hyperlink==19.0.0 idna==2.8 incremental==17.5.0 msgpack==0.6.1 msgpack-python==0.5.6 oauthlib==3.0.1 Pillow==6.0.0 psycopg2==2.8.3 pycparser==2.19 PyHamcrest==1.9.0 PyJWT==1.7.1 pypiwin32==223 python-decouple==3.1 python-social-auth==0.2.1 python3-openid==3.1.0 pytz==2019.1 pywin32==224 redis==2.10.6 requests==2.22.0 requests-oauthlib==1.2.0 six==1.12.0 social-auth-app-django==3.1.0 social-auth-core==3.2.0 sqlparse==0.3.0 Twisted==19.2.1 txaio==18.8.1 urllib3==1.25.3 i just want the server to recognize the routing application and start working -
how to call function django views.py without refresh page?
I write a model that user can follow/unfollow each other, but when the user tap on the button to follow or unfollow after the process, the page will be refreshed. I need a way to handle that action without refreshing page and change the text in this page. my model : class Follower(models.Model): follower = models.ForeignKey(User, related_name='followings', on_delete=models.CASCADE) following = models.ForeignKey(User, related_name='followers', on_delete=models.CASCADE) class Meta: unique_together = ('follower', 'following') def __str__(self): return u'%s follows %s' % (self.follower, self.following) my view : def follow(request, own_user_id , follow_state): """ follow function that add user who follow other user own : user that have channel page """ own = CustomUser.objects.get(pk=own_user_id) if follow_state == "followed": action = request.user.followings.get(following=own) action.delete() return redirect(f'http://127.0.0.1:8000/{own.channel_name}') else: action = Follower.objects.create(follower=request.user, following=own) action.save() return redirect(f'http://127.0.0.1:8000/{own.channel_name}') my template : {% if request.user == user_own %} <a href="{% url 'update-page' user.channel_name %}"> <button class="btn btn-light btn-flw">profile setting </button></a> {% else %} <a href="{% url 'follow-unfollow' user_own.id follow_state%}"> <button class="btn btn-light btn-flw">{{follow_state}}</button> </a> {% endif %} -
how to write query on ArrayModelField?
i am trying to query the array model field but unable to do it in my web page project_name,project_supervisor and all fields except Students which is array model fields are showing but data from array model is not showing.i want that if i want to access data from data using query year_data = students.objects.filter(batch_year__startswith='2012') then it will show all data on web page including Roll_No and Student_Name. models.py class Students(models.Model): Roll_No=models.CharField(db_column='Roll No',max_length=250) Student_Name = models.CharField(db_column='Student Name',max_length=250) class Meta: abstract = True class students(models.Model): _id = models.ObjectIdField() batch_year = models.CharField(db_column='Batch Year',max_length=250,default=True) # Field name made lowercase. Students = models.ArrayModelField(model_container=Students, ) project_name = models.CharField(max_length=250, db_column='Project Name',default=True) # Field name made lowercase. project_supervisor = models.CharField(max_length=250, db_column='Project Supervisor',default=True) # Field name made lowercase. external_supervisor = models.CharField(max_length=250,db_column='External Supervisor',default=True) # Field name made lowercase. co_supervisor = models.CharField(max_length=250,db_column='Co-Supervisor',default=True) # Field name made lowercase. project_id = models.CharField(db_column='Project Id',max_length=250,default=True) # Field name made lowercase. def __str__(self): return self.batch_year + '---' +self.project_name views.py def search(request): years = request.GET.get('text', 'Default') print('years', years) year_data = students.objects.filter(batch_year__startswith=years) -
Getting currency selection of form
it's greate to be here :) i was hopeing that smb. Is maybe able to explain to me how i can process a selection (RadioButton selection) further in my views.py. Currently I'm processing this staticaly for btc (Bitcoin) but i have to get this working for ltc, xmr etc. as currency also. How can i get the user selection of this form or in other words the selected currency the user has chosen? views.py ... if request.method == "POST": form = CurrencyBuySelectForm(request.POST) currency = form['currency'].value() # check account balance if form.is_valid: if currency == 'btc': price = dollar_to_coin(post.price_usd, 'BTC') if request.user.acc_btc_balance < price: messages.error(request,'Not enough balance to buy this message') return redirect('post', pk=post.pk) else: # generate transaction ... forms.py: WALLET_CHOICE = [ ('btc', 'BTC'), ('xmr', 'XMR'), ('ltc', 'LTC'), ... etc ] class CurrencyBuySelectForm(forms.Form): currency = forms.ChoiceField(choices=WALLET_CHOICE, widget=forms.RadioSelect()) captcha = CaptchaField() def __init__(self, *args, **kwargs): super(CurrencyBuySelectForm, self).__init__(*args, **kwargs) self.fields['currency'].label = mark_safe('') def clean(self): cleaned_data = super(CurrencyBuySelectForm, self).clean() currency = cleaned_data.get(choices=WALLET_CHOICE, widget=forms.RadioSelect()) if not currency: raise forms.ValidationError('Something went wrong') Thanks in advance -
django app structure for making a modular application
i am new to django and i wanna know if i would have 2 classes like home and booking for a booking reservation system should i make 2 apps like below : python manage.py startapp booking python manage.py startapp home or i should make an app named home for example and make a booking class inside that app ?? i want to know the standard way to do this in django because i could not find the way in documentation here is the way i do it : -
Django's get_initial() method not working as desired
I am using django's generic CreateView to build a comment system for my site. A user is allowed to do comment for a movie. Here is my Comment model- class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="comments", on_delete=models.CASCADE) body = models.TextField() movie = models.ForeignKey(Movie, related_name="comments", on_delete=models.CASCADE) created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) class Meta: ordering = ('created',) def __str__(self): return "comment by {} on {}".format(self.user.first_name, self.movie) Here is the CreateView i am using- class AddComment(LoginRequiredMixin, CreateView): form_class = CommentForm def get_initial(self): initial = super().get_initial() #for providing initial values to the form initial['user'] = self.request.user.id initial['movie'] = self.kwargs['movie_id'] return initial def get_success_url(self): movie_id = self.kwargs['movie_id'] return reverse('detail', kwargs={'pk':movie_id}) def render_to_response(self, context=None, **response_kwargs): movie_id = self.kwargs['movie_id'] return redirect(to = reverse('detail', kwargs={'pk':movie_id})) Here is the commentform - class CommentForm(forms.ModelForm): user = forms.ModelChoiceField(widget=forms.HiddenInput, queryset=get_user_model().objects.all()) movie = forms.ModelChoiceField(widget=forms.HiddenInput, queryset=Movie.objects.all()) class Meta: model = Comment fields = ('user','movie', 'body') I am trying to associate a comment to a user and a movie. I thus used get_initial() method to fill the form with initial data because user and movie were not present in the posted data. But somehow always form.is_valid() turns out to be false. I don't know where i went wrong. Please Help.