Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Registration Form error cant seem to locate
I am using Django in Mac. Last week, the registration is good but now when I rerun it I encountered a problem and I cant seem to figure out where the problem lies. Hope someone can help me. Thank you error: [19/Sep/2022 20:24:50] "POST /registerUser/ HTTP/1.1" 200 6995 /opt/homebrew/lib/python3.9/site-packages/PIL/Image.py:3011: DecompressionBombWarning: Image size (139513096 pixels) exceeds limit of 89478485 pixels, could be decompression bomb DOS attack. warnings.warn( invalid form <bound method BaseForm.non_field_errors of < UserForm bound=True, valid=True, fields=(first_name;middle_name;last_name;username;email;mobile_number;password;confirm_password)>> Views def registerUser(request): if request.user.is_authenticated: messages.warning(request, "You are already logged in!") return redirect ('myAccount') elif request.method == 'POST': form = UserForm(request.POST) m_form = MemberForm(request.POST, request.FILES) try: if form.is_valid() and m_form.is_valid(): first_name = form.cleaned_data['first_name'] middle_name = form.cleaned_data['middle_name'] last_name = form.cleaned_data['last_name'] username = form.cleaned_data['username'] email = form.cleaned_data['email'] mobile_number = form.cleaned_data['mobile_number'] password = form.cleaned_data['password'] user = User.objects.create_user(first_name=first_name, middle_name=middle_name, last_name=last_name, username=username, email=email, mobile_number=mobile_number, password=password) user.role = User.MEMBER user.save() member = m_form.save(commit=False) member.user = user member.save() # send verification email mail_subject = 'Please Activate Your Account' email_template = 'accounts/emails/account_verification_email.html' send_verfication_email(request, user, mail_subject, email_template) messages.success(request, 'You have signed up successfully! Please check your email to verify your account.') print(user.password) return redirect('signin') except Exception as e: print('invalid form') messages.error(request, str(e)) else: form = UserForm() m_form = MemberForm() context = { … -
Django - pass file path/url from html to view in order to change the source of my video stream
Hello I am fairly new to the Django and html world and and would like to be able to select a video file and then play it in an edited version (ai classification and some opencv editing). At the moment, playing of a local file works in that way that the file path of my dummy video file is fixed in my script where I load the VideoStream. However, I would like to be able to specify via html input which file to load. I have the problem that I do not know how to pass the selected file. Via urls parameters can be passed, but I do not know how I can pass the path or url of the video file as a parameter. Or can something like this be achieved via post requests and if so how? Here are parts of my script (I don't use post request for this atm): <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input id="myFileInput" type="text"> <input class="button1" id="inputfield" name="upload" type="file" accept="video/*" onchange="document.getElementById('myFileInput').src = window.URL.createObjectURL(this.files[0]); document.getElementById('buttonStart').className = 'button'; this.form.submit()" value="Select a File"/> </form> The file path is stored in 'myFileInput'. But I could also get the file path through post request. Then I … -
sending same attachments with different mails with Django mail
I'm sending mail with Django mailer from django.core.mail import send_mail,EmailMessage If i send one mail all is working and attachment is on mail and correctly opening in pdf. content = template.render(context) msg = EmailMessage(subject, content, from_email, ['mail@mail.com']) msg.content_subtype = 'html' msg.attach(invoice.name, invoice.read(), 'application/pdf') msg.send() If I want create new message with same attachment in same function msg1 = EmailMessage(subject, content, from_email,['mail@mail.com']) msg1.content_subtype = 'html' msg1.attach(invoice.name, invoice.read(), 'application/pdf') msg1.send() mail is sent but attachment can't be opened. Can't determine why is acting like this. What would be correct way to create new Email message? -
How to filter my data to the active user in Django?
I'm trying to pull through only the latest data for the active user to my Django template. However, I'm currently receiving the below error. Field 'id' expected a number but got <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x7f0682901a90>. Models.py: class HealthStats(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now=True) weight = models.DecimalField(max_digits=5, decimal_places=2) run_distance = models.IntegerField(default=5) run_time = models.TimeField() class Meta: db_table = 'health_stats' ordering = ['-date'] def __str__(self): return f"{self.user} | {self.date}" Views.py: def health_hub(request): model = HealthStats def get_queryset(self): user = self.user latest = HealthStats.objects.filter(user=user).latest('date') return latest context = { "user": model.user, "weight": model.weight, "date": model.date, "run_distance": model.run_distance, "run_time": model.run_time, "stats": HealthStats, "latest": get_queryset(model) } return render(request, 'health_hub.html', context) health_hub.html: {% extends 'base.html' %} {% load static %} {% block content %} <div class="container-fluid"> <div class="row"> <div class="col-sm-12 text-center"> <h1>My Health Summary</h1> </div> </div> </div> <div class="container-fluid"> <div class="row justify-content-center"> <h3>Welcome {{ latest.user }}!</h3> <p>Please see below for your latest stats:</p> <table class="table table-bordered"> <tr> <td>Weight: {{ latest.weight }}</td> <td>Run Distance: {{ latest.run_distance }} km</td> </tr> <tr> <td>Run Time: {{ latest.run_time }}</td> <td>Last Updated: {{ latest.date }}</td> </tr> </table> According to the error message, it looks like there is an issue with what I'm trying to pull through, but I'm not sure … -
Testing update view: how to pass.change value data in updateview with form?
I try to write testcase for one of my view that use a form. views.py def parametrage(request,pk): parametrage = get_object_or_404(Parametrage, asp_par_cle = pk) form = ParametrageForm(request, data=request.POST or None, instance = parametrage) print('form.data',form.data) if form.is_valid(): parametrage = form.save() parametrage.opr_nom = request.user.username parametrage.opr_dat = timezone.now() form.save() return redirect('pharmacy:dashboard') return render(request, 'pharmacy/parametrage.html', {'form': form}) tests.py class PharmacyParametrageTestCase(TestCase): def setUp(self): Parametrage.objects.create(asp_par_loc='TR',asp_par_ale=1,asp_par_con=8) def test_email_alert(self): instance = Parametrage.objects.get(asp_par_cle=1) data = json.dumps({"asp_par_ale":2,}) response = self.client.post(reverse('pharmacy:parametrage', kwargs={'pk':1}),instance=instance, data=data, follow=True, content_type='application/json') self.assertEqual(response.status_code,200) self.assertEqual(Parametrage.objects.get(asp_par_cle=1).asp_par_ale,2) The second assert failed because Parametrage instance is not updated. form.is_valid() return False and form.errors do not return any error. form.data is empty obviously, I never change asp_par_ale value but don't know how to do that in tests. I try to pass data but doesn't work neither appreciate some help -
Django video uploads new video not display
I'm using django 3, when I upload a video from the admin panel, it doesn't appear on the page. When I go to the video url, I get a 404 error, but my old uploads are visible, and the newly uploaded files are not visible. My English is not very good, I translated it with google translate and I'm sorry if there are any mistakes -
serve() is called twice everytime I reload a blog page in wagtail
I am using wagtail to build a blog website. In order to count the visits of each blog, I override the get_context() and serve() to set cookie. The codes are as follows: def get_context(self, request): authorname=self.author.get_fullname_or_username() data = count_visits(request, self) context = super().get_context(request) context['client_ip'] = data['client_ip'] context['location'] = data['location'] context['total_hits'] = data['total_hits'] context['total_visitors'] =data['total_vistors'] context['cookie'] = data['cookie'] context['author']=authorname return context def serve(self, request): context = self.get_context(request) template = self.get_template(request) response = render(request, template, context) response.set_cookie(context['cookie'], 'true', max_age=3000) return response And the function count_visits is as follows: def count_visits(request, obj): data={} ct = ContentType.objects.get_for_model(obj) key = "%s_%s_read" % (ct.model, obj.pk) count_nums, created = VisitNumber.objects.get_or_create(id=1) if not request.COOKIES.get(key): blog_visit_count, created =BlogVisitNumber.objects.get_or_create(content_type=ct, object_id=obj.pk) count_nums.count += 1 count_nums.save() blog_visit_count.count += 1 blog_visit_count.save() The problem I met is that when I reload the blog page, serve() was loaded twice. The first time request was with cookie info. But the second time the cookie of the request was {}, which caused the count of visit does not work correctly. I do not understand why serve() is called twice everytime I reload page. -
How to check if the email/username already exists in the db in django?
How to check if the email_id/ username already exists in the database in django? I want to check the existence of the email/username in the views rather than in serializer. Following is the code: @api_view(['POST']) def registerUser(request): f_name = request.data.get('f_name') l_name = request.data.get('l_name') username = request.data.get('username') email_id = request.data.get('email_id') password = make_password(request.data.get('password')) RegistrationRegister.objects.create( f_name = f_name, l_name = l_name, username = username , email_id = email_id, password = password, created = datetime.datetime.now().isoformat() ) return Response("User registered successfully ") The name of the table is RegistrationRegister. How can I validate the email and check if it exists in the db? -
Register data by multiple select django
I'm a beginner and I was trying to create a registered data form in the database, all the fields are registered well instead of the multiple select fields. from.py class SavePost(forms.ModelForm): user = forms.IntegerField(help_text = "User Field is required.") title = forms.CharField(max_length=250,help_text = "Title Field is required.") description = forms.Textarea() dep = forms.Textarea() class Meta: model= Post fields = ('user','title','description','file_path', 'file_path2', 'dep') HTML <div class="form-group mb-3 "> <label for="exampleFormControlSelect2"> multiple select</label> <select multiple class="form-control" id="dep" value={{ post.title }}> <option>Process</option> <option>Product</option> <option>Equipment</option> </select> </div> <div class="form-group mb-3 "> <label for="title" class="control-label">Title</label> <input type="text" class="form-control rounded-0" id="title" name="title" value="{{ post.title }}" required> </div> <div class="form-group mb-3"> <label for="description" class="control-label">Description</label> <textarea class="form-control rounded-0" name="description" id="description" rows="5" required>{{ post.description }}</textarea> thank you in advanced -
Display field from another model in ModelAdmin of User model
My Django project is based on built-in User model. For some extra attributes, I have defined another model: models.py: class Status(models.Model): email = models.ForeignKey(User, on_delete=models.CASCADE) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=False) def __str__(self): return self.email And here's the custom ModelAdmin: admin.py: class CustomUserAdmin(UserAdmin): model = User list_display = ['email'] search_fields = ['email'] I want list_display to show me is_verified and is_active fields from Status model but I'm lost. I've looked into some similar questions on SO like Display field from another model in django admin or Add field from another model Django but none of the solutions are applicable because one of my models is Django's built-in. -
Account with this Email already exists. how to fix this?
I tried to create a login form. But when I try to login django gives the error that Account with this Email already exists. i don`t now how to fix this.Help me plz Here is my code, please tell me where I'm going wrong: forms.py class AccountAuthenticationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) class Meta: model= Account fields = ('email', 'password') def clen(self): email = self.cleaned_data['email'] password = self.cleaned_data['password'] if not authenticate(email=email, password=password): raise forms.ValidationError("Invalid login") views.py def login_view(request): context = {} user = request.user if user.is_authenticated: return redirect("home") if request.POST: form = AccountAuthenticationForm(request.POST) if form.is_valid(): email=request.POST['email'] password = request.POST['password'] user =authenticate(email=email, password=password) if user: login(request,user) return redirect("home") else: form = AccountAuthenticationForm() context['login_form'] = form return render(request, 'account/login.html', context) login.html {% extends 'base.html' %} {% block content %} <h2>Login</h2> <form method="post">{% csrf_token %} {% for field in login_form %} <p> {{field.label_tag}} {{field}} {% if field.help_text %} <small style="color:grey">{field.help_text}</small> {% endif %} {% for error in field.errors %} <p style="color:red">{{error}}</p> {% endfor %} {% if login_form.non_field_errors %} <div style="color:red";> <p>{{login_form.non_field_errors}}</p> </div> {% endif %} </p> {% endfor %} <button type="submit">Log in</button> </form> {% endblock content %} I'm just getting started with Django. I will be glad if you point out my mistake -
I can't save data of <select> in html
I have django application with form. in model LIVING_COUNTRIES = [ ('AFGANISTAN', 'Afganistan'), ('ALBANIA', 'Albania'), ('ALGERIA', 'Algeria'), ('ANGORRA', 'Andorra')] class Employee(models.Model): country_living = models.CharField(max_length=50, choices=LIVING_COUNTRIES, default=FRESHMAN, blank=True, null=True) in html <select name="country" id="id_category" data="{{ data.country }}"> {% for each in living_countries_list %} <option value="{{ each.0 }}" class="living_countries">{{ each.1 }}</option> {% endfor %} </select> in view context['has_error'] = True if context['has_error']: employees = models.Employee.objects.all() living_countries_list = LIVING_COUNTRIES return render(request, 'authentication/employee_register.html', context) So I have form rendered in get() method of class-based view. When I click submit post method checks for errors. If there are any context['has_error'] is set to true. For simplycity I've written it down anyway. And if it is true we render form again. I want to have previous choice of user still displayed in html. I've done it on other inputs by `data="{{ data.field }}". How would I do that here? -
How do I bring through my data in Django Template view?
I'm trying to display my data from my HealthStats model to my template, however I can only pull through the user field. I've added the other fields to my template, but they're not showing. I would also like to be able to filter the output to only show records of the logged in user. Models.py class HealthStats(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now=True) weight = models.DecimalField(max_digits=5, decimal_places=2) run_distance = models.IntegerField(default=5) run_time = models.TimeField() class Meta: db_table = 'health_stats' ordering = ['-date'] def __str__(self): return f"{self.user} | {self.date}" Views.py: class HealthHistory(generic.TemplateView): model = HealthStats template_name = 'health_hub_history.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['stats'] = HealthStats.objects.all() return context health_hub_history.html {% extends 'base.html' %} {% load static %} {% block content %} <div class="container-fluid"> <div class="row"> <div class="col-sm-12 text-center"> <h1>My Health History</h1> </div> </div> </div> <div class="container-fluid"> <div class="row justify-content-center"> <div class="col-auto text-center p-3"> <table class="table table-striped table-hover table-bordered"> <tr> <td>User:</td> <td>Weight (lbs):</td> <td>Date:</td> <td>Run Distance (km):</td> <td>Run Time (HH:MM:SS):</td> </tr> {% for stat in stats %} <tr> <td>{{ user }}</td> <td>{{ weight }} </td> <td>{{ date }}</td> <td>{{ run_distance }}</td> <td>{{ run_time }}</td> </tr> {% endfor %} </table> </div> </div> </div> {% endblock content %} Any help would be appreciated! -
How to serialize a foreign key relationship as key value pair django rest framework
I'm trying to serialize an relationship in DRF whereas I attempt to get the following output: "statistics":[ "Attacks":{ "id":971, "home_value":3, "away_value":2, "value":5 }, "Corners":{ "id":972, "home_value":0, "away_value":0, "value":0 } ] I wrote the following code for my serializer of this model: class StatisticSerializer(serializers.ModelSerializer): class Meta: model = Statistic fields = ['id', 'home_value', 'away_value', 'name', 'value'] def to_representation(self, instance: Statistic): representation = {instance.name: { "id": instance.id, "home_value": instance.home_value, "away_value": instance.away_value, "value": instance.value }} return representation Which gets me the following output: "statistics":[ { "Attacks":{ "id":971, "home_value":3, "away_value":2, "value":5 } }, { "Corners":{ "id":972, "home_value":0, "away_value":0, "value":0 } } ] Is there any way to get it as demonstrated in the first example using django rest framework? -
how to call a function when app start in django?
i want to call the daily_data_log_checker function in that MainConfig class so that it can run when the app start class MainConfig(AppConfig): default_auto_field = 'django.db.models.AutoField' name = 'main' def daily_data_log_checker(): import datetime from datetime import datetime from datetime import date from main.models.status import DailyMachinePerformance from main.management.commands.jobscheduler import log_daily_data now_time = datetime.datetime.now() today = date.today() if(now_time.hour>= 11): daily_machine_performance = DailyMachinePerformance.objects.filter(date = today) if(len(daily_machine_performance) == 0): log_daily_data() -
Simple quest in view and settings
Well, I working on this problem about 2 weeks. Searching in google a lot, experimenting with options. But that is just not working -_-. I can't even pinpoint what the problem is, probably in views or settings with join. Just look. I had a lot of errors, at this moment I see: No module named 'path', , line 1004, in _find_and_load_unlocked I know this problem is simple, but I tired to struggle :D Settings from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'path.to.inject_form', ], }, }, ] urls urlpatterns = [ path('form/', views.SignUpp, name="SignUpp"), path("",views.head.as_view(), name="mainpage"), path("stocks/", views.stockpage.as_view(), name="stockpage"), path("search/", SearchResultStocks.as_view(), name="search-Stocks"), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) Views def SignUpp(request): if request.method == 'POST': form = UserSign(request.POST) if form.is_valid(): body = { 'Name': form.cleaned_data['Name'], 'email': form.cleaned_data['email'], 'Number': form.cleaned_data['Number'], } info_user = "\n".join(body.values()) send_mail( 'Sign', info_user, 'eric1122221@mail.ru', ['eric1122221@mail.ru'], fail_silently=False) form.save() return redirect("dental/mainpage.html") else: form= UserSign() context = { 'form': form } return render(request, 'base.html', context) class head(ListView): template_name = "dental/mainpage.html" model = signup class stockpage(ListView): template_name = "dental/stocks.html" model = stock context_object_name = "stocks" class SearchResultStocks(ListView): model = stock template_name … -
Migrating the database from legacy flask app to django
Hello i have an existing app made in Flask, it consist of simple database but it doesn't have migrations (flask-migrate) ever since and the data grows more. If i enable the migrations on django, could it screw the datas? and in case if i disable the migrations, can django writes up like the old existing ones? Here's my old db model (FLASK) from database.db import db class users(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(255), unique=True) project = db.Column(db.String(255)) reason = db.Column(db.String(255)) timestamp = db.Column(db.DateTime, default=now) And this is my new one (DJANGO) from django.db import models as db class users(db.Model): class Meta: managed = False id = db.AutoField(primary_key=True) name = db.CharField(max_length=255, unique=True) project = db.CharField(max_length=255) reason = db.CharField(max_length=255) timestamp = db.DateTimeField(auto_now_add=True) -
sorting in django admin list by a custom field alphabetically
I have a simple store / product relationship and I want to sort the products depending on the store name alphabetically. models: class Store(models.Model): name = models.CharField("name", max_length = 128) class Product(models.Model): number = models.PositiveIntegerField() name = models.CharField("name", max_length = 128) store = models.ForeignKey(Store, on_delete = models.CASCADE) and in the admin: class ProductAdmin(admin.ModelAdmin): list_display = ["number", "name", "get_store_name",] def get_store_name(self, obj): return f"""{obj.store.name}""" I know I cannot use order_by on custom fields. So I thought I need to override the get_queryset method probably? I found multiple examples to annotate by counted or calculated numbers, but never for strings. -
Optional URL for taggit Django
I'am using django-taggit in my project, to put tags on items. So i watched this tutorial to use the tags in class based views. I want to show all tags on top, and on click on the tags I want to show all items with the tag, and i've been using parameters in the url, to search for the items. But i want this parameter to be optional, so the user doesn't need to give a tag in the url. Is this possible? This is my URL so far: path('items/', views.ItemsView.as_view(), name='items'), -
Convert raw sql to django query
How can I convert this raw sql to django query?? knowledges.raw( ''' SELECT KnowledgeManagement_tblknowledge.KnowledgeCode,KnowledgeManagement_tblknowledge.KnowledgeTitle,KnowledgeManagement_tblknowledge.CreateDate,KnowledgeManagement_tblknowledge.CreatorUserID_id FROM KnowledgeManagement_tblknowledge LEFT JOIN KnowledgeManagement_tblusedknowledge ON KnowledgeManagement_tblknowledge.KnowledgeCode = KnowledgeManagement_tblusedknowledge.knowledge_id where register_status = 7 or register_status = 9 and Status = 1 Group by KnowledgeManagement_tblknowledge.KnowledgeCode order by count( KnowledgeManagement_tblusedknowledge.id) desc; ''' ) -
How to regroup entries in Django by model field (More complex query)?
First i'm not an exeperienced developer in Django, i use Django 4.0.6 on windows 10 and python 3.8.9 in a virtual environment. I need help with my query in Django: first here's my model: from django.db import models class MyWords(models.Model): WordText=models.CharField(max_length=1000, unique=True) WordStatus=models.IntegerField() WordType=models.CharField(max_length=30) and i have this sqllite database table with the following entries as example: db.sqlite3 MyWords Table: WordText WordStatus WordType Dog 0 Animal Cat 1 Animal Car 4 Object Lion 1 Animal Computer 4 Inanimate Object Stone 5 Inanimate Object Child 4 Human What i want to do is to get this info back this way: data == [ {'WordType':'Object', 'WordStatus':4,'WordText':'Car'}, {'WordType':'Animal', 'WordStatus':[0,1,1], 'WordText':'Dog','Cat','Lion'}, {'WordType':'Inanimate Object', 'WordStatus':[4,5], 'WordText':'Computer','Stone'}, {'WordType':'Human', 'WordStatus':4, 'WordText':'Human'} ] Essentially i want to regroup/categorize the entries by WordType so i can access them more easily. Is this possible in Django ORM? If yes, how? I first thought using something like a values_list with WordType as argument followed by a distinct and annotate, but i'm stucked. Something like this: data =MyWords.objects.all().values_list('WordType').distinct().annotate(WordStatus=?).annotate(WordText=?) I don't know if it's correct because i don't know what to replace the question marks with. I don't know if i'm on the correct path. So can anyone guide me please? N.B: I … -
Django Kubernetes Ingress CSRF Cookie not sent
Asking this question here because It's been a couple of days and I can't find anything useful. Problem: I have an app deployed to a Kubernetes cluster running on AWS EKS with a custom docker image on AWS ECR. The app works fine with GET requests but not with POST ones. The error given is Errore 403 forbidden CSRF Token not sent. Django version is 2.2.24 on DRF 3.11.2. I already added CSRF_TRUSTED_ORIGINS in settings.py, nothing changed. The ingress I'm using is AWS's Application Load Balancer set like this: apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: django labels: name: django annotations: alb.ingress.kubernetes.io/scheme: internet-facing alb.ingress.kubernetes.io/target-type: ip alb.ingress.kubernetes.io/backend-protocol: HTTP alb.ingress.kubernetes.io/listen-ports: '[{"HTTP":80}]' alb.ingress.kubernetes.io/group.name: "alta" alb.ingress.kubernetes.io/group.order: "2" alb.ingress.kubernetes.io/healthcheck-protocol: HTTP alb.ingress.kubernetes.io/healthcheck-port: traffic-port alb.ingress.kubernetes.io/healthcheck-path: /v1/app alb.ingress.kubernetes.io/healthcheck-interval-seconds: "15" alb.ingress.kubernetes.io/healthcheck-timeout-seconds: "5" alb.ingress.kubernetes.io/success-codes: "200" alb.ingress.kubernetes.io/healthy-threshold-count: "2" alb.ingress.kubernetes.io/unhealthy-threshold-count: "2" spec: ingressClassName: alb rules: - http: paths: - pathType: Prefix path: / backend: service: name: djangoapp-cluster-ip port: number: 80 Any help is much appreciated. -
Django - remove/hide labels for checkboxes
I would have thought this would be pretty simple but I have plugged away at this for some time and I can't figure it out. I have a multiple choice checkbox in a model form which is in a formset. All I want to do is remove the labels from the checkboxes. I can easily remove the label from the field but I can't figure out how to remove the labels from the checkboxes. I am trying to convert the display of the form to a grid. From this: To this: Here's my form code: class ResourceEditAddForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.portfolio = kwargs.pop('portfolio') super(ResourceEditAddForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.fields["portfolio"].initial = self.portfolio self.fields["portfolio"].required = False self.fields["skills"].queryset = self.portfolio.getSkills() class Meta: model = Resource fields = ['portfolio', 'name', 'skills', 'pct_availability', 'cost_per_day', 'email', 'timezone', 'update_request_time', 'calendar', 'start_date', 'end_date'] widgets = { 'portfolio': forms.HiddenInput(), 'start_date': DateInput(), 'end_date': DateInput(), 'update_request_time': TimeInput(), 'skills': forms.CheckboxSelectMultiple(), } ResourceEditAddFormSet = modelformset_factory( Resource, form=ResourceEditAddForm, extra=0 ) I could build a manual form to achieve this but I want to keep using model forms as there's a few fields other than skills which are managed fine by the form. If anyone can tell me how to … -
Serialize nested JSON to Django models
how can I create a nested structure from a nested JSON? I want my Hobby to have a ForeignKey to the Profile. It cant be that hard, but I really dont understand the error. It even creates the objects and saves them in my database but still says it does not find the field. I Get the following error with my code: AttributeError: Got AttributeError when attempting to get a value for field `description` on serializer `HobbySerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `RelatedManager` instance. Original exception text was: 'RelatedManager' object has no attribute 'description'. serializers.py: class HobbySerializer(serializers.ModelSerializer): class Meta: model = Hobby fields = ["name", "description"] class ProfileSerializer(serializers.ModelSerializer): user_hobby23 = HobbySerializer(many=False) class Meta: model = Profile fields = ["testfield1", "display_name", "mobile", "address", "email", "dob", "user_hobby23"] def create(self, validated_data): user_hobby_data = validated_data.pop('user_hobby23') profile_instance = Profile.objects.create(**validated_data) Hobby.objects.create(user=profile_instance, **user_hobby_data) return profile_instance models.py: class Profile(models.Model): display_name = models.CharField(max_length=30) mobile = models.IntegerField() address = models.TextField() email = models.EmailField() dob = models.DateField() photo=models.FileField(upload_to='profile/',null=True,blank=True) status = models.IntegerField(default=1) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) testfield1 = models.TextField(null=True) class Hobby(models.Model): user=models.ForeignKey(Profile,on_delete=models.CASCADE,related_name='user_hobby23',null=True) name = models.CharField(max_length=30) description = models.TextField() status = models.IntegerField(default=1) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views.py: class … -
How to call model method in ajax through views_api and assign the value to table data in DRF?
I am trying to understand the Django Rest Framework. As a beginner here, what I am trying is to call a method from a Model and update the value in the template. I am trying it from views_api.py with an ajax call. I was able to get other values, but I couldn't get three values. Here is what I have so far. reviews/models.py class Review(TimeStampedModel): project = models.ForeignKey('projects.Project', on_delete=models.CASCADE, related_name='reviews') fiscal_year = models.PositiveIntegerField(null=True, blank=True, db_index=True) fiscal_month = models.PositiveIntegerField(null=True, blank=True, db_index=True) has_validation = models.BooleanField('Has PFK', default=False) review_date = models.DateField(help_text='Date of the PFK', db_index=True) wp_validation_deadline = models.DateTimeField(blank=True, null=True, help_text='Deadline to validate WP') cutoff_date = models.DateTimeField(db_index=True, help_text='Up to when actuals are considered (date after accruals were entered)') fct_n_amount = models.DecimalField('FCT n amount', decimal_places=2, max_digits=12, null=True, blank=True) actuals_amount = models.DecimalField('Actual revenue traded', decimal_places=2, max_digits=12, null=True, blank=True, help_text='Cost to date (from monthly projectsales.xlsx)') events_amount = models.DecimalField('Total Events', decimal_places=2, max_digits=12, null=True, blank=True, help_text='In project currency (will be displayed in Thousands)') risks_real_amount = models.DecimalField('Total Risks - Most Likely', decimal_places=2, max_digits=12, null=True, blank=True, help_text='In project currency (will be displayed in Thousands)') risks_max_amount = models.DecimalField('Total Risks - Maximum', decimal_places=2, max_digits=12, null=True, blank=True, help_text='In project currency (will be displayed in Thousands)') opportunities_amount = models.DecimalField('Total Opportunities', decimal_places=2, max_digits=12, null=True, blank=True, help_text='In …