Django translate data from the DB {{ profession }} - django

Is it possible to translate DB entries? I have a dependent dropdown story that i need to translate. But i cant translate the dropdown fields, the fields come from other models and har hard coded. I can use HTML with JQ to achive this but i want to skip the manual labor to update the forms everytime new profession or professioncategories are added.
class Profession(models.Model):
name = models.CharField(max_length=30),
def __str__(self):
return self.name
class Professioncategory(models.Model):
profession = models.ForeignKey(Profession, on_delete=models.CASCADE)
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Skills(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
active = models.BooleanField(_('Active'), default=True)
profession = models.ForeignKey(Profession, on_delete=models.SET_NULL, null=True)
professioncategory = models.ForeignKey(Professioncategory, on_delete=models.SET_NULL, null=True)
posted_on = models.DateTimeField(_('Registrerad'), auto_now_add=True)
updated_on = models.DateTimeField(_('last updated'), auto_now=True)
years_of_exp = models.CharField(_('years of experiance'), max_length=20, choices=YEARS_OF_EXP, null=True, blank=True)

Related

How to use django-autocomplete-light and django-hacker to make a chained dropdown in django admin?

I have 3 models 1) university 2) courses and 3) enquiry.
My enquiry model has a foreign key to "course". And Course has a foreign key to the university. I only want to show the courses related to that university while adding an enquiry. I tried django-smart-select but failed to do so. I tried This answer but I dont understand the logic and failed to implement in my project.
this is my models.py file
class university(models.Model):
univ_name = models.CharField(max_length=100)
country = CountryField(blank=True, null=True)
univ_desc = models.CharField(max_length=1000)
univ_logo = models.ImageField(upload_to="media")
univ_phone = models.CharField(max_length=10, blank=True)
univ_email = models.EmailField(max_length=254, blank=True)
univ_website = models.URLField(blank=True)
assigned_users = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, default="")
def __str__(self):
return self.univ_name
class Meta:
verbose_name_plural = "Universities"
class Course(models.Model):
university = models.ForeignKey(university, on_delete=models.CASCADE)
course_name = models.CharField(max_length=100)
course_levels = models.ForeignKey(course_levels, on_delete=models.CASCADE)
intake = models.ForeignKey(intake, on_delete=models.CASCADE)
documents_required = models.ForeignKey(documents_required, on_delete=models.CASCADE)
course_requirements = models.ForeignKey(course_requirements, on_delete=models.CASCADE)
Active = models.BooleanField()
def __str__(self):
return self.course_name
class enquiry(models.Model):
student_name = models.CharField(max_length=100)
student_phone = models.CharField(max_length=10)
student_email = models.EmailField()
student_address = models.TextField()
current_education = models.ForeignKey(current_education, on_delete=models.CASCADE)
country_interested = CountryField(blank=True, null=True)
university_interested = models.ForeignKey(university, on_delete=models.CASCADE)
course_interested = models.ForeignKey(Course, on_delete=models.CASCADE, limit_choices_to={'Active':True})
level_applying_for = models.ForeignKey(course_levels, on_delete=models.CASCADE)
intake_interested = models.ForeignKey(intake, on_delete=models.CASCADE)
assigned_users = models.ForeignKey(User, on_delete=models.CASCADE, default="", limit_choices_to={"is_active": True})
enquiry_status = models.ForeignKey(enquiry_status, on_delete=models.CASCADE, default="")
course_interested= ChainedForeignKey(Course,chained_field= 'university_interested',chained_model_field= 'university',show_all= False,auto_choose= True,sort=True,limit_choices_to = {"Active": True},)
I want to show the course_interested field related to that university. Need help.
I tried using django-smart-select but failed to implement it. I am not aware of jquery and ajax so that is out of the question to use in my project.
got the solution I used the django-select2 and was able to solve this issue.

Error for my model with ManyToManyField in Django

