Problems saving to database on form - django

I'm trying to edit and save changes from my form to PostgreSQL database. I'm able to get the correct ID and can view everything fine. When I try and save it to the database it never saves, the form just does a quick refresh. If I use the shell I can update without any issues.
from turnover.models import *
t = Detail.models.get(id=1)
t.shift = 'Swing'
t.save()
Here is the link to the django code I'm currently working with. it's just snippits to give an ovewview of where I'm having problems.
Python Code: https://gist.github.com/1363921
HTML Update Template: https://gist.github.com/1363940
EDIT:
Issue was resolved, I had a field that was required that I was not filling out, thanks for the help from jro on using {{ form.errors }}

Related

Delete rows set to be deleted in a formset and duplicates issues

I know this question has been asked before (e.g. Django modelformset_factory delete modelforms marked for deletion) but I've tried all the possible solutions, including doing what the official documentation says (https://docs.djangoproject.com/en/3.0/topics/forms/formsets/), and I still cannot delete the forms from my formset.
I have a form which correctly sends POST data with everything I need (including the DELETE instruction).
[print(form_links_event.cleaned_data) for form in form_links_event.deleted_forms]
[{'description': 'asdasd', 'link': 'http://www.test.com', 'id': <linksEvent: linksEvent object (25)>, 'DELETE': True}
Nevertheless, I need to process the formset before saving all the instances (I need to attach the id of a related model), so I need to call save(commit=False):
instances_links_event = form_links_event.save(commit=False)
for link in instances_links_event:
link.event = instance_event
link.save()
form_event.save()
form_links_event.save()
Doing so, though, strips the .deleted_forms list. In fact:
[print(instances_links_event.cleaned_data) for form in instances_links_event.deleted_forms]
AttributeError: 'list' object has no attribute 'deleted_forms'
Therefore I'm stuck in a loop: I cannot save my form directly because I need to attach more data to it first, and in its raw state it has the 'deleted_forms' list. Once I save it with commit=False and process with the processing, though, the 'deleted_forms' is not there any more so that I cannot delete those rows set for deletion. Ideally, I'd like to do this:
instances_links_event = form_links_event.save(commit=False)
for link in instances_links_event:
if (link.delete = True):
link.delete()
link.event = instance_event
link.save()
form_links_event.save()
I'm using Django 3.0.6 with Python 3.7.
Update
Even without the commit=False, saving the form with form_links_event.save(), I keep having issues: when I save the form in my 'edit page' (i.e. bound form) save() saves the existing records again, even if I didn't edit anything, which means I end up with a lot of duplicates. Is something wrong with Django formset or is it just me?
My form:
<tbody id='linksEvent_body'>
{% for formLink in form_links_event.forms %}
{{formLink.non_field_errors}}
{{formLink.errors}}
<trclass="formLink">
{{ formLink.id }}
<td>{{formLink.link}}</td>
<td>{{formLink.description}}{{formLink.DELETE}}</td>
</tr>
{% endfor %}
</tbody>
I've been battling with this and working for days on end, trying all sorts of possible parameters and code. I found out that the first time the form is loaded/bound after having saved it, it is not loading the form_management data correctly (i.e. the -INITIAL value is not correct and the extra blank form is not there) and also the bound data is not always updated. If I try to fix it via JavaScript, for example counting the number of forms displayed and put that number in the -CURRENT parameter and that number -1 in the -INITIAL or things like that, Django wouldn't like it (the documentation itself says that it is discouraged to tamper with the form management data anyway, which I understand). Once I'd manually refresh the page (by placing the cursor on the address bar and hit enter, not by hitting ctrl/cmd + R, which would ask me to send the POST data again), then the form loads correctly and any further edit would nicely save correctly. So, the only way I could find to solve this issue, which looks and sound like a Django inline forms bug to me, is by placing this code in the page containing the form:
<script type='text/javascript'>
(function()
{
if( window.localStorage )
{
if( !localStorage.getItem('firstLoad') )
{
localStorage['firstLoad'] = true;
window.location=window.location;;
}
else
localStorage.removeItem('firstLoad');
}
})();
</script>
With this code in place everything works like a charm. I hope this will help others who'll face this frustrating issue like myself.
PS: the issue is independent from the commit=False instruction. And yes, I declared #never_cache in my view.

Django redirect page does not update the view

I'm using the Django Framework on Google App Engine.
I have multiple forms on the same view, to submit to different URL.
Trouble is after I get a form submitted: even if the called method update the datastore and some data, the previous page (where the forms are put in) is not refreshed, showing the updated data.
I could solve this problem using jQuery or some javascrip framework, appending dinamically content returned by the server but, how to avoid it?
Suggestions?
Am I wrong somewhere?
A part of "secure.html" template
<form action="/addMatch" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
Matches:
<br />
{% for m in matches%}
{{m.description}} ---> {{m.reward}}
{% endfor%}
the "/addMatch" URL view:
def addMatch(request):
form = MatchForm(request.POST)
if form.is_valid():
user = User.all().filter('facebookId =', int(request.session["pbusr"]))
m = Match(user=user.get(),description =form.cleaned_data["description"],reward=form.cleaned_data["reward"])
m.save()
return HttpResponseRedirect("/secure/")
else:
logging.info("Not valid")
return HttpResponseRedirect("/secure")
The view method whose seems not working:
#auth_check_is_admin
def secure(request):
model={}
user = User.all().filter('facebookId =', int(request.session["pbusr"]))
u = user.get()
if (u.facebookFanPageId is not None and not u.facebookFanPageId == ""):
model["fanPageName"] = u.facebookFanPageName
model["form"] = MatchForm()
model["matches"] = u.matches
else:
....
return render(request,"secure.html",model)
Francesco
Based on what you posted, it seems like you're redirecting properly and are having database consistency issues. One way to test this would be to look at the network tab in the Google Chrome developer tools:
Click on the menu icon in the upper right
Click on "Tools"
Click on "Developer Tools"
Click on "Network" in the thing that opened up at the bottom of the screen.
Now, there will be a new entry in the network tab for every request that your browser sends and every response it receives. If you click on a request, you can see the data that was sent and received. If you need to see requests across different pages, you might want to check the "Preserve log" box.
With the network tab open, go to your page and submit the form. By looking at the network tab, you should be able to tell whether or not your browser issued a new GET request to the same URL. If there is a new request for the same page but that request has the old content, then you have a datastore consistency issue. If there was NOT a new request that yielded a response with the data for the page, then you have a redirect issue.
If it turns out that you have a datastore consistency issue, then what's happening is the data is being stored, but the next request for that data might still get the old data. To make sure that doesn't happen, you need what's called "strong consistency."
In a normal App Engine project, you get strong consistency by putting entities in the same entity-group and using ancestor queries. I'm not certain of what database/datastore you're using for Django and how the different database layers interact with App Engine's consistency, so this could be wrong, but if you can give your users the right key and then fetch them from that key directly (rather than getting all users and filtering them by key), you might get strong consistency.

django 1.6 with django_tables2 cannot change DATETIME_FORMAT

python 2.7.5+. django_tables2 0.14.0
In settings.py:
USE_L10N = True
DATETIME_FORMAT = 'M j, Y H:i:s.u'
Didn't work. I tried {% load L10N %} at the top of my template. Didn't work.
I created a formats directory at the top of my project containing an en directory containing formats.py and added the following to my settings.py (yes, there are init.py files in the formats directory and in the en directory):
FORMAT_MODULE_PATH = '<project>.formats'
Didn't work.
I tried putting in {{created_at|date: 'M j, Y'}}{{created_at|time: 'H:i:s.u'}} before the {% render_table table %} tag from django_tables2. Got an error.
Tried the recommended django_tables2 method of, in my tables.py definition, adding to the Meta class:
localize('created_at')
Didn't work.
Tried putting 'localize=True' in the column definition for created_at in tables.py.
Didn't work.
The only thing that worked was modifying python2.7/site-packages/django/conf/locale/en/formats.py (in my virtual environment) but I won't be allowed to do that on my project because it's not considered portable.
I see stackoverflow entries that say this works but they are many years old and many django versions back. I see others here that say this doesn't work and they haven't/aren't going to fix it.
This functionality logs requests; during testing the other devs could really use seeing seconds and probably microseconds to help them debug but I can't seem to give it to them.
Any suggestions that I haven't already tried?
Thanks.
OK, blush - I got it. I made the following change in the model for the DateTimeField created_at:
#property
def nice_date(self):
# mm/dd/yyyy HH:mm:ss.uuuuuu
t = self.created_at.strftime("%m/%d/%Y %H:%M:%S.%f")
return t
Then, I displayed nice_date instead of created_at.
I hope this helps someone else.

Django-haystack search with whoosh returns 'No results' debugging unsuccessful

I am new to Django and Haystack. I have done everything suggested on the "getting started" page of the Haystack Documentation and on the debugging page, but I cannot see where my error lies. sqs.count() returns 0 even though rebuild_index seems to work, giving the right number of entries in the tables being indexed and producing index files into the whoosh_index directory.
search_indexes has the required text = lines, I have a search_sites.py, I have changed the settings.py and urls.py, and I have [model_name]_text.txt files in the right directory.
We are working on a university server where we had to update Django to work with Haystack after we installed Haystack because we realized it was an incompatible version (1.1 not 1.5) - could the old Django have messed with the Haystack installation somehow?
The following code will show you what has been indexed - replace with the correct path for your setup.
from whoosh.index import open_dir
ix = open_dir('<yourapp>/whoosh_indexes')
from pprint import pprint
pprint(list(ix.searcher().documents()))
If that doesn't shed any light you will have to post more details of your code - particularly the search_indexes.py
This might seem obvious but I had the same error and reading from http://django-haystack.readthedocs.org/en/latest/debugging.html I found out that I was using the wrong attribute name for the returned objects.
ensure that {{ result.object.title }} corresponds to your model field
for instance I had name as the model filed but kept wondering why I didn't get results.
I had to change to {{ result.object.name }} to list my results
name was the needed attribute. Hope this helps someone.

IntegrityError at /comments/post/ in django comments

I have been using Django inbuilt comments framework, for some time and it was working absolutely fine. Since we are in development phase initially after testing it, we did not try it out.
But yesterday I posted a comment, just for the fun of it and I landed with this error
IntegrityError at /comments/post/
(1048, "Column 'content_type_id' cannot be null")
This is not specific to any particular model, but happens on whichever model the comment is posted.
This error does not come when the comment is posted as an anonymous user
The comment is getting posted
I fail to understand what could have caused this error, the other things that we have been developing, have not in any way interfered with the comments app.
I know I have put very little information, but any kind of help will be really appreciated.
Not sure based on the information you've provided why you would be getting that error, but generally, comments package uses generic foreign keys from the contenttypes package to link the comment to whatever it "belongs" to. The error you're getting is because (for whatever reason) what the comment "belongs" to is undefined when saving the comment.
The default form to submit comments actually includes the contextual object that it should "belong" and passes this data along with the POST when the comment is submitted. Normally, you would display this form using {% render_comment_form %} template tag and pass in the owner:
{% render_comment_form for [owner] %}
Where [owner] the object that the comment would belong to.
Or you might use the {% get_comment_form %} tag to be able to customize the form:
{% get_comment_form for [owner] as form %}
If you've used an entirely custom way of including the form, you should check to make sure that you're passing all the hidden values that either of those two tags would include by default.
Additionally, if you are customizing the form, it's important to set the form's action with the {% comment_form_target %}.
Hopefully, that will be enough to help you further troubleshoot the problem.