Ad
Django Wont Store AuthUser Referenced As Foreign Key In My Model
I created my model that have authUser referenced as foreign key, then using django Form API i am trying to store data into my DB but my user field remains null.
I have used build-in FORM API to receive an uploaded file and before storing my file, i also store filename. I tried to do the same for userField but django throw ValueError.
Models.py
class sample(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True ,default=1)
submit_time = models.DateTimeField(auto_now=True)
file_name = models.CharField(max_length=1024)
score = models.FloatField(default=0.0)
is_pending = models.BooleanField(default=True)
is_complete = models.BooleanField(default=False)
json_URL = models.FilePathField()
sample = models.FileField(upload_to='samples/')
Views.py
@login_required
def upload(request):
if request.method == 'POST':
file = request.FILES['sample']
form = SampleForm(request.POST, request.FILES)
if form.is_valid():
new_sample = form.save(commit=False)
new_sample.file_name = file.name
new_sample.user = User.id #throws ValueError Cannot assign "sample.user" must be a "User" instance.
form.save()
return redirect('reports')
else:
print("form is invalid")
else:
form = SampleForm()
if request.method == 'GET':
return render(request, 'upload2.html', {'form': form})
forms.py
class SampleForm(forms.ModelForm):
class Meta:
model =sample
fields=('sample',)
my goal is to save the user id in my db so i know who uploaded the file.
Ad
Answer
You should use request.user
to the new_sample.user
object, or request.user.id
(or request.user.pk
) to the request.user_id
attribute, like:
# …
new_sample = form.save(commit=False)
new_sample.file_name = file.name
new_sample.user = request.user
form.save()
return redirect('reports')
# …
By using User.id
, you get a reference to the field of the User
model, not an object.
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad