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()).
Related
i have build some user to user message function. i have sender, receiver and text see below. The user now must choose his email and then the email where the message should go.
But what i want is that the user dont need tho choose it self i need a form function that query instantly request.user. but i dont know how to implement that on form. And that the user is not shown in the receiver list. Srry for my bad english hope you understand me.
views.py
def mailEMployee(request):
mail = Mailsysthem.objects.filter(ontvanger=request.user)
receiver = Mailsysthem.objects.filter(ontvanger=request.user)
sender = Mailsysthem.objects.filter(zender=request.user)
user = CustomUser.objects.filter(email=request.user)
form = Mailsythemform()
if request.method == 'POST':
form = Mailsythemform(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('mail')
context={
'form':form,
'receiver':receiver,
'sender':sender.all,
'mail':mail,
'user':user
}
return render(request,'emp/mail.html', context)
Forms.py
class Mailsythemform(forms.ModelForm):
class Meta:
model= Mailsysthem
fields= ['zender','ontvanger','subject','text']
models.py
class Mailsysthem(models.Model):
zender = models.ForeignKey(to=CustomUser, null=True, on_delete=models.SET_NULL,related_name='Zender')
ontvanger = models.ForeignKey(to=CustomUser, null=True, on_delete=models.SET_NULL,related_name='Ontvanger')
subject = models.CharField(null=True, max_length=200)
text = models.TextField(max_length=300, null=True, blank=True, verbose_name='Bericht')
date = models.DateTimeField(auto_now_add=True, blank=True)
solftdelete = models.BooleanField(default=False)
mail_opened = models.BooleanField(default=False)
url.py
path('mailemployee/', views.mailEMployee, name='mail'),
You need to provide initial value to your ModelForm (docs) as following:
form = JournalForm(initial={'sender': user.id})
I need to update the model according to the marked checkboxes in the django shape
How can I get only some of the table fields in a query
the "checked" line should be updated through the queryset
models.py
class moIn(models.Model):
date = models.DateTimeField(auto_now_add=True, verbose_name='')
dateUpdate = models.DateTimeField(auto_now=True)
ts = models.IntegerField(verbose_name='')
pl = models.IntegerField(verbose_name='')
rem = models.IntegerField(verbose_name='')
comment = models.TextField(max_length=200, verbose_name='', blank=True)
staffer = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name='')
checked = models.BooleanField(verbose_name='', default=False)
checkedUser = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name='', blank=True, null=True, related_name='checkedUser')
by clicking this checkbox, you will need to receive database records
forms.py
class checkForm(ModelForm):
checked = fields.BooleanField(required=False)
class Meta:
model = moIn
fields = {"id", "checked"}
views.py
def dashboard(request):
if request.user.groups.filter(name='DashBoardAccess').exists():
form = checkForm
f = tableDashFilter(request.GET, queryset=moIn.objects.all())
if request.method == 'POST':
form = checkForm(request.POST)
if form.is_valid():
tt = form.save(commit=False)
data = form.cleaned_data
field = data['checked']=True
f.qs.filter(checked=field).update(checked=True, checkedUser=request.user)
return HttpResponse('ok')
else:
context = {
'filter': f,
'form': form
}
return render(request, 'dashboard/index.html', context)
else:
raise Http404()
in a line in bold, you need to get only those lines in which the checkbox is marked
f.qs.filter(checked=field).update(checked=True, checkedUser=request.user)
You can get all the fields using ".values ()" for the queryset, and to use it with foreignKey, you need to explicitly specify the model fields:
f = tableDashFilter(request.GET, queryset=moIn.objects.values('id','date','ts','pl','rem','comment','checked','staffer__username','checkedUser__username'))
"Value" from the input, it is also going to be obtained through:
Since there can be several values (marked checkboxes), there will be a ".getlist"
checkID = request.POST.getlist('checked')
querySet filter:
f.qs.filter(id__in=checkID).update(checked=True, checkedUser=request.user)
in the html template through the loop, iterate over and insert into the input value of the model id
So I'm using the Django Form Wizard to split a simplified PostForm. In one of the steps, visitors can upload different images related to the Post.
Within the done method for the SessionWizardView, I'm saving the instance first and then check for the images within the formset.
However I get the following error message;
save() prohibited to prevent data loss due to unsaved related object
I tried setting the related Post id for the formset but I'm missing something here, formsets are still something I can't really follow.. Any help is appreciated!
models.py
class Post(models.Model)
title = models.CharField(max_length=200)
description = models.TextField(max_length=1000)
def __str__(self):
return self.title
class Image(models.Model):
post = models.ForeignKey('Post', on_delete=models.SET_NULL, null=True)
file = models.ImageField(upload_to='images/', null=True, blank=True)
alt = models.CharField(max_length=200, blank=True)
views.py
FORMS = [
('title', PostCreateForm),
('image', ImageFormset)
]
TEMPLATES = {
'title': 'post_form_title.html',
'image': 'post_form_image.html'
}
class PostWizardView(SessionWizardView):
form_list = FORMS
file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'temp/'))
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def done(self, form_list, form_dict, **kwargs):
instance = Post()
for form in form_list:
instance = construct_instance(form, instance)
instance.save()
post_id = instance.pk
if 'image' in form_dict:
formset = form_dict['image']
if formset.is_valid():
formset.save(commit=False)
for form in formset:
form.post = post_id
formset.save()
forms.py
class PostCreateForm(forms.ModelForm):
class Meta:
model = Image
fields = '__all__'
ImageFormset = inlineformset_factory(
Post,
Image,
form = PostCreateForm,
min_num=1,
can_delete=True
)
You should save the individual forms as you loop through them:
if formset.is_valid():
for form in formset:
if form.is_valid():
f = form.save(commit=False)
f.post = post_id
f.save()
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
I am getting an error when I try to update a record in Django using a form. I get an error that a record with that number already exists. Below is my model and view. This is really driving me nuts. I though that Django would just update the record instead of trying to write a new record.
class Report(models.Model):
report_number = models.CharField(max_length=4, unique=True)
detected = models.CharField(max_length=40)
computer_name = models.CharField(max_length=40)
username = models.CharField(max_length=15)
cab_date_time = models.CharField(max_length=40)
collector = models.CharField(max_length=40)
addresses = models.TextField()
fault = models.CharField(max_length=40)
known_malware = models.TextField(default='No')
collected_files = models.TextField(default='None')
registry_keys = models.TextField()
service_number = models.CharField(max_length=15, blank=True)
notes = models.TextField(blank=True)
sample_requested = models.CharField(max_length=4, blank=True)
action = models.CharField(max_length=35, blank=True)
And View
def reports(request, report_number):
instance = get_object_or_404(Report, report_number=report_number)
form = ReportForm(request.POST or None, instance=instance)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
return render(request, 'reports/report.html', {'form': form})
Here is the Form defination
from django.forms import ModelForm
from reports.models import Report
class ReportForm(ModelForm):
class Meta:
model = Report
exclude = ('moderator',)
def reports(request, report_number):
instance = get_object_or_404(Report, report_number=report_number)
if request.method == 'POST':
form = ReportForm(request.POST, instance=instance)
if form.is_valid():
form.save(force_update=True)
return HttpResponseRedirect('/')
else:
form = ReportForm(instance=instance)
return render(request, 'reports/report.html', {'form': form})