I am facing mapping user and profile in django - python

I am facing a problem with Django profile mapping with user.There is coming None in admin view
This is my models.py
profile_of = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)
session = models.CharField(max_length=20, blank=False, null=False )
batch = models.IntegerField() # batch = models.IntegerField(blank=False, null=False)
iit_program = models.CharField(blank=True, choices=IIT_PROGRAM, max_length=10)
college = models.CharField(max_length=50)
graduate_university = models.CharField(max_length=50, default='Dhaka University')
graduate_department = models.CharField(max_length=50, default='Software Engineering')
photo = models.ImageField(blank=True)
is_current = models.BooleanField(default=True)
This is my views.py
from django.shortcuts import render
from .forms import UserProfile
from django.contrib.auth.decorators import login_required
#login_required(login_url= '/accounts/login/')
def userProfileview(request):
form = UserProfile(request.POST or None)
if form.is_valid():
form.save()
context = {'form':form}
return render(request,'userprofile.html', context)
This is my forms.py
from django import forms
from .models import Profile
class UserProfile(forms.ModelForm):
class Meta:
model = Profile
fields =
['iit_program','batch','session','graduate_university','graduate_department','photo']

What you see in the admin list view is the Model converted to a string, you can control how the model is converted with the str function, the return value of this function must be a string
class Profile(models.Model):
profile_of = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)
...
def __str__(self):
return self.profile_of.name

Related

Connect the username when sending a report in django

I am beginner to django and I am trying to create a site to send reports after creating a profile, but when I send the report, the username of the author of the report is not saved, Just (None). I searched a lot about it and did not find it
models.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, verbose_name=("user"), null=True, on_delete=models.CASCADE)
identity_No = models.IntegerField( blank=True, null=True)
mobile_No = models.IntegerField( blank=True, null=True)
city = models.CharField( max_length=15,null=True)
class Meta:
verbose_name =("Profile")
verbose_name_plural =("Profile")
def __str__(self):
return '%s' %(self.user)
class Report(models.Model):
user = models.ForeignKey(User, verbose_name=("user"), on_delete=models.CASCADE)
Report_type =models.CharField( max_length=100, blank=True, null=True)
Region =models.CharField( max_length=30, blank=True, null=True)
city =models.CharField( max_length=30, blank=True, null=True)
sector =models.CharField( max_length=30, blank=True, null=True)
report =models.TextField( max_length=3000, blank=True, null=True)
files =models.FileField( blank=True, null=True)
class Meta:
verbose_name =("Report")
verbose_name_plural =("Report")
def __str__(self):
return '%s' %(self.user)
form.py
Shorten the time, attach only the report
class ReportForm(forms.ModelForm):
class Meta:
model = Report
fields = ['Report_type', 'Region', 'city','sector','report','files' ]
view.py
def report(requst):
if requst.method == 'POST':
report_form = ReportForm(requst.POST)
if report_form.is_valid() :
report_form.save()
return redirect ('accounts:home')
else:
report_form = ReportForm()
return render(requst, 'user/report.html', {
'report_form': report_form,
enter image description here })
You can link the new report wrapped in the ReportForm to the logged in user request.user with:
from django.contrib.auth.decorators import login_required
#login_required
def report(requst):
if requst.method == 'POST':
report_form = ReportForm(requst.POST)
if report_form.is_valid():
report_form.instance.user = request.user
report_form.save()
return redirect ('accounts:home')
else:
report_form = ReportForm()
return render(requst, 'user/report.html', { 'report_form': report_form })
Note: You can limit views to a view to authenticated users with the
#login_required decorator [Django-doc].

slug not auto generate after add page in django

