I work on a group project with django. I have a problem with file upload. It is an web app to create, share forms with some additional options (graphs, charts,....). I should mention that i am new to django (total beginner)
1.models.py:
class Form(TimeStampedModel, TitleSlugDescriptionModel):
author = models.ForeignKey(User,
on_delete=models.CASCADE)
title = models.CharField(max_length=512)
is_final = models.BooleanField(default=False)
is_public = models.BooleanField(default=False)
is_result_public = models.BooleanField(default=False)
image = models.ImageField(upload_to="upload_location", null=True,
blank=True, width_field="width_field",
height_field="height_field")
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
file = models.FileField(upload_to="upload location", null=True,
blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('form-detail', kwargs={'slug': self.slug})
2. forms.py:
class DocumentUpload(forms.ModelForm):
class Meta:
model = Form
field = ["image", "file"]
3. Certainly, i made a migration, changed main settings (urls, MEDIA_ROOT etc)
4. views.py THIS IS MY PROBLEM
I try to modified existing "create_form(request)" function.
In any tutorials we use "form = form from forms.py", In my project we use "form = model from models.py". How should I modify this this function to complete this upload files.
def create_form(request):
if request.method == 'POST':
user = request.user
data = ParseRequest(request.POST)
parsed_form = data.form()
parsed_questions = data.questions()
form = Form(request.FILES, author=user,
title=parsed_form['title'],
is_final=parsed_form['is_final'],
is_public=parsed_form['is_public'],
is_result_public=parsed_form['is_result_public'],
description=parsed_form['description'])
form.save()
for d in parsed_questions:
question = Question(request.FILES, form=form, question=d['question'])
question.save()
for opt in d['options']:
option = Option(question=question, option=opt)
option.save()
return render(request, 'forms/form_form.html', {})
I would appreciate any help, thx
i needed to use a form from forms.py and add additional field manually.
Thx
Related
I am making a small project to rate salesmen. I have regions and each region has its salesmen. So, if region "blahblah" is selected, form should show salesmen choices which are related to that region. I have found some answers via stackoverflow, but it still shows all salesmen, regardless of their regions.
My model is this:
class Region(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True)
def __str__(self):
return self.name
class Salesman(models.Model):
region = models.ForeignKey(Region,
related_name='region',
on_delete=models.CASCADE)
name = models.CharField(max_length=40)
surname = models.CharField(max_length=40)
def __str__(self):
return self.name
class Rating(models.Model):
RATING_CHOICES = [(i, str(i)) for i in range(1,6)]
salesman = models.ForeignKey(Salesman,
related_name='salesman',
on_delete=models.CASCADE)
phone = models.CharField(max_length=15, blank=True)
rating = models.IntegerField(choices=RATING_CHOICES, blank=False)
sent_time = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.phone
I found modified __init__ method for my forms.py:
class RateAddForm(forms.ModelForm):
class Meta:
model = Rating
def __init__(self, region_id=None, **kwargs):
super(RateAddForm, self).__init__(**kwargs)
if region_id:
self.fields['salesman'].queryset = Salesman.objects.filter(region=region_id)
And also my views.py is this:
def report_add(request, region_id):
if request.method == 'POST':
print(region_id)
form = RateAddForm(request.POST, region_id=region_id)
if form.is_valid():
message = "Thanks!"
form.save()
return HttpResponse(message)
else:
print("Something went wrong!")
form = RateAddForm()
else:
form = RateAddForm(request.POST)
return render(request,
'account/report.html',
{'form': form})
It still shows me all salesmen on my database, even if i choose a region. How to solve this problem that form should show only salesmen of selected region. Thanks in advance!
Try setting the self.base_fields['salesman'].queryset instead of
self.fields['salesman'].queryset (i.e "base_fields" instead of "fields").
(That's what I do when I need to filter in Admin forms)
I have a view in which the user can edit their profile everything worked fine and everything was being updated (biography, first_name, username, email and profile-picture) but now that I added a new app that contains three views in which the user can upload, delete and like posts, the user update sistem stoped working for some reason just the (update, email, first_name)still worked. The update view calls 2 models, User that lets you edit(name, username and email) and Profile that lets you edit(bio and change the profile pictures) it looks like when I added the upload, delete and like functions mentioned before, the whole Profile model "disapeared" even tho is there. The error I am getting is RelatedObjectDoesNotExist User has no profile.
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_pic = models.ImageField(upload_to='profile_pics', null=True, blank=True, default='default.png')
bio = models.CharField(max_length=400, default=1, null=True)
connection = models.CharField(max_length = 100, blank=True)
follower = models.IntegerField(default=0)
following = models.IntegerField(default=0)
def __str__(self):
return f'{self.user.username} Profile'
class Post(models.Model):
text = models.CharField(max_length=200)
video = models.FileField(upload_to='clips', null=True, blank=True)
user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username')
liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked')
updated = models.DateTimeField(auto_now=True)
created =models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.text)
LIKE_CHOICES = (
('Like', 'Like'),
('Unlike', 'Unlike'),
)
class Like(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=10)
def __str__(self):
return str(self.post)
views.py
def edit_profile(request):
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
form1 = UpdateProfileForm(request.POST, request.FILES, instance=request.user.profile)
if form.is_valid and form1.is_valid:
form.save()
form1.save()
return redirect('profile')
else:
form = EditProfileForm(instance=request.user)
form1 = UpdateProfileForm(instance=request.user)
args = {
'form': form,
'form1': form1,
}
return render(request, 'profile-edit.html', args)
urls.py
urlpatterns = [
path('<username>/', views.profile, name='profile'),
path('edit-profile', views.edit_profile, name='edit-profile'),
]
forms.py
class EditProfileForm(UserChangeForm):
class Meta:
model = User
fields = (
'first_name',
'username',
'email',
)
exclude = ('password',)
class UpdateProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = (
'bio',
'profile_pic',
)
If you need to see more code please let me know in the comments.
Add the following in your views before the if statement:
profile, created = Profile.objects.get_or_create(user=request.user)
You need the ", created" since the result of get_or_create will be a tuple not an object - the profile either already exists or must be created.
For your new problem, change the following line:
form1 = UpdateProfileForm(request.POST, request.FILES, instance=request.user.profile)
to:
form1 = UpdateProfileForm(request.POST or None, request.FILES, instance=request.user.profile)
I am following this tutorial: https://tutorial-extensions.djangogirls.org/en/homework_create_more_models/
Which i am adding onto a simple blog I made so i can add comments
Me error:
name 'get_object_or_404' is not defined
From this method in views.py
def add_comment_to_post(request, pk):
post = get_object_or_404(Post, pk=pk)
# post = Post
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('post_detail', pk=post.pk)
else:
form = CommentForm()
return render(request, 'add_comment_to_post.html', {'form': form})
As you see the #hashed out line. This allows me to get to the comment view but then then I get the error that Cannot assign "<class 'blog.models.Post'>": "Comment.post" must be a "Post" instance.
That makes sense but wanted to point that out.
I assume this is a database issue?
my models.py:
from django.db import models
from django.contrib.auth.models import User
STATUS = (
(0,"Draft"),
(1,"Publish")
)
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
class Comment(models.Model):
comment = models.CharField(max_length=100)
created_on = models.DateTimeField(auto_now_add=True)
post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments')
def __str__(self):
return self.comment
class Meta:
ordering = ['created_on']
Everything in the tutorial has been followed to a T. I even went through it 3 times, and re copy and pasted everything in, re migrated, etc.
Is there something I am missing the point of?
For the error
name 'get_object_or_404' is not defined
I looked around the blog, and they don't seem to import get_object_or_404. Add to the top of your code:
from django.shortcuts import get_object_or_404
Here is documentation on it.
I am using CreateView from DJango to save data to the DB. To do this, I am following the instructions here: Form handling with class-based views
According to my understanding, after the data is saved to the DB, the control is to be passed to a type of "success screen" - in this case, for my scenario, control is to be passed to a "details page". The details page is represented by the following URL:
url(r'^owner/(?P<pk>[0-9]+)/contact/details/$', views.MstrstoreheadcontactDetailsView.as_view(),
name='owner-contact-details'),
Below (in the class Mstrstoreheadcontact) the "details page" is being called by the get_absolute_url function (which is part of the Mstrstoreheadcontact model)
from the models.py file
class Mstrstoreheadcontact(models.Model):
tenantid = models.ForeignKey('Mstrauthowner', models.DO_NOTHING, db_column='tenantid', blank=True, null=True)
contactid = models.BigIntegerField(primary_key=True, default=0)
genderid = models.BigIntegerField(blank=True, null=True, default=0)
firstname = models.CharField(max_length=20, blank=True, null=True)
lastname = models.CharField(max_length=20, blank=True, null=True)
officephoneno = models.CharField(max_length=20, blank=True, null=True)
cellphoneno = models.CharField(max_length=20, blank=True, null=True)
class Meta:
managed = False
db_table = 'MstrStoreHeadContact'
def get_absolute_url(self):
return reverse('masterdata:owner-contact-details', kwargs={'pk': self.contactid})
For me the code: return reverse('masterdata:owner-contact-details', kwargs={'pk': self.contactid} is supposed to take the control to the "details page" that will display the new record that has been added to the DB.
The problem
When the code above is executed, the variable self.contactid is set to 0. See below:
This results in the following URL to be placed in the address bar:
http://127.0.0.1:8000/masterdata/owner/0/contact/details
Because of the "0", this leads to a 404 error. In the DB, the value is set - for example to 10.
Again, the data saves to the DB JUST FINE- there is no problem with
this part. The problem lies with what happens AFTER the data is saved
to the DB.
Below are some entries from the urls.py file
from the urls.py file
url(r'^owner/(?P<pk>[0-9]+)/contact/details/$', views.MstrstoreheadcontactDetailsView.as_view(),
name='owner-contact-details'),
url(r'^owner/(?P<tenantid>[0-9]+)/contacts/add/$', views.MstrstoreheadcontactCreateView.as_view(),
name='owner-contact-add'),
from the views.py file
class MstrstoreheadcontactCreateView( CreateView ):
model = Mstrstoreheadcontact
fields = [ 'firstname', 'lastname', 'genderid', 'officephoneno', 'cellphoneno']
def form_valid(self, form):
contact = form.save(commit=False)
contact.tenantid = Mstrauthowner.objects.get(tenantid=self.kwargs['tenantid'])
return super(MstrstoreheadcontactCreateView, self).form_valid(form)
It seems like the code is not getting the data back from the DB properly (after the data has been saved). What can I do to fix the problem?
TIA
Well, thank goodness for debuggers. The following changes resolved all the problems for me :-)
views.py
class MstrstoreheadcontactCreateView( CreateView ):
model = Mstrstoreheadcontact
fields = [ 'firstname', 'lastname', 'genderid', 'officephoneno', 'cellphoneno']
def form_valid(self, form):
form.instance.tenantid = Mstrauthowner.objects.get(tenantid=self.kwargs['tenantid'])
return super(MstrstoreheadcontactCreateView, self).form_valid(form)
models.py
class Mstrstoreheadcontact(models.Model):
tenantid = models.ForeignKey('Mstrauthowner', models.DO_NOTHING, db_column='tenantid', blank=True, null=True)
contactid = models.BigIntegerField(primary_key=True, default=0)
[... snip ..]
def get_absolute_url(self):
[... snip ...]
return reverse('masterdata:owner-contact-details', kwargs={'pk': self.tenantid.pk})
I have a Modelform:
class POwner4NewModel(ModelForm):
class Meta:
model = ProductOwner
exclude = ("o_owner","o_owner_desc","o_product_model","o_main_image","o_thumbnail","o_gallery_images","o_timestamp","o_status")
This is the model's schema:
class ProductOwner(models.Model):
o_owner = models.ForeignKey(User, verbose_name="Owner")
o_owner_desc = models.TextField(verbose_name="Seller Description")
o_product_model = models.ForeignKey(ProductModel, verbose_name="Product")
o_main_image = models.ImageField(upload_to=settings.CUSTOM_UPLOAD_DIR, verbose_name="Product Main Image", blank=True)
o_thumbnail = models.ImageField(upload_to=settings.CUSTOM_UPLOAD_DIR, verbose_name="Product Thumbnail (100x100)px", blank=True)
o_gallery_images = models.ManyToManyField(ProductImages, verbose_name="Product Gallery Images", related_name="product_images", blank=True)
o_status = models.CharField(max_length=100, choices=PRODUCT_STATUS, verbose_name="Product Status", default="approved")
o_timestamp = models.DateTimeField(auto_now_add=True, verbose_name="Date Created")
o_internationlisation = models.ManyToManyField(Countries, verbose_name="Available in", related_name="product_countries")
This is my code trying to save the form:
def save_m_owner(self, request):
form = POwner4NewModel(request.POST, request.FILES)
form = form.save(commit=False)
form.o_owner = request.user
form.o_owner_desc = self.product_model.p_description
form.o_product_model = self.product_model
form.o_status = "unapproved"
form.o_main_image = self.product_model.p_main_image
form.save()
I've tried adding form.save_m2m() but it says form does not have that attribute. So now, in the field using o_internationlisation, the m2m is not saved. I'm not sure what I'm doing wrong here, could use some help, thanks!
form doesn't have save_m2m() because you overwrote form with a model instance when you did form = form.save(commit=False)
try using something else like instance = form.save(commit=False) etc. then you should be able to use form.save_m2m() (of course after the instance.save()).