How can I get user selected radio option? Django - python

I have a model named UserAddress and a form created from the same model which is UserAddressForm.
class UserAddress(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
address = models.CharField(max_length=120)
address2 = models.CharField(max_length=120, null=True, blank=True)
city = models.CharField(max_length=120, null=True, blank=True)
phone = models.CharField(max_length=120)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __unicode__(self):
return self.get_address()
def get_address(self):
return"%s,%s,%s,%s" %(self.address, self.address2,self.city,self.phone)
I am displaying all the user addresses in the html with a radio check-box. I want to get the user selected address in my view and assign to another model instance which I am unable to figure out. How can I do this?

If your models structure is following:
class UserAddress(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
address = models.CharField(max_length=120)
address2 = models.CharField(max_length=120, null=True, blank=True)
city = models.CharField(max_length=120, null=True, blank=True)
phone = models.CharField(max_length=120)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __unicode__(self):
return self.get_address()
def get_address(self):
return"%s,%s,%s,%s" %(self.address, self.address2,self.city,self.phone)
class Order(models.Model):
address = models.ForeignKey(UserAddress)
You can make a form based on Order model, put ModelChoiceField and specify widget to be RadioSelect
from django import forms
class OrderForm(forms.Form):
address = forms.ModelChoiceField(
queryset=UserAddress.objects.all(),
widget=forms.widgets.RadioSelect(),
)
In that case when you handle OrderForm submit you will have address which user is choose.

Related

Cannot assign "'1'": "Groups.profile" must be a "Profile" instance

I have Profile Model that have instance model user.. I am trying to create group using form. that group model have Profile model as instance, so how do I select authenticated user automatic to create group, I getting confused...
This is my Group Model
class Groups(models.Model):
profile = models.ForeignKey(Profile, related_name='my_groups', on_delete=models.CASCADE)
groups_name = models.CharField(max_length=150)
slug = models.SlugField(max_length=150, unique=True)
cover_pic = models.ImageField(upload_to='images/groups/', null=True, blank=True)
type_group = models.CharField(max_length=150)
created_date = models.DateTimeField(auto_now_add=True)
about_group = models.TextField(max_length=600)
members = models.ManyToManyField(Profile,through="GroupMember")
def __str__(self):
return self.groups_name
This is my profile Model
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
slug = models.SlugField(max_length=100, unique=True)
profile_pic = models.ImageField(upload_to='images/user/profile/', null=True, blank=True)
cover_pic = models.ImageField(upload_to='images/user/profile/', null=True, blank=True)
user_bio = models.TextField(null=True,blank=True, max_length=255)
designation = models.CharField(blank=True,null=True, max_length=255)
education = models.CharField(blank=True, null=True, max_length=255)
marital_status = models.CharField(blank=True, null=True, max_length=60)
hobbies = models.CharField(blank=True, null=True, max_length=500)
location = models.CharField(blank=True, null=True, max_length=500)
mobile = models.IntegerField(blank=True, null=True)
def __str__(self):
return str(self.user)
This is form for create group
class GroupCreateForm(forms.ModelForm):
class Meta:
model = Groups
fields = ('cover_pic', 'profile', 'groups_name', 'type_group', 'about_group')
profile = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control input-group-text',
'value':'',
'id':'somesh',
'type': 'hidden',
}))
This is create group html file
this is html page
this is error..
You have set a CharField for profile in your form. When you send data to this form, it tries to make a Group record with a FK to a CharField for example "1" and this gives you error because you should pass Profile object to Group.
Depends on what exactly you want, there are some options.
You can use ModelChoiceField. Read about it in https://docs.djangoproject.com/en/3.2/ref/forms/fields/#django.forms.ModelChoiceField
Or you can use Inline FormSet and read about it in https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets
And an example for Inline FormSet in Creating a model and related models with Inline formsets

User object has no attribute customer

I am trying to create cart using django but i am getting this error. while I try to check that the user is authenticated or no i used customer = request.user.customer but it says user has no attribute customer
Here is my views.py
def cart(request):
if request.user.is_authenticated:
customer = request.user.customer
order, created = OrderModel.objects.get_or_create(customer=customer, complete=False)
items = order.orderitem_set.all()
else:
items = []
context = {}
return render(request, 'Home/cart.html', context)
here is my models.py
class CustomerModel(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE, null=True, blank=True, default='')
customer_name = models.CharField(max_length=1000, null=True)
customer_phone = models.CharField(max_length=20, null=True)
def __str__(self):
return self.customer_name
class OrderModel(models.Model):
customer = models.ForeignKey(CustomerModel, on_delete=models.SET_NULL, null=True, blank=True)
order_date = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False,null=True,blank=True)
transaction_id = models.CharField(max_length=1000, null=True)
def __str__(self):
return str(self.id)
class OrderItem(models.Model):
product = models.ForeignKey(ProductModel, on_delete=models.SET_NULL, null=True, blank=True)
order = models.ForeignKey(OrderModel, on_delete=models.SET_NULL, null=True, blank=True)
quantity = models.IntegerField(default=0, null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
class Address(models.Model):
customer = models.ForeignKey(CustomerModel, on_delete=models.SET_NULL, null=True, blank=True)
order = models.ForeignKey(OrderModel, on_delete=models.SET_NULL, null=True, blank=True)
address = models.CharField(max_length=10000)
city = models.CharField(max_length=1000)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.address
I am stuck here and cant understand what to do.
I think changing the line customer = request.user.customer to customer = request.user.customermodel may solve your problem. If you want to use customer = request.user.customer add related name to your CustomerModel's field:
user = models.OneToOneField(User, on_delete = models.CASCADE, null=True, blank=True, default='', related_name='customer')
Note: Make sure that your user object has a related profile.
For example add an extra condition to your codes like following:
if hasattr(request.user, 'customer'): # If you have related name otherwise use customermodel
customer = request.user.customer
else:
# Return a proper message here
Because if your user object has no related profile this line of code will raise RelatedObjectDoesNotExist error type.
For the user field of the CustomerModel, you must set "related_name" and "related_query_name" to "customer":
user = models.OneToOneField(User, on_delete = models.CASCADE, null=True, blank=True, default='', related_name='customer', related_query_name='customer')
You have to set the "related_name" parameter in your CustomerModel customer field for reverse access
user = models.OneToOneField(User, related_name="user", on_delete = models.CASCADE, null=True, blank=True, default='')
if you don't set the related name django will generate field name + "_set" for the access (user_set in your example)

Why django model save function does not respond?

I am trying to create a blog post model and I added a schedule filed on Django model that I can schedule my post by date and time if schedule time == now. Then post should be verified and display to dashboard so for this I used def save function. But save function does not respond. When I tried to schedule a blog post from admin panel it did not change verified = True. Here is code what I did so far:
from django.utils import timezone
now = timezone.now() # get the current time
class Blog(models.Model):
author = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="post")
title = models.CharField(_("Title of blog post"),
max_length=250, null=True, blank=True)
header = models.CharField(
_("Blog title eg. TIPS, "), max_length=250, null=True, blank=True)
slug = models.SlugField(_("Slug of the title"), max_length=250,
unique_for_date='publish', null=True, blank=True)
photo = models.ImageField(_("Blog post main image"), default="img.png",
null=True, blank=True, upload_to='users/avatar')
read_time = models.TimeField(
_("Blog post read time"), null=True, blank=True)
category = models.ForeignKey(Category, verbose_name=_(
"Blog category list"), on_delete=models.CASCADE, null=True, blank=True)
publish = models.DateField()
tags = TaggableManager(blank=True)
description = HTMLField()
views = models.IntegerField(default="0") # <- here
verified = models.BooleanField(
_("Approved post before push on production"), default=False)
schedule = models.DateTimeField(
_("Schedule post by date and time"), auto_now=False, auto_now_add=False, null=True, blank=True)
class Meta:
verbose_name = _('blog')
verbose_name_plural = _('blogs')
def __str__(self):
return self.title
def save(self, *args, **kwargs):
if self.schedule >= now:
self.verified = True
print(self.verified)
else:
self.slug = slugify(self.title) # this also not respond
super(Blog, self).save(*args, **kwargs)
what is now ? I don't see it defined. I think that the correct way to do it is
from django.utils.timezone import now
if self.schedule <= now():
do it
The save() function is only called when you save an object. This thus means that although an object has a self.schedule that is already passed the current timestamp, one should wait until the object is saved again (and that can take a long time).
It is better to annotate the queryset with a field that specifies that it is verified when self.scheduled is less than (or equal to) Now(). We thus can define a manager that injects the annotation, and remove the verified field:
from django.db.models import BooleanField, ExpressionWrapper, Q
from django.db.models.functions import Now
class BlogManager(models.Manager):
def get_queryset(self, *args, **kwargs):
return super().get_queryset(*args, **kwargs).annotate(
verified=ExpressionWrapper(Q(scheduled__lte=Now()), BooleanField())
)
class Blog(models.Model):
author = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="post")
title = models.CharField(_("Title of blog post"),
max_length=250, null=True, blank=True)
header = models.CharField(
_("Blog title eg. TIPS, "), max_length=250, null=True, blank=True)
slug = models.SlugField(_("Slug of the title"), max_length=250,
unique_for_date='publish', null=True, blank=True)
photo = models.ImageField(_("Blog post main image"), default="img.png",
null=True, blank=True, upload_to='users/avatar')
read_time = models.TimeField(
_("Blog post read time"), null=True, blank=True)
category = models.ForeignKey(Category, verbose_name=_(
"Blog category list"), on_delete=models.CASCADE, null=True, blank=True)
publish = models.DateField()
tags = TaggableManager(blank=True)
description = HTMLField()
views = models.IntegerField(default=0)
schedule = models.DateTimeField(
_("Schedule post by date and time"), auto_now=False, auto_now_add=False, null=True, blank=True)
objects = BlogManager()

