I am creating an online debate app using Django. I have used a class-based list view to create different topics using pk and once I click on the topic it takes me to its details page and once I go to the detail page I need two text-boxes to enter my for point and against point and after entering the point I need to display the point below the text-box. I have created a list of topics but I'm unable to do the text-box to that particular page.
This is my models.py
class DebateModel(models.Model):
title = RichTextUploadingField(blank=True,null= True)
body = models.TextField(max_length = 5000 , null=True,blank=True)
date_published = models.DateTimeField(auto_now_add=True)
date_update = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class ForModel(models.Model):
DebateModel = models.ForeignKey(DebateModel,related_name="for_point",on_delete=models.CASCADE)
body = models.TextField(max_length = 5000)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s %s' % (self.DebateModel.title, self.body)
class AgainstModel(models.Model):
DebateModel = models.ForeignKey(DebateModel,related_name="against_point",on_delete=models.CASCADE)
body = models.TextField(max_length = 5000)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s %s' % (self.DebateModel.title, self.body)
this is my forms.py
class EditFor(forms.ModelForm):
class Meta:
model = ForModel
fields = ('body',)
widgets = {
'body': forms.Textarea(attrs={'class':'form-control'}),
}
this is my views.py
class HomeView(ListView):
model = DebateModel
template_name = "debate/home.html"
class ArticleDetailView(DetailView):
model = DebateModel
template_name = "debate/content.html"
context_object_name = 'debate'
class AddForView(CreateView):
model = ForModel
template_name="debate/content.html"
form_class = EditFor
def form_valid(self,form):
form.instance.DebateModel_id = self.kwargs['pk']
return super().form_valid(form)
success_url = reverse_lazy('debate/home.html')
this is my urls.py
path('',HomeView.as_view(),name = "home"),
path('article/<int:pk>',ArticleDetailView.as_view(),name = "debate-detail"),
path('article/<int:pk>/forpoint',AddForView.as_view(),name="add_For"),
This is my content.html
<button onclick="myFunction()">for</button>
<button onclick="myFunction()">against</button>
<form method="post" action="Add_For/">
{%csrf_token%}
</form>
<script>
function myFunction() {
var x = document.createElement("TEXTAREA");
var t = document.createTextNode("enter your for point");
var y = document.createElement("INPUT");
y.setAttribute("type", "submit");
document.body.appendChild(y);
x.appendChild(t);
document.body.appendChild(x);
}
</script>
Related
I created the following model in my django app:
class Post(models.Model):
title = models.CharField(max_length=125, unique=True)
slug_title = models.SlugField(max_length=255, unique=True)
body = models.TextField()
published_date = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
status = models.BooleanField(default=False)
class Meta:
ordering = ['-published_date']
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug_title = slugify(self.title)
super(Post, self).save(*args, **kwargs)
I want to be able to use an API to do POST/GET requests later on, so I decided to use graphene-django. Everything is installed properly and working.
As per the tutorials, I created my schema.py file as follow:
# define schema
class PostType(DjangoObjectType):
class Meta:
model = Post
fields = ('title', 'body', 'author', 'published_date', 'status', 'slug_title')
class UserType(DjangoObjectType):
class Meta:
model = get_user_model()
class PostInput(graphene.InputObjectType):
title = graphene.String()
slug_title = graphene.String()
body = graphene.String()
author = graphene.Int()
published_date = graphene.DateTime()
status=graphene.Boolean()
class CreatePost(graphene.Mutation):
class Arguments:
input = PostInput(required=True)
post = graphene.Field(PostType)
#classmethod
def mutate(cls, root, info, input):
post = Post()
post.title = input.title
post.slug_title = input.slug_title
post.body = input.body
post.author = input.author
post.published_date = input.published_date
post.status = input.status
post.save()
return CreatePost(post=post)
class Query(graphene.ObjectType):
all_posts = graphene.List(PostType)
author_by_username = graphene.Field(UserType, username=graphene.String())
posts_by_author = graphene.List(PostType, username=graphene.String())
posts_by_slug = graphene.List(PostType, slug=graphene.String())
def resolve_all_posts(root, info):
return Post.objects.all()
def resolve_author_by_username(root, info, username):
return User.objects.get(username=username)
def resolve_posts_by_author(root, info, username):
return Post.objects.filter(author__username=username)
def resolve_posts_by_slug(root, info, slug):
return Post.objects.filter(slug_title=slug)
class Mutation(graphene.ObjectType):
create_post=CreatePost.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
The query part is working as expected, but my mutation section doesn't seem to be working. When I try to create a mutation, I get the below:
{
"data": {
"create_post": {
"post": null
}
}
}
I created a quick test to see if any errors would output when I run the mutation, but everything seems ok there.
def test_mutation_1(self):
response = self.query(
'''
mutation {
createPost(input:{
title:"Test Title",
body:"Test body",
author:1,
publishedDate:"2016-07-20T17:30:15+05:30",
status:false
})
{
post {
title
}
}
}
'''
)
self.assertResponseNoErrors(response)
I get no error messages.
Any help would be appreciated!
The error: errors=[GraphQLError('Cannot assign "1": "Post.author" must be a "User" instance.'
The solution: Alter my CreatePost class to the following:
post.author = User.objects.get(pk=input.author_id)
Instead of:
post.author = input.author_id
I new her and need help
I create a few models:
Customer
Orders
How to make the ADD button dynamic
If I use a filter and my url is http://127.0.0.1:8000/admin/catalog/order/?order_customer__id=3, in this case pass the following value to the button <a href="{% url opts|admin_urlname:'add ' %}?order_customer={{cl.result_list.0.order_customer.id}}"
To prompt you to fill out the form when creating a new record. Accordingly, the url should look like this
http://127.0.0.1:8000/admin/catalog/order/add/?order_customer=3
If the filter is missing url http://127.0.0.1:8000/admin/catalog/order/, the button has a default value
Accordingly, when switching to the creation form, the url has a standard value
http://127.0.0.1:8000/admin/catalog/order/add
Django 3.2.6
addons smart_selects
models.py
class Customer(models.Model):
"""docstring for Customer."""
customer_name = models.CharField(max_length=200, verbose_name='Назва юридичної особи/ФОП', help_text='Введіть поністю назву юридичної особи чи фізичної особи підприємця')
customer_inn = models.CharField(max_length=15, verbose_name='ЄДРПОУ', help_text='Введеіть ЄДРПОУ для юридичної особи чи ідентифікаційний код для ФОП')
customer_adress = models.TextField(max_length=200, verbose_name='Юридична адреса клієнта' , help_text='Притриймуйтесь формату аналогічно витягу ЄДР. Наприклад: 79000, Область, Район, Місто/Селище, вулиця/проспект Назва вулиці, Номебр будинку, квартира')
customer_ceo = models.CharField(max_length=50, verbose_name='Керівник/підписант')
class Meta:
verbose_name = 'Клієнт'
verbose_name_plural = 'Клієнти'
def __str__(self):
"""
String for representing the Model object.
"""
return self.customer_name
class Order(models.Model):
order_customer = models.ForeignKey('Customer', on_delete=models.CASCADE, verbose_name="Клієнт")
order_date = models.DateField(verbose_name='Дата заявки')
order_adress = ChainedForeignKey(
'MarketAdress',
chained_field = "order_customer",
chained_model_field= "customermarkeradress",
show_all = False,
auto_choose = True,
sort = True,
verbose_name= 'Адреса точки')
order_number = models.CharField(max_length=10, verbose_name='Номер заявки')
# oder_brand = models.ForeignKey('CustomerBrand', on_delete=models.CASCADE, verbose_name="Назва вивіски")
oder_brand = ChainedForeignKey(
'CustomerBrand',
chained_field = "order_customer",
chained_model_field= "customer",
show_all = False,
auto_choose = True,
sort = True,
verbose_name= 'Вивіска')
class Meta:
verbose_name = 'Заявка'
verbose_name_plural = 'Заявки'
def __str__(self):
"""
String for representing the Model object.
"""
return str(self.oder_brand)
admin.py
#admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
list_display = ['customer_name', 'customer_inn', 'сontract', 'orders_lists', 'orders_add']
inlines = [OrderInline, EnvironmentActInstanceInline]
def сontract(self, obj):
link_buttom = reverse('downloadWordcontarct', args=[obj.pk])
return mark_safe(f'<a class="button" label="Догорів" href="{link_buttom}">Сформувати</a>')
сontract.short_description = "Договір"
def orders_lists(self, obj):
argsus=obj.pk
link_buttom = reverse("admin:catalog_order_changelist") + "?" + "order_customer__id=" + str(argsus)
#return format_html('{} order', link_buttom)
return mark_safe(f'<a class="button" label="Заявки" href="{link_buttom}">Перейти до заявки</a>')
orders_lists.short_description = "Заявки"
def orders_add(self, obj):
argss=obj.pk
link_buttom = reverse ("admin:catalog_order_add") + "?" + "order_customer=" + str(argss)
return mark_safe(f'<a class="button" label="Заявки" href="{link_buttom}">Створити</a>')
orders_add.short_description = "Додати заявку"
#admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
list_display = ['order_customer', 'order_date', 'order_number', 'order_adress', 'oder_brand', 'butt_ord']
def butt_ord(self, obj):
link_buttom = reverse('downloadWordorder', args=[obj.pk])
return mark_safe(f'<a class="button" label="Заявка" href="{link_buttom}">Заявку</a>')
butt_ord.short_description = "Сформувати"
enter image description here
enter image description here
I have a model:
class Movie (models.Model):
category = models.CharField(max_length=50, verbose_name='Kategoria filmu', default= 'unassigned', null=False, choices=category_choices)
source = models.CharField(max_length=50, verbose_name='Źródło filmu', default= 'unassigned', null=False, choices=source_choices)
promotion = models.BooleanField(default=False, verbose_name='PROMOCJA FILMU')
author = models.CharField(max_length=50, verbose_name='Nazwa influencera')
title = models.CharField(max_length=50, verbose_name='Nazwa filmu')
content = models.TextField(max_length=10000, verbose_name='HTML EMBEDED do filmu')
date_posted = models.DateTimeField(default=timezone.now)
youtube_url = models.URLField(blank=True, max_length=300)
tiktok_url = models.URLField(blank=True, max_length=300)
insta_url = models.URLField(blank=True, max_length=300)
I am passing it to the view with djnago-filter with different category choice:
views.py:
#HotTop View
class HotTopView (FilterView):
model = Movie
template_name = 'pages/hot_top.html'
filterset_class = MovieFilter
paginate_by = 6
def get_queryset(self):
category_qs = self.model.objects.filter(category="HOT-TOP")
return category_qs.order_by('-date_posted')
#Odkrycia View
class OdkryciaView (FilterView):
model = Movie
template_name = 'pages/odkrycia.html'
filterset_class = MovieFilter
paginate_by = 6
def get_queryset(self):
category_qs = self.model.objects.filter(category="ODKRYCIA")
return category_qs.order_by('-date_posted')
and my filters.py:
class MovieFilter(django_filters.FilterSet):
author = django_filters.CharFilter(label='', lookup_expr='contains', widget=TextInput(attrs={'placeholder': 'Search'}))
class Meta:
model = Movie
fields = ['author']
The question is how can i change placeholder of my serach form depending on the view (HotTop or Odkrycia). I want it to be - when i am in HotTop View -> Search in Hot Top and when i am in Odkrycia - > Search in Odkrycia
I think you could pass an argument
class MovieFilter(django_filters.FilterSet):
author = django_filters.CharFilter(label='', lookup_expr='contains', widget=TextInput(attrs={'placeholder': 'Search'}))
class Meta:
model = Movie
fields = ['author']
def __init__(self, *args, **kwargs):
placeholder = kwargs.pop('placeholder', None)
super().__init__(*args, **kwargs)
if placeholder :
self.fields['author'].widget = TextInput(attrs={'placeholder': f'Search in {placeholder}'})
and then in the views you can use get_filterset_kwargs method to pass the view name.
#HotTop View
class HotTopView(FilterView):
...
def get_filterset_kwargs(self):
kwargs = super(HotTopView, self).get_filterset_kwargs()
kwargs['placeholder'] = "Hot Top"
return kwargs
...
the other view:
#Odkrycia View
class OdkryciaView(FilterView):
...
def get_filterset_kwargs(self):
kwargs = super(OdkryciaView, self).get_filterset_kwargs()
kwargs['placeholder'] = "Odkrycia"
return kwargs
...
I hope that answers your question.
I am new to django and maybe this is a stupid question but i got stuck with this for a while now.. so i have a few categories of meds, like AINS, antidepressants and each of this category has its own meds, and i am trying to show my users all the meds of a specific category: so if a users types in www.namesite.com/meds/AINS the it will show only the meds for that specific category .. AINS.I think that i should get the absolute url of every category and filter all the meds in that specific category?
Model:
class Category(models.Model):
category = models.CharField(max_length=30)
slug = models.SlugField()
def __str__(self):
return self.category
def get_absolute_url(self):
return reverse("meds", kwargs={'slug':self.category})
class Meta:
verbose_name_plural = 'Categorii'
class Medicament(models.Model):
title = models.CharField(max_length=50)
description = models.TextField(max_length=200)
category = models.ForeignKey(Category, on_delete='CASCADE')
price = models.DecimalField(decimal_places=2, max_digits=4)
prospect = models.TextField(default='Prospect')
company = models.TextField(default = 'company')
nr_unitati = models.IntegerField()
quantity = models.CharField(max_length=5, default='mg')
date_added = models.DateTimeField(auto_now_add=True)
rating = models.IntegerField(null=True, blank=True)
amount = models.IntegerField(default=0)
def __str__(self):
return self.title + ' ' + self.company + ' ' + str(self.nr_unitati) + ' ' + self.quantity
class Meta:
verbose_name_plural = 'Medicamente'
Views:
class MedCategoriesView(DetailView):
model = Category
template_name = 'products/AINS.html'
context_object_name = 'all_categories'
def get_context_data(self, **kwargs):
context = super(AINS_ListView, self).get_context_data(**kwargs)
context['meds'] = Medicament.objects.filter(category=self.object)
return context
Urls:
path('medicaments/<slug>/', MedCategoriesView.as_view(), name='meds'),
Using function based views.
def medicament(request, slug):
try:
medicaments = Medicament.objects.filter(category__slug=slug)
except Medicament.DoesNotExist:
raise Http404("Medicament does not exist")
return render(request, 'products/AINS.html', {'medicaments': medicaments})
I have searched 20-30 posts and I did not find anything useful. I am to store data to database by selecting values from HTML file or form in view. Please tell me how I can achieve this. what code I am missing. Thanks in advance for Help.
view.py
def blog_list(request):
form = AttendanceForm()
if request.method == "POST":
form1 = AttendanceForm(request.POST)
if form1.is_valid:
form1.save()
return render(request, 'blog/blog_list.html',{
'form1':form1,
})
return render(request, 'blog/blog_list.html',{
'form':form,
})
my forms.py
class AttendanceForm(forms.ModelForm):
action = forms.ModelChoiceField(queryset=Action.objects.all(), empty_label="-----------", required=True)
employee = forms.ModelChoiceField(queryset=Employee.objects.all(), empty_label="-----------", required=True)
class Meta:
model = Action
fields = ['employee','action']
my model.py
class Action(models.Model):
action_name = models.CharField(max_length = 100)
def __str__(self):
return self.action_name
class Employee(models.Model):
employee_id = models.AutoField(primary_key = True)
employee_name = models.CharField(max_length = 100)
def __str__(self):
return self.employee_name
class Attendance(models.Model):
u = models.ForeignKey(Employee)
action = models.ForeignKey(Action)
action_time = models.DateTimeField(default=timezone.now())
In Python you need to call methods by using parentheses.
if form.is_valid():
form.save()
It is working fine after these changes in Model:
class Action(models.Model):
action_name = models.CharField(max_length = 100)
def __str__(self):
return self.action_name
class Employee(models.Model):
employee_id = models.AutoField(primary_key = True)
employee_name = models.CharField(max_length = 100)
def __str__(self):
return self.employee_name
class Attendance(models.Model):
employee = models.ForeignKey(Employee)
action = models.ForeignKey(Action)
action_time = models.DateTimeField(default=timezone.now())