I tried to add page for posts blog article for my django site.But it's slug model is not autogenerate after add it into the add post page but it work well in admin page.
example in title field when i type how to master python fastly it will auto generated in slug field with "-" in only admin page.but when I type same thing on add post page it won't generate slug automatically.
mycode
models.py
from django.db import models
from django.contrib.auth.models import User
from django_summernote.fields import SummernoteTextField
from django.urls import reverse
from django.template.defaultfilters import slugify
STATUS = (
(0,"Draft"),
(1,"Publish")
)
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
title_type = models.CharField(max_length=50, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = SummernoteTextField(blank=True, null=True)
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
image = models.ImageField(upload_to='images',null=True, blank=True)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('home')
views.py
class AddPostView(CreateView):
model = Post
form_class = PostForm
template_name = 'add_post.html'
admin page
And add post page
The slug field should not be editable, remove the 'slug' field from the fields of AddPostView and of the Admin.
class AddPostView(CreateView):
model = Post
fields = ['title', 'title_type', 'author', 'updated_on', 'content',
'created_on', 'status', 'image']
form_class = PostForm
template_name = 'add_post.html'

Trying to implement Django Admin model validation

I am a beginner and trying to implement bid system in Django. I want it to work on both Django admin page and and template, therefore I created modelform and modeladmin in Admins.py.
models.py:
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
class category(models.Model):
category = models.CharField(max_length=50, default='SOME STRING')
def __str__(self):
return f"{self.category}"
class bid(models.Model):
listing = models.ForeignKey('listing', on_delete=models.CASCADE)
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
bid = models.DecimalField(max_digits=6, null=True, decimal_places=2)
def __str__(self):
return f"{self.user}, {self.listing} {self.bid}"
class listing(models.Model):
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
Title = models.CharField(max_length=50)
Description = models.CharField(max_length=300)
Price = models.DecimalField(max_digits=6, null=True, decimal_places=2)
category = models.ForeignKey(category, on_delete=models.CASCADE, related_name="categories")
def __str__(self):
return f"{self.Title}"
admin.py
from django.contrib import admin
from .models import User, listing, category, bid
from django.core.exceptions import ValidationError
from django import forms
admin.site.register(User)
admin.site.register(listing)
admin.site.register(category)
class bidForm(forms.ModelForm):
class Meta:
model=bid
fields = ['user', 'listing', 'bid']
def clean(self):
start_price = self.cleaned_data.get('listing.Price')
userbid = self.cleaned_data.get('bid')
if userbid <= start_price:
raise ValidationError('Please place a bid higher than starting price')
return self.cleaned_data
class bidAdmin(admin.ModelAdmin):
form = bidForm
list_display = ('user', 'listing', 'bid')
admin.site.register(bid, bidAdmin)
It returns the following error:
'<=' not supported between instances of 'decimal.Decimal' and 'NoneType'.
Also I want to compare instances of previous and current bid on a listing to place a new bid, also modify any of previously placed bids even if it's lower than highest bid. but I have no idea how to code that. Please, help me...

Django NOT NULL constraint failed: shop_product.user_id

I am new to Django and I am trying to learn by practicing with some project but I am stuck with this problem,
NOT NULL constraint failed: shop_product.user_id
models.py
from django.db import models
from django.conf import settings
from django.core.urlresolvers import reverse
class Category(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='category_created')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Product(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='product_created')
category = models.ForeignKey(Category, related_name='products')
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
available = models.BooleanField(default=True)
negiotiable = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='product_liked',
blank=True)
class Meta:
ordering = ('name',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('products_detail',
args=[self.slug])
Here is my views.py but am not sure if there is problem with my views and I think the problem will have to be with my models....
views.py
from django.views.generic import *
from django.core.urlresolvers import reverse_lazy
from .models import Category, Product
class CategoryList(ListView):
model = Category
class CategoryDetail(DetailView):
model = Category
class ProductList(ListView):
model = Product
class ProductDetail(DetailView):
model = Product
class ProductCreate(CreateView):
model = Product
fields = ("category", 'name', 'image', 'description', 'price', 'stock','available', 'negiotiable')
class ProductUpdate(UpdateView):
model = Product
fields = ('name', 'image', 'description', 'price', 'stock','available', 'negiotiable')
class ProductDelete(DeleteView):
model = Product
success_url = reverse_lazy('product_list')
Please let me know what could be done.
Either Add User into list:
class ProductCreate(CreateView):
model = Product
fields = ["category", 'name', 'image', 'description', 'price','stock','available', 'negiotiable', 'user']
OR make sure Field must be null=true and blank=True.
class Product(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='product_created', null=True, blank=True)
Add a form for your product,
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = "__all__"
Also, your user field must be null=True and blank=True.
Then in your create view,
class ProductCreate(CreateView):
model = Product
form_class = ProductForm
def form_valid(self, form):
form.instance.user = self.request.user
form.save()
return super(ProductCreate, self).form_valid(form)
Now, whenever a product is created, the user who created would be added as the user of the product.

type object 'UploadSerializers' has no attribute 'HyperlinkedModelSerializer'

trying to do the Django Rest Framework foreign key serialization ,,however I got this error,
models.py
class ProductsTbl(models.Model):
model_number = models.CharField(
max_length=255,
blank=True,
unique=True,
error_messages={
'unique': "這 model number 已經被註冊了 ."
}
)
name = models.CharField(max_length=255, blank=True, null=True)
material = models.CharField(max_length=255, blank=True, null=True)
color = models.CharField(max_length=255, blank=True, null=True)
feature = models.TextField(blank=True, null=True)
created = models.DateTimeField(editable=False)
modified = models.DateTimeField(auto_now=True)
release = models.DateTimeField(blank=True, null=True)
twtime = models.DateTimeField(blank=True, null=True)
hktime = models.DateTimeField(blank=True, null=True)
shtime = models.DateTimeField(blank=True, null=True)
jptime = models.DateTimeField(blank=True, null=True)
suggest = models.TextField(blank=True, null=True)
description = models.TextField(blank=True, null=True)
user = models.ForeignKey(User, blank=True, null=True)
useredit = models.CharField(max_length=32, blank=True, null=True)
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.created = timezone.now()
return super(ProductsTbl, self).save(*args, **kwargs)
def get_image_path(instance, filename):
return '/'.join(['thing_images', instance.thing.slug, filename])
class Upload(models.Model):
thing = models.ForeignKey(ProductsTbl, related_name="uploads")
image = models.ImageField(upload_to=get_image_path, verbose_name='Image')
def save(self, *args, **kwargs):
super(Upload, self).save(*args, **kwargs)
if self.image:
image = Image.open(self.image)
i_width, i_height = image.size
max_size = (640, 480)
if i_width > 1000:
image.thumbnail(max_size, Image.ANTIALIAS)
image.save(self.image.path)
api/serializers.py
from rest_framework import serializers
from ..models import *
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
UserModel = get_user_model()
class UploadSerializers(serializers.ModelSerializer):
class Meta:
model = Upload
fields = ('image',)
class ProductsTblSerializer(serializers.HyperlinkedModelSerializer):
uploads = UploadSerializers.HyperlinkedModelSerializer(many=True,read_only=True)
class Meta:
model = ProductsTbl
fields = ('model_number',
'created',
'name',
'release',
'twtime',
'hktime',
'shtime',
'jptime',
'feature',
'material',
'suggest',
'description',
'cataloggroup',
'place',
'scale',
'slug',
'user',
'uploads')
api/urls.py
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^productsTbls/$', views.ProductsTblListView.as_view(), name='productsTbls_list'),
url(r'^productsTbls/(?P<pk>\d+)/$', views.ProductsTblDetailView.as_view(), name='productsTbls_detail'),
url(r'^productsTbls/pdelete/(?P<id>[-\w]+)/$',views.api_delete_product,name='api_delete_p'),
url(r'^productsTbls/register/$', views.CreateUserView.as_view(), name='productsTbls_register'),
]
api/views.py
from rest_framework.parsers import JSONParser
from django.views.decorators.csrf import csrf_exempt
from django.forms import modelformset_factory
from django.template.defaultfilters import slugify
from rest_framework import permissions
from rest_framework.generics import CreateAPIView
from django.contrib.auth import get_user_model
from rest_framework.permissions import AllowAny
class ProductsTblListView(generics.ListCreateAPIView):
queryset = ProductsTbl.objects.order_by('-created')
serializer_class = ProductsTblSerializer
class ProductsTblDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = ProductsTbl.objects.all()
serializer_class = ProductsTblSerializer
however ,,if I changed the api/serializers.py like below
......
class ProductsTblSerializer(serializers.ModelSerializer):
uploads = UploadSerializers(many=True,read_only=True)
......
I can see http://127.0.0.1:8000/api/productsTbls/ my page come out,,but without the image link,how can I show the image link in "uploads":[]? thank you (django rest framework 3.4)
You've inherited your UploadSerializer class from serializers.ModelSerializer, not from serializers.HyperLinkedModelSerializer
class UploadSerializers(serializers.ModelSerializer):
class Meta:
model = Upload
fields = ('image',)
So when you try to use it as
uploads = UploadSerializers.HyperlinkedModelSerializer(many=True,read_only=True)
it doesn't have that attribute.
If you make your initial declaration of UploadSerializers inherit from the hyperlink class, it should work.
class UploadSerializers(serializers.HyperlinkedModelSerializer):
class Meta:
model = Upload
fields = ('image',)
Then you should be able to use:
uploads = UploadSerializers(many=True,read_only=True)

Categories

Resources