How do I make a input from the user to search for something in django/python?

I'm relatively new in python/django thing. Having 3 models with some fields for example:
class Card(models.Model):
id = models.AutoField(primary_key=True)
cardtype_id = models.CharField(max_length=10)
holder_name = models.CharField(max_length=100)
card_number = models.IntegerField(default=0)
email = models.EmailField(blank=True)
birthday = models.DateField(blank=True, default=None)
created = models.DateTimeField(default=timezone.now)
updated = models.DateTimeField(default=timezone.now)
strip = models.CharField(max_length=20, default="strip")
def __str__(self):
return self.holder_name
class Transaction(models.Model):
id = models.AutoField(primary_key=True)
description = models.CharField(max_length=100)
class CardTransactions(models.Model):
card = models.ForeignKey(Card, on_delete=models.CASCADE)
transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE)
value = models.DecimalField(max_digits=7, decimal_places=2, blank=True)
value_date = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(default=timezone.now)
description = models.CharField(max_length=200, blank=True)
table_value = models.DecimalField(max_digits=7, decimal_places=2, blank=True)
discount = models.DecimalField(max_digits=7, decimal_places=2, blank=True)
net_value = models.DecimalField(max_digits=7, decimal_places=2, blank=True)
doc_number = models.CharField(max_length=20, blank=True)
How can I ask the user to input, for example, the "card_number" and print out the "description" on a HTML page?
from django.forms import model_to_dict
def my_view(request):
card_num = request.GET.get('cc')
return HttpResponse(str(model_to_dict(Card.objects.filter(card_number=card_num).first()))
at least something like that
You will need to write views and templates to do this task.
One view would be to render the html template where you will have a form to input the value.
Clicking on the button will call another view with parameter card_number which will retrieve the description from the database associated with the card_number and return back to the template where the same can be shown with some div as per your design.
Ajax can be used to call the view and fetch the response.
See below links for reference:
https://docs.djangoproject.com/en/2.0/intro/tutorial03/
https://docs.djangoproject.com/en/2.0/intro/tutorial04/

Make a form from models using ModelForm, Models have many Foreignkeys( one class is the foreign key for the other.)

I wanted to make a form which should be showing all the fields defined in models, wether the fields include a foreign key to some other class in the models. I am using ModelForm to generate forms.
My models look like
class Employee(Person):
nickname = models.CharField(_('nickname'), max_length=25, null=True,
blank=True)
blood_type = models.CharField(_('blood group'), max_length=3, null=True,
blank=True, choices=BLOOD_TYPE_CHOICES)
marital_status = models.CharField(_('marital status'), max_length=1,
null=True, blank=True, choices=MARITAL_STATUS_CHOICES)
nationality = CountryField(_('nationality'), default='IN', null=True,
blank=True)
about = models.TextField(_('about'), blank=True, null=True)
dependent = models.ManyToManyField(Dependent,
through='DependentRelationship')
pan_card_number = models.CharField(_('PAN card number'), max_length=50,
blank=True, null=True)
policy_number = models.CharField(_('policy number'), max_length=50,
null=True, blank=True)
# code specific details
user = models.OneToOneField(User, blank=True, null=True,
verbose_name=_('user'))
date_added = models.DateTimeField(_('date added'), auto_now_add=True)
date_modified = models.DateTimeField(_('last modified'), auto_now=True)
#models.permalink
def get_absolute_url(self):
return ('contacts_employee_detail', [str(self.id)])
class Person(models.Model):
"""Person model"""
title = models.CharField(_('title'), max_length=20, null=True, blank=True)
first_name = models.CharField(_('first name'), max_length=100)
middle_name = models.CharField(_('middle name'), max_length=100, null=True,
blank=True)
last_name = models.CharField(_('last name'), max_length=100, null=True,
blank=True)
suffix = models.CharField(_('suffix'), max_length=20, null=True,
blank=True)
slug = models.SlugField(_('slug'), max_length=50, unique=True)
phone_number = generic.GenericRelation('PhoneNumber')
email_address = generic.GenericRelation('EmailAddress')
address = generic.GenericRelation('Address')
date_of_birth = models.DateField(_('date of birth'), null=True, blank=True)
gender = models.CharField(_('gender'), max_length=1, null=True,
blank=True, choices=GENDER_CHOICES)
class Address(models.Model):
"""Street Address model"""
TYPE_CHOICES = (
('c', _('correspondence address')),
('p', _('present address')),
('m', _('permanent address')),
)
address_type = models.CharField(_('address type'), max_length=1,
choices=TYPE_CHOICES)
content_type = models.ForeignKey(ContentType,
limit_choices_to={'app_label': 'contacts'})
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
street = models.TextField(_('street'), blank=True, null=True)
city = models.CharField(_('city'), max_length=200, blank=True, null=True)
province = models.CharField(_('State/UT'), max_length=200, blank=True,
null=True)
post_code = models.CharField(_('postal code'), max_length=15, blank=True,
null=True)
country = CountryField(_('country'), default='IN')
date_added = models.DateTimeField(_('date added'), auto_now_add=True)
date_modified = models.DateTimeField(_('date modified'), auto_now=True)
So please if anyone could help me out, or suggest me some useful links from where i can get some help. Thank You!!!
Here is the documentation...
Basic usage is:
class EmployeeForm(ModelForm):
class Meta:
model = Employee
fields = ('somefield','otherfield')
etc...
fields is a optional argument, used for defining witch fields will be presented on the form... You can also override some fields using the following
class EmployeeForm(ModelForm):
otherfield = forms.CharField(...)
class Meta:
model = Employee
fields = ('somefield','otherfield')
That means, Your form is created from Employee model, "somefield" and "otherfield" will be added as form fields, and somefield will be populated directly from your model, but otherfield will be defined as if you override it in the form class...
EDIT: Overriding is used for small changes, so ,it is not right to change the data type of the field... As far as you gave the field same name, there is no problem, it will match the related model field using the name of the form field... So:
class SomeModel(Model):
somefield = CharField()
class SomeForm(ModelForm):
somefield = Charfield(Widget=...)
class Meta:
model = SomeModel
Since field names are equivalent, there is no problem...
Basic reason for overriding is, you may wish to use a widget to change the appearance of the form field(making a TextField looks like a single line Charfield) or pass some attributes (like defining cols and rows of a text field, or addng a simlpe datepicker to a datetime field. Or you may wish to use choices parameter to populate a field with value-label pairs...
You must aviod any kind of data-based changes, if you do, you might get a database level error.

Categories

Resources