I have created this simple model:
from django.db import models
from slugify import *
class News(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
pub_date=models.DateTimeField(auto_now_add=True)
likes = models.IntegerField(default=0)
visits = models.IntegerField(default=0)
slug = models.SlugField()
status = models.BooleanField(default=True)
#approved = models.BooleanField(default=False)
def __unicode__(self):
return unicode(self.title)
def save(self, *args, **kwargs):
self.title = slugify(self.title)
super(News, self).save(*args, **kwargs)
admin.py
from django.contrib import admin
from news.models import News
admin.site.register(News)
Whenever I create a news content in the admin panel with a Persian title, the title does not display on the panel. When the title is in ascii characters, there is not such problem
My Django version is 1.5.5 and mysql database is utf8. I've added this to settings.py (though not sure it is relevant!)
from __future__ import absolute_import, unicode_literals
So appreciate your hints.
I expect the problem is that you're using the slugify function, which explicitly strips out non-ASCII characters.
I'm not sure why you want to slugify the title in the first place, but you might want to look into the new awesome-slugify library, which deals correctly with those characters.
Related
folder structure
enter image description here
models.py from face_detect
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Profile(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE,null=True)
mobile = models.CharField(max_length=10,null=True)
add = models.CharField(max_length=10,null=True)
image = models.FileField(null=True)
def __str__(self):
return self.user.username
models.py from otp
from django.db import models
from django.contrib.auth.models import User
from face_detect.models import Profile
import random
# Create your models here.
class Code(models.Model):
number = models.CharField(max_length=5, blank=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self):
return str(self.number)
#otp verification
def save(self, *args, **kwargs):
number_list = [x for x in range(10)]
code_items = []
for i in range(5):
num = random.choice(number_list)
code_items.append(num)
code_string = "".join(str(item) for item in code_items)
self.mobile = code_string
super().save(*args,**kwargs)
signals.py from otp
from face_detect.models import Profile
from django.contrib.auth.models import User
from .models import Code
from django.db.models.signals import post_save
from django.dispatch import receiver
#receiver(post_save, sender=User)
def post_save_generate_code(sender, instance, created, *args, **kwargs):
if created:
Code.objects.create(user=instance)
apps.py from otp
from django.apps import AppConfig
class OtpConfig(AppConfig):
name = 'otp'
def ready(self):
import otp.signals
init.py from otp
default_app_config = 'otp.apps.OtpConfig'
admin.py from otp
from django.contrib import admin
from .models import Code
# Register your models here.
admin.site.register(Code)
code seen in http://127.0.0.1:8000/admin/otp/code/
enter image description here
code is not visible.
how can i make the code visible so i can use it for otp verification while login.
Thanks in advance
In admin page you will see the __str__ method, so there seems to be nothing wrong with your code most probably your code instance's value is "", Also one other thing
def __str__(self):
return str(self.number)
you dont need to cast it to str here its already char field
and another thing is here:
def __str__(self):
return self.user.username
in Profile model you made user nullable so this means not all the profile instances might not have user so you will get NoneType has no attribute username
change it to this to prevent this errors:
def __str__(self):
return self.user.username if self.user else ""
I'm building my first app within Django and I'm trying to query a "load" based on the company that i've attached to the load. Here's the model in question.
class Load(models.Model):
company = models.ForeignKey(UserCompany, null=True,
on_delete=models.CASCADE)
load_number = models.IntegerField()
carrier = models.CharField(max_length=255)
pickup_date = models.DateField()
delivery_date = models.DateField()
shipper = models.CharField(max_length=255)
consignee = models.CharField(max_length=255)
po_number = models.CharField(max_length=255)
pu_number = models.CharField(max_length=255)
pieces = models.IntegerField()
description = models.TextField()
date_created = models.DateTimeField(blank=True, null=True)
def publish(self):
self.date_created = timezone.now()
self.save()
def __str__(self):
return str(self.load_number)
Now I'm trying to display a list on a page, but only display the loads attached to a specific company. The user needs to be attached to that company as well so here are my user models.
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserCompany(models.Model):
company_name = models.CharField(max_length=200)
def __unicode__(self):
return self.company_name
def __str__(self):
return self.company_name
# User Model
class UserProfileInfo(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
# Additional Classes
profile_pic = models.ImageField(upload_to='profile_pics',
blank=True)
company = models.ForeignKey(UserCompany,
null=True,on_delete=models.CASCADE)
def __str__(self):
return self.user.username
Then i'm trying to query the "loads" within this view.
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, get_object_or_404
from django.shortcuts import redirect
import datetime
from django.conf import settings
from django.utils import timezone
from django.http import HttpResponse
from django.views.generic import View, DetailView
from easy_pdf.views import PDFTemplateResponseMixin
from loads.models import Load
from .forms import LoadForm
from users.models import UserCompany, UserProfileInfo
# Create your views here.
class PDFUserDetailView(PDFTemplateResponseMixin, DetailView):
model = Load
template_name = 'loads/load_pdf.html'
def load_list(request):
loads =
Load.objects.filter(company=request.company).order_by('date_created')
return render(request, 'loads/load_list.html', {'loads':loads})
I was able to get the query working based on the user, so my thought is that this query would be the same. This is not the case. I have a feeling that i'm referencing company wrong and maybe I somehow need to filter 2 more levels down all the way to the original UserCompany class, just not sure how to accomplish that.
The error that i'm getting is:
AttributeError: 'WSGIRequest' object has no attribute 'company'
request.company isn't a thing you can do. Instead of
Load.objects.filter(company=request.company).order_by('date_created')
You try something like this:
current_user = request.user
company = current_user.userprofileinfo.company
Load.objects.filter(company=company).order_by('date_created')
request just holds information about the current request which you can read more about here
I am trying to get my admin.py to read Chinese, however I do not know how can I do it. This is what I have.
admin.py
from django.contrib import admin
from collection.models import Thing
class ThingAdmin(admin.ModelAdmin):
model = Thing
list_display = ('name', 'description',)
prepopulated_fields = {'slug': ('name',)}
admin.site.register(Thing, ThingAdmin)
models.py
from django.db import models
class Thing(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
slug = models.SlugField(unique=True)
now I can type it in English and slug will be generated properly, but when I try it in Chinese slug is blank.
any one knows how to do it?? thank you!
I just had similar problem. You need to convert chinese to text that can be stored in SlugField.
Include unidecode and optionally slugify:
from unidecode import unidecode
from django.template.defaultfilters import slugify
And overwrite save to something like this:
class ThingAdmin(admin.ModelAdmin):
model = Thing
list_display = ('name', 'description',)
prepopulated_fields = {'slug': ('name',)}
def save(self, *args, **kwargs):
self.slug = slugify(unidecode(self.name))
return super(ThingAdmin, self).save(*args, **kwargs)
You also need to make sure slug will be always unique, which I do not see in your code.
It will decode name 투자 to this slug tuja, etc.
I have exhausted all avenues in trying to put together a solution for this, but my current knowledge of Python and Django can only get me so far.
I'm creating a basic ticketing system and CreateView used to work until I created a Profile model and then separated the Ticket model into its own app. There were already a couple of tickets created when I refactored my code which is why I know ListView works, DeleteView works as well as DetailView. CreateView works until I hit the save button.
My views and models are below; I hope someone can please help me sort this out.
Ticket Model
from django.db import models
from django.contrib.auth.models import User
....
from qcapp.models import Profile
class Ticket(models.Model):
# Relations
user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="tickets", verbose_name="user")
# Attributes
title = models.CharField(max_length=250, verbose_name="Title", help_text="Enter a Ticket Title")
color = models.CharField(max_length=7,
default="#ffffff",
validators=[RegexValidator("(^#[0-9a-fA-F]{3}$)|(^#[0-9a-fA-F]{6}$)")],
verbose_name="Color",
help_text="Enter the hex color code, like #ccc or #cccccc")
description = models.TextField(max_length=1000)
created_date = models.DateTimeField(default=timezone.now, verbose_name='Created Date')
created_by = models.ForeignKey(User, related_name='created_by_user')
# Attributes
# Object Manager
objects = managers.ProjectManager()
# Meta and String
class Meta:
verbose_name = "Ticket"
verbose_name_plural = "Tickets"
ordering = ("user", "title")
unique_together = ("user", "title")
def __str__(self):
return "%s - %s" % (self.user, self.title)
def get_absolute_url(self):
return reverse('ticket_detail', args=[str(self.id)])
Ticket View (CreateView Only)
# -*- coding: utf-8 -*-
...
from django.views.generic import CreateView, UpdateView, DeleteView
...
from .models import Ticket
...
class TicketCreate(CreateView):
model = Ticket
template_name = "tickets/ticket_form.html"
fields = ['title', 'description']
def form_valid(self, form):
form.instance.created_by = self.request.user
return super(TicketCreate, self).form_valid(form)
...
Profile Model(Imported Into Ticket Model)
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import post_save
from . import managers
class Profile(models.Model):
# Relations
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="profile", verbose_name="user")
# Attributes
interaction = models.PositiveIntegerField(default=0, verbose_name="interaction")
# Attributes
# Object Manager
objects = managers.ProfileManager()
# Custom Properties
#property
def username(self):
return self.user.username
# Methods
# Meta and String
class Meta:
verbose_name = "Profile"
verbose_name_plural = "Profiles"
ordering = ("user",)
def __str__(self):
return self.user.username
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_profile_for_new_user(sender, created, instance, **kwargs):
if created:
profile = Profile(user=instance)
profile.save()
It looks like you need to add the following to your TicketCreate class in the form_valid function:
form.instance.user = Profile.objects.get(user=self.request.user)
Let me know if that works!
I want to write a very basic tagging app in Django that is almost identical to the Generic Foreign Key example in the docs (django-tagging and django-taggit are overblown for me).
The challenge is displaying all the items of a particular tag, no matter its content type, in the tag detail template.
My guess was to make a Tag with name and slug, then TaggedItem with ctype/object_id/content_object. Blog post gets a many-to-many with Tag, and a signal to save a new TaggedItem. Maybe TaggedItem should've gotten a slug? and maybe Post should've gotten a generic relation instead of a many to many? My query guess is in tags/views.py under context['tagged_items']. That's where I'm stuck now.
# blog/models.py:
from django.db import models
from django.core.urlresolvers import reverse
from django.utils import timezone
class Post(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField()
body = models.TextField()
tags = models.ManyToManyField('tags.Tag', blank=True)
published = models.DateTimeField(default=timezone.now)
class Meta:
ordering = ['-published']
def __unicode__(self):
return u'%s' % self.title
def get_absolute_url(self):
return reverse('blog.views.post_detail', args=[str(self.slug)])
# tags/models.py:
from django.db import models
from django.core.urlresolvers import reverse
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.db.models.signals import post_save
from blog.models import Post
class Tag(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField()
def __unicode__(self):
return u'%s' % self.title
def get_absolute_url(self):
return reverse('tags.views.tag_detail', args=[str(self.slug)])
class TaggedItem(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
def create_tagged_item(sender, **kwargs):
if 'created' in kwargs:
if kwargs['created']:
instance = kwargs['instance']
if instance.tags.all:
content_type = ContentType.objects.get_for_model(instance)
object_id = instance.id
tagged_item = TaggedItem.objects.create(content_type=content_type, object_id=object_id)
post_save.connect(create_tagged_item, sender=Post)
# tags/views.py:
from django.views.generic import ListView, DetailView
from django.contrib.contenttypes.models import ContentType
from .models import Tag
from .models import TaggedItem
class TagListView(ListView):
model = Tag
class TagDetailView(DetailView):
model = Tag
def get_context_data(self, **kwargs):
context = super(TagDetailView, self).get_context_data(**kwargs)
context['tagged_items'] = TaggedItem.objects.filter(content_object__tags__in=self.object.slug) # ????
return context
You don't have any kind of relationship between Tag and TaggedItem, which is making things difficult.
It seems to me that the M2M should be between those two models, and not on Post at all. The whole point is that anything can "be" a tagged item, hence the generic relationship, and that item can have multiple tags. With that, you can then do:
tag = Tab.objects.get(slug=my_slug)
tagged_items = TaggedItem.objects.filter(tags=tag)
content_objects = [item.content_object for item in tagged_items]
But actually, if you're going for simplicity I don't know why you don't use exactly the code from the docs, without the separate Tag model at all. You'll end up with many TaggedItems with the same tag slug/name, but that's OK: you can still do
tagged_items = TaggedItem.objects.filter(slug=my_slug)
and get the content_objects as before.
I ended up going with Timo Zimmermann's approach: looping through possible tags on a generic Entry item. http://www.screamingatmyscreen.com/2012/6/django-and-generic-relations/ Admin friendly and no need for a TaggedItem!
class TagDetailView(DetailView):
model = Tag
def get_context_data(self, **kwargs):
context = super(TagDetailView, self).get_context_data(**kwargs)
item_list = []
for item in ActivityItem.objects.all():
if self.object in item.tags:
item_list.append(item)
context['item_list'] = item_list
return context
Thanks to #DanielRoseman and #Ben for weighing in.