Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django choice from db
I'm newbie with django and I'm trying to make a MultipleChoiceField that recive some choices from a model. # function that get n querysets and allow to put as option def gen_choices(null_option=False, *querysets): out = [] if null_option: out = out + [(None, '---------')] for queryset in querysets: for element in queryset: out = out + [(element.__str__(), element.__str__())] print(out) return out # FORM class MyFormHere(forms.ModelForm): # CHOICES MY_CHOICE = gen_choices(True, Model1.objects.all(), Model2.objects.all()) Can I do this better and safer? I don't if this is the best way to do what i want to do. -
ProgrammingError: function lower(bigint) does not exist (Django, AWS RDS, PostgreSQL)
In my Django Rest Framework project, I have a custom filter_backends that allows filtering by case insensitively: class CaseInsensitiveOrderingFilter(OrderingFilter): def filter_queryset(self, request, queryset, view): ordering = self.get_ordering(request, queryset, view) if ordering: new_ordering = [] for field in ordering: # field = str(field) print(Lower(field)) if field.startswith('-'): new_ordering.append(Lower(field[1:]).desc()) else: new_ordering.append(Lower(field).asc()) return queryset.order_by(*new_ordering) return queryset This works fine in development. Now I hosted the django app on elastic beanstalk and I configured a postgresql database via amazon relational database service (RDS). When I try now to call the API, I get this error: ProgrammingError at /api/profile_list/ function lower(bigint) does not exist LINE 1: ..."."author_id") GROUP BY "user_user"."id" ORDER BY LOWER(COUN... HINT: No function matches the given name and argument types. You might need to add explicit type casts. This error appears only in the RDS deployment. I tried to type cast the fields in django with: field = str(field) But this is not working. Is there any way to allow caseinsensitive ordering without the lower function, or how can I conditionally check if it is a number (and cast then?) or a text abd -
django filter data (coordinates of canvas) and combine to form a new data coordinate
I have a canvas which lets user lets draw on it and save it (it saves the coordinates in the database as points and lines) , and the user can retrieve the drawing they saved. My model class Drawing(models.Model): drawingJSONText = models.TextField(null=True)# coordinates saved project = models.CharField(max_length=250) My sample data - drawingJSONText field {"points":[{"x":109,"y":286,"r":1,"color":"black"},{"x":108,"y":285,"r":1,"color":"black"},{"x":106,"y":282,"r":1,"color":"black"},{"x":103,"y":276,"r":1,"color":"black"},],"lines":[{"x1":109,"y1":286,"x2":108,"y2":285,"strokeWidth":"2","strokeColor":"black"},{"x1":108,"y1":285,"x2":106,"y2":282,"strokeWidth":"2","strokeColor":"black"},{"x1":106,"y1":282,"x2":103,"y2":276,"strokeWidth":"2","strokeColor":"black"}]} I am able to retrieve the drawing , but i am trying to filter the data based on project field and i need to add all coordinates of the queryset and plot it onto canvas def load(request): """ Function to load the drawing with drawingID if it exists.""" try: #drawingJSONData1 = json.loads(Drawing.objects.get(id=1).drawingJSONText) #drawingJSONData2 = json.loads(Drawing.objects.get(id=3).drawingJSONText) #drawingJSONData = dict() #drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData1["points"] #drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData2["lines"] #drawingJSONData = json.dumps(drawingJSONData) #drawingJSONData = Drawing.objects.get(id=3).drawingJSONText filterdata = Drawing.objects.filter(project=1) drawingJSONData = filterdata.drawingJSONText # Sending context with appropriate information context = { "loadIntoJavascript": True, "JSONData": drawingJSONData } # Editing response headers and returning the same response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context)) return response -
How to integrate a python file onto a Django project?
I am trying to include a machine learning component in my Django project. I have the method written in python. How do I get to make it work on the website using Django. Can I simply drag the ".py" file into the file structure and call it from an HTML page? I am new to Django any help would be greatly appreciated. -
ValueError at /jobs/approve/1 Cannot query "client1": Must be "Application" instance
Models: class Application(models.Model): job = models.ForeignKey(Job, related_name='applications', on_delete=models.CASCADE) scope_of_work = models.TextField(max_length=250, null=True, blank=False) fee = models.CharField(max_length=250, null=True, blank=False) examples = models.ImageField(default='examples.jpg', upload_to='profile_pics', blank=True) external_link = models.URLField(null=True, blank=True) created_by = models.ForeignKey(User, related_name='applications', on_delete=models.CASCADE) created_at = models.DateField(auto_now_add=True) def __str__(self): return str(self.created_by) class ApproveJob(models.Model): PENDING = 'pending' ACTIVE = 'approve' CHOICES_STATUS = ( (PENDING, 'Pending'), (ACTIVE, 'Approve'), ) approve = models.ForeignKey(Application, related_name='approved_job'on_delete=models.CASCADE) status = models.CharField(max_length=20, choices=CHOICES_STATUS, default=PENDING) def __str__(self): return self.approve Views: def approve_job(request, application_id): approve = get_object_or_404(ApproveJob, pk=application_id, approve=request.user) if request.method == 'POST': form = ApproveForm(request.POST, instance=approve) if form.is_valid(): approve = form.save(commit=False) approve.status = request.POST.get('status') approve.save() return redirect('dashboard') else: form = ApproveForm(instance=approve) return render(request, 'job/approve_job.html',{'form':form, 'approve':approve}) -
Reverse django custom admin site URL
I'm trying to get reverse for my custom admin which is using proxy model, but I cann't find out how to reverse to sub page. In my panel admin, model Advertisement has few pages and I want to reverse to one of them. I've already tried: reverse("admin:app_list", args['advertisement', 'deactivatedadvertisements']) class DeactivatedAdvertisements(Advertisement): class Meta: proxy = True class DeactivatedAdvertisementsAdmin(admin.ModelAdmin): """Panel for listing deactivated advertisements allowing to activate them.""" ordering = ["-deactivated_at"] list_display = [ "advertisement_title", "user", "root_category", "activate", "deactivated_at", ] I want to get url admin/advertisement/deactivatedadvertisement/ How can I reach it? -
Do i need to implement JWT in Django?
I am not very fimiliar with authentication but I know that JWT is the best practice and market standard but do I really need to implement JWT in Django can I not use Django built-in cookie-based authentication if not then and what are the advantages of using JWT over Django cookie-based authentication. -
How to make only the owner of a Product able to edit or delete it
I am developing a supplier management system. I have different admins and different suppliers, i will like that only the particular supplier that added the product is able to edit or delete it, so that even other suppliers are not able to edit or delete it. models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) # CUSTOM USER FIELDS firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) class user_type(models.Model): is_admin = models.BooleanField(default=False) is_supplier = models.BooleanField(default=False) user = models.OneToOneField(User, on_delete=models.CASCADE) class Product(models.Model): name = models.CharField(max_length=36) price = models.PositiveIntegerField() description = models.TextField() views.py @login_required @supplier_required def Editproduct(request, pk): title = "Edit Product" product = Product.objects.get(id=pk) form = AddProductForm(instance=product) if request.method == 'POST': form = AddProductForm(request.POST, request.FILES, instance=product) if form.is_valid(): form.instance.user = request.user form.save() messages.success(request, "Product Edited Successfully") return redirect('product') context = {"form":form, "title":title} return render(request, "core/editproduct.html", context) @login_required @supplier_required def DeleteProduct(request, pk): title = "Delete Product" product = Product.objects.get(id=pk) try: product.delete() messages.success(request, "Product Deleted Successfully.") return redirect('product') except: messages.error(request, "Failed to Delete Product.") return redirect('product') -
If user log in again, how to redirect the user to the last page he visited in his last session in django?
I am developing a website using django, and I want to redirect a user to the last page he was at during his last session before log out when he log in again. How can I do this? -
How to get the Total Sum for different fields of an object with annotate in Django?
I've got three models like this: class Corredor (models.Model): dorsal=models.IntegerField(primary_key=True) tipo=models.CharField(max_length=50) nombre=models.CharField(max_length=50) f_nacimiento=models.DateField(default=1/1/1975) nacimiento=models.IntegerField() categoria=models.CharField(max_length=50) pais=models.CharField(max_length=50) equipo=models.CharField(max_length=50) nombre_equipo=models.CharField(max_length=50) lid=models.BooleanField() gre=models.BooleanField() jor=models.BooleanField() giro=models.BooleanField() tour=models.BooleanField() vuelta=models.BooleanField() abandono_giro=models.IntegerField(default=0) etapa_aban_giro=models.IntegerField(default=0) abandono_tour=models.IntegerField(default=0) etapa_aban_tour=models.IntegerField(default=0) abandono_vuelta=models.IntegerField(default=0) etapa_aban_vuelta=models.IntegerField(default=0) class Meta: ordering=['nombre'] def __str__(self): return self.nombre class Equipo (models.Model): alias=models.CharField(max_length=50, primary_key=True) lid1=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid1", on_delete=models.CASCADE) lid2=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid2", on_delete=models.CASCADE) lid3=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid3", on_delete=models.CASCADE) lid4=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid4", on_delete=models.CASCADE) gre1=models.ForeignKey(Corredor,limit_choices_to={'gre':True, 'giro':True, 'tipo': "Rider"}, related_name="gre1", on_delete=models.CASCADE) gre2=models.ForeignKey(Corredor,limit_choices_to={'gre':True, 'giro':True, 'tipo': "Rider"}, related_name="gre2", on_delete=models.CASCADE) gre3=models.ForeignKey(Corredor,limit_choices_to={'gre':True, 'giro':True, 'tipo': "Rider"}, related_name="gre3", on_delete=models.CASCADE) jlg1=models.ForeignKey(Corredor,limit_choices_to={'jor':True, 'giro':True, 'tipo': "Rider"}, related_name="jlg1", on_delete=models.CASCADE) jlg2=models.ForeignKey(Corredor,limit_choices_to={'jor':True, 'giro':True, 'tipo': "Rider"}, related_name="jlg2", on_delete=models.CASCADE) lid_sup=models.ForeignKey(Corredor,limit_choices_to={'lid':True, 'giro':True, 'tipo': "Rider"}, related_name="lid_sup", on_delete=models.CASCADE) gre_sup=models.ForeignKey(Corredor,limit_choices_to={'gre':True, 'giro':True, 'tipo': "Rider"}, related_name="gre_sup", on_delete=models.CASCADE) jlg_sup=models.ForeignKey(Corredor,limit_choices_to={'jor':True, 'giro':True, 'tipo': "Rider"}, related_name="jlg_sup", on_delete=models.CASCADE) ganador_e1=models.ForeignKey(Corredor,limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e1", on_delete=models.CASCADE) ganador_e2=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e2", on_delete=models.CASCADE) ganador_e3=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e3", on_delete=models.CASCADE) ganador_e4=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e4", on_delete=models.CASCADE) ganador_e5=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e5", on_delete=models.CASCADE) ganador_e6=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e6", on_delete=models.CASCADE) ganador_e7=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e7", on_delete=models.CASCADE) ganador_e8=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e8", on_delete=models.CASCADE) ganador_e9=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e9", on_delete=models.CASCADE) ganador_e10=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e10", on_delete=models.CASCADE) ganador_e11=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e11", on_delete=models.CASCADE) ganador_e12=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e12", on_delete=models.CASCADE) ganador_e13=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e13", on_delete=models.CASCADE) ganador_e14=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': "Rider"}, related_name="ganador_e14", on_delete=models.CASCADE) ganador_e15=models.ForeignKey(Corredor, limit_choices_to={'giro':True, 'tipo': … -
Django IntegrityError (null value in column violates not-null constraint) allows model object to be saved but then deletes object?
When troubleshooting the error django.db.utils.IntegrityError: null value in column "experience" violates not-null constraint DETAIL: Failing row contains (7, f, null, 1, 1, null, 5)., I added a save function to my model to print out the experience value so that I could see if it was really null or not. The experience value being saved is not null. When I ran my code after adding this save function, the object seemed to be created successfully without error when I click 'save' in helm. But, when I go to view my Scheduler objects, nothing appears there. Additionally, I get the message at the top of helm that my object was created successfully along with a message that the schedule event with ID "None" does not exist. I am really confused on why this is happening. My guess is that the save method I added is making it so that Django is not checking to see if errors exist which causes the object to appear created when it is not. I am fairly certain that the IntegrityError still exists and that this is related to why the object is deleted immediately after creation. I would appreciate any help someone can provide. Django … -
django media images wont display
I have deployed a Django project on a server. The project has a blog app in which you can add posts from the admin page. Each post has some paragraphs, a title, and an image. The posts get created perfectly, but sometimes when I revisit the site, the pictures I uploaded don't display. I have found out that if I clear the browser's cache by pressing ctrl+f5, the images will get displayed. But this is not ok, and I cant tell every user to clear their browser cache, obviously. here is a sample of this problem: and everything goes back to normal after cache clearing. this is my settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' and I have added this line in my main urls.py: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to style form's dropdown options and add picture, instead of a generic list using Django
I want to have a user's profile pic and the value in the database when trying to submit a form. Currently the form just has a drop down that lists all the objects' ids in the DB, example: Object (1) Object (2) Object (3) Object (4) Object (5) I want the drop down to have: Username, profile pic (their actual image from static files), Object 1's string (whats actually in the DB) Username, profile pic (their actual image from static files), Object 2's string (whats actually in the DB) Username, profile pic (their actual image from static files), Object 3's string (whats actually in the DB) Username, profile pic (their actual image from static files), Object 4's string (whats actually in the DB) Username, profile pic (their actual image from static files), Object 5's string (whats actually in the DB) Here is some code, i'm open to any python solution (crispy/widget/etc.) My form.py from django.contrib.auth import get_user_model from .models import Observation, Data, Hypothesis, Experiment, Comment User = get_user_model() class SubmitObservation(ModelForm): description = forms.CharField(widget=forms.Textarea, label='Submit an Observation') class Meta: model = Observation fields = ('description',) exclude = ('user', 'status', 'activate_date', 'deactivate_date') #observation = forms.CharField(label='Observation', max_length=250) class SubmitData(ModelForm): data_description = forms.CharField(widget=forms.Textarea, label='Data') … -
csrf token missing axios to django rest framework
i was trying to make post request and face with error code 403,csrf token was missing.. tried many methods but didnt work at last disabled csrf token on settings.py and worked , so found the problem was in csrf token class Axios extends React.Component{ constructor(){ super() this.state = { persons: [] } } post(){ axios.post('http://127.0.0.1:8000/api/create', { title: 'titan', body: 'this is working', }) .then(function (response) { console.log(response); }) } get(){ axios.get('http://127.0.0.1:8000/api').then(Response=>{ console.log(Response.data) }) } componentDidMount(){ this.post(); this.get(); } render(){ return( <div> <h1>fetch</h1> </div> ) } } export default Axios; this is my code pls tell me a way to put csrf token in this as well as import statement... currently using axios -
Get User Specific Answer attribute from primary model instance - django
I have a Question model and then an Answer Model. Answer model saves answers specific to the logged-in user. I have successfully saved the answer of the login user and verified it in the admin. However, I am unable to get the answer, specifically for the logged-in user. Can you please point me in the right direction? I have already tried https://docs.djangoproject.com/en/3.1/ref/models/relations/ My Model: class Question(models.Model): question = models.CharField(max_length=200, null=True, blank=True) edit_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.question class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) answer = models.TextField(max_length=600, null=True, blank=True, default=" ") edit_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.answer My View def InterviewQuestion(request): questions = Question.objects.all() context = {'questions':questions} return render(request, 'jobs/ace-interview.html', context) My Template {% for question in questions %} <div class="card"> <div class="card-body"> <h5 class="card-title">{{question.question}}</h5> <p class="card-text">{{question.answer_set.answer}}</p> </div> </div> {% endfor %} I want Answer here specific to the user -
Django Admin Panel can't access specific items
I've got a model of an article and everything works fine except when I change their status to draft - it disappears from Admin Django Panel. New articles are successfully added, but then don't show, admin panel just can't access them. When I change the URL to force the admin panel to show me the details so I could edit it, I get a message that the article with given ID doesn't exist. So basically every draft article gets lost. But I know they have to exist in my database, because they show up on my article list view, but I can't go to detail view or draft view as I always get "No NewsModel matches the given query" Django 2.0.5 models.py class NewsModel(models.Model): STATUS_CHOICES = ( ('draft','Draft'), ('published','Published'), ) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) title = models.CharField(max_length=250) slug = AutoSlugField(populate_from='title') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES) image = models.ImageField(upload_to="news/") description = models.TextField(null=True, blank=True) def get_absolute_url(self): from django.urls import reverse return reverse('main:news_details', kwargs={'slug':self.slug}) def __str__(self): return self.title class Meta: ordering = ('-publish',) verbose_name = 'News' verbose_name_plural = 'News' admin.py @admin.register(NewsModel) class NewsAdmin(admin.ModelAdmin): list_display = ('title', 'game', 'news_type', 'author', 'finish', 'publish') views.py def news_details(request, slug): … -
Problems with django-microsoft-auth
A customer told me that he needs to make a system, in Django, that authenticates users against Azure Active Directory. I'm trying to use django-microsoft-auth (https://django-microsoft-auth.readthedocs.io/en/latest/usage.html) but I have several problems. When I'm going to execute the test site, I have the following error: ModuleNotFoundError: No module named 'tests.site' so I don't see how this test site works. I'm executing in Windows 10, 64 bits. I already do the conection to Azure Active Directoy but I don't know can I see the user that it's connected, make a login and a logout link, manage the user permits. I think that the quick start guide it's very poor for Django beginners deverlopers, like me, because not especify all of this items. I will ver glad if somebody can help me. I have spent many hours trying to solve these problems. Thanks. -
Django migration throws relation does not exist before migration makes the table
I'm trying to start from a clean database and run all the migrations, but I have a for that's used in a view that has options that it pulls from the database. When I try to run the migration, it throws an error. Commenting out the code fixes it, but this doesn't seem like a good solution for deploying to new environments. I've seen other questions where the answer is to just comment out your urls.py, but I was wondering if anyone found a clean solution for this? -
I am not able to add item to database
I have a product model, which i have the modelforms to make a form for and then implemented in my views and templates. After submitting the form, the product is not being added to the database and I don't know what the error seems to be. I made sure to use the enctype="multipart/form-data" because of the image field in the form and also request.FILES. N.B:I am getting Error Adding Product which is the else statement if the form is not valid, but i don't know how the form is not valid. models.py class Product(models.Model): name = models.CharField(max_length=36) price = models.PositiveIntegerField() description = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() image = models.ImageField(upload_to='images/products', default='images/products/default-product.jpeg', blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) is_favourite = models.ManyToManyField(User, related_name='favourite', blank=True) country = CountryField(blank_label='(select country)') def __str__(self): return self.name forms.py class AddProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' exclude = ['user'] views.py @login_required @supplier_required def Addproduct(request): title = "Add New Product" form = AddProductForm() if request.method == 'POST': form = AddProductForm(request.POST, request.FILES) if form.is_valid(): form.instance.user = request.user form.save() messages.success(request, "Product Added Successfully") return redirect('product') else: messages.error(request, "Error Adding Product") context = {"form":form, "title":title} return render(request, "core/addproduct.html", context) addproduct.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} … -
MultipleChoiceFilter to Checkboxes
I have a ModelMultipleChoiceFilter working, however I cant find a way to adjust it from a input multiple choice to a checkbox list. This is what I currently have: This is what I want to convert it to: My current code: class GameFilter(django_filters.FilterSet): gamemodes = django_filters.ModelMultipleChoiceFilter( queryset=GameMode.objects.all(), label='Game modes (or)', ) -
how to create urls/path in django restframework?
My project structure is like this: project |----app1 |--app1.1 |--app1.2 |--app1.3 so my question is how to add url/path? -
Django Many to Many Fields Not Saving Rest Framwork
Hi guys I'm trying to save many to many data from rest Post method when I post it give me blank none items added to many to many fields. Please check and help me how I can fix this issue Views.py @api_view(['POST', 'GET']) def AddDisco(request, *args, **kwargs): if request.method == 'POST': data=request.data serializer = serializers.DiscoSerializer(data=data) if serializer.is_valid(): print('it is valid') serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) if request.method == 'GET': qs = Disco.objects.all() serailzer = serializers.DiscoSerializer(qs, many=True) return Response(serailzer.data, status=status.HTTP_200_OK) return Response(serializer.data, status=status.HTTP_200_OK) Models.py class MusicGenre(models.Model): title = models.CharField(max_length=50, unique=True) description = models.CharField(max_length=100) createdAt = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Disco(models.Model): title = models.CharField(max_length=100) genre = models.ManyToManyField(MusicGenre, blank=True) Serializer.py class DiscoSerializer(serializers.ModelSerializer): class Meta: model = models.Disco fields = '__all__' depth = 1 when I try to post from api it wont add the items in genre it gives me blank Please help me to solve this issue -
How to get data correctly from a django model to Django REST framework
I'm working with Python 3.9 and Django 3.1.6. I have a quite long model in models.py. Short version is something like this: class Check (models.Model): @property def total_body_fat_percentage(self): if self.client_gender == "M": total_body_fat_percentage = (self.Yuhasz * 0.097) + 3.64 pass else: total_body_fat_percentage = total_body_fat_percentage = float((self.Yuhasz * 0.1429) + 4.56) return total_body_fat_percentage @property def muscle_weight_percentage(self): muscle_weight_percentage =self.muscle_weight*100/self.weight return muscle_weight_percentage These fields return a float number. Something like 14.407. Of course there are other fields in there such as Yuhasz, client_gender, etc. I need these values into JSON. I tried to use the following serializer on serializer.py: class PercentagesSerializer(ModelSerializer): class Meta: model = Check fields = ('total_body_fat_percentage', 'muscle_weight_percentage') And I have the following class on views.py: class PercentagesAPI(APIView): authentication_classes = [] permission_classes = [] serializer = PercentagesSerializer def get(self, request, format=None): lista = Check.objects.all() print(lista) response = self.serializer(lista) print(response) json_response= json.dumps(response.data) print(json_response) data = { 'percentages': json_response } return Response(response.data) But it returns no data. Shell console states that it gets the queryset, it gets the fields, but it doesn't seems to get the values: <QuerySet [<Check: Check object (1)>]> PercentagesSerializer(<QuerySet [<Check: Check object (1)>]>): total_body_fat_percentage = ReadOnlyField() muscle_weight_percentage = ReadOnlyField() {} Thank you in advance for your advices and help! -
Facing HTTPError 404
I am using Django as frontend and Firebase as backend. I am trying to render a html page after a post request. As I tried to run the program I am getting HTTPError 404 Here is my view.pyViews.p After I run the http://127.0.0.1:8000/post_create/ on Chrome I get the following error Error I am trying to solve this problem from 3-4 days but unable to get solution. I am not getting why this error is occuring. Your help would be appreciated Thank you. -
Display Multiple Chart.js Charts in Django Template Using Loop
I want to filter multiple charts using for loop in django template. The data displays correctly, and I can get it to display the first chart only. Guys, i am having trouble using for loop in django template i do not know how to use for loop to display multiple charts in django template i am unable to find solution of displaying multiple charts and django kindly help me please. Template {% for data in data_list %} <div class="box col-lg-3 pull-up"> <div class="box-footer p-0 no-border"> <div class="chart"> <canvas id="chartjs" class="h-80"></canvas> </div> </div> </div> {% endfor %} <script> $(function () { 'use strict'; //----chart var dasChartjs = document.getElementById("chartjs").getContext("2d"); var blue_trans_gradient = dasChartjs.createLinearGradient(0, 0, 0, 100); blue_trans_gradient.addColorStop(0, 'rgba(247, 147, 26,1)'); blue_trans_gradient.addColorStop(1, 'rgba(255,255,255,0)'); var DASStats = { responsive: true, maintainAspectRatio: false, datasetStrokeWidth : 3, pointDotStrokeWidth : 4, tooltipFillColor: "rgba(247, 147, 26,0.8)", legend: { display: false, }, hover: { mode: 'label' }, scales: { xAxes: [{ display: false, }], yAxes: [{ display: false, ticks: { min: 0, max: 85 }, }] }, title: { display: false, fontColor: "#FFF", fullWidth: false, fontSize: 30, text: '52%' } }; // Chart Data var DASMonthData = { labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"], datasets: [{ label: …