I want to show data in dropdown from database in setting window. Right now I am showing from hard-coded array.
MY_CHOICES = (
('a', 'Cat1'),
('b', 'Cat2'),
)
categories = models.CharField("Survey", help_text="Select Survey", choices=MY_CHOICES, max_length=3, blank=True)
models.py
# encoding: utf-8
from cms.models import CMSPlugin, python_2_unicode_compatible
from django.db import models
from django.core.exceptions import ValidationError
from cms.models import CMSPlugin
class Survey(models.Model):
name = models.CharField(max_length=400)
description = models.TextField()
def __unicode__(self):
return (self.name)
def questions(self):
if self.pk:
return Question.objects.filter(survey=self.pk)
else:
return None
class SurveyPluginModel(CMSPlugin):
MY_CHOICES = (
('a', 'Cat1'),
('b', 'Cat2'),
)
categories = models.CharField("Survey", help_text="Select Survey", choices=MY_CHOICES, max_length=3, blank=True)
name = models.CharField("Survey Name", max_length=255, default='Survey Name',
help_text='Enter Survey Name')
description = models.CharField("Survey Description", max_length=500, blank=True, help_text='Write Description here')
def __str__(self):
return "Returning some Survey Text"
I want to show survey in Edit Setting Window.
How to fill surveys from db value?
Try this
class Survey(models.Model):
name = models.CharField(max_length=400)
description = models.TextField()
def __unicode__(self):
return (self.name)
def questions(self):
if self.pk:
return Question.objects.filter(survey=self.pk)
else:
return None
class SurveyPluginModel(CMSPlugin):
categories = models.ForeignKey("Survey", help_text="Select Survey", max_length=3, blank=True)
name = models.CharField("Survey Name", max_length=255, default='Survey Name',
help_text='Enter Survey Name')
description = models.CharField("Survey Description", max_length=500, blank=True, help_text='Write Description here')
def __str__(self):
return "Returning some Survey Text"
Related
I am getting Issue while edit a record based on CHatquestion ID, if option is null then i need to add a record based on same chatquestion id, if chatqustion id exist in option it will work,
i am trying to multiple way to solve this issue but still can't find solution.
Models.py # thease are all 3 models
class Problem(models.Model):
Language = models.IntegerField(choices=Language_CHOICE, default=1)
type = models.CharField(max_length=500, null=True, blank=True)
def __str__(self):
return self.type
class ChatQuestion(models.Model): # Eding record based on chatquestion id
question = RichTextField(null=True, blank=True)
problem_id = models.ForeignKey(
Problem,
models.CASCADE,
verbose_name='Problem',
)
def __str__(self):
return self.question
is_first_question = models.BooleanField(default=False)
class Option(models.Model):
option_type = models.CharField(max_length=250, null=True, blank=True)
question_id = models.ForeignKey(
ChatQuestion,
models.CASCADE,
verbose_name='Question',
null=True,
blank=True
)
problem=models.ForeignKey(
Problem,
models.CASCADE,
verbose_name='Problem',
null=True,
blank=True
)
next_question_id = models.ForeignKey(ChatQuestion, on_delete=models.CASCADE, null=True, blank=True,
related_name='next_question')
def __str__(self):
return self.option_type
forms.py
class EditQuestionForm(forms.ModelForm):
class Meta:
model = ChatQuestion
fields =('question','problem_id')
class EditOptionForm(forms.ModelForm):
class Meta:
model = Option
fields =('option_type',)
views.py
def question_edit(request,id=None):
if id is not None:
queryset = get_object_or_404(ChatQuestion,pk=id)
queryset1=get_object_or_404(Option,question_id=queryset )
else:
queryset = None
queryset1 = None
if request.method=="POST":
form = EditQuestionForm(request.POST ,instance=queryset)
form1=EditOptionForm(request.POST, instance=queryset1)
if form.is_valid() and form1.is_valid():
question=form.cleaned_data['question']
option_type=form1.cleaned_data['option_type']
if id:
queryset.question=question
queryset.save()
queryset1.option_type=option_type
queryset1.save()
messages.success(request,'Sucessful')
return redirect('/fleet/list_chatbot')
else:
print(form.errors)
messages.error(request,'Please correct following',form.errors)
elif id:
form = EditQuestionForm(instance=queryset)
form1=EditOptionForm(instance=queryset1)
if not queryset1:
form1=EditOptionForm()
else:
form = EditQuestionForm()
form1=EditOptionForm()
context={
'form':form,
'form1':form1
}
return render(request,'chatbot/question_edit.html',context=context)
I am new to django. Currenty I am trying to make social network website. Here is my model of profile class. I want to assign value of slug field to the username of the User. But can't find or think of any way to do this.
If anyone know any way of doing this I'll be thankfull if you suggest me how to do this
from django.contrib.auth.models import User
from django_countries.fields import CountryField
from django.db import models
class Profile(models.Model):
GENDER = [
('NONE', 'none'),
('MALE', 'male'),
('FEMALE', 'female')
]
first_name = models.CharField(max_length=100, blank=False)
last_name = models.CharField(max_length=100, blank=True)
email = models.EmailField(max_length=200, blank = True)
bio = models.TextField(default='No bio data', max_length=400)
user = models.OneToOneField(User, on_delete = models.CASCADE)
gerder = models.CharField(max_length=6, choices=GENDER, default='NONE')
country = CountryField()
avatar = models.ImageField(default='avatar.png', upload_to='avatars/')
friends = models.ManyToManyField(User, blank = True, related_name='friends')
slug = models.SlugField(unique = True, blank = True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
favourite = models.CharField(max_length=300, blank=True)
def __str__(self):
return f'{self.user.username}-{self.created}'
```
I like using Django Autoslug https://pypi.org/project/django-autoslug/
pip install django-autoslug
After install, make sure you import it in your models.py file
from autoslug import AutoSlugField
Here is how the slug would look in your case:
slug = AutoSlugField(populate_from='user')
found out that using this in profile class will automatically assign username of the user
def save(self, *args, **kwargs):
self.slug = slugify(self.user.username)
super().save(*args, **kwargs)
this is my final profile class
from django_countries.fields import CountryField
from django.db import models
from django.template.defaultfilters import slugify
class Profile(models.Model):
GENDER = [
('NONE', 'none'),
('MALE', 'male'),
('FEMALE', 'female')
]
first_name = models.CharField(max_length=100, blank=False)
last_name = models.CharField(max_length=100, blank=True)
email = models.EmailField(max_length=200, blank = True)
bio = models.TextField(default='No bio data', max_length=400)
user = models.OneToOneField(User, on_delete = models.CASCADE)
gerder = models.CharField(max_length=6, choices=GENDER, default='NONE')
country = CountryField()
avatar = models.ImageField(default='avatar.png', upload_to='avatars/')
friends = models.ManyToManyField(User, blank = True, related_name='friends')
slug = models.SlugField(unique = True, blank = True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
favourite = models.CharField(max_length=300, blank=True)
def __str__(self):
return f'{self.user.username}-{self.created}'
def save(self, *args, **kwargs):
self.slug = slugify(self.user.username)
super().save(*args, **kwargs)
```
I'm trying to build a form that automatically fills some fields in a class based create view that lets logged in users create a Job. However, I can't seem to find the correct way of doing this for fields that aren't the user (eg. request.user).
So the create view is trying to get a company_name from the logged in user, company_name field belongs to a model called Company. Each Company has an owner with a foreign key to the User model. All the reuest I've tried so far have led to a 'WSGIRequest' error.
So far I've tried to request:
company_name
user.company_name
company.company_name
company
user
I don't understand how these requests work, I have seen examples for getting the logged in users name and I'm not familiar how to do this otherwise.
Please can someone help me understand how this works and how I should be doing this?
I'm using Django 2.2 with python 3.6
Auth Models:
class User(AbstractBaseUser, PermissionsMixin):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
phone_number = models.CharField(max_length=15)
email = models.EmailField(max_length=250, unique=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
last_login = models.DateTimeField(null=True, blank=True)
date_joined = models.DateTimeField(auto_now_add=True)
objects = UserManager()
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
def __str__(self):
return self.first_name
def get_absolute_url(self):
return "/users/%i/" % self.pk
class Company(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
company_name = models.CharField(max_length=100, unique=True)
company_address = models.CharField(max_length=100, unique=True)
company_website = models.URLField(blank=True, null=True)
company_verified = models.BooleanField(default=False)
def __str__(self):
return self.company_name
View
class JobCreateView(LoginRequiredMixin, CreateView):
model = Job
form_class = JobForm
template_name = 'jobs/job_create.html'
def form_valid(self, form):
form.instance.company_name = self.request.user
form.instance.job_reference = self.request.job.pk
return super(JobCreateView, self).form_valid(form)
def get_success_url(self):
return reverse('jobs:job_details', kwargs={'pk': self.object.pk})
Other Model:
class Job(models.Model):
JOB_TYPE = (
('1', 'Service'),
('2', 'Repair'),
('3', 'Quotation'),
('4', 'Consultation'),
('5', 'Report'),
('6', 'Design'),
)
ACCOUNT_TYPE = (
('1', 'Existing Customer'),
('2', 'Charge to Account'),
('3', 'New Customer'),
('4', 'Pre-Paid/C.O.D'),
('5', 'Issued and Acc App'),
)
company_name = models.ForeignKey(Company, related_name='jobs', verbose_name="Company Name", on_delete=models.CASCADE)
job_reference = models.CharField(max_length=50, blank=False)
contact_person = models.CharField(max_length=50)
contact_number = models.IntegerField()
contact_person_email = models.EmailField(max_length=100, blank=True, null=True)
site_address = models.CharField(max_length=100)
job_type = models.CharField(choices=JOB_TYPE, max_length=50, default='1')
account_type = models.CharField(choices=ACCOUNT_TYPE, max_length=50, default='1')
job_details = models.CharField(max_length=1000)
created = models.DateTimeField(default=now, blank=True)
def __str__(self):
return str(self.company_name)
def get_absolute_url(self):
return reverse('jobs:detail', kwargs={'pk': self.pk})
For anyone trying to solve a problem like this, the answer is;
Views:
class JobDocketCreate(CreateView):
model = JobDocket
form_class = JobDocketForm
template_name = 'jobs/job_docket_create.html'
def form_valid(self, form):
form.instance.technician = self.request.user
form.instance.job = Job.objects.get(pk=self.kwargs['job_pk'])
print(form.instance.job)
print(form.instance.technician)
context = {'job_pk':self.kwargs['job_pk']}
return super(JobDocketCreate, self).form_valid(form)
def get_context_data(self, **kwargs):
context = super(JobDocketCreate, self).get_context_data(**kwargs)
context['job_pk'] = self.kwargs['job_pk']
return context
def get_success_url(self):
return reverse('jobs:my_job_dockets')
Form action in View:
action="{% url 'jobs:create_job_docket' job_pk %}"
I hope someone can help me. I am a student and a beginner in django. I am trying to allow a certain premium user to view the premium content of a specific book. I already have models for the books, users, and membership type. However, I would like to know how I can connect those 3 so that a certain user can only see just the ALLOWED PREMIUM CONTENT of ONE specific book coming from a list of books.
Here's the code sample:
class Book(models.Model):
code = models.SlugField(unique=True, help_text="Enter BIC Code", null=True)
title = models.CharField(max_length=200)
author = models.ForeignKey('Author', on_delete=models.CASCADE, null=True)
artist = models.ForeignKey('Artist', on_delete=models.CASCADE, null=True)
summary = models.TextField(max_length=1000, help_text="Enter a brief description of the book")
book_type = models.ForeignKey('Type', on_delete=models.SET_NULL, null=True)
isbn = models.CharField('ISBN', max_length=15, help_text='Enter ISBN number')
status = models.CharField(choices=STATUS_CHOICES, default='Ongoing', null=True, max_length=30)
genre = models.ManyToManyField(Genre, help_text="Select a genre for this book")
language = models.CharField(max_length=50, null=True,
help_text="Enter the book's natural language (e.g. English, Tagalog, Japanese etc.)")
released_date = models.CharField(max_length=50, null=True, help_text="Enter the Released Date (e.g. March 2014)")
cover = models.ImageField(upload_to='book_cover', null=True, validators=[img_file_extension],
help_text="Image File Only")
teaser = models.FileField(upload_to='book_preview', validators=[pdf_file_extension], help_text="PDF File Only")
featured = models.BooleanField(null=True, default=False)
timestamp = models.DateTimeField(default=timezone.now)
def display_genre(self):
return ', '.join([genre.name for genre in self.genre.all()[:3]])
display_genre.short_description = 'Genre'
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
def get_absolute_url(self):
return reverse('book-detail', args=[str(self.id)])
def __str__(self):
return self.title
class Page(models.Model):
book = models.ForeignKey('Book', on_delete=models.CASCADE, null=True)
file = models.FileField(upload_to='book_content', validators=[pdf_file_extension], help_text="PDF File Only")
def __str__(self):
return self.book.title
def get_absolute_url(self):
return reverse('page-detail', kwargs={'id', self.id})
class Membership(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
title = models.ManyToManyField(Book)
premium = models.BooleanField(default=False)
reference = models.CharField(max_length=40, blank=True)
def __str__(self):
return self.user.username
i don't know what to do after in views.py
class PageDetailView(LoginRequiredMixin, generic.View):
def get(self, request, *args, **kwargs):
book = get_object_or_404(Book)
page = get_object_or_404(Page)
membership = get_object_or_404(Membership, user=request.user)
context={'object': None}
if #-----------------------
return render(request, "catalog/page_detail.html", context)
I am trying to make a formset of 3 foreign keys. Servicer, Sdescrition, and Stag. For some reason it is give me this error
ManagementForm data is missing or has been tampered with
I am pretty new at coding, if there is a better way than inlineform_factory please let me know and suggest. Thank you very much. I am pretty much trying to connect three foreign keys together put them into a single form page on the webpage. Once again, Thank you
Views.py
def home(request):
title = 'Please Enter Company Information'
SdescriptionFormSet = inlineformset_factory( Servicer, Sdescription, form = InputFormSdescription, extra=1)
StagFormSet = inlineformset_factory( Sdescription, Stag, form = InputFormStag, extra=1) #new
Sdescription_formset = InputFormSdescription()
Stag_formset = StagFormSet()
if request.POST:
FormServicer = InputFormServicer(request.POST or None)
FormSdescription = InputFormSdescription(request.POST or None) #new
if FormServicer.is_valid() and FormSdescription.is_valid():
servicer = FormServicer.save(commit=False)
Sdescription_formset=SdescriptionFormSet(request.POST, instance =servicer)
sdescription = FormSdescription.save(commit=False) #new
Stag_formset=StagFormSet(request.POST, instance =sdescription) #new
if Sdescription_formset.is_valid():
servicer.save()
Sdescription_formset.save()
sdescription.save() #n
Stag_formset.save() #new
return HttpResponseRedirect(reverse('serv.views.home'))
else:
FormServicer = InputFormServicer()
Sdescription_formset = SdescriptionFormSet(instance=Servicer())
Stag_formset=StagFormSet(instance=Sdescription())
context = {
"title": title,
"FormServicer": FormServicer,
"Sdescription_formset": Sdescription_formset,
"Stag_formset": Stag_formset, #new
}
return render(request, 'serv.html', context)
Models.py:
class Servicer(models.Model):
servicer_name = models.CharField(max_length=45,unique=True)
pub_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.servicer_name
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
# adds view site button on admin.
def get_absolute_url(self):
return '/video/%s/' % self.id
class Sdescription(models.Model):
servicer = models.ForeignKey(Servicer, on_delete=models.CASCADE, blank=True, null=True)
address = models.CharField(max_length=100,blank=True, null=True, unique=True)
address_line_2= models.CharField(max_length=100, blank=True, null=True)
city= models.CharField(max_length=50, blank=True, null=True)
state= models.CharField(max_length=25, blank=True, null=True)
zip = models.CharField(max_length=15, blank=True, null=True)
near_landmark = models.CharField(max_length=200, blank=True, null=True)
main_contact_name = models.CharField(max_length=20, blank=True, null=True)
phone_number1 = models.CharField(max_length=20, blank=True, null=True)
phone_number2 = models.CharField(max_length=20, blank=True, null=True)
comments = models.TextField(max_length=200, blank=True, null=True)
website = models.CharField(max_length=40, blank=True, null=True)
email = models.EmailField(max_length = 20,blank=True, null=True)
image = models.ImageField(upload_to='uploads/',blank=True, null=True)
def __str__(self):
return '%s %s %s %s %s %s %s %s %s %s %s' % (self.address,
self.address_line_2, self.city, self.state, self.zip,
self.near_landmark, self.phone_number1, self.phone_number2, self.comments,
self.website, self.email)
class Stag(models.Model):
tag_name = models.CharField(max_length=30,blank=True, null=True)
price = models.DecimalField(max_digits=9, decimal_places=2,blank=True,
null=True)
comments = models.CharField(max_length=100,blank=True, null=True)
sdescription = models.ForeignKey(Sdescription,
on_delete=models.CASCADE,blank=True, null=True)
def __str__(self):
return '%s $%s %s' % (self.tag_name, self.price, self.comments)
Forms.py:
class InputFormServicer(forms.ModelForm):
class Meta:
model = Servicer
fields=['servicer_name']
class InputFormSdescription(forms.ModelForm):
class Meta:
model = Sdescription
fields=['address','address_line_2','city','state','zip','near_landmark',
'main_contact_name', 'phone_number1', 'phone_number2', 'comments',
'website', 'email','image'
]
class InputFormStag(forms.ModelForm):
class Meta:
model = Stag
fields=['tag_name','price','comments']
Serv.html:
<h1>{{title}}</h1>
<form method='POST' action=''> {% csrf_token %}
{{FormServicer}}
{{Sdescription_formset.as_p}}
{{Sdescription_formset.management_form}}
{{Stag_formset.as_p}}
{{Stag_formset.management_form}}
<input type='submit' value='save'/>
</form>