I am working for a personal project that is using an API and having user authentication with JWT (but used in serializer). I wanted to implement ManyToManyField for user and city but it doesn't work properly. This is the extended model I have found and django aggregation . I want that the UserSearchLocation to store the City and when logged in to see the city, while other users will not see it until the search same city.
models.py
class UserSearchLocation(models.Model):
city_name = models.CharField(max_length=85, blank=False)
def __str__(self):
return self.city_name
class City(models.Model):
user_searched_locations = models.ManyToManyField(User,
through='UsersLocations',
through_fields=('city', 'user'),
related_name="my_cities",
blank=True)
id = models.AutoField(primary_key=True, editable=False)
location = models.CharField(max_length=85)
country = models.CharField(max_length=85, blank=True)
country_code = models.CharField(max_length=2, blank=True)
latitude = models.DecimalField(max_digits=6, decimal_places=4,
null=True, blank=True)
longitude = models.DecimalField(max_digits=6, decimal_places=4,
null=True, blank=True)
zip_code = models.PositiveIntegerField(default=0)
#users_location = models.ManyToManyField(UserSearchLocation)
def __str__(self):
return f'{self.location}, {self.country_code}'
def save(self, *args, **kwargs):
self.location = self.location.capitalize()
self.country = self.country.capitalize()
self.country_code = self.country_code.capitalize()
return super(City, self).save(*args, **kwargs)
class Meta:
verbose_name_plural = 'cities'
unique_together = ("location", "country_code")
class UsersLocations(models.Model):
id = models.AutoField(primary_key=True, editable=False)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
city = models.ForeignKey(City,
on_delete=models.CASCADE,
related_name='locations_by_users',
null=True)
To add in localhost/admin/ a City works, but when to add a UserSearchLocation I have this error:
Exception Value:
column base_usersearchlocation.user_id does not exist
LINE 1: SELECT "base_usersearchlocation"."user_id", "base_usersearch...
Your error says the city.location doesn't exist - location is a CharField on your City model - are you sure you've run migrations and don't have any naming conflicts?

How do I show only a subset of options in a Django dropdown menu

I have an app that allows users to signup and register for courses (from a 'TrainingInstance' model). These events have names etc and are categorised as Past or Current in the database (in the 'Training' model). When I show the BuildOrderForm in my template, I want only options for Current trainings to be shown in the dropdown menu. How can this be done in Django without javascript or Ajax?
I have the following form in forms.py:
class BuildOrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ['training_registered']
And the following models in models.py:
class Training(models.Model):
""" Model which specifies the training category (name) and whether they are Past or Present"""
YEAR = (
('current', 'current'),
('past', 'past'),
)
name = models.CharField(max_length=200, null=True)
year= models.CharField(max_length=200, null=True, choices=YEAR, default='current')
def __str__(self):
return self.name
class TrainingInstance(models.Model):
""" Creates a model of different instances of each training ( May 2021 etc) """
name = models.CharField(max_length=200, null=True, blank=True)
venue = models.CharField(max_length=200, null=True, blank=True)
training = models.ForeignKey(Training, on_delete= models.CASCADE, null = True)
training_month = models.CharField(max_length=200, null=True, blank=True)
participant_date = models.CharField(max_length=20, null=True, blank=True)
staff_date = models.CharField(max_length=20, null=True, blank=True)
graduation_date = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return self.name
class Order(models.Model):
REGSTATUS = (
('registered', 'registered'),
('enrolled', 'enrolled'),
('holding', 'holding'),
('withdrawn', 'withdrawn'),
('waiting', 'waiting'),
)
customer = models.ForeignKey(Customer, on_delete= models.CASCADE, null = True)
training_registered = models.ForeignKey(TrainingInstance, on_delete= models.SET_NULL, blank = True, null = True)
registration_date = models.DateTimeField(null=True,blank=True)
regstatus = models.CharField(max_length=200, null=True, choices=REGSTATUS, default='registered')
def __str__(self):
return self.customer.username
Here is what I have done - which works but I'm also open to feedback about good/bad practice.
class BuildOrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ['training_registered']
def __init__(self,*args,**kwargs):
super (BuildOrderForm,self ).__init__(*args,**kwargs)
self.fields['training_registered'].queryset = TrainingInstance.objects.filter(training__year ="current")

Annotate querying, pk

