I'm working on a basic social media django project with the help of an udemy course. The following are the models i created:
group : models.py
register = template.Library()
class Group(models.Model):
name = models.CharField(max_length=255,unique=True)
slug = models.SlugField(allow_unicode=True,unique=True)
description = models.TextField(blank=True,default='')
description_html = models.TextField(editable=False,default='',blank=True)
members = models.ManyToManyField(User,through="GroupMember")
class GroupMember(models.Model):
group = models.ForeignKey(Group,related_name='memberships',on_delete=models.CASCADE)
user = models.ForeignKey(User,related_name='user_groups',on_delete=models.CASCADE)
post : models.py
class Post(models.Model):
user = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now=True)
message = models.TextField()
message_html = models.TextField(editable=False)
group = models.ForeignKey(Group,related_name='posts',null=True,blank=True)
And the part that does not make any sense to me is the following:
post_list.html
{% for member_group in get_user_groups %}
<a href="{% url 'groups:single' slug=member_group.group.slug %}">{{ member_group.group.name
}}</a></li>
{% endfor %}
{% for other_group in get_other_groups %}
{{ other_group.name }}</li>
{% endfor %}
What does "get_user_groups","get_other_groups" and "register = template.Library()" mean here and how are they related? Also what are they trying to achieve here? I'm clueless guys, help me out.
That's an example of custom template tags. There is probably a custom_tags.py file where you created the custom template tags within a folder called template_tags that shows the work being done to create the content of those tags.
get_user_groups isn't pulling from views.py or directly referencing your models.py. Instead, it's referencing queries stored in custom_tags.py
Find a detailed breakdown here:
https://medium.com/#hiteshgarg14/creating-custom-template-tags-in-django-application-7bd1dcfeb144
This can be useful if you want to display content from a query on a variety of different views without having to redundantly insert that query into multiple functions within views.py. In this case, it looks like it will be used to insert group membership information within a variety of views by using custom tags.
Related
I usually develop in PHP but I took it upon myself to learn Django so please be patient with me, I have a long way to go... I am working on a project that simply does one thing for now, user can login and when the user is logged in the app will show an Iframe that streams some digital content that is created by another server I have which is stored in this model:
class Show(models.Model):
show = models.CharField(max_length = 200)
description = models.TextField()
mfg_date = models.DateTimeField(auto_now_add = True)
iframe = models.CharField(max_length = 300, null=True)
group = models.ForeignKey(
Group,
default='1',
on_delete=models.CASCADE,)
active = models.CharField(max_length = 1, choices = Active)
def __str__(self):
return self.show
def show_desc(self):
return self.description[:50]
My views.py currently:
from django.shortcuts import render
from django.views.generic import TemplateView
class StreamingView(TemplateView):
template_name = 'stream/stream.html'
And my template stream.html:
{% extends '_base.html' %}
{% load static %}
{% block title %}[I would like to print "show" from my model here{% endblock title %}
{% block content %}
<div class="pricing-header px-3 py-3 pt-md-5 pb-md-4 mx-auto text-center">
<h2>[I would like to print "show" from my model here]</h2>
<iframe width="560" height="315" src="[input "iframe" as the iframe src based on user group, and if user has multiple groups create second iframe to show both at the same time]" frameborder="0" allowfullscreen></iframe>
</div>
{% endblock content %}
My question is this:
I am looking to query the group/groups the user belongs to and based on this information create a variable that can input the src of the iframe, it would be best to be able to loop through all the possible "iframe" that the user can see (based on the foreign key to users group) and fill the iframe src on my template with the value stored in my model only if the "show" is active. If the user does not belong to any group or if the show is marked inactive I would like to show an error message something like "You do not have access, please contact the site administrator"
What is the best way to do this? I have been researching Q objects and think I may be able to accomplish this with them?
And lastly is it possible to edit the urls.py to create a urlpattern that takes the name of the group that the user belongs to and uses this name for the url?
Thank you in advance for your help!
In Django's admin panel, how do I add hard-coded links to a Django model's form page (/add/ page). These are links to documentation that will never change. I want these links to appear every time on the form as a reference for the user to figure out what values to input into the fields.
Do I need: Custom field? Built-in field already? Modify the admin templates somehow? Add a helper function somewhere?
I'm not referring to the "change list" view; I am referring to the /change/ or /add/ page view when you go and add or edit an object within a model.
models.py
class DateRange(models.Model):
date_name = models.CharField(max_length=100)
adwords_name = models.CharField(max_length=100)
bingads_name = models.CharField(max_length=100)
def __str__(self):
return self.date_name
forms.py
class DateRangeAdminForm(forms.ModelForm):
class Meta:
model = DateRange
fields = '__all__'
admin.py
#admin.register(DateRange)
class DateRangeAdmin(admin.ModelAdmin):
form = DateRangeAdminForm
list_display = ['date_name', 'adwords_name', 'bingads_name']
Extending change_form.html could work -- it'll add links at the top.
Create this file in your namespaced templates directory, referred to here as "templates-dir"
templates-dir/admin/myapp/daterange/change_form.html:
{% extends "admin/change_form.html" %}
{% block object-tools %}
{{ block.super }}
<ul>
<li>
Adwords documentation
</li>
<li>
Bing ads documentation
</li>
</ul>
{% endblock object-tools %}
Relevant docs:
https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#overriding-admin-templates
https://docs.djangoproject.com/en/2.0/howto/overriding-templates/#overriding-from-an-app-s-template-directory
I'm new to Django and programming. I'm trying to call the field from a model through a template other than specified in my url patterns but I keep on getting a blank display in the div block I want i to display in. I want a list of categories to be displayed in the left side-bar. I have looked at many answers on SO Django foreign key relation in template and How to display one field from a model in Django template and Ive worked through the Django docs.
I've created a list of categories in the admin class. The code is working as intended but Im not able to extend this list to be displayed from the base.html template class so that I have category navigation throughout.
I have two models:
class Post(models.Model):
category = models.ForeignKey(Categories, related_name='topic')
...
class Categories(models.Model):
topics = models.CharField(max_length=100)
...
Here is my view which works in the 'categories.html' template
def categories(request):
category = Categories.objects.all()
return render(request, 'posts/categories.html', {"category": category})
The url pattern related to it
url(r'^categories/$', views.categories, name='category'),
Here is how i'm calling the field
{% for field in category %}
<div class="col-sm-10">{{ field.topics }}</div>
{% endfor %}
I've tried alot of different approaches such as:
{% for field in category.topic.all %}
{% endfor %}
Please assist. Thank you in advance.
So I'd like to think what I'm doing is fairly common. I'm attempting to display a result set using Django. I have looked online for a while and here is what I've come up with:
models.py{
from django.db import models
from django.conf import settings
class SalesRep(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
class Sales(models.Model):
seller = models.ForeignKey(SalesRep)
sold_on = models.DateField("Sold On")
}
sales_view.py{
from salesteam.models import SalesRep, Sales
from django.views.generic import ListView
class SellerHome(List View):
model = SalesRep
template_name = 'production/sales.html'
#property
def rep_sales(self):
return Sales.objects.filter(SalesRep=self)
}
sales.html{
<div id="total-sales">
{% for sale in SellerHome.rep_sales%}
<li>{{ sale.id }}</li>
{% empty %}
<li>You don't currently have any sales</li>
{% endfor %}
</div>
}
For the sake of completeness I even tried writing just the property out as Sales.objects.all() but still no luck. Thanks for taking a look as I'm fairly new to HTML, Django, and Python. Any help on what I'm doing wrong would be much appreciated. Let me know if you have any questions :)
I'm not sure what tutorial you've followed, but there is a lot of errors in your code... I'm assuming you would like to display all Sales for the logged in user?
In this scenario, I would change the model slightly to add a related_name to Sales foreign key to SalesRep:
class SalesRep(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
class Sales(models.Model):
seller = models.ForeignKey(SalesRep, related_name='sales')
sold_on = models.DateField('Sold On')
Documentation: https://docs.djangoproject.com/en/1.7/ref/models/fields/#django.db.models.ForeignKey.related_name
And I would change the views to use DetailView:
from django.views.generic import DetailView
class SellerDetailView(DetailView):
model = SalesRep
template_name = 'production/sales.html'
context_object_name = 'seller'
def get_object(self):
return self.request.user
Docs on DetailView — https://docs.djangoproject.com/en/1.7/ref/class-based-views/generic-display/#detailview
<div id="total-sales">
<ul>
{% for sale in seller.sales.all %}
<li>{{ sale.id }}</li>
{% empty %}
<li>You don't currently have any sales</li>
{% endfor %}
</ul>
</div>
First, I'd recommend avoiding class based views, at least as you are learning Django, since they are not really necessary and needlessly complicated for what you are doing.
Anyway, to answer your question using class-based views, your problem is in your template and your view. You'll want to put your rep_sales logic in a get_queryset, set the model to be Sales, not SalesRep, and then reference object_list in the template. More info.
However, I'd instead recommend writing a normal, function-based Django view. Something like this might get you started:
def view_all_sales(request):
my_sales_rep = SalesRep.objects.get(request.user)
all_my_sales = Sales.objects.filter(seller=my_sales_rep)
return render(request, "production/sales.html", {
"sales": all_my_sales
})
I am developing an application with Django framework and I'm new to it
I need to create a query that simply joins 2 tables( type and subType ) and then later on use the result in the views the models file looks like this:
class Type(models.Model):
name = models.CharField(max_length=60)
description = models.CharField(max_length=200)
class SubType(models.Model):
name = models.CharField(max_length=60)
description = models.CharField(max_length = 200)
Type = models.ForeignKey(Type)
And in home.html file I have : (I dropped out the bootstrap code to make it more readable )
<ul>
<li ><a href="/home" >Home Page</a></li>
{% for type in all_types %}
<li >
{{ type.name }}
<ul >
--The Inner Loop--
</ul>
</li>
{% endfor %}
</ul>
I need to create an list of types and then inside each type I need to create another list which contains the subTypes of each type
I have no idea how do I have to create the query inside the views.py
def index(request):
list_all_types = #Here I have to create a join query via django models
t = loader.get_template('home.html');
c = Context({
'all_types' : list_all_types,
});
return HttpResponse(t.render(c));
So please let me know how do I have to make the query and replace the correct code with the comment part in views.py and what changes do I have to add to make to the home.html to make it enabled show all the subTypes instead of --inner loop in home.html
Thanks in advance
You don't need to do anything in the view other than get the types:
types = Type.objects.all()
In the template, you just iterate over type.subtype_set.all:
<ul>
{% for subtype in type.subtype_set.all %}
<li>{{ subtype.name }}</li>
{% endfor %}
</ul>
Note that this is well covered by the tutorial. (As is the use of the render shortcut rather than loading and rendering the template separately.)
(Actually, what I said at first was not quite true: for the sake of efficiency, you can add prefetch_related() to the Type query.)