How database data can be updated by id - Django - django

Hi guys im new in django and I want to update my database.
I have my form and my model that create correctly all the data in my database.
When this was created the performance field gets default value 0 and the created field gets the creation date.
Everything up to this moment is perfect.
I have this model and this view:
models.py
from django.contrib.auth.models import User
class Model(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
id = models.AutoField(primary_key=True)
performance = models.FloatField(default=0)
created = models.DateTimeField(auto_now_add=True, null=True)
class Meta:
ordering = ['-created']
views.py
def form_x(request):
user = request.user
form = XForm(request.POST or None)
if form.is_valid():
performance = form_data.get('performance')
obj = Model.objects.create(user=user,
performance=performance,)
return redirect('form')
else:
form = TForm()
return render(request, 'funciones/btc.html', {'form':form})
My question:
How can i update the performance field searching by id, AUTOMATICALLY after 1 min
once the POST request has been sent?
i dont know whats better if use a function update view or a Class Update View
What you recommend?
Thank you so much!

Related

Django ModelForm: change a field value when blank

Is there any way to change a field value (related to a foreign key) in a Django ModelForm once the form is initialized and filled by the user (I'm using request.POST). I want to change the value when the user doesn't select any option of the dropdown list. I tried this formulari_mostra.data['pools'] = 1 in views.py after saving the feedback from the form with no result:
def sample_form(request):
formulari_mostra=FormulariMostra()
if request.method=="POST":
formulari_mostra=FormulariMostra(request.POST or None)
if formulari_mostra.is_valid():
feedback = formulari_mostra.save(commit=False)
sample = Sample.objects.all()
feedback.sample = sample
feedback.save()
formulari_mostra.save_m2m()
formulari_mostra.data['pools'] = 1
messages.success(request, 'Mostra enregistrada correctament!')
return render(request, "sample/formulari_mostra.html", {'formulari':formulari_mostra})
I got this message:
This QueryDict instance is immutable
I know I can set an initial (default) before introducing data in the form but I don't want to have the default option highlighted in the dropdown.
My model:
class Sample(models.Model):
id_sample = models.AutoField(primary_key=True)
name = models.CharField(unique=True, max_length=20)
sample_id_sex = models.ForeignKey(Sex, on_delete=models.CASCADE, db_column='id_sex', verbose_name='Sexe')
indexes = models.ManyToManyField(Index, through='SamplePoolIndexCand', through_fields=('sample_id', 'index_id'), blank=True, verbose_name="Índexs")
pools = models.ManyToManyField(Pool, through='SamplePoolIndexCand', through_fields=('sample_id', 'pool_id'), blank=True, verbose_name="Pools")
gene_cand_lists = models.ManyToManyField(GeneCandList, through='SamplePoolIndexCand', through_fields=('sample_id', 'gene_cand_list_id'), blank=True, verbose_name="Llista de gens candidats")
class Meta:
db_table = 'sample'
def __str__(self):
return self.name
My forms.py:
class FormulariMostra(ModelForm):
class Meta:
model = Sample
fields = ("name", "sample_id_sex", "pools",)
first - you are setting the polls property after save() is called, so even if this would work, you are not saving the change.
second - if you want to set the polls property to model, then set it to the model instead of the form (formulari_mostra). I dont know how your models look like, so I can only assume the model which has the pools property is in the variable feedback, so you want to do:
feedback = formulari_mostra.save(commit=False)
feedback.pools = 1
feedback.save()

Django modelformset_factory() adding field manually in views

Disclaimer: I am new at Django so I'm sure my code is ugly.
Problem:
My current Model is built as follows:
class person(models.Model):
email = models.EmailField()
date = models.DateField()
phone_number = models.IntegerField()
name = models.CharField(max_length = 50)
belongs_to_group = models.ForeignKey(Group, related_name='group', on_delete=models.SET_NULL, null=True)
belongs_to_user = models.ForeignKey(User, related_name='user', on_delete=models.SET_NULL, null=True)
I have built a modelformset_factory for this using the following code:
personModelFormset = modelformset_factory(
person,
fields=('email', 'date' , 'phone_number', 'name'),
extra=1)
This makes the fields the form renders in the HTML email, date , phone_number, and name. This means that to successfully save the form to the database, I need to also add the fields belongs_to_group and belongs_to_user manually since the website user shouldn't be able to edit these (they should be automatically generated).
Attempted Solution:
To try to do this, I used the following view:
def classes(request):
#add form creation method here
user = request.user
group = value #taken from another form
if request.method == 'POST':
form_2 = personModelFormset (request.POST)
if form_2.is_valid():
for form in form_2:
form.belongs_to_group = value
form.belongs_to_user = user
form.save()
return redirect('home')
But this does not append the information to the form. This method works for me in a normal modelform, so I think I'm not using the modelformset_factory correctly. Does anyone know how I should correctly append the "behind the scenes" model fields to the formsetfactory? Thank you!

saving foreignkey instances in the createview in views.py

I've a models called job, application, attachments. when a job is already created an a user wants to apply for the job I get an integrity error that says null value in column "job_id" violates not-null constraint
If I add job in the fields part of class Meta of ApplicationForm everything runs successful but when the user select the job he whats to apply he is forced to select again the job to fill in the job field,
So I want is to automatically add the job field to be added in createview in views.py
here is my code
models.py
class Application(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='applied_jobs',
null=True, on_delete=models.SET_NULL)
job = models.ForeignKey(Job, related_name='applications', on_delete=models.CASCADE)
career_briefing = models.CharField(max_length=250, null=True)
class Attachments(models.Model):
application = models.ForeignKey(Application, related_name='attachments', on_delete=models.CASCADE)
cv = models.CharField(max_length=150, null=True)
form.py
class ApplicationForm(forms.ModelForm):
cvs = forms.CharField(max_length=6000, widget=forms.HiddenInput(), required=False)
class Meta:
model = Application
fields = ('career_briefing',)
views.py
class ApplicationCreateView(LoginRequiredMixin, CreateView):
model = Application
form_class = ApplicationForm
message = _("succesfuly applied")
template_name = 'jobs/application_form.html'
message = _("successful")
def form_valid(self, form):
cvs = form.cleaned_data['cvs']
form.instance.user = self.request.user
form.instance.job = self.kwargs.get('pk')
apply = form.save(commit=False)
apply.job = self.kwargs.get('pk')
apply.user = self.request.user
apply.save()
doc = Attachments(cv=cvs)
doc.application = apply
doc.save()
return super(ApplicationCreateView, self).form_valid(form)
def get_success_url(self):
messages.success(self.request, self.message)
return reverse("jobs:list")
urls.py
urlpatterns = [
....
url(r'^details/(?P<pk>\d+)/$', JobDetailView.as_view(), name='detail'),
url(r'^details/apply/$', ApplicationCreateView.as_view(), name='apply'),
.....
]
What I expect is that a user submits the application form successful but i get an integrity error " null value in column "job_id" violates not-null constraint ",
For me I think the job instance is not saved ,if this is the real problem may someone please show me how to solve it,
If that's not the problem may someone help me out with this
thanks in advance

Django multi-form save

I already tried nearly everything I could find regarding this, but I am pretty sure I am just one small suggestion away from solving my issue.
I am trying to save to forms that I generated using the forms method of Django at the same time. These forms have a ForeignKey relationship.
My model:
class Publisher(models.Model):
company = models.CharField(max_length=255)
address1 = models.CharField(max_length=255)
address2 = models.CharField(max_length=255)
city = models.CharField(max_length=255)
zipcode = models.CharField(max_length=10)
email = models.EmailField(max_length=255)
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
tc = models.BooleanField()
timestamp = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.company
class PublisherQuestions(models.Model):
referal = models.TextField()
updates = models.BooleanField()
publisher = models.ForeignKey(Publisher)
preferredCommunication = models.ForeignKey(PublisherCommunication)
def __unicode__(self):
return self.publisher
class PublisherForm(ModelForm):
class Meta:
model = Publisher
class PublisherQuestionsForm(ModelForm):
class Meta:
model = PublisherQuestions
exclude = ('publisher')
and my view:
def register(request):
if request.method == 'POST':
form = PublisherForm(data = request.POST)
formQuestions = PublisherQuestionsForm(data = request.POST)
if form.is_valid() and formQuestions.is_valid():
publisher = form.save()
formQuestions.publisher = publisher
formQuestions.save()
return HttpResponseRedirect('/thanks/')
So, what I try to do, is to save the second form "formQuestions" with the foreign key publisher against the publisher_id from the PublisherForm.
Unfortunately MySQL / Django is giving me the following error.
Column 'publisher_id' cannot be null
This might be a complete newbie question and yes there has been many people asking nearly the same, but none of the solutions worked for me.
Thanks for your help, as always appreciated!
You can try the following to check whether you get the same error or not:
publisher = form.save()
questions = formQuestions.save(commit=False)
questions.publisher = publisher
questions.save()
With commit=False you get the Model without saving it to the database.
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method
In fact it is the Model you want to manipulate, adding the Publisher and not the form.
If you need to access the data from the form I think you should use for example this:
https://docs.djangoproject.com/en/dev/ref/forms/api/#accessing-clean-data
How I understood it is that you have a ModelForm and not a Model, so if you want to manipulate the Model you first need to create it, or at least it is the cleanest way of manipulating Model data. Otherwise you can manipulate the Form data but it is another story, you want to choose the raw data or the clean data etc.

Store the current user in a field of a django model

I'm trying to find the way of store the user who creates an object and I want to do it automatically. I've found some things but nothing works for me. Here is the code:
Models.py:
class Track(models.Model):
...
usuari = models.ForeignKey(User)
Forms.py:
class TrackForm(forms.ModelForm):
class Meta:
model = Track
Views.py
def pujar_track(request):
if request.method=='POST':
formulari = TrackForm(request.POST, request.FILES)
if formulari.is_valid():
formulari.save()
return HttpResponseRedirect('/inici')
else:
formulari = TrackForm()
return render(request,'principal/trackForm.html',
{'formulari':formulari})
I've seen about put:
usuari = models.ForeignKey(User, blank=True, editable=False) but
But I don't know when can I set the user in the field.
Thanks in advice!
You can hide usuari from your TrackForm, so the user can't select it:
class TrackForm(forms.ModelForm):
class Meta:
model = Track
exclude = ('usuari',)
And then, replace your formulari.save() with:
track = formulari.save(commit=False)
track.user = request.user
track.save()
This is a common use case and detailed in the Django docs.