I have a model in Django with a foreign key to Django User Model. I am trying to update my model with a form, but database isn't updating. I can't figure out the problem.
model.py
from django.conf import settings
class UserInfo(models.Model):
username = models.CharField(max_length = 30)
owner = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,)
form.py
from django import forms
from society.models import UserInfo
class Editform(forms.ModelForm):
username=forms.CharField(widget=forms.TextInput(attrs={'onchange': 'this.form.submit();', 'class': 'editinput'}))
class Meta:
model = UserInfo
fields ='__all__'
views.py
from django.shortcuts import render
from society.models import UserInfo
from django.contrib.auth.models import User
from society.forms import Editform
def ProfileView(request):
user = request.user
username = UserInfo.objects.get(owner=user)
if request.method == 'POST':
form = Editform(request.POST, instance=username)
if form.is_valid():
form.save()
else:
form = Editform(instance=username)
return render (request, 'profile_view.html', {'user':username, 'form':form})
url.py
from django.conf.urls import url
from django.contrib import admin
import society.views
urlpatterns = [
url(r'^$', 'society.views.home'),
url(r'^admin/', admin.site.urls),
url(r'^login/', 'django.contrib.auth.views.login'),
url(r'^logout/', 'django.contrib.auth.views.logout'),
url(r'^userreg/', 'society.views.UserReg'),
url(r'^profile/', 'society.views.ProfileView'),
]
profile_view.html
<div>
<form method="POST">
{% csrf_token %}
{{form.username}}
{{user.username}}
</form>
</div>
When ever I change form.username, user.username change instantly but the database is not updating. I tried with adding a submit button, but still no luck.
You should pass record id for updating existing UserInfo record.
from django.shortcuts import render
from society.models import UserInfo
from django.contrib.auth.models import User
from society.forms import Editform
def ProfileView(request):
user_id = request.POST.get('user_id')
user = UserInfo.objects.get(pk=user_id)
if request.method == 'POST':
form = Editform(request.POST, instance=user)
if form.is_valid():
form.save()
else:
form = Editform(instance=user)
return render (request, 'profile_view.html', {'user':username, 'form':form})
You can update in 2 method for eg: here i am going to update Your username,
1) if you using object.get():
get_name = UserInfo.objects.get(owner=user)
get_name['username'] = 'Your Input what you need to change'
get_name.save()
2) if you using object.filter():
get_name = UserInfo.objects.filter(owner=user).update(username='your data') # or form.username
Thats it..
Apart from anything else, you haven't pointed your form at anything, so the form can't connect to the logic of the view - in effect, you've specified the form should POST content, but not where to.
The form should point to a URL in your urls.py file, which is of course linked to the view you've shown above. That works in the following way:
<form action="{% url 'core.views.new_comment' %}" method="post">
{% csrf_token %}
...
</form>
There's more guidance about how this works here in the docs. (Obviously people know that the answer's in the docs, the trick is finding it. :) )
(Also, your formatting is off in the views.py, but I think that's just a cut and paste problem when entering the question.)
Anyway I soloved this problem, Thank You everyone. Just Changed the form.py
from django import forms
from society.models import UserInfo
class Editform(forms.ModelForm):
username=forms.CharField(widget=forms.TextInput(attrs={'onchange': 'this.form.submit();', 'class': 'editinput'}))
class Meta:
model = UserInfo
exclude =('owner',)
As owner is a mandatory field, but I omitted it from template it was showing mandatory field error. Its working now. Thanks anyway.
Related
I created a small Django application to manage data that fits a simple a model. For now I only need two views: one to list all records and another to edit a record with a generic form. Everything functions as expected, except the redirection from the edit view upon a successful update. In urls.py are the following contents:
from django.urls import path
from . import views
app_name = 'reqs'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.ReqUpdateView.as_view(), name='update'),
]
In forms.py:
from django.forms import ModelForm
from .models import Requirement
class RequirementForm(ModelForm):
class Meta:
model = Requirement
fields = ['name', 'priority', 'source' , 'rationale']
And the templeate requirement_form.html:
<h1>{{ requirement.id }} - {{ requirement.name }}</h1>
<form method="post" novalidate>
{% csrf_token %}
<table>
{{ form.as_table }}
<tr><td></td><td><button type="submit">Save</button></td></tr>
</table>
</form>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<br><br>
Back to list
Finally views.py, on a first attempt to redirect the update to the list:
from django.views.generic import ListView, UpdateView
from django.urls import reverse_lazy
from .models import Requirement
from .forms import RequirementForm
class IndexView(ListView):
template_name = 'reqs/index.html'
context_object_name = 'requirements_list'
def get_queryset(self):
return Requirement.objects.order_by('subject')
class ReqUpdateView(UpdateView):
model = Requirement
form_class = RequirementForm
success_url = reverse_lazy('/')
With this formulation the Save button produces this error:
Reverse for '/' not found. '/' is not a valid view function or pattern name.
I also tried an empty string as argument to reverse_lazy, as well as the path name index, but a similar error message is produced.
On a second attempt I tried to redirect to the same page, redefining the get_success_url method to do nothing:
class ReqUpdateView(UpdateView):
model = Requirement
form_class = RequirementForm
context_object_name = 'requirement_update'
def get_success_url(self):
pass #return the appropriate success url
This returns a 404 error trying to redirect the browser to /reqs/1/None.
A third attempt to redirect to the form with the same record:
class ReqUpdateView(UpdateView):
model = Requirement
form_class = RequirementForm
context_object_name = 'requirement_update'
def get_success_url(self):
pk = self.kwargs["pk"]
return reverse("update", kwargs={"pk": pk})
Which complains about not finding the view:
Reverse for 'update' not found. 'update' is not a valid view function or pattern name.
How can I redirect success to a valid URL? It can either be the items list or the item update view, as long as it works.
There are few misconception that you did
reverse parameter should be as documented
URL pattern name or the callable view object
You have set namespace but you are not reversing with namespace as documented
So in your case
def get_success_url(self):
pk = self.kwargs["pk"]
return reverse("reqs:update", kwargs={"pk": pk})
reverse / reverse_lazy are used to get the url using view name or pattern name. If you want to use a url directly just write:
success_url = '/'
For the case of return reverse("update", kwargs={"pk": pk}) not working since you set app_name = 'reqs' you should be using return reverse("reqs:update", kwargs={"pk": pk}) instead.
I am trying to show a newsletter form, and it is not shown in the page
This is my models.py
from django.db import models
# Create your models here.
class newsletter_user(models.Model):
email = models.EmailField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.email
This is my forms.py
from django import forms
from .models import newsletter_user
class newsletterForm(forms.ModelForm):
class Meta:
model = newsletter_user
fields = ['email']
def clean_email(self):
email = self.cleaned_data.get('email')
return email
This is my admin.py
from django.contrib import admin
from .models import newsletter_user
# Register your models here.
class newsletterAdmin(admin.ModelAdmin):
list_display = ('email','date_added',)
admin.site.register(newsletter_user,newsletterAdmin)
This is the views.py
from django.shortcuts import render
from .models import newsletter_user
from .forms import newsletterForm
# Create your views here.
def newsletter_subscribe(request):
form = newsletterForm(request.POST or none)
if form.is_valid():
instance = form.save(commit=false)
if newsletter_user.objects.filter(email=instance.email).exists():
print("already exists")
else:
instance.save()
context = {'form':form,}
template = "/blog/templates/footer.html"
return render(request, template, context)
This is the html
<form method="post" action=''>
<div class = "input-group">
{{form}} {% csrf_token %}
<span class = "input-group-btn">
<button class="btn btn-default" type="submit">Subscribe</button>
</span>
</div>
</form>
This is my urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.BlogIndex.as_view(), name='home'),
url(r'^(?P<slug>[-\w]+)/$', views.BlogDetail.as_view(), name='entry_detail'),
url(r'^ckeditor/', include('ckeditor_uploader.urls')),
url(r'^footer/$', subscribe_views.newsletter_subscribe, name='subscribe'),
]
My Project directory
The button is shown
But the form is not shown..
This is my source in web browser RIGHT-CLICK->VIEW SOURCE
The url router will send the request to the first matching view. That is the only one that is called, and that view has to provide the context data that the template consumes. (You can also write your own context processor to insert context that you need everywhere.)
Since another pattern also matches /footer/, your request is clearly handled by some other view.
url(r'^(?P<slug>[-\w]+)/$', views.BlogDetail.as_view(), name='entry_detail'),
If the other view doesn't provide form into the context, there's nothing for Django to render.
Your view function newsletter_detail() is not called from other views, so that context is not used. (Using the undefined none there would have caused a run time error, which shows that the code was never evaluated.)
Catch-all routes such as entry_detail should either be used as the last url route, or be made more specific. Something like r'^/blog/(?P<slug>[-\w]+)/$', for instance, which will not match /footer/.
For a simple "subscribe" form in the footer, I recommend writing it as just html, and set up a route /subscribe/ to handle POST requests. There's not anything to gain by using Django's form framework for such a simple case (Just one field).
The django docs has an example of how you can implement something like this.
You footer.html template fragment should not require any context that is not automatically inserted by a context processor. Django's CsrfViewMiddleware provides the {% csrf_token %}, so that's an example of something you can use in template fragments such as a footer.
If you need some complicated form in your footer, you can write custom middleware to insert a Django Form instance in every context, (but you should probably give it a less generic name than form).
You may need to make some changes in your view somewhat like this,
def newsletter_subscribe(request):
if request.method == 'POST':
form = newsletterForm(request.POST)
if form.is_valid():
instance = form.save(commit=false)
if newsletter_user.objects.filter(email=instance.email).exists():
print("already exists")
else:
instance.save()
else:
form = newsletterForm()
context = {'form':form,}
template = "/blog/templates/footer.html"
return render(request, template, context)
You only need to initialise the form with request.POST , if request method is actually "POST". Else, just initialise a blank form.
I'm trying to create a marketplace website similar to craigslist.
I created a form according to the Django tutorial "Working with forms", but I don't know how to render information I got from the POST forms.
I want to make information(subject,price...etc) that I got from POST show up on another page like this. http://bakersfield.craigslist.org/atq/3375938126.html and, I want the "Subject"(please look at form.py) of this product(eg.1960 French Chair) to show up on another page like this. http://bakersfield.craigslist.org/ata/ }
Can I get some advice to handle submitted information?
Here's present codes. I'll appreciate all your answers and helps.
<-! Here's my codes -->
◆forms.py
from django import forms
class SellForm(forms.Form):
subject = forms.CharField(max_length=100)
price = forms.CharField(max_length=100)
condition = forms.CharField(max_length=100)
email = forms.EmailField()
body = forms.TextField()
◆views.py
from django.shortcuts import render, render_to_response
from django.http import HttpResponseRedirect
from site1.forms import SellForm
def sell(request):
if request.method =="POST":
form =SellForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
price = form.cleaned_data['price']
condition = form.cleaned_data['condition']
email = form.cleaned_data['email']
body = form.cleaned_data['body']
return HttpResponseRedirect('/books/')
else:
form=SellForm()
render(request, 'sell.html',{'form':form,})
◆urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^sechand/$','site1.views.sell'),
url(r'^admin/', include(admin.site.urls)),
)
◆sell.html
<form action = "/sell/" method = "post">{% csrf_token%}
{{ form.as_p }}
<input type = "submit" value="Submit" />
</form>
I assume you have a Sell model/table in your db(where you store the users' "sells"), otherwise it wouldn't make any sense. This means you can save yourself some time and use a ModelForm,
instead of a simple Form. A model form takes a database table and produces an html form for it.
forms.py
from django.forms import ModelForm
from yourapp.models import Sell
class SellForm(ModelForm):
class Meta:
model = Sell
In your views.py you need one more view that displays the Sells that your users have
posted for others to see. You also need an html template that this view will render with context about each Sell.
sell_display.html
{% extends 'some_base_template_of_your_site.html' %}
{% block content %}
<div id="sell">
<h3> {{ sell.subject }}</h3>
<p> {{ sell.condition }}</p>
<p> {{ sell.body }}</p>
<!-- the rest of the fields.. -->
</div>
{% endblock %}
We also need a new url entry for the displaying of a specific Sell
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Changed `sell` view to `sell_create`
url(r'^sechand/$','site1.views.sell_create'),
# We also add the detail displaying view of a Sell here
url(r'^sechand/(\d+)/$','site1.views.sell_detail'),
url(r'^admin/', include(admin.site.urls)),
)
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from yourapp.models import Sell
from yourapp.forms import SellForm
def sell_detail(request, pk):
sell = get_object_or_404(Sell, pk=int(pk))
return render_to_response('sell_display.html', {'sell':sell})
def sell_create(request):
context = {}
if request.method == 'POST':
form = SellForm(request.POST)
if form.is_valid():
# The benefit of the ModelForm is that it knows how to create an instance of its underlying Model on your database.
new_sell = form.save() # ModelForm.save() return the newly created Sell.
# We immediately redirect the user to the new Sell's display page
return HttpResponseRedict('/sechand/%d/' % new_sell.pk)
else:
form = SellForm() # On GET request, instantiate an empty form to fill in.
context['form'] = form
return render_to_response('sell.html', context)
This is enough to get you going I think. There are patterns to make these things more modular and better, but I don't want to flood you with too much information, since you are a django beginner.
can i add the ajax code with django?
i have created a simple registraion form that have 5 fields . i wish to disply the each fields in different pages but in a single window . it means by using next button 5 pages want to disply in a single window. same time all content of each page i want add to my database. is this possible in django with ajax..
my codes are as follows :
#view
from django.shortcuts import render_to_response
from registration.models import UserDetails
from forms import UserForm
from django import forms
from django.template import RequestContext
from django.http import HttpResponseRedirect
def user_details(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
form.save()
else:
form = UserForm()
return render_to_response("career.html", {"form": form},context_instance=RequestContext(request))
#form
from django import forms
from registration.models import UserDetails
class UserForm(forms.ModelForm):
pass
class Meta:
model = UserDetails
#model
from django.db import models
class UserDetails(models.Model):
fname=models.CharField(max_length=20)
lname=models.CharField(max_length=20)
email = models.EmailField()
address = models.CharField(max_length=50)
country = models.CharField(max_length=20)
def __unicode__(self):
return self.fname
return self.lname
return self.email
return self.address
return self.country
#url
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^registration/$', 'registration.views.user_details', name='user_details'),
url(r'^admin/', include(admin.site.urls)),
)
# template
<form enctype="multipart/form-data" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" ....>
</form>
Whay have you tried for ajax call?
Server just serve some result to client then it is up to your client code:
either it is post back that you refresh page
or iframe, you refresh a frame in parent doc
or html tag like tag that you inject by $(targetElement).html($someResultFromServer)
In most case server does not even care what and how it looks like client(rich or thin),
Thats you javascript, query and css codes which to works on behalf of client. Vice versa, in most case client does not even care what is and how it looks like it is server: Loosely coupled
For ajax calls you can follow this link: http://api.jquery.com/jQuery.ajax/
As Martin Thurau stated your question is very hard to understand. Regardless I think that what you are asking for is a stepped form.
Best you take a look at Django's Form Wizard here
can i add the ajax code with django?
i have created a simple registraion form that have 5 fields . i wish to disply the each fields in different pages but in a single window . it means by using next button 5 pages want to disply in a single window. same time all content of each page i want add to my database. is this possible in django with ajax..
my codes are as follows :
#view
from django.shortcuts import render_to_response
from registration.models import UserDetails
from forms import UserForm
from django import forms
from django.template import RequestContext
from django.http import HttpResponseRedirect
def user_details(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
form.save()
else:
form = UserForm()
return render_to_response("career.html", {"form": form},context_instance=RequestContext(request))
#form
from django import forms
from registration.models import UserDetails
class UserForm(forms.ModelForm):
pass
class Meta:
model = UserDetails
#model
from django.db import models
class UserDetails(models.Model):
fname=models.CharField(max_length=20)
lname=models.CharField(max_length=20)
email = models.EmailField()
address = models.CharField(max_length=50)
country = models.CharField(max_length=20)
def __unicode__(self):
return self.fname
return self.lname
return self.email
return self.address
return self.country
#url
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^registration/$', 'registration.views.user_details', name='user_details'),
url(r'^admin/', include(admin.site.urls)),
)
# template
<form enctype="multipart/form-data" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" ....>
</form>
Whay have you tried for ajax call?
Server just serve some result to client then it is up to your client code:
either it is post back that you refresh page
or iframe, you refresh a frame in parent doc
or html tag like tag that you inject by $(targetElement).html($someResultFromServer)
In most case server does not even care what and how it looks like client(rich or thin),
Thats you javascript, query and css codes which to works on behalf of client. Vice versa, in most case client does not even care what is and how it looks like it is server: Loosely coupled
For ajax calls you can follow this link: http://api.jquery.com/jQuery.ajax/
As Martin Thurau stated your question is very hard to understand. Regardless I think that what you are asking for is a stepped form.
Best you take a look at Django's Form Wizard here