How should I query when I use pk with annotate?
I need to redirect to user profile when a guest click in link.
Models
class Posty(models.Model):
title = models.CharField(max_length=250, blank=False, null=False, unique=True)
sub_title = models.SlugField(max_length=250, blank=False, null=False, unique=True)
content = models.TextField(max_length=250, blank=False, null=False)
image = models.ImageField(default="avatar.png",upload_to="images", validators=[FileExtensionValidator(['png','jpg','jpeg'])])
author = models.ForeignKey(Profil, on_delete=models.CASCADE)
updated = models.DateTimeField(auto_now=True)
published = models.DateTimeField(auto_now_add=True)
T_or_F = models.BooleanField(default=False)
likes = models.ManyToManyField(Profil, related_name='liked')
unlikes = models.ManyToManyField(Profil, related_name='unlikes')
created_tags = models.ForeignKey('Tags', blank=True, null=True, related_name='tagi', on_delete=models.CASCADE)
class CommentPost(models.Model):
user = models.ForeignKey(Profil, on_delete=models.CASCADE)
post = models.ForeignKey(Posty, on_delete=models.CASCADE, related_name="comments")
content1 = models.TextField(max_length=250, blank=False, null=False)
date_posted = models.DateTimeField(default=timezone.now)
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.content1)
class Profil(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
age = models.PositiveIntegerField(blank=True, null=True)
country = models.CharField(max_length=50)
user = models.OneToOneField(Account, on_delete=models.CASCADE)
avatar = models.ImageField(default="avatar.png", upload_to="images",validators=[FileExtensionValidator(['png', 'jpg', 'jpeg'])])
slug = models.SlugField(blank=True)
gender = models.CharField(max_length=6, choices=GENDER)
friends = models.ManyToManyField(Account, blank=True, related_name="Friends")
social_facebook = models.CharField(max_length=250, null=True, blank=True)
social_instagram = models.CharField(max_length=250, null=True, blank=True)
social_twitter = models.CharField(max_length=250, null=True, blank=True)
social_youtube = models.CharField(max_length=250, null=True, blank=True)
social_linkedin = models.CharField(max_length=250, null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
Views
if tag == None:
my_tag = Posty.objects.annotate(
latest_comment = Subquery(CommentPost.objects.filter(post=OuterRef('id')).values('content1').order_by('-date_posted')[:1]),
my_author=Subquery(CommentPost.objects.filter(post=OuterRef('id')).values('user__user__username').order_by('-date_posted')[:1]),
)
I got a correct username, but I can't get a correct redirect:
Unfortunately, you need to annotate the CommentPost's id information as well with the queryset just like you added the username information. That will end up being a lot of subquery added to the original queryset. Rather I would suggest to use prefetch related to preload the CommentPost information with the original queryset (for reducing DB hits) and directly access that information from template. For example:
# view
my_tag = Posty.objects.prefetch_related('commentpost_set')
# template
{% for post in my_tag %}
<span> {{post.commentpost_set.last.content1}}<span>
<span> {{post.commentpost_set.last.user.username}}<span>
{% endfor %}
Also, last is a queryset function which returns the last object of a given queryset. I can access the CommentPost queryset from a Posty object by reverse querying.

Update existing M2M relationship in Django

I'm trying to save an existing instance of a customer record. Its model has a M2M to the vehicle model (since a customer can multiple vehicles). After reading several questions/answer here, I still do not know how to solve this.
Customer model:
class Customer(models.Model):
vehicle_id = models.ManyToManyField(VehicleSale)
name = models.CharField(max_length=40, blank=True, db_index=True, null=True,
verbose_name='name')
lic = models.CharField(max_length=20, blank=True, db_index=True, null=True,
verbose_name='license')
addr = models.CharField(max_length=40, blank=True, null=True, verbose_name='address')
city = models.CharField(max_length=15, blank=True, null=True, verbose_name='city')
state = models.CharField(max_length=2, blank=True, null=True, verbose_name='state')
zip = models.CharField(max_length=10, blank=True, null=True, verbose_name='zipcode')
email = models.EmailField(blank=True, null=True, verbose_name='email')
tel1 = models.CharField(max_length=15, blank=True, verbose_name='Tel. 1', null=True)
tel2 = models.CharField(max_length=15, blank=True, verbose_name='Tel. 2', null=True)
ssn = models.CharField(max_length=12, blank=True, db_index=True, null=True,verbose_name='SSN')
class Meta:
db_table = 'customer'
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
self.name = self.name.upper()
self.addr = self.addr.upper()
self.city = self.city.upper()
self.state = self.state.upper()
return super(Customer, self).save(*args, **kwargs)
In the view, after defining customer as
customer = current_vehicle.customer_set.all()
I tried the following:
if 'customer' in request.POST:
if customer:
customer_form = CustomerForm(request.POST, instance=customer[0])
if customer_form.is_valid():
customer_form.save()
Also tried adding before customer_form is defined:
customer.vehicle_id = current_vehicle.id
And then this after the form:
customer_form.vehicle_id = current_vehicle.id
Form is not valid so it's not saved. Upon checking {{ form.errors}}, it always reports vehicle_id is required.
Finally, after the answer in this, I adjusted it to my scenario by adding:
obj = customer_form.save(commit=False)
and hoping to assign vehicle_id, but it fails immediately.
What am I missing?
Thanks.
1st EDIT:
The section on the view now looks as:
customer_form = CustomerForm(request.POST, instance=customer[0])
customer_form.save()
customer_form.vehicle_id.add(current_vehicle)
You are misunderstanding what a ManyToMany field is here:
customer_form.vehicle_id = current_vehicle.id
vehicle_id is defined as a ManyToMany field on your Customer model, therefore you can't just assign a single id to it. You have to add an instance of VehicleSale model, eg:
customer_form.vehicle_id.add(current_vehicle)
See docs here:
https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/
See also this answer for why you can't save until you populate the vehicle_id relation:
https://stackoverflow.com/a/2529875/202168