Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Httml Button in Django app to run a Python script
I am using Geonode that is actually a django app installed inside a docker container. What I want to do is, to edit an html page of my app and add an extra button that when the user presses it a python script will run. So far, I have added the button in the html page, a function in my views.py file and a url in the urls.py but it doesnt seem to work. html page <a href={{ request.get_full_path }} class="btn btn-primary btn-block" data-dismiss="modal" name="layer_approve" id="layer_approve">{% trans "Approve Layer" %}</a> views.py def layer_approval(request): # I keep it simple to make sure it works return redirect('www.google.gr') urls.py from django.urls import path urlpatterns += [ url(r'^layer_approval/', include('geonode.views.layer_approval')) ] I am completely new to Django. Any advice? -
Model is not iterable in Django
I'm getting this error when I click on a button. When I click the button I'm calling a function named apply. So first of all, I've two models, JobServices and MissionEffectuee, the table MissionEffectuee is normally filled with content of JobServices. The 2 models: class JobServices(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) #create_user service_name = models.CharField(max_length=100, default="nom du service") hour = models.IntegerField(default="Heures") amount = models.FloatField(default="Cout") service_date = models.DateTimeField(auto_now_add=True, null=True) description = models.CharField(max_length=2000, null=True, default="annonce") image_url = models.CharField(max_length=2000, null=True, blank=True) image = models.ImageField(null=True, blank=True) class MissionEffectuee(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) service = models.ForeignKey(JobServices, on_delete=models.CASCADE, null=True) rcd_date = models.DateTimeField(auto_now_add=True, null=True) Here is the views methods def apply(request, my_id): task_applied = JobServices.objects.get(id=my_id) task_done, failed = MissionEffectuee.objects.get_or_create(id=my_id) if failed: for c in task_applied: task_done.service = c.service_name task_done.user = c.user print("it's saved") task_done.save() else: print("Element is already there") return redirect('../taches') context = {'task_done': task_done} return render(request, 'task_apply.html', context) What I want is whenever I click on the button, service_name of the model Jobservices and user of the model User to be saved in the table MissionEffectuee in the attributes service and user respectively, but as for now, in the table these two columns are filled with hypen (-). But the rcd_date attributes normally filled … -
for making html form attach with mysql database i get error̥ which says:Exception Type: ValueError Exception Value
I am binding my html form to mysql database table in django after running the server the form is visible in the browser but after clicking on submit this error occurs which says after filling the form and clicking on submit button I get following error Exception Type: ValueError Exception Value: The view Insertemp.views.Insertrecord didn't return an HttpResponse object. It returned None instead. from django.shortcuts import render from Insertemp.models import EmpInsert from django.contrib import messages #from django.http import HttpResponse def Insertrecord(request): if request.method=='POST': if request.POST.get('pname')and request.POST.get('pcategory')and request.POST.get('pdetails')and request.POST.get('foundedin')and request.POST.get('orderoftest')and request.POST.get('t1')and request.POST.get('t2')and request.POST.get('t3')and request.POST.get('f1')and request.POST.get('f2')and request.POST.get('f3')and request.POST.get('f4')and request.POST.get('f5'): saverecord=EmpInsert() saverecord.pname=request.POST.get('pname') saverecord.pcategory=request.POST.get('pcategory') saverecord.pdetails=request.POST.get('pdetails') saverecord.foundedin=request.POST.get('foundedin') saverecord.foundedin=request.POST.get('orderoftestimonial') saverecord.t1=request.POST.get('t1') saverecord.t2=request.POST.get('t2') saverecord.t3=request.POST.get('t3') saverecord.f1=request.POST.get('f1') saverecord.f2=request.POST.get('f2') saverecord.f3=request.POST.get('f3') saverecord.f4=request.POST.get('f4') saverecord.f5=request.POST.get('f5') saverecord.save() messages.success(request,'Record Saved Successfully...!') return render(request,'Index.html') else: return render(request,'Index.html') -
Django add a custom link in admin list with an ID url link
I have my django admin models list page and i would to add a custom column for every single items in ilst wit a custom a href with item.id as parameter: <a href="http://test/<item.id>">Go to example page </a> Here my actual page: How can i add my custom liink on every list item and get an item field value? So many thanks in advance -
How to write form_valid method in django correctly
In my views.py I had a method: def form_valid(self, form): form.instance.fisher_id = self.request.user.fisher_id return super().form_valid(form) Then I changed my code to create Modal Window and save it.But I need to return in my code super().form_valid(form) because have problem with fisher DUBLICATE ERROR KEY. My code now looks like this: def form_valid(self, form): form.instance.fisher_id = self.request.user.fisher_id form.save() self.object = form.save() self.object.file.save('1.pdf', self.get_file()) # return super().form_valid(form) return HttpResponseRedirect(self.get_success_url()) And I have a problem DUBLICATE ERRROR KEY without this comment string.How can I impelement both this returns ?Please Help -
Add member to an existing group in Ldap with django
I want to add a member to a group in LDAP using Django-ldap-auth. Here is my model.py class LdapGroup(ldapdb.models.Model): """Class for representing an LDAP group entry.""" # LDAP meta-data base_dn = "cn=groups,dc=digiops,dc=com" object_classes = ["groupOfNames"] # attributes name = CharField(db_column="cn", max_length=255, primary_key=True) members = ListField(db_column="member") perm = ListField(db_column="memberOf") def save(self, *args, **kwargs): self.members = [self.members] pprint(self.members) super(LdapGroup, self).save(*args, **kwargs) def __str__(self): return self.name def __unicode__(self): return self.name class Meta: managed = Falsee here and here is my view.py: obj=LdapGroup.objects.get(name="active") obj.members = "uid=test , dc=test , dc=com" obj.save() it will overwrite all members that already exist in this group. I also try to get all the existing members and then add it to group along with the new member. obj.members = listAllMembers obj.save() but i got the error unhashable type: 'list' -
ImportError: cannot import name 'User' from partially initialized module 'apps.accounts.models' ((most likely due to a circular import)
I have imported User model from accounts app in Blogs app and BlogPost model to User app. But I got this circular imort issue. How to solve this?? Accounts.models.py looks like this: from apps.blogs.models import BlogPost class Subscribers(models.Model): email = models.EmailField(unique=True) date_subscribed = models.DateField(auto_now_add=True) def __str__(self): return self.email class Meta: verbose_name_plural = "Newsletter Subscribers" # binding signal: @receiver(post_save,sender=BlogPost) def send_mails(sender,instance,created,**kwargs): subscribers = Subscribers.objects.all() if created: for abc in subscribers: emailad = abc.email send_mail('New Blog Post ', f" Checkout our new blog with title {instance.title} ", emailad, [emailad], fail_silently=False) else: return My blogs models.py from apps.accounts.models import User class BlogPost(models.Model): author = models.CharField(max_length=64, default='Admin') image = models.ImageField(blank=True, null=True) title = models.CharField(max_length=255) ............. class Comment(models.Model): # blog = models.ForeignKey(BlogPost, on_delete=models.CASCADE, default=1) user = models.ForeignKey(User, on_delete=models.CASCADE) blog = models.ForeignKey(BlogPost, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=255) email = models.EmailField() ................. I also tried using from django.contrib.auth import get_user_model User = get_user_model() But this gives another issue of django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'accounts.User' that has not been installed No exceptions were raised hadnt I imported BlogPost model in accounts.models.py. So, Iam stuck. -
Django Rest Framework - wrong data validating with nested serializer
Models: class Section(models.Model): name = models.CharField(max_length=50) building = models.ForeignKey(Building, related_name='sections', on_delete=models.CASCADE) class Standpipe(models.Model): name = models.CharField(max_length=50) section = models.ForeignKey(Section, related_name='pipes', on_delete=models.CASCADE) Serializers: class StandpipeSerializer(serializers.ModelSerializer): class Meta: model = Standpipe fields = '__all__' class SectionSerializer(serializers.ModelSerializer): pipes = StandpipeSerializer(many=True, required=False) class Meta: model = Section fields = ('name', 'building', 'pipes') def create(self, validated_data): pipes_data = validated_data.pop('pipes') section = Section.objects.create(**validated_data) for pipe_data in pipes_data: Standpipe.objects.create(section=section, **pipe_data) return section View is just a regular ModelViewSet. I didn`t override any methods. I send this data in request: { 'name': 'One', 'building': 1, 'pipes': [ {'name': 'PipeOne'}, {'name': 'PipeTwo'}, ] } But in validated data i get only {'name': 'One', 'building': <Building: Building object (1)>} In serializer initial data we can see: <QueryDict: {'name': ['One'], 'building': ['1'], 'pipes': ["{'name': 'PipeOne'}", "{'name': 'PipeTwo'}"]}> If i try to get key 'pipes' from initial dict i get only second dict "{'name': 'PipeTwo'}" AND only in string format. If i remove 'required=False' from it, i get an error: {'pipes': [ErrorDetail(string='This field is required.', code='required')]} Cant understand why it goes wrong. I tried to use solution from the documentation -
Dictionary comprehension with Q
Let's say I have the following piece of code: criteria = {'description': 'tt', 'hostname': '2'} filters = Q() {filters.add(Q(**{k+'__icontains': v}), Q.AND) for k,v in criteria.items()} I can't figure out how to avoid doubling the outcome: {<Q: (AND: ('description__icontains', 'tt'), ('hostname__icontains', '2'))>, <Q: (AND: ('description__icontains', 'tt'), ('hostname__icontains', '2'))>} I understand I should shift Q.AND somewhere, shouldn't I? -
Django BaseCommand ignores ipdb
When I write the following in Django command: from django.core.management import BaseCommand import oauth2_provider import ipdb TIMESECONDS = 86400 class Command(BaseCommand): def handle(self, *args, **options): ipdb.set_trace() oauth2_provider.cleartokens(REFRESH_TOKEN_EXPIRE_SECONDS=TIMESECONDS) and trying to run it this way: user1@rupass:/data/app$ python manage.py cleartokens [2021-07-13 11:37:10,324] DEBUG: raven.contrib.django.client.DjangoClient: Configuring Raven for host: None [2021-07-13 11:37:10,324] INFO: raven.contrib.django.client.DjangoClient: Raven is not configured (logging is disabled). Please see the documentation for more information. [2021-07-13 11:37:10,514] INFO: oauth2_provider.models: 0 Revoked refresh tokens to be deleted [2021-07-13 11:37:10,522] INFO: oauth2_provider.models: 0 Expired refresh tokens to be deleted [2021-07-13 11:37:10,527] INFO: oauth2_provider.models: 0 Expired access tokens to be deleted [2021-07-13 11:37:10,532] INFO: oauth2_provider.models: 0 Expired grant tokens to be deleted ipdb breakpoint seems to be ignored. Why? -
Taking different Form inputs foreach iteration of the for loop in Django View function
I want to take start_channel and end_channel input from user in Django function view to visualization purposes. I have different data to visualize. In my view function, I need to take start_channel and end_channel input for each data. This is my code: def visualize_power_prob(request, test_set_pk): # this is my django function view. ... # some operations here for data_idx, data_doc in enumerate(data_set): # I need to take start_channel and end_channel input here via using form. # And then I'll use these informations to visualize the current data How can I take user input for each data without breaking the for loop? -
Django error - Pillow is not installed even though it is
I'm running Django in a virtual environment on my raspberry pi. I want to use ImageField, which requires pillow to be installed. It's installed but if I run python manage.py makemigrations I get the following error: Cannot use ImageField because Pillow is not installed. But I have installed Pillow: (DjangoEnv) pi@raspberrypi:~/Django $ pip show pillow Name: Pillow Version: 8.3.1 Summary: Python Imaging Library (Fork) Home-page: https://python-pillow.org Author: Alex Clark (PIL Fork Author) Author-email: aclark@python-pillow.org License: HPND Location: /home/pi/Django/DjangoEnv/lib/python3.7/site-packages Django is in the same location: (DjangoEnv) pi@raspberrypi:~/Django $ pip show django Name: Django Version: 3.2.5 Summary: A high-level Python Web framework that encourages rapid development and clean, pragmatic design. Home-page: https://www.djangoproject.com/ Author: Django Software Foundation Author-email: foundation@djangoproject.com License: BSD-3-Clause Location: /home/pi/Django/DjangoEnv/lib/python3.7/site-packages The location should also be in the python path print(sys.path) ['', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/pi/Django/DjangoEnv/lib/python3.7/site-packages'] Any Ideas as to what could cause this error? Thanks -
How to optimize Django interacting with database tables
How can I optimize this function please? I have tree tables: Edges with more than 77 000 lines et 20 columns Nodes: with more than 60 000 lines et 20 columns RoadType: with more than 30 lines et 20 columns def optimizing(request, pk): degree_crs = "EPSG:4326" meter_crs = "EPSG:3857" road_network = RoadNetwork.objects.get(pk=road_network_id) # Retrieve all nodes of the road network as a GeoDataFrame. nodes = Node.objects.select_related('network').filter(network=road_network) columns = ['id', 'node_id', 'location'] values = nodes.values_list(*columns) nodes_gdf = gpd.GeoDataFrame.from_records(values, columns=columns) nodes_gdf['location'] = gpd.GeoSeries.from_wkt( nodes_gdf['location'].apply(lambda x: x.wkt), crs=degree_crs) nodes_gdf.set_geometry('location', inplace=True) # Retrieve all edges of the road network as a GeoDataFrame. edges = Edge.objects.select_related('road_type', 'source', 'target').filter(network=road_network) columns = ['edge_id', 'lanes', 'road_type', 'source', 'target', 'geometry'] values = edges.values_list(*columns) edges_gdf = gpd.GeoDataFrame.from_records(values, columns=columns) # Retrieve all Road type of a network as DataFrame rtypes = RoadType.objects.filter(network=road_network) columns = ['id', 'default_lanes', 'color'] values = rtypes.values_list(*columns) rtypes_df = pd.DataFrame.from_records(values, columns=columns) models.py class Edge(models.Model): geometry = models.LineStringField(null=True) name = models.CharField(max_length=200, blank=False) target = models.ForeignKey(Node, on_delete=models.CASCADE) source = models.ForeignKey(Node, on_delete=models.CASCADE) network = models.ForeignKey(RoadNetWork, on_delete=models.CASCADE) road_type = models.ForeignKey(RoadType, on_delete=models.CASCADE) class Node(models.Model): network = models.ForeignKey(RoadNetWork, on_delete=models.CASCADE) node_id = models.BigIntegerField() name = models.CharField('Node Name', max_length=200) location = models.PointField() class RoadType(models.Model): network = models.ForeignKey(RoadNetwork, on_delete=models.CASCADE) road_type_id = models.SmallIntegerField() -
Listing users with their last article with one SQL request on Django
class User(models.Model): name = models.CharField(max_length=255) class Article(models.Model): user = models.ForeignKey(User) content = models.TextField() I need to list all users with their last article. How can I get them with one database request? # Something like: {% for user in users %}: {{ user.full_name }}: {{ user.last_message }} {% endfor %} John Doe: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Jake Carr: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Malcolm Gordon: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ingredia Ameter: Lorem ipsum dolor sit amet, consectetur adipiscing elit. -
Django ManyToMany query, passing to HTML
I am new to Django and have a problem which I don't understand. I have Article talbe with articles. Then I must add tags to each article. I create another table Tag that has only 1 column (name). In Article I add another column: tags = models.ManyToManyField('Tag') In html template I already have this for-loop: for article in object_list: (show article fields) and then for each article another for-loop: for scope in article.scopes.all <span class="badge {% if scope.is_main %}badge-primary{% else %}badge-secondary{% endif %}">{{ scope.tag.name }}</span> (show tags, with some logic that one tag must me 'main tag'). I have a view function: articles = Article.objects.all() context = {'object_list': articles} But object article doesn't have all the tags. I can't print article.tags. Also, I don't know the meaning of 'scopes' parameter in html line: for scope in article.scopes.all. Also I don't know how scope.tag.name should work (html file was there at the beginning, I shoudn't change it). How do I do it properly? How should I pass tags for each article from view to html? For each article I must use another query? Also, when I use admin, I can't add tags from m2m table, this field just not there. I … -
Django admin InlineTab within not directly connected models
In my Django Admin project i have two models connected to an external User models: a_cards: class a_cards(models.Model): CK_CHOICES = ( ('A', 'Ambassador'), ('M', 'Medico'), ('P', 'Paziente'), ('S', 'Senator'), ) c_num = models.CharField(max_length=200, unique=True, null=True, blank=True, verbose_name="Numero card") c_data = models.DateTimeField(auto_now=True) c_type = models.CharField( max_length=1, choices=CK_CHOICES, verbose_name="Tipo utenza") c_email = models.CharField(max_length=200, unique=True, null=True, blank=True, verbose_name="Notifica Email") c_agente = models.ForeignKey(AgenteProfile, on_delete=models.CASCADE, null=True, blank=True, related_name="ag_id", verbose_name="Agente") c_user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE, verbose_name="Cliente" ) the c_user field relate with User model. Now i have the UserProfile model: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, ) u_name = models.CharField(max_length=200, verbose_name="Nome") u_sname = models.CharField(max_length=200, verbose_name="Cognome") u_rsoc = models.CharField(max_length=250, verbose_name="Ragione Sociale", null=True, blank=True) u_dob = models.CharField(max_length=20, verbose_name="Data di nascita") u_tel = models.CharField(max_length=100, verbose_name="Telefono") u_ind = models.CharField(max_length=250, verbose_name="Indirizzo") u_citta = models.CharField(max_length=100, verbose_name="Citta") ... The fiels user is related also to User model Id field. Now my problem is in django admin connect directly using a ùtabularInline for example a_cards data to UserProfile data (display UserProfile data inline for every row with the same User id) but i cannot understand how i can do it if models are not directly related. There are some tecniques for achieve this? So many thanks in advance Manuel -
Why is my href generating # in the url in Django Python?
I am new to Django. I am using an HTML template for making a sidebar. Whenever I click on the sub-menu button URL is generated with a # e.g http://localhost:8000/#form . When removing # manually forms works fine. here is my HTML code: <!-- ========== Left Sidebar Start ========== --> <div class="vertical-menu"> <div data-simplebar class="h-100"> <!--- Sidemenu --> <div id="sidebar-menu"> <!-- Left Menu Start --> <ul class="metismenu list-unstyled" id="side-menu"> <li class="menu-title">Main</li> <li> <a href="javascript: void(0);" class="waves-effect"> <span class="badge rounded-pill bg-primary float-end">20+</span> <i class="mdi mdi-view-dashboard"></i> <span> Dashboard </span> </a> <ul class="sub-menu" aria-expanded="false"> <li><a href="index.html">Dashboard One</a></li> <li><a href="form">Form</a></li> </ul> </li> <li> <a href="widgets.html" class="waves-effect"> <i class="mdi mdi-cube-outline"></i> <span> Widgets </span> </a> </li> . . . here is my urls.py code: from django.urls import path, include from .import views urlpatterns = [ path('', views.index, name="index"), path('form', views.form, name="form"), ] here is my views.py code: from django.shortcuts import render, redirect def index(request): return render(request, 'index.html', {}) def form(request): return render(request, 'form.html', {}) -
ModuleNotFoundError: No module named 'playgrounddebug_toolbar' , i followed documentation but still i getting this error
Django debug tool Error I followed the step by step written in the documentation https://django-debug-toolbar.readthedocs.io/en/latest/installation.html but still i getting this weird error, unable to understand it, can someone please help me out :) enter image description here -
Selected Options are deleted after renumbering a Adding/Removing Dynamic Formset with Selection Options using Javascript
I have created a dynamic formset for my django project to add and remove forms dynamically. To preserve the value of the fields after renumbering, I am saving the value of the field before renumbering and I am assigning the same value after renumbering the forms. It is working wonderfully in the text inputs but due to my limited experience and knowledge in javascript, I am not able to preserve the value of the selcted options. Any help and suggestions are highly welcomed. Thank You. <style type="text/css"> fieldset { border: none; } </style> <form id="demo" action="{% url 'my_formset' %}" method="POST"> {% csrf_token %} {{p_form}} <br> <hr> <!-- Keep Track of the Total Form Here --> <input id="total_forms" name="TOTAL_FORM_COUNT" value="0" type="hidden"> <!-- This is the Form that will be duplicated. We will hide this form. --> <fieldset disabled class="empty-form" style="display: none"> <fieldset class="fieldset" id="fs_0"> <label>Name</label> <input type="text" id="id-f-0-name" name="id-f-0-name" value=""> <label>Select:</label> <select id="id-f-0-item" name="id-f-0-item" placeholder=""> <option disabled selected value={{None}}> Select Item </option> <option value='1'>Butter</option> <option value='2'>Milk</option> <option value='3'>Tofu</option> <option value='4'>Soyabeans</option> </select> <button type="button" id="d-0" class="delete_form" onclick="del_form(this.id);"> DELETE </button> </fieldset> </fieldset> <!-- This is where we will insert the form --> <fieldset class="forms"> </fieldset> <!-- This is the ADD Button to add … -
Getting untraceable error 'tuple' object has no attribute 'get'
I am trying to save the form with some validation. Here is my forms.py class AddPatientForm(ModelForm): class Meta: model = Patient fields = [ 'category', 'case_paper_number', 'full_name', 'age', 'birth_date', 'gender', 'mobile_number', 'email', 'address_line_1', 'address_line_2', 'city', 'pin_code', 'referred_by', ] widgets = { 'birth_date': widgets.DateInput(format=('%m/%d/%Y'), attrs={'class':'form-control', 'type':'date'}), } def clean_full_name(self): data = self.cleaned_data full_name = data['full_name'] if not len(full_name)>=10: raise ValidationError('Enter valid full name') Here is my views.py if request.method == 'GET': return render(request, 'main/addpatient.html', {'casepapernumber': casepapernumber, 'form':form}) elif request.method=='POST': form = AddPatientForm(request.POST) try: # if form.is_valid(): newpatient = form.save(commit=False) if form.cleaned_data['category'] == 'ANC': newpatient.is_anc = True if form.cleaned_data['category'] == 'INF': newpatient.is_inf = True if form.cleaned_data['category'] == 'GYNAC': newpatient.is_gynac = True newpatient.save() return redirect('allpatients') else: messages.add_message(request, messages.ERROR, 'Something went wrong!') return (request, 'main/addpatient.html', {'casepapernumber': casepapernumber, 'form':form}) except ValueError: messages.add_message(request, messages.ERROR, 'Please submit valid data') return (request, 'main/addpatient.html', {'casepapernumber': casepapernumber, 'form':form}) When there is valid data, new object is being created but I am getting attribute error. When form is not valid still getting error. I am struggling too much to validate form data. Traceback "POST /addpatient/? HTTP/1.1" 500 67207 Internal Server Error: /addpatient/ Traceback (most recent call last): File "C:\Users\Prashant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Prashant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\deprecation.py", line 96, in … -
django from does not save form and create pdf file
Can you explain please why my form do not show pdf file in DJANGO. There is my code: views.py class CountryCreateView(CountryViewMixin, core.FormModalView): form_class = CountryForm template_name = 'home/country.html' template_name_success = 'home/application_success.html' template_name_pdf = 'home/application_pdf.html' def get_file(self): template = render_to_string( template_name=self.template_name_pdf, context={ 'name': self.name, 'address': self.address, 'registration_number': self.registration_number, 'note': self.note, 'status': self.status, } ) # self.object = form.save() html = HTML(string=template) pdf_file = html.write_pdf() # object.file.save('1.pdf', self.get_file()) return File(BytesIO(pdf_file)) def form_valid(self, form): self.object = form.save() self.object.file.save('1.pdf', self.get_file()) return HttpResponseRedirect(self.get_success_url()) forms.py class CountryForm(core.ModelForm): class Meta: model = Country fields = ( 'name', 'address', 'registration_number', 'note', 'status',) I need to save from django field form fields to PDF.This code must to work. But I do not understand Why it doesn't working(((Please help -
Nested JSON output for Primary and Foreign key Django Rest Framework
Iam using Django 3.2 with Restframework. I have a Model as a for a Primary key named Tag and a Model connected as a foreign key named TagItem. I tried to get a nested JSON output for it but its not working as expected. Models.py class Tags(models.Model): tagId = models.CharField(primary_key=True, max_length=100,default=1) section = models.CharField(max_length=100) class TagItem(models.Model): tagId= models.ForeignKey(Tags, on_delete=models.CASCADE,default=1) select = models.BooleanField(default=False) name = models.CharField(max_length=50) views.py def get_tag_details(request): if request.method == 'GET': tag = Tags.objects.all() tagitem = TagItem.objects.all() TagSerializeobj = TagsSerializer(tag,many=True) TagItemSerializeobj = TagItemSerializer(tagitem, many=True) result = {} result['tag'] = TagSerializeobj.data for item in TagItemSerializeobj: if item.tagId == result['tag'].tagId: result['tagItem'] = item return Response(result) Error: 'ListSerializer' object is not iterable How to iterate of get items nested under related Tags only. Required output { "id": 1, "section": "crafts", "items": [ { "id": "10", "select": false, "name": "Wood" }, { "id": "11", "select": false, "name": "Clay" } ] }, { "id": 2, "section": "states", "items": [ { "id": "20", "select": false, "name": "Andhra Pradesh" }, { "id": "21", "select": false, "name": "Arunachal Pradesh" }, ] } -
TypeError : Object of type function is not JSON serializable
I have defined the following code in the views.py I am getting TypeError : Object of type function is not JSON serializable Libaries: from django.db.models.query import QuerySet from django.shortcuts import render from django.http import HttpResponse , Http404 , JsonResponse import json from json import JSONEncoder from FeedPost.models import trill def home(request, *args, **kwargs): return render(request, "feed.html", context={}, status=200) Where the error occured def trills_list_view(request, *args , **kwargs): qs = trill.objects.all() trills_list = [{"id": x.id, "name": x.name} for x in qs] data = { "response": trill_list } return JsonResponse(data) def trill_list(request, trill_id, *args, **kwargs): data = { "id" : trill_id, } status = 200 try: obj = trill.objects.get(id=trill_id) data['name'] =obj.name except: data['message'] = "Not found" status = 404 return JsonResponse(data, status=status) -
Checkbox button on a bootstrap modal inside django form
I currently have a form in my django app. Inside my form, there's a button to open a bootstrap modal for our 'terms & conditions'. and inside the modal, I have a checkbox that a user can click to unsubscribe from our service. And the submit button is located on the form itself, not on the modal (modal only has a single checkbox). Everything works perfectly fine except that Django doesn't seem to save the value of checkbox to our database. I wonder if I need to use AJAX or Jquery to make this happen? Any guidance will be greatly appreciated. HTML - Template <div class="modal fade" id="terms_conditions" tabindex="-1" role="dialog" aria-labelledby="termsLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="termsLabel">Terms and conditions</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="checkbox_subscription"> {% csrf_token %} {% for field in form.subsc %} {{ field.tag}} {% endfor %} <label>Please check this button to unsubscribe</label> </div> </div> </div> </div> </div> <div class="terms_and_conditions"> {% for field in form.t_c %} {{ field.tag}} {% endfor %} <label>Please accept <a href="#" data-toggle="modal" data-target="#terms_conditions">terms and conditions</a>.</label> </div> forms.py class ApplicationForm(forms.ModelForm): class Meta: model = Enquiry fields = ['name','other','t_c','subsc' ] t_c = forms.BooleanField() subsc … -
Django- how to display multiple images uploaded from admin in template?
I would like to upload multiple photos to the Django admin and display them in views.py. Here's what I have so far: models.py class Show(models.Model): title = models.CharField(max_length=1024) slug = models.SlugField(max_length=1024) class ShowPhoto(models.Model): show = models.ForeignKey( Show, on_delete=models.CASCADE, related_name="photos" ) photo = models.ImageField() forms.py from django import forms from django.core.validators import validate_image_file_extension from django.utils.translation import gettext as _ from .models import Show, ShowPhoto class ShowAdminForm(forms.ModelForm): class Meta: model = Show fields = ( "title", "slug", ) photos = forms.FileField( widget=forms.ClearableFileInput(attrs={"multiple": True}), label=_("Add photos"), required=False, ) def clean_photos(self): """Make sure only images can be uploaded.""" for upload in self.files.getlist("photos"): validate_image_file_extension(upload) def save_photos(self, show): """Process each uploaded image.""" for upload in self.files.getlist("photos"): photo = ShowPhoto(show=show, photo=upload) photo.save() admin.py from django.contrib import admin from django.template.loader import get_template from django.utils.translation import gettext as _ from .models import Show, ShowPhoto from .forms import ShowAdminForm class ShowPhotoInline(admin.TabularInline): model = ShowPhoto fields = ("showphoto_thumbnail",) readonly_fields = ("showphoto_thumbnail",) max_num = 0 def showphoto_thumbnail(self, instance): """A (pseudo)field that returns an image thumbnail for a show photo.""" tpl = get_template("shows/admin/show_thumbnail.html") return tpl.render({"photo": instance.photo}) showphoto_thumbnail.short_description = _("Thumbnail") How would I write a views.py method so that the multiple photos upload from the ShowPhoto model can be rendered in the template?