Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Anyone who knows Navbar&Bootstrap?
I have no idea with this problem.. Navbar's Dropdown doesn't work! with this message enter image description here this is my code <head> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavDropdown"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Features</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Pricing</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <a class="dropdown-item" href="{%url 'home'%}">Portfolio</a> <a class="dropdown-item" href="{%url 'signup'%}">회원가입</a> <a class="dropdown-item" href="{%url 'login'%}">로그인</a> <a class="dropdown-item" href="#">로그아웃</a> </div> </li> </ul> </div> </nav> {%block contents%} {%endblock%} -
How to change my models.TextField to models.JSONField?
I'm using django as my backend and it was working very fine, but after I tried to replaced text = models.TextField(blank=True, null=True) text = models.JSONField(blank=True, null=True) but I got the text field is shown as string with slashes \ "text": "{\"name\": [\"test\", \"test2\"]}", while styles field look as json "style": { "borderRadius": "5px", "backgroundColor": "orange" }, despite they both are jsonfield. models.py class elements(models.Model): tag = models.CharField(blank=True, null=True, max_length=20) # it was # text = models.TextField(blank=True, null=True) # now it is text = models.JSONField(blank=True, null=True) src = models.TextField(blank=True, null=True) style = models.JSONField(blank=True, null=True) main = models.ForeignKey( 'self', null=True, blank=True, related_name="sub", on_delete=models.PROTECT) def __str__(self): return "<elements: {} {}>".format(self.tag, self.text, self.src, self.style) def __repr__(self): return self.__str__() also after a run python manage.py makemigrations then python manage.py migrate I got an error DETAIL: Token "add" is invalid. CONTEXT: JSON data, line 1: add... the full error Operations to perform: Apply all migrations: account, admin, auth, authtoken, contenttypes, myapp, sessions, sites Running migrations: Applying myapp.0006_auto_20200905_1410...Traceback (most recent call last): File "/Users/apple/Desktop/learning web stack from clonning notion.so/backend/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.InvalidTextRepresentation: invalid input syntax for type json DETAIL: Token "add" is invalid. CONTEXT: JSON data, line 1: add... The above exception … -
Django cache and page part that depends on login
Suppose I have some page at example.com/page If a user is not logged in, then I show Log in button. If the user is logged in, then I show menu. The problem is that it doesn't work with cache. If I render page and save it in cache, then it is always with login button. How to avoid this? -
Extending User model when users haven't created accounts yet
I am building a system for a startup where customers can book small home repair services with the service providers. Everything so far was done manually by a human, using a large spreadsheet that stores contact information of the service providers, like name, e-mail, location, phone, etc. As the customers reach the company's website asking for repairs, a person go though the spreadsheet, looking for a suitable service provider, contact the provider and checks availability and books a time/date that works for both provider and customer. The idea now is to automate this process, sending sms and whatsapp messages to both parties, instead of a person having to deal with this process, by using Trello. The startup owners want to avoid the trouble of having to ask for all service providers to create accounts for now, but I think it's a good idea to extend the Django's User model, as later on it would be easy to transition to a system where the providers has their own accounts with username and password, and easily connect with all the services that have been done. But right now I can't use the User model, as I don't have any accounts yet. Should … -
django ajax post without csrftoken in post ajax
html {% load static %} <input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg" multiple> <input type = "button"id = "btn_upload"value = "submit"></input>```` javascript $(document).ready(function(){ $('#btn_upload').click(function(){ console.log("is it working?"); const formdata = new FormData(); const inputfile = $('input[name="avatar"]'); const files = inputfile[0].files.val(); for(let i = 0; i<files.length; i++){ formdata.append('images',files[i]); } formdata.append('CSRFToken',csrf); $.ajax({ contentType : false, processData : false, data : formdata, url : '', type : 'POST', success : function(result){ console.log("succeed") } }); }); }); I want to give over the data by POST method without using form But in django setting {% csrf_token %} is needed when using POST method How can I give data without using form and {% csrf_token %}? -
Why is wrong url being returned after image is uploaded
I uploaded image and it gets save in correct location and url uploaded to db. But response is wrong. "http://127.0.0.1:8000/media/media/img.jpg" is being returned instead of "http://127.0.0.1:8000/media/img.jpg" where its being saved. Why is extra media/ being added? api.js def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() if request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) profile = UserDetail() profile.user = user profile.profile_pic = uploaded_file_url profile.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) url.js urlpatterns = [ path('api/auth', include('knox.urls')), path('api/auth/register', RegisterAPI.as_view()), path('api/auth/login', LoginAPI.as_view()), path('api/auth/user', UserAPI.as_view()), path('api/auth/logout', knox_views.LogoutView.as_view(),name='knox-logout'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.js STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/images') serializer class ProfilePicSerializer(serializers.ModelSerializer): class Meta: model = UserDetail fields = '__all__' class UserSerializer(serializers.ModelSerializer): profile_pic = ProfilePicSerializer(source='user_detail', read_only=True) class Meta: model = User fields = ('id', 'username', 'email','profile_pic') -
Raspberry Pi camera stream to django website
I have been experementing in python django, and got the idea to make my raspberry pi camera stream to the website. The only tutorials I could find were about showing youtube videos on the website. Is there any way to do it from the raspberry pi camera? -
Djnago causing errors with StreamingHttp Response
I created a django app to stream coordinates of ISS on a map, here is the view which generates the streaming http response def IssnowCoordinatesStream(request): def IssDataStream(sleep_time = 1): while True: streamData = GenerateIssData() yield 'data:{0}\n'.format(streamData.decode()) time.sleep(sleep_time) response = StreamingHttpResponse( IssDataStream(), status = 200, content_type = "text/event-stream" ) response['Cache-Control'] = 'no-cache' return response This is the output from the view at [localhost/stream] data:{"issnow_satid": 2447, "key": "e622c32c-b949-4abe-b3d8-ca75dbd8039e", "timestamp": "2020-09-05 13:23:36.018709", "message": "Success", "longitude": -29.8005, "latitude": -28.4975, "speed": 27554, "altitude": 428} And from my index view i am trying to access the stream using javascript var source = new EventSource('/stream') source.addEventListener('message', (e) => { obj = JSON.parse(e.data) console.log(obj); }, false); But it's not able to parse the data and the following error comes up on the terminal Traceback (most recent call last): File "C:\Python37\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Python37\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Python37\lib\wsgiref\handlers.py", line 279, in write self._write(data) File "C:\Python37\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\Python37\lib\socketserver.py", line 799, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine [05/Sep/2020 18:45:52] "GET /streams/issnow HTTP/1.1" 500 59 Can anyone help in solving this error. Note I browsed the … -
Django ajax: show comment's replies div
i have a comment section with replies in my app and I would like to show and hide replies by clicking on button. This is what I done: ajax $(document).ready(function () { $("#showReplies").click(function () { $.ajax({ type: 'get', success: function (data) { console.log(data.comment); $('.replies').load("http://127.0.0.1:8000/comment_replies/" + data.comment.id); } }) }); }); post_comments.html <h3>Comments:</h3> {% for comment in post.comment_set.all %} <p>{{ comment.content }}</p> <small>{{ comment.author }} / {{ comment.date_of_create|date:"d E Y" }}</small> <button type="button" id="showReplies">Show replies</button> {% endfor %} comment_replies.html {% for reply in replies %} <p>{{ reply.content }}</p> <small>{{ reply.author }} / {{ reply.date_of_create|date:"d E Y" }}</small> {% endfor %} urls.py path('comment_replies/<int:comment_id>/', comment_replies, name='comment_replies'), views.py def comment_replies(request, comment_id): comment = Comment.objects.get(id=comment_id) #replies = Reply.objects.filter(comment=comment) # context = {'replies': replies} # return render(request, 'blog/comment_replies.html', context) return JsonResponse({'comment': model_to_dict(comment)}, status=200) How can I get appropriate url in ajax? Data logs whole template in console after clicking button instead of comment object. When I go to url http://127.0.0.1:8000/comment_replies/4/ I get {"comment": {"id": 4, "author": 1, "content": "test", "date_of_create": "2020-09-05T09:56:05.218Z", "post": 9, "topic": null}} Data.comment gives undefined. -
Django Like Syste --> RedirectView not redirecting to post
I ran into a problem while trying to figure out how to implement a liking system for my Django blog. I have a post Detail View and a PostRedirectView. I want the redirect view to get the absolute URL for the Post I look at and toggle a like/unlike as my liking system is a ManyToManyField linked in my models.py for the post. Here is the related code: views.py class PostDetailView(DetailView): model = Post template_name = 'blog/post_detail.html' context_object_name = 'post' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) comments_connected = Comment.objects.filter(post_connected=self.get_object()).order_by('-date_posted') data['comments'] = comments_connected data['form'] = NewCommentForm(instance=self.request.user) return data def post(self, request, *args, **kwargs): new_comment = Comment(content=request.POST.get('content'), author=self.request.user, post_connected=self.get_object()) new_comment.save() return self.get(self, request, *args, **kwargs) class PostLikeRedirect(RedirectView): def get_redirect_url(self, *args, **kwargs): obj = get_object_or_404(Post, pk=self.kwargs.get('id')) return obj.get_absolute_url() urls.py path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/<int:pk>/like', PostLikeRedirect.as_view(), name='post-like'), models.py class Post(models.Model): content = models.TextField(max_length=1000) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="users_who_authored") like = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="users_who_liked") def __str__(self): return f'{self.author} posts: {self.content[:8]}' @property def number_of_comments(self): return Comment.objects.filter(post_connected=self).count() def __str__(self): return f'{self.author} posted' The error I get is 404 page not found when I go to post/id(e.g. 2)/like and the error message No Post matches the given query. I know what the error means I just … -
The code of an HTML dropdown button seems fine, but it doesn't work [closed]
I am following a book to learn Django. One of the dropdown buttons is not working, the code is the same as the one provided by the book. I tried to find reason on my own, but it heavily involves bootstrap or something. Anyone can take a look at the snippet below. <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="{% url 'home' %}">Newspaper</a> {% if user.is_authenticated %} <ul class="navbar-nav mr-auto"> <li class="nav-item"><a href="{% url 'article_new' %}">+ New</a></li> </ul> {% endif %} <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="collapse navbar-collapse" id="navbarSupportedContent"> {% if user.is_authenticated %} <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{ user.username }} </a> <div class="dropdown-menu dropdown-menu-lg-right" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="{% url 'password_change'%}">Change password</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'logout' %}"> Log Out</a> </div> </li> </ul> {% else %} <form class="form-inline ml-auto"> <a href="{% url 'login' %}" class="btn btn-outline-secondary"> Log In</a> <a href="{% url 'signup' %}" class="btn btn-primary ml-2"> Sign up</a> </form> {% endif %} </div> </nav> -
hi I have django problem, Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name
I want to see http://127.0.0.1:8000/bookmark/ page. But I go there, there is an error in website. error message is NoReverseMatch at /bookmark/ Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/bookmark/ Django Version: 3.1 Exception Type: NoReverseMatch Exception Value: Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name.3 and my code is [base.html] <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}django web programming {% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <!-- 하위 html 파일에서 이 부분에 style 태그를 추가할 가능성이 있으므로 block 태그를 기입. 블록태그이름은 extra-style로 지정함 변경가능 --> {% block extra-style %}{% endblock %} <style> .nav-link{ font-size: 18px; font-weight: 500; } </style> </head> <body style = "padding-top:90px;"> <!-- home.html (4) 참고 --> <nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top"> <span class="navbar-brand mx-5 mb-0 font-weight-bold font-italic"> Motdongsan</span> <!-- <a class="navbar-brand" href="#">Navbar</a> --> <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="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item mx-3 btn btn-light"> <a class="nav-link" href="{% url 'home'%}">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item mx-3 btn btn-light"> <a class="nav-link" href="{% url 'bookmark:index'%}">Bookmark</a> </li> … -
How to change the redirect_uri in moziila_django_oidc?
I want to integrate Keycloak into a Django project and I am using mozilla_django_oidc to do so. The problem I have is that when I send a request to the authorization endpoint of keycloak the redirect_uri is being set as: redirect_uri=http%3A%2F%2Fdjango%3A8000%2Foidc%2Fcallback%2F, but instead of django there should be the IP of my application. I don't know why it uses django as the domain name. My configuration in the settings.py looks like this: OIDC_RP_CLIENT_ID = os.environ['OIDC_RP_CLIENT_ID'] OIDC_RP_CLIENT_SECRET = os.environ['OIDC_RP_CLIENT_SECRET'] OIDC_OP_AUTHORIZATION_ENDPOINT = 'http://172.20.159.83:8080/auth/realms/Test/protocol/openid-connect/auth' OIDC_OP_TOKEN_ENDPOINT = 'http://172.20.159.83:8080/auth/realms/Test/protocol/openid-connect/token' OIDC_OP_USER_ENDPOINT = 'http://172.20.159.83:8080/auth/realms/Test/protocol/openid-connect/userinfo' OIDC_OP_JWKS_ENDPOINT = 'http://172.20.159.83:8080/auth/realms/Test/protocol/openid-connect/certs' LOGIN_REDIRECT_URL = 'http://172.20.159.83/test' LOGOUT_REDIRECT_URL = 'http://172.20.159.83/' And in the urls.py it is: path('oidc/', include('mozilla_django_oidc.urls')), The request to the authorization endpoint with all parameters: http://172.20.159.83:8080/auth/realms/Test/protocol/openid-connect/auth?response_type=code&scope=openid+email&client_id=MyApplication&redirect_uri=http%3A%2F%2Fdjango%3A8000%2Foidc%2Fcallback%2F&state=3YxLAg8kX1bC1yTDMqKh8L05bIP5z9cB&nonce=jZ6KEZhk9tWOwdXRSqTUoF8lzg7aLU70 So, as the title says, how can I change the django part of the redirect uri to point to the IP of my application? How is this parameter being set? -
Django Rest Framework 'list' object has no attribute values
I have the code and error stacktrace below. I am trying to access localhost:8000/fundamentals/ but I get the error 'list' object has no attribute 'values' error web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner web_1 | response = get_response(request) web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 202, in _get_response web_1 | response = response.render() web_1 | File "/usr/local/lib/python3.7/site-packages/django/template/response.py", line 105, in render web_1 | self.content = self.rendered_content web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/response.py", line 70, in rendered_content web_1 | ret = renderer.render(self.data, accepted_media_type, context) web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/renderers.py", line 724, in render web_1 | context = self.get_context(data, accepted_media_type, renderer_context) web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/renderers.py", line 655, in get_context web_1 | raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request) web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/renderers.py", line 563, in get_raw_data_form web_1 | data = serializer.data.copy() web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 562, in data web_1 | ret = super().data web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 264, in data web_1 | self._data = self.get_initial() web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 412, in get_initial web_1 | for field in self.fields.values() web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 413, in <listcomp> web_1 | if not field.read_only web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 412, in get_initial web_1 | for field in self.fields.values() web_1 | … -
Session key failed
i am creating todo app. After login when i add any task. It show error: failed 'SESSION_KEY'. When i debug the code it show SESSION_KEY. after removing the request.seesion from post method in TODOlist class it works. I don't know how to fix this issue. class Login(TemplateView): template_name = 'login.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request): try: username = self.request.POST.get('username').strip() password = self.request.POST.get('password').strip() if username is None or password is None: return HttpResponse('Invalid User', 500) user = authenticate(request, username=username, password=password) if not user: return HttpResponse('User Doest exist', 500) else: login(request, user) if SESSION_KEY in request.session: return redirect('todolist') except Exception as e: return HttpResponse({'failed {}'.format(e, 200)}) class Todolist(TemplateView): template_name = 'todo_page.html' def get(self, request, *args, **kwargs): if SESSION_KEY in request.session: return render(request, self.template_name) def post(self, request): if SESSION_KEY in request.session: try: data = self.request.POST.get task_list = Task( user_id=request.session["SESSION_KEY"], task=data('task') ) task_list.save() return redirect('todolist') except Exception as e: return HttpResponse('failed {}'.format(e), 500) -
Django -- Forbidden (CSRF token missing or incorrect.): /vote/
I have a website with an AJAX upvote or downvote option on a post. The problem I am having is that the voting works on my Post detail page but not on my index page. I am getting the error Forbidden (CSRF token missing or incorrect.): /vote/ Both pages call the same view and URL pattern. index.html: {% for post in posts %} <span id="post_{{forloop.counter}}" data-value="{{post.id}}"></span> <button class="vote_action" value="upvote_button"> + </i></button> <span id="votes">{{post.points}}</span> <button class="vote_action" value="downvote_button"> - </button> {% endfor %} <script type="text/javascript"> // JQUERY - AJAX SCRIPT FOR voting $(document).ready(function(){ {% for post in posts %} $('.vote_action').click(function(e) { var postid = document.getElementById('post_{{forloop.counter}}').getAttribute('data-value'); var button = $(this).attr("value"); e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "vote" %}', data: { postid: postid, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'postvote', button: button, }, success: function(json){ if (json.length < 1 || json == undefined) { //empty } document.getElementById("votes").innerHTML = json['result'] }, error: function(xhr, errmsg, err) {} }) }) {% endfor %} }) </script> post_detail.html: <span id="vote_id" data-value="{{post.id}}"></span> <button class="vote_action" value="upvote_button"> + </i></button> <span id="votes">{{post.points}}</span> <button class="vote_action" value="downvote_button"> - </button> <script type="text/javascript"> // JQUERY - AJAX SCRIPT FOR voting $(document).ready(function(){ $('.vote_action').click(function(e) { var postid = document.getElementById('vote_id').getAttribute('data-value'); var button = $(this).attr("value"); e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "vote" … -
Photos removed from the disk continue to appear on the website
I'm developing a website for my student project. I use Django and Docker for containers. I cloned from GitLab the part that my friend did (code, photos, etc.) and then removed some photos from a folder with photos on my disk, but the photos still exist on my website (on localhost). I cleaned cache, removed and created containers again, double-checked my code, but still, photos appear. What can I do? Where are the photos stored? My code for showing photos: <div class="row justify-content-center"> <div class="col-12 col-lg-10"> <ul class="nav nav-tabs" id="bitTab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="bit1-tab" data-toggle="tab" href="#bit1" role="tab" aria-controls="bit1" aria-selected="true">BIT1</a> </li> . . . <div class="tab-content" id="bitGalleryTabContent"> <div class="tab-pane fade show active" id="bit1" role="tabpanel" aria-labelledby="bit1-tab"> {% for i in i|rjust:15 %} <a style="border: 0;" href="{% static 'images/bit1/' %}{{ forloop.counter }}.png" title="BIT"> <img src="{% static 'images/bit1Thumbnails/' %}{{ forloop.counter }}.png" alt="BIT1"> </a> {% endfor %} </div> . . . -
Why DRF Nested Serializer is returning an error
I am using django rest framework for my rest api based project. I am using nested serializer to save child model object along with parent object. Below is snap of my code This is my parent model : class DeliveryNote(models.Model): vdate=models.DateField("Date") voucherno=models.OptionalCharField("Voucher No.") class Meta: verbose_name="Delivery Note" verbose_name_plural="Delivery Notes" db_table="INV_DeliveryNote" This is my child model : Class DeliveryItem(models.Model): deliverynote=models.ForeignKey(DeliveryNote,on_delete=models.CASCADE,related_name='items') itemname=models.CharField("Item Name") qty=models.FloatField("Quantity") class Meta: verbose_name="Delivery Item" verbose_name_plural="Delivery Items" db_table="INV_DeliveryItems" This is my parent serializer: class DeliveryNoteSerializer(eserializer): items=DeliveryItemSerializer(required=False,many=True,read_only=False) def create(self, validated_data): items_data=validated_data.pop('items',None) vinstance=DeliveryNote.objects.create(**validated_data) if items_data: for item in items_data: DeliveryItem.objects.create(deliverynote=vinstance,**item) return vinstance def update(self,instance,validated_data): items_data=validated_data.pop('items',None) vinstance=super(DeliveryNoteSerializer, self).update(instance, validated_data) items_dict=dict((i.id,i) for i in instance.items.all()) if items_data: for item in items_data: if "id" in item.keys(): iinstance=items_dict.pop(item["id"]) item.pop('id') for x in item.keys(): setattr(iinstance,x,item[x]) iinstance.save() else: DeliveryItem.objects.create(deliverynote=vinstance,**item) if len(items_dict)>0: for item in items_dict.values(): item.delete() return vinstance class Meta: model = DeliveryNote fields='__all__' This is my child serializer: class DeliveryItemSerializer(serializers.ModelSerializer): def create(self, validated_data): return DeliveryItem.objects.create(**validated_data) class Meta: model = DeliveryItem fields='__all__' I am using django rest framework viewset to generate end points. My payload is: { "vdate":"31-08-2020", "voucher_no":"111", "items":[ { "itemname":12, "qty":"10.00" } ] } This generates following error : "items": [ { "deliverynote": [ "This field is required." ] } ] What am I doing … -
How to serialize uploaded image in django rest framework
My Profile_pic doesnt show in response. Only id, username and email. profile_pic is already stored in db with correct user_id. userdetailmodel.js from django.contrib.auth import get_user_model from django.db import models User = get_user_model() class UserDetail(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(null=True, blank=True) serializer.js class ProfilePicSerializer(serializers.ModelSerializer): profile_pic = serializers.ImageField(max_length=None, use_url=True) class Meta: model = UserDetail fields = '__all__' class UserSerializer(serializers.ModelSerializer): profile_pic = ProfilePicSerializer(source='user.userdetail.profile_pic',read_only=True, many=True) class Meta: model = User fields = ('id', 'username', 'email','profile_pic') api.js class UserAPI(generics.RetrieveAPIView): permission_classes = [permissions.IsAuthenticated,] serializer_class = UserSerializer def get_object(self): return self.request.user -
How to update this data from a forms?
i have tried UpdateView, but it didn't work out! please help me quickly I have a form on a page that gets information from database. How to update this data from a forms? Lorem ipsum dolor sit amet consectetur, adipisicing elit. Debitis repudiandae delectus, pariatur quibusdam doloribus. Voluptatem ad ab beatae dolorum magnam architecto, velit perspiciatis, provident delectus dolores, repudiandae sunt expedita eos voluptates deserunt nam dicta earum mollitia obcaecati! Nam minima enim soluta ratione, vel, sapiente illum eligendi recusandae deleniti earum, aliquid iusto ullam, doloribus tempore aperiam ipsum velit assumenda nostrum quo. views.py class EntityUpdate(UpdateView): model = Entity fields = [ 'entity_type', 'full_name', 'identifier', ] template_name_suffix = '_update_form' def ex_record(request, pk): enforcement = Enforcements.objects.get(pk=pk) enform = EnforcementForm(instance=enforcement) debtor = EntityForm(instance=enforcement.debtor_id, prefix='debtor') claimer = EntityForm(instance=enforcement.claimer_id, prefix='claimer') issuer = EntityForm(instance=enforcement.issuer_id, prefix='issuer') claims = ClaimsForm(instance=enforcement) if request.method == 'POST': if debtor.is_valid() and claimer.is_valid() and issuer.is_valid() and claims.is_valid() and enform.is_valid(): # save without commit enform_instance = enform.save(commit=False) # save id of Forein Keys debtor_instance = EntityForm(request.POST, instance=enforcement).save() claimer_instance = EntityForm(request.POST, instance=enforcement.claimer_id).save() issuer_instance = EntityForm(request.POST, instance=enforcement.issuer_id).save() claims_instance = claims.save() # connect ForeinKeys in Enforcement enform_instance.debtor_id = debtor_instance enform_instance.issuer_id = issuer_instance enform_instance.claim_id = claims_instance enform_instance.claimer_id = claimer_instance # commit to DB enform_instance.save() return render(request, 'zzam_db/view.html', … -
Why is my .css file not fully rendering on server, but working locally?
Essentially, my style.css file is only partially rendering on the live server, despite working properly in my local development environment. Prior to this update I just pushed, things were working fine - I changed some content in the .css file, but not the content that is being affected by this issue. The parts of the CSS file that seem to be affected: table.student { width: 75%; border: 3px inset; margin-left: auto; margin-right: auto; } table.admin { width: 50%; border: 3px inset; margin-left: auto; margin-right: auto; } h1{ font-family: Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, sans-serif; font-size: 30px; padding: 1%; text-align: center; } The rest of the .css file is being applied just fine. I didn't change the file location (myapp/static/css/style.css), or how/where the file is called (in my base.html file with the line <link rel="stylesheet" href="{% static 'css/style.css' %}">). I have run collectstatic with no discernible effect. The python version I am using is 3.7.2 -
One button affecting another form. Django Python
I am creating Blog where user can Like and Pin their Favourite posts. My problem is that when I pin my post and then click on like so it automatically unpin and I have to pin it again . Please test it yourself and help me that how to prevent two forms clashing with each other. ThankYou... Please Help... My Post model with Like and Pin. class Post(models.Model): """Blog Post""" title = models.CharField(max_length=255) title_tag = models.CharField(max_length=55) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) category = models.CharField(max_length=255) likes = models.ManyToManyField(User, related_name='liked_posts') pins = models.ManyToManyField(User, related_name='pinned_posts') views = models.IntegerField(default=0) My like view : def like_post(request, post_id): post = get_object_or_404(Post, id=request.POST.get('post_id')) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) post.views = post.views - 1 post.save() liked = False else: post.likes.add(request.user) post.views = post.views - 1 post.save() liked = True return HttpResponseRedirect(reverse('blog:post', args=[post_id])) My pin view: def pin_post(request, post_id): post = get_object_or_404(Post, id= request.POST.get('post_id')) pinned = False if post.pins.filter(id=request.user.id).exists(): post.pins.remove(request.user) post.views = post.views -1 post.save() pinned = False else: post.pins.add(request.user) post.views = post.views -1 post.save() pinned = True return HttpResponseRedirect(reverse('blog:post', args=[post_id])) My post view: def post(request, post_id): post = Post.objects.get(id=post_id) post.views = post.views + 1 post.save() total_likes = post.total_likes() liked = False if … -
Querying from AJAX in Django (GET)
I have a template (menu.html), and I am making an AJAX call with JavaScript. Then, I want to process that call (throughout the GET parameters) and make a query from Django's ORM. \ My JavaScript code is: $.ajax("/showcart", { type: "GET", data: { product: product, type: product_type }, success: function(response) { console.log("SUCCES SUCCESS SUCCESS") console.log(response); }, error: function(resp) { console.log("ERROR ERROR ERROR!") console.log(resp) } }) product is the name of my product, and product_type is the size of my product. Then, in my views.py, I handle this call with: def showcart(request): product = request.GET['product'] if request.GET['type'] == "small": size = f"{request.GET['type']}_price" elif request.GET['type'] == "large": size = f"{request.GET['type']}_price" else: size = "price" product_name = product.split("-")[0] product_id = product.split("-")[1] return JsonResponse( { "product_name": product_name, "product_id": product_id, "size": size, "queryresult": "nothing here", } ) For example, product_name is "Sub" and I have a model in models.py called Sub. My goal is querying the price, for instance, with the product_name. But, since it is a string type, Django doesn't allow me to do that. Does anyone know how this works? Thanks, -
Is there a way to expose Django admin as a RESTful API?
I want to create, update and delete my objects using an API just like I can from an admin panel but I already have a user API and I don't want to repeat myself. Is there a library I can use to achieve what I want? I've tried django-restful-admin but it did not work properly on Django 3.1 (django.core.exceptions.AppRegistryNotReady was raised though I configured it properly). -
My django form is not working when i iterate through it using for loop
Basically if I tried to use this code {% for field in form %} <div class="input"> <label for="" class="labelinput">{{field.label}}</label> {{field}} </div> {% endfor %} the form data wont make it pass is_valid().But it renders out the form fine. and if I use this code <form action="" method="post"> {% csrf_token %} {{form}} <input type="submit" value=""> it worked perfectly fine. How do I get the first code to work because I want to add classes between the label and the input field