My goal is to let users upload files to user-specific folders.
The error I get is
no such column: notendur_document.user_id
Here is the relevant part of my views.py file. This is where the upload happens.
#login_required
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('notendur.views.list'))
else:
form = DocumentForm() # An empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render_to_response(
'notendur/list.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
This is my models.py file:
def _upload_path(instance,filename):
return instance.get_upload_path(filename)
class Document(models.Model):
docfile = models.FileField(upload_to=_upload_path)
user = models.ForeignKey(User)
def get_upload_path(self,filename):
return "media/uploads/"+str(self.user.id) + "/" + '%Y.%m.%d' + filename
According to the relevant .html file, the error happens in the documents variable in list().
register user method in views.py:
def register_user(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
args = {}
args.update(csrf(request))
args['form'] = UserCreationForm()
return render_to_response('register.html', args)
Just pass pk=True in your foreingkey
ex. user = models.ForeignKey(User,pk=True)
this will solve the issue
Related
I always get this Error
DoesNotExist at /file/new/1
StaffUser matching query does not exist.
My models.py
class StaffUser(User):
department = models.ForeignKey(Dept, on_delete=models.RESTRICT)
My Views.py
def FileUploadForm(request, pk):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
folder = Folder.objects.get(id=pk)
if form.is_valid():
form.save(commit=False)
u = StaffUser.objects.get(username=request.user)
form.instance.fileuser = u
form.instance.folder = folder
form.instance.department = u.department
form.save()
messages.success(request, f'File Successfully uploaded to {folder}!')
return redirect('home')
else:
form = UploadFileForm()
return render(request, "pages/fileup_form.html", {'form': form, 'pk':pk})
I want to get the department of the user and add to the database
This is my update views:
def EditDoctor(request,slug=None):
if request.method == "POST":
obj = get_object_or_404(Doctor,slug=slug)
form = DoctorUpdateFrom(request.POST,instance=obj)
if form.is_valid():
form.save()
return redirect('hospital:all-doctor')
else:
form = DoctorUpdateFrom()
context = {'doctor_form':form}
return render (request,'hospital/edit-doctor.html', context)
The main problems I am not seeing any existing value in my forms. it's just rendering an empty forms.
You need to pass the instance to the form in case of a GET request as well:
def EditDoctor(request,slug=None):
obj = get_object_or_404(Doctor,slug=slug) # 🖘 fetch the object for both paths
if request.method == "POST":
form = DoctorUpdateFrom(request.POST,instance=obj)
if form.is_valid():
form.save()
return redirect('hospital:all-doctor')
else:
form = DoctorUpdateFrom(instance=obj) # 🖘 pass the instance to edit
context = {'doctor_form':form}
return render (request,'hospital/edit-doctor.html', context)
In general, I make a page on the site. The meaning is this: a person comes in, loads an xml file, selects several parameters, and outputs the result. I did not find how to handle the xml file at once. So I upload its file with the parameters to the database, and then redirect us to the page with the result. Everything works fine, but there is a problem. I have not figured out how to create a unique link for the result each time. Now I have one link for the results and it just shows the last one ...
views.py of uploader
def upload_file(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('lessons:index')
else:
form = DocumentForm()
return render(request, 'templates/upload/upload.html', {'form': form})
downloader
views.py of handler
def lessons_view(request):
a = keker()
return render(request, 'templates/lessons/ocenki.html', {'ocenki': a})
keker if handler function
Try code like this (python 3.6):
# models.py
class Document(Model):
...
reference = CharField(max_length=128, db_index=True, null=False)
...
# forms.py
import secrets
...
class DocumentForm(ModelForm):
...
def save(self, commit=True):
self.instance.reference = secrets.token_hex(128)
return super().save(commit)
# views.py
...
def upload_file(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('lessons:index', kwargs=dict(reference=form.instance.reference))
else:
form = DocumentForm()
return render(request, 'templates/upload/upload.html', {'form': form})
...
def lessons_view(request, reference):
a = keker(reference)
return render(request, 'templates/lessons/ocenki.html', {'ocenki': a})
# urls.py
...
url(r'^/(?P<reference>\w+)/$', 'index', name='index'),
...
I want to redirtect page, after saving modelform. when i pushed save button, page redirecte, but no any things saved.
def channelAdd(request):
if request.method == 'POST':
form = ChannelForm(request.POST)
if form.is_valid():
channelid = form.cleaned_data['channelid']
form.save()
return HttpResponseRedirect(reverse('updateChannelInfo', args=[channelid]))
else:
form = ChannelForm()
return render(request, 'web/channelAdd.html', {'form':form})
This will get you closer to the solution. I'm not positive if you have 'updateChannelInfo' as the name in urls.py (so please double-check that). I think the complexity here is getting the correct channelId to be sent
def channelAdd(request):
if request.method == 'POST':
form = ChannelForm(request.POST)
if form.is_valid():
channelid = form.cleaned_data['channelid']
form.save()
return HttpResponseRedirect(reverse('updateChannelInfo', args = [self.object.id])))
else:
form = ChannelForm()
return render(request, 'web/channelAdd.html', {'form':form})
If you are willing to share your urls.py and forms.py files, this would help with getting the correct names into arguments
Another way I have had success with the dynamic direct after form submission is to use
def add_channel (request):
if request.method == 'POST':
form = ChannelForm(request.POST)
if form.is_valid():
channel.save()
return HttpResponseRedirect(reverse('channel_detail', args=[channel.id]))
else:
form = ChannelForm()
return render(request, 'channel_example.html', {'form': form})
Edit your view like this,
if form.is_valid():
form.save()
return redirect('updateChannelInfo', channelId=self.object.id)
I have a Django form that allows a user to save their UserProfile details, but it only allows this to occur once. Given that additional saves ask to create a new entry, but i have a one-to-one relation between the user field and user UserProfile field.
When a user is created a UserProfile entry is not created. Rather they cannot access their account until these details are filled out.
I want to pre-populate the form with existing data when a student goes to access the form a second time.
def student_details(request):
#this is a form
if request.user.is_authenticated():
if request.method == 'POST':
form = DetailsForm(request.user, request.POST, request.FILES)
if form.is_valid():
note = form.save(commit=False)
note.user = request.user
note.completed_form = True
note.save()
return HttpResponseRedirect('/student-portal/')
else:
if request.user.get_profile():
pass
form = DetailsForm(request.user)
else:
form = DetailsForm(request.user)
return render_to_response("student-details.html", {'form': form}, context_instance=RequestContext(request))
return HttpResponseRedirect('/')
Sorry guys just found out how to do this:
def student_details(request):
#this is a form
if request.user.is_authenticated():
if request.method == 'POST':
form = DetailsForm(request.user, request.POST, request.FILES)
if form.is_valid():
note = form.save(commit=False)
user_profile = UserProfile.objects.get(user=request.user)
if user_profile:
note.id = user_profile.id
note.user = request.user
note.completed_form = True
note.save()
return HttpResponseRedirect('/student-portal/')
else:
try:
user_profile = UserProfile.objects.get(user=request.user)
form = DetailsForm(request.user, instance=user_profile)
except:
form = DetailsForm(request.user)
return render_to_response("student-details.html", {'form': form}, context_instance=RequestContext(request))
return HttpResponseRedirect('/')
The idea here is to query to see if a user_profile linked to that user already exists and then specify the ID for that entry.