So i have this two models in django:
class Course(models.Model):
def get_image_path(self, filename):
return os.path.join('courses', str(self.slug), filename)
def __str__(self):
return self.name
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Course, self).save(*args, **kwargs)
name = models.CharField(max_length=255, verbose_name="Nombre")
description = models.CharField(max_length=255, verbose_name="DescripciĆ³n")
price = models.DecimalField(max_digits=12,decimal_places=2, verbose_name="Precio")
slug = models.SlugField(blank=True, max_length=255)
icon_img = models.ImageField(upload_to=get_image_path, blank=True, null=True, verbose_name="Imagen")
background_color = ColorField(default="#026085")
class Meta:
verbose_name = "curso"
verbose_name_plural = "cursos"
class UserCourse(models.Model):
user = models.ForeignKey(User)
course = models.ForeignKey(Course)
So whenever a user "buys" a course, it is stored in UserCourse. I have a view where the system shows a list of all the courses the user has bought. This is the view code:
def user_course_list_view(request, username):
context_dict = {}
try:
user_courses = UserCourse.objects.filter(user=request.user).course_set
context_dict['courses'] = user_courses
context_dict['heading'] = "Mis cursos"
except:
context_dict['courses'] = None
context_dict['heading'] = "Mis cursos wey"
return render(request, 'courses/course_list.html', context=context_dict)
I dont know where is the error and I cant seem to catch the exception (im using django with docker)
tl;dr
Something like this should work.
usercourse_objects = UserCourse.objects.filter(user=request.user).select_related('course')
user_courses = [x.course for x in usercourse_objects]
Explanation
There are multiple ways to do this, but one way would be to first get all the UserCourse objects for the current user:
usercourse_objects = UserCourse.objects.filter(user=request.user)
Then, for each UserCourse object, get the related Course:
user_courses = [x.course for x in usercourse_objects]
Now, the second line causes N database queries (one for each time we follow the course foreign key relation. To prevent this, the first line can be changed to:
usercourse_objects = UserCourse.objects.filter(user=request.user).select_related('course')
This pre-populates the course attribute of the UserCourse objects. More info about select_related() can be found here.
Related
I am making a small project to rate salesmen. I have regions and each region has its salesmen. So, if region "blahblah" is selected, form should show salesmen choices which are related to that region. I have found some answers via stackoverflow, but it still shows all salesmen, regardless of their regions.
My model is this:
class Region(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True)
def __str__(self):
return self.name
class Salesman(models.Model):
region = models.ForeignKey(Region,
related_name='region',
on_delete=models.CASCADE)
name = models.CharField(max_length=40)
surname = models.CharField(max_length=40)
def __str__(self):
return self.name
class Rating(models.Model):
RATING_CHOICES = [(i, str(i)) for i in range(1,6)]
salesman = models.ForeignKey(Salesman,
related_name='salesman',
on_delete=models.CASCADE)
phone = models.CharField(max_length=15, blank=True)
rating = models.IntegerField(choices=RATING_CHOICES, blank=False)
sent_time = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.phone
I found modified __init__ method for my forms.py:
class RateAddForm(forms.ModelForm):
class Meta:
model = Rating
def __init__(self, region_id=None, **kwargs):
super(RateAddForm, self).__init__(**kwargs)
if region_id:
self.fields['salesman'].queryset = Salesman.objects.filter(region=region_id)
And also my views.py is this:
def report_add(request, region_id):
if request.method == 'POST':
print(region_id)
form = RateAddForm(request.POST, region_id=region_id)
if form.is_valid():
message = "Thanks!"
form.save()
return HttpResponse(message)
else:
print("Something went wrong!")
form = RateAddForm()
else:
form = RateAddForm(request.POST)
return render(request,
'account/report.html',
{'form': form})
It still shows me all salesmen on my database, even if i choose a region. How to solve this problem that form should show only salesmen of selected region. Thanks in advance!
Try setting the self.base_fields['salesman'].queryset instead of
self.fields['salesman'].queryset (i.e "base_fields" instead of "fields").
(That's what I do when I need to filter in Admin forms)
I have been attempting to import data into my Django project using Django import-export. I have two models Ap and Job, Job has a FK relationship with Ap. Using the Admin, I can select the file and the type, CSV. So far my program seems to run, but gets hung up on the FK. I'm close, something is off and causing the import script to fail.
Models.py
class Ap(models.Model):
line_num = models.IntegerField()
vh = models.IntegerField()
vz = models.IntegerField()
status = models.CharField(
choices=statuses, default="select", max_length=40)
classified = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Job(models.Model):
aplink = models.ForeignKey(Ap, related_name=(
"job2ap"), on_delete=models.CASCADE)
job_num = models.IntegerField()
description = models.CharField(max_length=200)
category = models.CharField(
choices=categories, default="select", max_length=40)
status = models.CharField(
choices=statuses, default="select", max_length=40)
dcma = models.BooleanField(default=False),
due_date = models.DateField(blank=True),
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
views.py
class ImportView(View):
def get(self, request):
form = ImportForm()
return render(request, 'importdata.html', {'form': form})
def post(self, request):
form = ImportForm(request.POST, request.FILES)
job_resource = JobResource()
data_set = Dataset()
if form.is_valid():
file = request.FILES['import_file']
imported_data = data_set.load(file.read())
result = job_resource.import_data(
data_set, dry_run=True) # Test the data import
if not result.has_errors():
job_resource.import_data(
data_set, dry_run=False) # Actually import now
else:
form = ImportForm()
return render(request, 'importdata.html', {'form': form})
resource.py
class CharRequiredWidget(widgets.CharWidget):
def clean(self, value, row=None, *args, **kwargs):
val = super().clean(value)
if val:
return val
else:
raise ValueError('this field is required')
class ForeignkeyRequiredWidget(widgets.ForeignKeyWidget):
def clean(self, value, row=None, *args, **kwargs):
if value:
print(self.field, value)
return self.get_queryset(value, row, *args, **kwargs).get(**{self.field: value})
else:
raise ValueError(self.field + " required")
class JobResource(resources.ModelResource):
aplink = fields.Field(column_name='aplink', attribute='aplink', widget=ForeignkeyRequiredWidget(Ap,'id'),
saves_null_values=False)
job_num = fields.Field(saves_null_values=False, column_name='job_num', attribute='job_num',
widget=widgets.IntegerWidget())
description = fields.Field(column_name='description', attribute='description', saves_null_values=False,
widget=CharRequiredWidget())
class Meta:
model = Job
fields = ('aplink', 'job_num', 'description',)
clean_model_instances=True
admin.py
class JobResource(resources.ModelResource):
class Meta:
model=Job
fields=('aplink','job_num','description',)
class JobAdmin(ImportExportModelAdmin):
resource_class = JobResource
admin.site.register(Job, JobAdmin)
CSV file, data to import. I have tried leaving the first column empty, as will as putting the Id of the only Ap stored in the table ie 1. I have also tried hard coding the line_num, which is 1200 the first column as well.
CSV file for importing data:
Date importing errors:
In your resources, while defining fields, you need to include id field in the list. So change JobResource to the following:
class JobResource(resources.ModelResource):
class Meta:
model = Job
fields = ('id', 'aplink', 'job_num', 'description')
If you have defined a custom id field, then you will need to provide:
import_id_fields = ('your_id_field')
Is It possible to add one or more Char Fields to each ManyToMany field option?
My Models:
class engineeringUni(models.Model):
field2 = models.CharField(max_length=200)
des_eng = models.CharField(max_length=1000, default='Add description')
def __str__(self):
return self.field2
def description_eng_universities(self):
return self.des_eng
class engineering_courses(models.Model):
course_name = models.CharField(max_length=400)
course_description = models.CharField(max_length=1000, default='This is a description')
course_offered_by = models.ManyToManyField(engineeringUni, related_name='course_offered_by')
course_duration = models.IntegerField(blank=False, default='2')
def __str__(self):
return self.course_name
def description_course(self):
return self.course_description
def offered_by_courses(self):
return self.course_offered_by
def duration_courses(self):
return str(self.course_duration)
As you can see in the image, I have the options in the ManyToMany field. Those options are:
University 1
University 2
University 3
What I want to have is an additional text (Char) field next to each of these options (University 1, University 2, University 3).
Is this possible?
EDIT 1:
Current code:
class engineering_courses(models.Model):
course_name = models.CharField(max_length=400)
course_description = models.CharField(max_length=1000, default='This is a description')
course_offered_by = models.ManyToManyField(
engineeringUni,
through='ThroughModel',
through_fields=('course', 'university'),
)
course_duration = models.IntegerField(blank=False, default='2')
def __str__(self):
return self.course_name
def description_course(self):
return self.course_description
def offered_by_courses(self):
return self.course_offered_by
def duration_courses(self):
return str(self.course_duration)
class ThroughModel(models.Model):
course = models.ForeignKey(engineering_courses, on_delete=models.CASCADE)
university = models.ForeignKey(engineeringUni, on_delete=models.CASCADE)
additional_text = models.CharField(max_length=200)
EDIT 2: Problem fixed. I was getting that no table error because I had deleted the migration files and on deleting database (db.sqlite3) file and applying migration again, It fixed.
You can use a through model in the ManyToManyField (docs). This model can be used to store any additional fields.
class engineering_courses(models.Model):
# ...
course_offered_by = models.ManyToManyField(engineeringUni, related_name='course_offered_by', through='ThroughModel')
class ThroughModel(models.Model):
course = models.ForeignKey(engineering_courses)
university = models.ForeignKey(engineeringUni)
additional_text = models.CharField()
Take another look at the django docs referenced in the answer from arjun27. You have more than one foreign key in your ThroughModel, so django is confused. Try specifying the through fields in your engineering_course model, migrate the changes, and see if that works.
Mark
I have a model that includes a foreign key:
class Part(models.Model):
partType = models.ForeignKey(PartType, on_delete=models.CASCADE)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
part_name = models.CharField(max_length=60)
class QuotePart(models.Model):
quote = models.ForeignKey(Quote, on_delete=models.CASCADE)
line = models.PositiveSmallIntegerField(default=1)
partType = models.ForeignKey(PartType, on_delete=models.CASCADE)
# part can be None if the part has not been selected
part = models.ForeignKey(Part, on_delete=models.CASCADE,blank=True,null=True)
I have a form that allows parts to be added to a quote and want to want to limit the choices on the form to just the Parts that are the right PartType but my code is not working:
class QuoteBikePartForm(ModelForm):
def __init__(self, *args, **kwargs):
super(QuoteBikePartForm, self).__init__(*args, **kwargs)
self.fields['partType'].widget.attrs['disabled'] = True
self.fields['frame_part'].widget.attrs['disabled'] = True
partType = kwargs.pop('partType')
self.fields['part'].queryset = Part.objects.filter(partType=partType.pk)
class Meta:
model = QuotePart
fields = ['quote','line','partType','frame_part', 'part', 'quantity','cost_price', 'sell_price']
QuoteBikePartFormSet = inlineformset_factory(Quote, QuotePart, form=QuoteBikePartForm)
I have tried a number of different things and so far no luck.
you can use 'self.instance.key_name' to the access the value.
I hava an Article model ,contains a title column,which can be stored mix with white space,what i want is that ,every time i query an article,space in title content could be repaced with dash,for url friendly.
models.py:
class Article(models.Model):
STATUS = (
(0,'on'),
(1,'off')
)
#id = models.IntegerField(primary_key=True,help_text='primary key',auto_created=True)
category = models.ForeignKey(Category,related_name='articles', help_text='foreigner key reference Category')
#author = models.ForeignKey(myadmin.User, help_text='foreigner key reference myadmin User')
title = models.CharField(max_length=100, help_text='article title')
description = models.TextField(help_text='article brief description')
content = models.TextField(help_text='article content')
like = models.IntegerField(default=0,help_text='like numbers')
secretcode = models.CharField(max_length=512,help_text='who has the code can scan')
status = models.IntegerField(choices=STATUS,help_text='status of the article')
createtime = models.DateTimeField(auto_now_add=True,help_text='time that first created')
modifytime = models.DateTimeField(auto_now=True,help_text='time when modified')
articles = models.Manager()
def __str__(self):
return self.title
class Meta:
db_table = 'article'
my view.py:
def get(self,request):
offset = int(request.GET.get('offset', 0))
category = request.GET.get('category')
end = offset+10
articlecatalogs = Article.articles.filter(category__name=category)[offset:end]
i was thinking creating a custom Manager and define a method to transform the data,but the query conditions needed are from request,in here,i don't know how to do it ?can someone help me?
I think you have to use slug filed as well and overwrite your save method for save slug something like this :
class Article(models.Model):
slug = models.SlugField("slug")
category = models.ForeignKey(Category,related_name='articles', help_text='foreigner key reference Category')
-- more fields --
def __str__(self):
return self.title
def get_absolute_url(self):
return self.slug
def save(self, *args, **kwargs):
if not self.slug:
self.slug = self.title.strip(" ").replace(' ','-')
super(Article, self).save(self, *args, **kwargs)
#property
def get_title(self):
""" write python code for remove extra spaces so can can dispay your tile in html and call this method with instance when you want to print title """
return new_title_without_extra_spaces
for details page you can use slug value for get a instance. Hope this would be helpful to you.