Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
User's profile is not creating
I am building a BlogApp and I am tried to register user Today BUT it shows AttributeError: 'User' object has no attribute 'encode' This was working before few days but when i tried today then it is keep showing. When i python manage.py createsuperuser in terminal then same error is showing. Full Traceback Traceback (most recent call last): File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\app\users\views.py", line 10, in signup_view user = form.save() File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\forms.py", line 131, in save user.save() File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save super().save(*args, **kwargs) File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 727, in save force_update=force_update, update_fields=update_fields) File "C:\DELL\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 776, in save_base update_fields=update_fields, raw=raw, using=using, File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\django\dispatch\dispatcher.py", line 182, in send for receiver in self._live_receivers(sender) File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\django\dispatch\dispatcher.py", line 182, in <listcomp> for receiver in self._live_receivers(sender) File "D:\app\mains\models.py", line 264, in post_save_create_profile Profile.objects.create(user=instance) File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 453, in create obj.save(force_insert=True, using=self.db) File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 727, in save force_update=force_update, update_fields=update_fields) File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 765, in save_base force_update, using, update_fields, File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 908, in _do_insert … -
Getting repeated data white using django orm
im filtering that user whoes order_status is completed and who have listing_id 5001. But im getting output data repeated Here is my Code: models.py class Users(models.Model): name = models.CharField(max_length=100) phone = models.CharField(max_length=20, blank=True, null=True) ''' class Meta: managed = False db_table = 'users' class UserOrder2(models.Model): order_id = models.AutoField(primary_key=True) order_status = models.CharField(max_length=30,default='None') listing_id = models.CharField(max_length=250,default='None') user_id = models.ForeignKey(Users, on_delete=models.CASCADE, db_column="user_id") ''' class Meta: managed = False db_table = 'user_order' class UserOrderProduct2(models.Model): order_id = models.ForeignKey(UserOrder2, on_delete=models.CASCADE, db_column="order_id") product_name = models.CharField(max_length=100) ... class Meta: managed = False db_table = 'user_order_product' Views.py class UserPurchaseQuantityView(generics.GenericAPIView): def post(self, request): listing_id= request.data.get('listing_id') kwargs = {} kwargs['userorder2__listing_id'] = listing_id kwargs['userorder2__order_status'] = 'Order Delivered' queryset = Users.objects.filter(**kwargs) data = UsersSerializer(queryset, many=True).data return Response(data) serializers.py class UserOrderProductSerializer2(serializers.ModelSerializer): class Meta: fields = ["product_id", "product_quantity", "product_price", "sub_total", "product_name"] model = UserOrderProduct2 class UserOrderSerializer(serializers.ModelSerializer): product_detail = UserOrderProductSerializer2(source="userorderproduct2_set", many=True) class Meta: fields = ["user_id", "order_date", "product_detail"] model = UserOrder2 class UsersSerializer(serializers.ModelSerializer): user_detail = UserOrderSerializer(source="userorder2_set", many=True) class Meta: fields = "__all__" model = Users I'm getting repeated output like this: [ { "id": 51238, "name": "aaa", "phone": "123456789", "email": "aaa@gmail.com", "user_detail": [ { "user_id": 51238, "order_date": "2021-07-27 15:55:56" "product_detail": [ { "product_id": 20767, "product_quantity": 1, "product_price": 150.0, "sub_total": 150.0, "product_name": "EMINAZ 2mg Tablet 10's" ] … -
Which is better for massive applications, node js or django? [closed]
I am currently fluent in Python and Java script I want powerful, massive, fast, efficient, and high-speed application programming. So what is best in this case, use Node js or Django? -
Hi, I have a question that how much data can e stored in db.sqlite3(default) in django?
I am hosting a django app. So i wanted to know that what is the storage limit of db.sqlite3.It would be great if someone advised me in this point. Thanks in advance!! -
Graph Generated By Chart.js Has Entirely Different Coordinates
I am trying to sketch out a real-time graph in Django and I deployed Chart.js functions' to help me out. What I did was to return a dictionary containing the points that I would like to plot within the script tag. The keys of the dictionary will be assigned to the "label" field while the values to the "data" field. However, the points that were plotted out were completely different from the dictionary that I provided and on top of that extra points kept appearing out of nowhere which didn't seem to cease until I manually stopped the process. Below is a portion of the html code: <div class="centerpane"> <canvas id="myChart" width="400" height="200"></canvas> </div> <script > var ctx = document.getElementById('myChart').getContext('2d'); 'use strict'; var main_graph_points = "{{ main_graph_points }}"; //the dictionary var graphData = { type: 'line', data: { labels: Object.keys(main_graph_points), datasets: [{ label: 'main graph', data:Object.values(main_graph_points), backgroundColor: [ 'rgba(73, 198,230, 0.5)', ], borderWidth: 1 }], options:{ scales: { xAxes: [{ type: 'category', }] } }, }, } var myChart = new Chart(ctx,graphData ); var socket = new WebSocket("ws://localhost:8000/ws/mysite/"); socket.onmessage = function(e){ var djangoData = JSON.parse(e.data); console.log(djangoData); document.querySelector("#app").innerText = djangoData.value; }</script> //contents of the dictionary main_graph_points={20: 59.96601343154907, 24: 59.89738027254739, 28: 59.9285344282786, … -
AttributeError: The serializer field might be named incorrectly and not match any attribute or key
How do i join 3 tables using django orm.. my code is working fine if i join 2 tables. But if i join 3 tables then im getting Got AttributeError when attempting to get a value for field user_detail on serializer UsersSerializer. The serializer field might be named incorrectly and not match any attribute or key on the UserOrder instance. Original exception text was: 'UserOrder' object has no attribute 'userorder2_set'. here is my code: models.py: class Users(models.Model): name = models.CharField(max_length=100) ''' class Meta: managed = False db_table = 'users' class UserOrder2(models.Model): order_id = models.AutoField(primary_key=True) user_id = models.ForeignKey(Users, on_delete=models.CASCADE, db_column="user_id") .... class Meta: managed = False db_table = 'user_order' class UserOrderProduct2(models.Model): order_id = models.ForeignKey(UserOrder2, on_delete=models.CASCADE, db_column="order_id") product_name = models.CharField(max_length=100) ''' class Meta: managed = False db_table = 'user_order_product' View.py class UserPurchaseQuantityView(generics.GenericAPIView): def post(self, request): # queryset = UserOrder.objects.filter(user_id=51238).prefetch_related('user_id').prefetch_related('order_id') queryset = UserOrder.objects.filter(user_id=51238) data = UsersSerializer(queryset, many=True).data return Response(data) serializers.py class UserOrderProductSerializer2(serializers.ModelSerializer): class Meta: fields = ["product_id", "product_quantity", "product_price", "sub_total", "product_name", "product_img"] model = UserOrderProduct2 class UserOrderSerializer(serializers.ModelSerializer): product_detail = UserOrderProductSerializer2(source="userorderproduct2_set", many=True) class Meta: fields = ["user_id", "order_total", "total_without_dc", "order_date"] model = UserOrder2 class UsersSerializer(serializers.ModelSerializer): user_detail = UserOrderSerializer(source="userorder2_set", many=True) class Meta: fields = ["name","user_detail"] model = Users -
Second model within the same form returns invalid on powershell
im having trouble with getting the 2nd model within the same form being valid. Can anyone help? The 1st model device_frm works well. It saves the info I need in the table I want. But the 2nd model does not even get saved. Appreciate if anyone can help to solve this issue. Been stuck on this for days views.py def device_add(request): if request.method == "POST": device_frm = DeviceForm(request.POST) ##Part A1 dd_form = DeviceDetailForm(request.POST) if device_frm.is_valid(): device_frm.save() device = Device.objects.all() if dd_form.is_valid(): print("valid") else: print("invalid") return render(request, 'interface/device-added.html',{'devices':device}) else: device_frm = DeviceForm() dd_frm = DeviceDetailForm() di_frm = DeviceInterfaceForm() return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_frm}) models.py class DeviceModel(models.Model): modelname = models.CharField(max_length=50) date_added = models.DateTimeField(default=timezone.now) def __str__(self): return self.modelname class DeviceDetail(models.Model): hostname = models.CharField(max_length=50) mgt_interface = models.CharField(max_length=50) mgt_ip_addr = models.CharField(max_length=30) subnetmask = models.CharField(max_length=30) ssh_id = models.CharField(max_length=50) ssh_pwd = models.CharField(max_length=50) enable_secret = models.CharField(max_length=50) device_model = models.ForeignKey(Device, on_delete=models.CASCADE) def __str__(self): return self.hostname forms.py class DeviceForm(ModelForm): class Meta: model= Device fields= ['hostname', 'ipaddr'] class DeviceDetailForm(ModelForm): class Meta: model= DeviceDetail fields= ['hostname', 'mgt_interface', 'mgt_ip_addr', 'subnetmask', 'ssh_id', 'ssh_pwd', 'enable_secret', 'device_model'] def clean(self): cleaned_data = super().clean() hostname = cleaned_data.get('hostname') if len(hostname) < 8: raise forms.ValidationError(f'Hostname needs to be more than 8 character long, {hostname}') return cleaned_data -
How to show Json data to Django template?
I store JSON data to TextField : Data in TextField: [{"id":1,"Name":"AC","Quantity":"12","Weight":"200","WeightTypes":"KG", "TotalWeight":"2400","CustomsCharge":"300.0","Subtotal":"3600"}, {"id":2,"Name":"Soap","Quantity":"12","Weight":"500", "WeightTypes":"GRAM","TotalWeight":"6","Customs Charge":"0.0","Subtotal":"12"}] I receive data in my view.py: using products = json.loads(data) After that, i am trying to show each item's in Django templates {% for p in products %} {% for key, value in p.items %} <tr> <td>{{value.id}}</td> <td>{{value.Name}}</td> <td>{{value.Quantity}}</td> <td>{{value.CustomsCharge}}</td> <td>{{value.Subtotal}}</td> </tr> {% endfor %} {% endfor %} But it's not working! How can i get each value from this Jason field? Thank you in advance. -
Bootstrap: reduce horizontal spacing between cards when using card-columns class
I'm attempting to render several rows of Bootstrap cards, with each row having two cards side-by-side. My code is working, but there is lots of space between the cards when the screen is expanded. Here is the code: HTML (uses Django template) {% block body %} <h2>{{ title }}</h2> <div class="container-fluid"> <div class="card-columns mx-auto col-10"> {% for entry in entries %} <div class="mx-auto card h-100 mb-3" style="max-width: 480px"> <a href="{% url 'listing' listing.id %}"> <img class="card-img-top" src="{{ entry.image.url }}" alt="{{ entry.title }}"> </a> <div class="card-body"> <h5 class="card-title">{{ entry.title }}</h5> <p class="card-text">{{ listing.description }}</p> </div> </div> {% empty %} No content found. {% endfor %} </div> </div> {% endblock %} CSS: body { min-height: 100vh; background-color: #ecf1f4; } .card-columns { column-count: 2; column-gap: 20px; /* does not affect the spacing! */ justify-content: center; flex-wrap: wrap; display: flex; } @media (max-width: 500px) { .card-columns { column-count: 1; } } The column-gap does not affect the spacing. Is this being overridden by something else? Or, is there another mistake, perhaps? Thanks in advance for any advice you can give this CSS newbie! -
django.db.utils.ProgrammingError: Column does not exist
I have a model class that inherits from two abstract models: # cars app class Car( PolymorphicModel, BaseSyncModel, ): """Car parent model.""" id: models.UUIDField = models.UUIDField( # noqa: A003 primary_key=True, default=uuid.uuid4 ) store: models.ForeignKey = models.ForeignKey( CarStores, on_delete=models.CASCADE ) price: models.IntegerField = models.IntegerField() year: models.IntegerField = models.IntegerField( validators=[MinValueValidator(1900), MaxValueValidator(2021)], ) brand = models.TextField("Car's brand") It inherits from the PolymorphicModel and from a class to make sync, it is like that: class BaseSyncModel(models.Model): updated_at = models.DateTimeField(auto_now=True, editable=False) class Meta: abstract = True My problem is, when I pushed it to GitHub, the CI raised the following error: django.db.utils.ProgrammingError: column "updated_at" of relation "cars_car" does not exist I think it is related to the multiple inheritances because the other classes that don't inherit from PolymorphicModel didn't raise the same error. I have no idea how to proceed with that. -
Django: How to add a middleware which will return 200 when request method is OPTIONS
I have a requirement for testing purpose, whenever the request.method == "OPTIONS" then it should return status = 200. How can a write a middleware for this in Django -
"User object has no attribute 'encode'" when i register user
I am building a BlogApp and Today i tried to signup and then this error is keep showing 'User' object has no attribute 'encode' AND Then i tried to register in all my previous versions then this error is showing them all. BUT it was working before few days. Then i restarted my pc but still same error. When i try to save from python manage.py createsuperuser then it is also showing that error in terminal views.py def signup_view(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'registration/signup.html', {'form': form}) forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=200) password1 = forms.CharField(widget=forms.PasswordInput()) username = forms.CharField(help_text=False) class Meta: model = User fields = ( 'email', 'username', ) models.py @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() full traceback Traceback (most recent call last): File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\app\users\views.py", line 10, in signup_view user = form.save() File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\forms.py", line 131, in save user.save() File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save super().save(*args, **kwargs) File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", … -
How to skip some rows that have errors in django-excel
I'm usign django-excel library in my Django project, and I want to skip some rows before save it to the database using the save_to_database() method. I have something like the following: file = form.cleaned_data['file'] file.save_to_database( model=MyModel, mapdict = fields, initializer=self.choice_func, ) All is working ok but I want to validate the data before call save_to_database function. The idea to do it is to add the rows that are not valid in an array and return it to notify the user that those fields not were saved. -
NOT NULL constraint failed: blogs_comment.blog_id
I'm a beginner at django please help I've been trying to solve it for 2 hours, Thank you so much! <I got this django error IntegrityError at /blog/431cdef3-d9e7-4abd-bf53-eaa7b188d0fd> `python #Views from django.shortcuts import render from .models import Blog from .forms import CommentForm def home(request): template = 'blogs/home.html' blogs = Blog.objects.all() context = {'blogs':blogs} return render(request, template, context) def blog(request, pk): template = 'blogs/blog.html' blog = Blog.objects.get(pk=pk) context = {'blog':blog} if request.method == 'POST': form = CommentForm(request.POST) form.save() else: form = CommentForm() context['form'] = form return render(request, template, context) #Forms from django.forms import ModelForm from .models import Comment class CommentForm(ModelForm): class Meta: model = Comment fields = ['description'] #Models from django.db import models import uuid class Blog(models.Model): header = models.CharField(max_length=200) posts = models.TextField(null=True) footer = models.TextField(null=True, blank=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.header class Comment(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name='comments') description = models.TextField(blank=True, null=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.description ` -
Is there a way to make a circle around Long & Lat, say a 5 miles?
I am looking to make a radius of 5 miles using known longitude & latitude. how do we do that math in python? Thank you for your wisdom in advance. -
django and axios: why OPTIONS is requested when POST (restapi) is requested
I am using axios for doing a POST request in my reactjs page. const url = "test/"; const data = { email: "test@test.com", password: "test", }; const headers = { headers: { Accept: "application/json", "Content-Type": "application/json", }, }; axios.post(url, data, headers) .then((res) => { console.log(res); }) .catch((err) => { console.log(err); }) In my Django view(which corresponds to the url) I have intentionally put a wrong python statement. i.e def test(request): a+=1 And when run the axios code i get and also In my Django console i see: Traceback (most recent call last): ......... ........../views.py", line 139, in test a+=1 NameError: name 'a' is not defined But generally if I am not using rest api, Django shows the traceback html when anything wrong happens in the browser itself. Even with ajax i can see the response in the developertools. But with axios its not showing Can someone help how to achieve this. I want to capture the traceback also in the script -
How to solve 'This field is required' for django forms
I created a blog like app. Whenever I update an entry and press the submit button, I want it to take me to view page for that blog entry. However it just redirects me to the update page. When I check form.errors it says that 'This field is required' for all of the fields. But all of the fields are filled with data. views.py from django.shortcuts import render,redirect from .models import CR,GC from .forms import CrForm,GcForm # Create your views here. def Home(request): return render(request,'base.html') def crlistview(request): crs = CR.objects.all() context = {'crs':crs} return render(request,'cr_list.html',context) def CreateCr(request): form = CrForm() if request.method == 'POST': form = CrForm(request.POST) if form.is_valid(): form.save() return redirect('crlist') context = {'form':form} return render(request,'cr_form.html',context) def UpdateCr(request,pk): cr = CR.objects.get(id=pk) form = CrForm(instance=cr) context = {'form':form,} if request.method == 'POST': form = CrForm(request.POST,instance=cr) if form.is_valid(): form.save() return redirect('crlist') return render(request,'cr_form.html',context) def gclistview(request): gcs = GC.objects.all() context = {'gcs':gcs} return render(request,'gc_list.html',context) def gcview(request,pk): gc = GC.objects.get(id=pk) context = {'gc':gc} return render(request,'gc_view.html',context) def UpdateGc(request,pk): gc = GC.objects.get(id=pk) form = GcForm(instance=gc) context = {'form':form} if request.method == 'POST': form = GcForm(request.POST,instance=gc) if form.is_valid(): form.save() return redirect('gcview') return render(request,'gc_update.html',context) forms.py from django.forms import ModelForm from django import forms from .models import CR, … -
Remove underline from href attribute that reference a Django template
At the top of one of my website pages, I have some text representing the name of my company. When the user clicks the text (a link in this case), they are redirected to the index route via the Django template. Currently, the text is decorating. It's always the traditional blue color of a hyperlink and it's underlined when the user hovers over it. I'm trying to turn off this text decoration. Here is my attempt (which doesn't work): layout.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="{% static 'my_app/styles.css' %}" rel="stylesheet"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Pacifico"> </head> <body> <div id="logo"> <a href="{% url 'index' %}">ABC Company</a> </div> </body> CSS #logo { font-family: 'Pacifico', serif; text-align: center; font-size: 60px; font: 400 100px/1.5; color: #2b2b2b; text-decoration: none; } #logo:hover { text-decoration: none; } If I remove the href, the text goes back to the color specified in the #logo id in the CSS. Any ideas why the text-decoration isn't being turned off? Thanks in advance! -
How to get in Django Month / Year Archive as a list in first page?
looking to make a list by month in home page for iterate in first page like this: Aug 2021 July 2021 Jun 2021 and every month has no post, don't show in this list. this my code: #blog/models.py class Post(models.Model): title = models.CharField(max_length=255) content = RichTextField() author = models.ForeignKey(User,on_delete=models.CASCADE,) created_at = models.DateTimeField(auto_now_add=True) published_at = models.DateTimeField(null=True, blank=True, editable=False) #blog/views.py def month_archive(request, year, month): a_list = Post.objects.filter(created_at__year=year).filter(created_at__month=month) context = { 'year' : year, 'month': month, 'month_archive' : a_list, } return render(request, 'blog/month_archive.html', context) def home(request): posts = Post.objects.all() paginator = Paginator(posts, 5) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'posts': posts, 'page_obj': page_obj, } return render(request, 'blog/home.html', context) and i want to show it in home.html like: <li><a href="/blog/archive/2021/08">Aug 2021</a></li> <li><a href="/blog/archive/2021/07">Jul 2021</a></li> ... -
Django + Disable Caching for extended viewset
How to disable Django Cacheing for one of the viewset in below scenario ? I want to disable caching for viewset with name SecondViewSet, I am using @method_decorator(never_cache, name="list") on SecondViewSet it is not working, kindly advise Abstract Viewset class AbstractDataViewSet(ListAPIView): http_method_names = ['get', 'options'] permission_classes = [IsAuthorizedUser] @method_decorator(cache_page(settings.VIEWSET_CACHE_TIMEOUT)) def list(self, request, *args, **kwargs): return Response(data={"message":"appdata"} First Viewset class FirstViewSet(AbstractDataViewSet): group_permissions = { 'GET': ( roles.ACCOUNTING, ) } Second Viewset class SecondViewSet(AbstractDataViewSet): group_permissions = { 'GET': ( roles.ACCOUNTING, ) } Third Viewset class ThirdViewSet(AbstractDataViewSet): group_permissions = { 'GET': ( roles.ACCOUNTING, ) } -
vscode django debugging error: Couldn't import Django
I tried to debug a django project using vscode. But the next one came. ImportError Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? File "/Users/cubest_june/hj-django/english/manage.py", line 11, in main from django.core.management import execute_from_command_line The above exception was the direct cause of the following exception: File "/Users/cubest_june/hj-django/english/manage.py", line 13, in main raise ImportError( File "/Users/cubest_june/hj-django/english/manage.py", line 22, in <module> main() Even when I just ran python manage.py runserver, it ran without any problems, and both Django and Python are installed. (django-envs) ➜ english git:(main) ✗ django-admin --version 3.2.5 (django-envs) ➜ english git:(main) ✗ python --version Python 3.9.0 What is the cause of this problem and how to fix it? This is my first time doing something like this, so I don't know what kind of information I need. Let me know and I'll edit it. -
What is wrong--Mobile Compatibility not Working
I have been working on a website and at the moment, the header works and is responsive in desktop but when I get to mobile, the bootstrap doesn't show and it doesn't interact with mobile this is my code I have so far if anyone could tell me what is wrong that would be super helpful. <div class="continer-fluid"> <nav class="navbar navbar-inverse bg-inverse navbar-fixed-top"> <div class="navbar navbar-expand-lg "> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="container"> <a href="/" class="navbar-brand"> <img src="{% static "app/content/collectore-luxury-logo11.png" %}" width="30" height="30" class="d-inline-block align-top" alt=""> Website </a> <div class="collapse navbar-collapse " id="#navbarSupportedContent"> <ul class="nav navbar-nav mr-auto mt-2 mt-lg-0"> <li class="nav-item"><a href="{% url 'home' %}">Home</a></li> <li class="nav-item"><a href="{% url 'about' %}">About</a></li> <li class="nav-item"><a href="Medium Blog">Blog</a></li> <li class="nav-item"><a href="{% url 'New Thing' %}">New Thing</a></li> </ul> -
How to render all data related to object id in views.py
I am trying to create a webapp for a restaurant to display the different menus available, Breakfast, Lunch, evening etc. I have created models for Menu, Menu Category and Menu Items. I have a menu.html page that displays the available menus to view image of menu list on site . What I would like to happen when a user clicks the menu they wish to view is a menu_detail page to load and populated with required categories and items for that particular menu. Currently when clicked it will load the correct menu based on id but then only load a single category with the same id not all categories related to that menu and wont render any items models.py from django.db import models """ A Menu represents a collection of categories of food items. For example, a restaurant may have a Lunch menu, and a Dinner menu. """ class Menu(models.Model): name = models.CharField(max_length=246, unique=True,) slug = models.SlugField(max_length=24, unique=True, help_text='The slug is the URL friendly version of the menu name, so that this can be accessed at a URL like mysite.com/menus/dinner/.') additional_text = models.CharField(max_length=128, null=True, blank=True, help_text='Any additional text that the menu might need, i.e. Served between 11:00am and 4:00pm.') order … -
Django For Backend, Frontend Or Both
Please can Django be used to create a full functioning web application in Backend, Frontend or both and if so, can anyone suggest sites to learn on, a tutorial or complete web application course on Django or smth relating to how to code using Django. Thank You -
Image update issue in drf using put method
I am using Django rest framework, I have a issue regarding update my html data with image field using put method. Everthing is fine in response using postman but when i use ajax then it gives me following error in console. PLease help to resolve this issue. I want to update my data with image using put method only but above error interrupt my work. Please help me to resolve my issue I want to update my data with image using put method only but above error interrupt my work. Please help me to resolve my issue My views,py file: @api_view(['PUT']) # @csrf_exempt @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def update_blog(request, id): try: blog = Blog.objects.get(id=id) except Blog.DoesNotExist: return Response(status=404) if blog.user_id != request.user.id: return Response({'response':'You do not have permission to update that'}) if request.method == 'PUT': serializer = AddBlogSerializer(blog, context={'request': request}, data=request.data) if serializer.is_valid(): serializer.save() data = {'result':'success', 'message':'Blog post updated successfully'} return Response(data=data, status=200) if not serializer.is_valid(): data = { 'result': 'error', 'message':serializer.errors} return Response(data=data) My response data is fine in views.py file My bootstrap html modal <!-- Modal --> <div class="modal fade" id="exampleModal1" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Update Blog</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" …