Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update using record with no pk in body using UpdateAPIView
I am trying to develop an update (PUT) endpoint that would not require adding pk to the url or body. The code below requires the currentbal_autorecharge entered as an id and it works. But i will like to update records without adding the pk to the body of request. I would prefer to use the token to get the current user and then use that to complete the update. i can successfully get the current user and current user id using the view below. How can i utilize this pk without entering it in the body? class CurrentBalance(models.Model, Main): currentbal_autorecharge = models.OneToOneField(User, on_delete=models.CASCADE, related_name='currentbal_autorecharge') currentbal_update = models.DecimalField(decimal_places=2, max_digits=10000, null=True) def __str__(self): return self.currentbal_autorecharge.phone class CurrentBalanceSerializer(serializers.ModelSerializer): class Meta: model = CurrentBalance fields = ( 'currentbal_autorecharge', 'currentbal_update' ) class CurrentBalanceUpdate(UpdateAPIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) # queryset = CurrentBalance.objects.all() serializer_class = CurrentBalanceSerializer def update(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) print(serializer) serializer.is_valid(raise_exception=True) serializer.save() return JsonResponse({"status": "success"}) -
Expected view to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly
I am customizing the value given when sending get: list request from django modelviewset. In the meantime, the following error occurs and questions are asked. Traceback (most recent call last): File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\viewsets.py", line 114, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "D:\school\대회 및 프로젝트\CoCo\feed\views.py", line 20, in list instance = self.get_object() File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\generics.py", line 88, in get_object assert lookup_url_kwarg in self.kwargs, ( AssertionError: Expected view CreateReadPostView to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. I sent a list request, but I don't know why I got into trouble at looked_up field and pk. Can you determine why this problem occurred? Here's my code. Thank in advance. views.py class CreateReadPostView (ModelViewSet) : … -
'Authentication Unsuccessful' When Trying To Send Email Through Django
I've been trying to send emails using my Outlook email through Django but have been getting a variety of error messages, including (535, b'5.7.3 Authentication unsuccessful [SYBPR01CA0102.ausprd01.prod.outlook.com]') Apparently I need to allow SMTP AUTH, but cannot find how to do this as I am using Outlook in my browser and don't have it downloaded (it keeps requesting I pay for it, but I'd prefer not to as I really don't see the need for this small project, unless I need to). I did however pay for the email. I've also read that Outlook doesn't support smpt: Outlook 365 OAuth 535 5.7.3 Authentication unsuccessful My settings in Django are: DEFAULT_FROM_EMAIL = '###@###.###' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp-mail.outlook.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '###@###.###' EMAIL_HOST_PASSWORD = '########' My question is can I send Outlook emails through Django? If so, what am I doing wrong? Thank you. -
How can I define the color of my Navbar from Materialize CSS codes that I've used
newbie here, the navbar default color is materialize red I want to change it to light blue: <nav> <div class="nav-wrapper"> <a href="/" class="brand-logo">LARAYAN ONLine BookStore</a> <ul id="nav-mobile" class="right hide-on-med-and-down"> <li><a href="/">Home</a></li> <li><a href="/register">Register</a></li> <li><a href="/login">Login</a></li> </ul> </div> -
Django Image Shows As A Error How TO Fix?
I have an image called paris and I am trying to display it on my website it just shows the image url thing but does not display the image image <head> <style> img { border: 1px solid #ddd; border-radius: 4px; padding: 5px; width: 150px; } </style> </head> <body> <h2>Thumbnail Images</h2> <p>Use the border property to create thumbnail images:</p> <img src="paris.jpg" alt="One Piece" style="width:150px"> </body> my full home code: <!-- base.html --> <!DOCTYPE html> {% extends 'main/base.html' %} {% block title%} home {% endblock %} {% block content %} <html> <head> <style type="text/css"> body { background-color: #212F3C; } .sidenav2 h1 { margin-top: 196px; margin-bottom: 100px; margin-right: 150px; margin-left: 350px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } .sidenav3 h1 { margin-top: -125px; margin-bottom: 100px; margin-right: 150px; margin-left: 400px; padding-left: 290px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } .sidenav4 h1 { margin-top: -128px; margin-bottom: 100px; margin-right: 150px; margin-left: 800px; padding-left: 290px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } .sidenav6 h1 { margin-top: 250px; margin-bottom: 100px; margin-right: 150px; margin-left: 600px; padding-left: 290px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } .sidenav7 h1 { margin-top: -130px; margin-bottom: 100px; margin-right: 150px; margin-left: 50px; padding-left: 240px; text-decoration: none; font-size:25px; color: #F7F9F9; display:block; } .sidenav8 h1 { margin-top: 370px; … -
I deployed my Django server via Heroku, the build was successful, but keep getting 'Application Error' on the deployed URL
I deployed my Django server via Heroku, the build was successful. Whenever I go to the deployed URL, I get an application error without no specific error. It just says for me to check my logs. Here is my log. Is there something Im missing? still new to deploying with Heroku. -----> Python app detected -----> No change in requirements detected, installing from cache -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 -----> Installing SQLite3 -----> Installing requirements with pip -----> $ python manage.py collectstatic --noinput /app/.heroku/python/lib/python3.6/site-packages/environ/environ.py:630: UserWarning: /tmp/build_b0b32caa_/portfolio_project/.env doesn't exist - if you're not configuring your environment separately, create one. "environment separately, create one." % env_file) 330 static files copied to '/tmp/build_b0b32caa_/staticfiles'. -----> Discovering process types Procfile declares types -> (none) -----> Compressing... Done: 71M -----> Launching... Released v19 https://coreys-portfolio-server.herokuapp.com/ deployed to Heroku -
(Django) How to create a verification mixin that references two models?
I have two classes Organisation, and Staff in addition to the User class. I want to create a mixin called "UserIsAdminMixin" that checks whether the user logged in has the role "admin" in a specific Organisation. The classes (simplified) class Organisation(models.Model): name = models.CharField(max_length=50) class Staff(models.Model): class Role(models.TextChoices): ADMIN = 'ADMIN', "Admin" STAFF = 'STAFF', "Staff" user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, db_index=True, related_name="staff_profiles", on_delete=models.SET_NULL) organisation = models.ForeignKey('organisations.Organisation', db_index=True, related_name="staff", on_delete=models.CASCADE) role = models.CharField(max_length=10, choices=Role.choices, default=Role.STAFF) I then currently have this for my UserIsAdmin mixin: class UserIsAdminMixin: def dispatch(self, request, *args, **kwargs): if self.request.user.staff_profiles.filter(organisation=self.get_object(), role=Staff.Role.ADMIN): return super().dispatch(request, *args, **kwargs) else: raise PermissionDenied This works great for this view: organisations.views.py (URL: organisation/<int:pk>) class OrganisationDetail(LoginRequiredMixin, UserIsAdminMixin, generic.DetailView): model = Organisation template_name= "organisations/detail.html" login_url = "login" But I'd also like it to work for this view as well, which it obviously doesn't as self.get_object() returns a Staff object in this case when it's expecting an Organisation object: staff.views.py (URL: organisation/<int:pk_alt>/staff/<int:pk>) class StaffDetail(LoginRequiredMixin, UserIsAdminMixin, generic.DetailView): model = Staff template_name="staff/detail.html" login_url = "login" I was able to make changes to the mixin to get it to work in the second scenario but not the first: class UserIsAdminMixin: def dispatch(self, request, *args, **kwargs): if self.request.user.staff_profiles.filter(organisation__pk=self.kwargs['pk_alt']), role=Staff.Role.ADMIN): return … -
Why we need django-session?
I have writen a function that has two functionality: take a request object and render a template with Product view, It adds product-id to django session corresponding to the product that the user clicked "add to cart" def catalog(request): if 'cart' not in request.session: request.session['cart'] = [] cart = request.session['cart'] request.session.set_expiry(0) store_items = Product.objects.all() ctx = { 'store_items': Product.objects.all(), 'cart_items': len(cart) } if request.method == "POST": cart.append(int(request.POST['obj_id'])) return redirect('catalog') return render(request, 'catalog.html', ctx) What is a django session? Why and when should we use it? And the most important question, does django session store data on the server-side or client-side using cookie? -
How do i group all expenses of the same category in django?
I am new to Django and trying to group and retrieve all expenses of the same category together and retrieve them in one "link like" table raw which when clicked can then display all the expenses in that category in another form. I have these Models: class Category(models.Model): name = models.CharField(max_length=50) class Meta: verbose_name_plural = 'Categories' unique_together = ("name",) def __str__(self): return self.name class Expense(models.Model): amount = models.FloatField() date = models.DateField(default=now, ) description = models.TextField() owner = models.ForeignKey(to=User, on_delete=models.CASCADE) category = models.CharField(max_length=50) def __str__(self): return self.category class Meta: ordering = ['-date', '-pk'] homeView: def home(request): categories = Category.objects.all() expenses = Expense.objects.filter(owner=request.user) paginator = Paginator(expenses, 5) page_number = request.GET.get('page') page_obj = Paginator.get_page(paginator, page_number) currency = UserPreference.objects.filter(user=request.user) # .currency query = Expense.objects.values('category').annotate(total=Sum( 'amount')).order_by('category') context = { 'expenses': expenses, 'page_obj': page_obj, 'currency': currency, 'query': query } return render(request, 'expenses/home.html', context) mytemplate: <div class="app-table"> <table class="table table-stripped table-hover"> <thead> <tr> <th>Amount</th> <th>Category</th> <th>Description</th> <th>Date</th> <th></th> </tr> </thead> <tbody> {% for myquery in query %} <tr class="clickable-row" data-href="https://www.mavtechplanet.com/"> <td>{{myquery.category }}</td> </tr> {% endfor %} </tbody> </table> </div> I am trying to figure out things but are not coming out clearly. Any help is highly appreciated. -
django text form view error 'User' referenced before assignment
i have this view that has 3 forms a form for the signin and one for the signup and the other one is for posting a text as a post where this text is saved to the database here is my views.py file from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout as django_logout from django.contrib import messages from django.urls import reverse from .models import * from .forms import * def home(request): user = request.user # for rendering texts text_form = TextForm() signin_form = SigninForm() signup_form = SignupForm() if request.method == "POST": if 'text_form' in request.POST: text_form = TextForm(request.POST) if text_form.is_valid() and request.user.is_authenticated: user = request.user obj = text_form.save(commit=False) author = User.objects.filter(email=user.email).first() obj.author = author text_form.save() if 'signin_form' in request.POST: signin_form = SigninForm(request.POST) if signin_form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user: login(request, user) elif user is None: messages.error(request, 'ُEmail or password is incorrect') if 'signup_form' in request.POST: signup_form = SignupForm(request.POST) if signup_form.is_valid(): User = signup_form.save() full_name = signup_form.cleaned_data.get('full_name') email = signup_form.cleaned_data.get('email') raw_password = signup_form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) texts = Text.objects.all().order_by('-id') context = {'signin_form': signin_form,'signup_form': signup_form,'text_form': text_form,'texts': texts} return render(request, 'main/home.html', context) in my models.py #the text model class Text(models.Model): … -
Class Style not working on Django Template
I'm trying to color the background of readonly input text in my Django templates. I'm being brief in code because the only thing is not working is the color background. I'm using the field 'rua' as the example. Maybe the problem is with the link of 'my own css' inside the base.html. My forms.py: 'rua': forms.TextInput(attrs={'readonly': 'readonly', 'id': 'rua', 'class': 'readonly'}), My template: {% extends "base.html" %} {% load static %} {% block content %} <script src="https://cdn.rawgit.com/igorescobar/jQuery-Mask-Plugin/master/src/jquery.mask.js"></script> <!-- customer login start --> <div class="customer_login"> <div class="container"> <div class="row"> <!--register area start--> <div class="col-lg-6 col-md-6 mx-auto"> <div class="account_form register"> {% if register_edit == 'register' %} <p>{{ msg }}</p> <h2>Não tem conta? Registre-se!</h2> <form method="post" action="{% url 'account:register' %}"> {% else %} <h2>Altere os dados da sua conta</h2> <form method="post" action="{% url 'account:edit' %}"> {% endif %} {% csrf_token %} <div>{{ user_form.as_p }}</div> <div>{{ profile_form.as_p }}</div> <p><button type="submit">Enviar</button></p> </form> </div> </div> <!--register area end--> </div> </div> </div> <!-- customer login end --> <script src="{% static 'js/cadastro.js' %}" type="text/javascript"></script> {% endblock %} My base.html {% load static %} <!doctype html> <html class="no-js" lang="pt-br"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>Denise Andrade - Store</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Favicon --> … -
linking class to another automatically
i have this class class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=200) def __str__(self): return self.name i want the User class to be linked to customer.user automatically once a User is created is there a way to do that? -
AttributeError at /cart/ 'NoneType' object has no attribute 'price'
I'm working on a e-commerce site, I wanted to change the products that I previously had. I went into the admin site and uploaded the new products you see in the photo. Once I saw everything was working I decided to delete 6 old products through the admin page. I then went to my cart and got this error, I'm confused why I'm getting this error with new products and not my original products site with new products error yellow page def cart(request): # check authenticated user data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items': items, 'order': order, 'cartItems': cartItems} return render(request, 'store/cart.html', context) -
Haystack + Solr + Django range faceting
I am using Django-Haystack with Solr(6x) backend in attempt to add faceted search to my application. I hit a problem, since I cannot find a way to implement range faceting. My query looks like this (looking at solr documentation): class FacetedProductSearchForm(FacetedSearchForm): def no_query_found(self): return SearchQuerySet().facet('price', range_filed='price', range_start=0, range_end=1000, range_gap=50, mincount=1, limit=10).all() My expectation of the results would be something like this: 0-50 (3) 50-100 (2) 100-150 (4) ... But what I get is still just a count of products not grouped in ranges but just a count of specific prices: 114 (2) 165 (3) 250 (3) ... *(sample values dont add together, this is just to demonstrate the point) In my template, I simply iterate over facets. {% if facets.fields.price %} <dt>Price</dt> {% for price in facets.fields.price|slice:":5" %} <dd> <a href="{{ request.get_full_path }}?selected_facets=price_exact:{{ price.0|urlencode }}">{{ price.0 }}</a> ({{ price.1 }}) </dd> {% endfor %} {% endif %} How can I implement range faceting in this scenario, using haystack and solr? -
django template tags nested if statment error
I have a sign up form and i want the user when clicks submit the invalid fields borders becomes red with my "danger-borders" class and an error message appears under it , in order to do that i used django template tags but it gave an error saying Invalid block tag on line 88: 'else', expected 'empty' or 'endfor'. Did you forget to register or load this tag? i double checked but everything seem ok here is the code: {% if signup_form.errors %} {% for field in signup_form %} {% if field.errors %} <input type="text" class="danger-borders" name="{{field}}" > <p class="text-danger ml-2">{{ field.errors | striptags }}</p> {% elif not field.errors %} {{field}} {% endif %} {% elif not signup_form.errors %} {% field %} {% endfor %} {% endif %} also i'm not sure that this is how to check if the errors doesn't exist in those two lines "{% elif not signup_form.errors %}" and "{% elif not field.errors %}" -
Django: Cannot assign string: class must be a class instance
This is my first Django's page. I know that it exists many reported problems like this but I haven't found the correct answer. I have a database that I can show perfectly, and I wannna allow to users to add new entries. models.py class Server(models.Model): client = models.ForeignKey(settings.AUTH_USER_MODEL, null=False, blank=False, on_delete=models.CASCADE) name = models.CharField(primary_key=True, max_length=20) ip = models.CharField(max_length=13) class Usuario(models.Model): id = models.AutoField(primary_key=True) servidor = models.ForeignKey(Server, null=False, blank=False, on_delete=models.CASCADE) correo = models.EmailField() fpago = models.DateField('Fecha de pago', auto_now_add=True) And views.py @login_required(login_url='login/') def suscripciones(request): obj_usuarios = Usuario.objects.all() if request.method == 'POST': servidor = request.POST.get('servidor') correo = request.POST.get('correo') consulta = Usuario(servidor=servidor, correo=correo) consulta.save() return render(request, 'APP/suscripciones.html', {'obj_usuarios': obj_usuarios}) The model works when without the request.method and consulta but with this code I get this error: Cannot assign "(string with the server's name)": "Usuario.servidor" must be a "Server" instance. Thanks so much. -
Pass arrays from django to js with ajax
I'm trying to pass 2 arrays via ajax from my views to my javascript. When I console.log my arrays i get 2 empty ones. I feel like I know what the error is but I can't solve it. I'm going to include my code first, than my toughts. views.py: In my first method, I want to pass my data to 2 arrays (dates,weights). In get_data is where I want to send my data to js. from django.shortcuts import render from django.contrib import messages from django.contrib.auth.models import User from django.http import JsonResponse from django.shortcuts import get_object_or_404 from users import models from users.models import Profile from .forms import WeightForm import json dates = [] weights = [] dates_queryset = [] def home(request): form = WeightForm() if request.is_ajax(): profile = get_object_or_404(Profile, id = request.user.id) form = WeightForm(request.POST, instance=profile) if form.is_valid(): form.save() return JsonResponse({ 'msg': 'Success' }) dates_queryset = Profile.objects.filter(user=request.user) dates = dates_queryset.values_list('date', flat=True) weights = dates_queryset.values_list('weight', flat=True) return render(request, 'Landing/index.html',{'form':form}) def get_data(request, *args,**kwargs): data = { 'date': dates, 'weight': weights } return JsonResponse(data) url: url(r'^api/data/$', get_data, name='api-data'), Ajax call: var endpont = '/api/data' $.ajax({ method: 'GET', url: endpont, success: function(data){ console.log(data); }, error: function(error_data){ console.log("Error"); console.log(error_data); } }) Js console.log output: {date: Array(0), … -
How can I see a translation in my website
I am currently working on my website, which is a translator which you input a phrase and it gets translated into an invented language. Here's the code of the translator function: def translator(phrase): translation = "" for letter in phrase: if letter.lower() in "a": if letter.isupper: translation = translation + "U" else: translation = translation + "u" elif letter.lower() in "t": if letter.isupper: translation = translation + "A" else: translation = translation + "a" elif letter.lower() in "c": if letter.isupper: translation = translation + "G" else: translation = translation + "g" elif letter.lower() in "g": if letter.isupper: translation = translation + "C" else: translation = translation + "c" return translation However, I am stuck in showing this funcion in my web, here's the code in views.py: from .translate import translator def translator_view(request): return render(request,'main/translator.html') def translated_view(request): text = request.GET.get('text') print('text:', text) translate = translator dt = translator.detect(text) tr = translated.text context = { 'translated': tr } return render(request, context, 'main/translated.html') Here's the template where you introduce the text: <form action="{% url 'translated' %}" method= "get"> <div class="form-group"> <center><h2 class = "display-3">TRANSLATE YOUR DNA CHAIN</h2></center> <br> <br> <textarea class="form-control" id="exampleFormControlTextarea1" rows="6"></textarea> <br> <button type='Submit' class= "btn btn-primary btn-lg btn-block">Translate</button> </div> </form> … -
How to pass a url parameter into the views to be used by other class functions and the template
Please I have a serious problem that has left me with all kinds of errors for days. There are some functionalities I want to implement but don't know how to. Any help would be greatly appreciated. I want to create a register form that registers a user and sends them to their profile page after they have registered. I tried doing this by trying to pass the username the user filled in the form into the urls argument for my profile view. However, I don't know exactly how to do this and each code I find online only leads me to error. I am new to django. In addition to this, I want to create my profile view such that if a user searches their own template, then they can edit it, I used UpdateView for this and if it is not their profile then they can only view it as read only, I used the detailView for this. Also, please can someone also help me understand how to pass a url parameter into a class based view, how can all the functions in the view access this parameter. How can I use a variable from a function in a … -
How to Reformat the value of serializable django response?
I am newbie to django. I was following the following tutorial enter link description here All the steps are doing good. Suppose I have the following code from snippets.models import Snippet from snippets.serializers import SnippetSerializer from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser snippet = Snippet(code='foo = "bar"\n') snippet.save() serializer = SnippetSerializer(snippet) serializer.data I get the following output {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'foo: u'bar'....} I want to return back the just created data in the database (from the api) to the client. So, my question are: What is the best strategy to do that?I mean in the views what I should do. If i want for example the return data has the following format { "answer": "data saved:<bar>, 'pk': 2 } -
Django modify Many to Many relation
I have 4 Tables as follows: class Problem(models.Model): id = ... description = ... # A problem will have multiple languages class Language(models.Model): id = ... language = ... problem = models.ForeignKey(Problem, null=False, on_delete=models.CASCADE) # test table. Each test will have multiple problems class Test(models.Model): id = ... title = ... problems = models.ManyToManyField(Problem, through='testProblemRelation') below table defines the relation between Test and Problem. Here I want to define a field "allowed_languages" which will control the relationship between Problem table and language table only for a given test instance without affecting the general relationship between the problem language class TestProblemRelation(models.Model): problem = models.ForeignKey(Problem, on_delete=models.CASCADE) test = models.ForeignKey(Test, on_delete=models.CASCADE) allowed_languages = models.JsonField(...) # languages which are allowed for each problem. #field will contain multiple problem ids and a list of language ids associated to each problem id . What to write here??? For example a problem 'Shortest Path' has 3 languages related to it which are C,C++ and Java. I use a post api to create a test such that it contains 'Shortest Path' problem with only java language related to it. However the problem outside this test should still have all 3 languages. I am not getting any idea on … -
Colapsable Button Bootstrap Django
I'm trying to create a social media news feed, with the posts, but I dont want to show the comments just if the user presses the button Show Comments. The problem is that when I press the button of one post, all the post will extend comments. I don't really know how to solve this... {% for post in posts %} <div class="container"> <div class="row"> <div class="[ col-xs-12 col-sm-offset-1 col-sm-5 ]"> <div class="[ panel panel-default ] panel-google-plus"> <div class="panel-heading"> <img class="[ img-circle pull-left ]" width="50" height="50" src="{{post.author.profile.image.url}}" alt="Mouse0270" /> <h3 class="author">{{post.author}}</h3> <h5><span>Shared publicly</span> - <span><a href="{% url 'post-detail' post.id %}"> {{post.date_posted}} </a></span> </h5><br> </div> <div class="panel-body"> {% if user == post.author %} <a class="text-right" href="{% url 'post-update' post.id %}"><p>Update</a> <a class="text-danger text-right" href="{% url 'post-delete' post.id %}">Delete post</a> {% endif %} <p>{{post.content}}</p> {% if post.image %} <img src ="{{post.image.url}}" width="300" height="300" border="0" class="img-thumbnail"> {% endif %} {% if post.video %} <video width="250" controls > <source src="{{post.video.url}}" type="video/mp4" > </video> {% endif %} </div> <br/> <div class="container" > <a href="{% url 'add-comment' post.id %}"><button class="btn btn-primary">Add comment</button></a> </div> <br> <button type="button" class="btn btn-danger btn-block" data-toggle="collapse" data-target="#demo">See comments</button> <div id="demo" class="collapse"> {% for comment in post.comments.all %} <div class="container"> <div class="row"> <div … -
Unique email verification to social-django
I have this webapp that has three login options (the normal method, google, facebook). The email is defined as unique, so I put this verification in the normal method, but I don't have that in the Facebook and gmail login methods, so when I log in to Google and try to log in to Facebook, it gives an error because it is the same email. I used AbstractUser to create a new user model. The error: How can i fix this? i want to show a error message on the login with the django messages if possible -
wrong response format django-rest-framework
iam creating a music web app using react-redux and django and i have function that returns single playlist it returns html response instead of json knowing that its working right when the two apps are seperated but when iam using django routs as my main routs and react like an interface only using this line: urlpatterns += re_path(r'', TemplateView.as_view(template_name='index.html')), here is my function **django** class getplaylist(APIView): renderer_classes = [JSONRenderer] def get(self,request): id=request.META.get('HTTP_ID',None) plst=playlist.objects.get(id=id) return Response(plst) **react** export const getPlaylist=(id)=>{ return dispatch=>{ dispatch(getPlaylistStart()) axios.get('http://127.0.0.1:8000/songs/getplaylist/',{headers:{ 'id':id}}) .then(res=>{ console.log(res); dispatch(getPlaylistSuccess(res.data)) }) } } and this is the response playlist(pin):"<!doctype html><html lang="en"><head><meta charset="utf-8"/><link rel="icon" href="/favicon.ico"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><meta name="description" content="Web site created using create-react-app"/><link rel="apple-touch-icon" href="/logo192.png"/><link rel="manifest" href="/manifest.json"/><title>Songs App</title><link href="/static/css/2.3327982c.chunk.css" rel="stylesheet"><link href="/static/css/main.18cf81d6.chunk.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><script>!function(e){function r(r){for(var n,f,l=r[0],i=r[1],a=r[2],c=0,s=[];c<l.length;c++)f=l[c],Object.prototype.hasOwnProperty.call(o,f)&&o[f]&&s.push(o[f][0]),o[f]=0;for(n in i)Object.prototype.hasOwnProperty.call(i,n)&&(e[n]=i[n]);for(p&&p(r);s.length;)s.shift()();return u.push.apply(u,a||[]),t()}function t(){for(var e,r=0;r<u.length;r++){for(var t=u[r],n=!0,l=1;l<t.length;l++){var i=t[l];0!==o[i]&&(n=!1)}n&&(u.splice(r--,1),e=f(f.s=t[0]))}return e}var n={},o={1:0},u=[];function f(r){if(n[r])return n[r].exports;var t=n[r]={i:r,l:!1,exports:{}};return e[r].call(t.exports,t,t.exports,f),t.l=!0,t.exports}f.m=e,f.c=n,f.d=function(e,r,t){f.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:t})},f.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},f.t=function(e,r){if(1&r&&(e=f(e)),8&r)return e;if(4&r&&"object"==typeof e&&e&&e.__esModule)return e;var t=Object.create(null);if(f.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var n in e)f.d(t,n,function(r){return e[r]}.bind(null,n));return t},f.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return f.d(r,"a",r),r},f.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},f.p="/";var l=this.webpackJsonpfrontend=this.webpackJsonpfrontend||[],i=l.push.bind(l);l.push=r,l=l.slice();for(var a=0;a<l.length;a++)r(l[a]);var p=i;t()}([])</script><script src="/static/js/2.25085612.chunk.js"></script><script src="/static/js/main.dc42ca8e.chunk.js"></script></body></html>" -
How to show django form in bootstrap modal
I have a model called Folder and with this model i have CreateView, for that i have created a folder_form.html file. So right now if a user want to create folder they have to click on the click folder button on the homepage, the folder_form.html page will load. What i want to achieve is that load this form on the homepage inside a Bootstrap Modal instead of loading a new page.I tried doing this but it doesn't worked. **views.py** import requests from django.shortcuts import render from django.views.generic.base import TemplateView from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required from django.views.generic.list import ListView from ahmed_drive.models import Folder, Fileshare from . import models from django.views.generic.detail import DetailView from django.db.models import Q from django.views.generic.edit import UpdateView, CreateView, DeleteView from django.http.response import HttpResponseRedirect #### Normal Pages Related Views #### class HomeView(TemplateView): template_name = "ahmed_drive/home.html" #### Pages Related Folder Model #### @method_decorator(login_required, name="dispatch") class FolderCreate(CreateView): model = Folder fields = ["name", "parent"] def formvalid(): if form.is_valid(): form.save() return redirect('home.html') else : return render(request,{'form': form}) folder_form.html {% extends 'base.html' %} {% block content %} {% load crispy_forms_tags %} <main class="p-5"> <div class="row"> <div class="col-sm-6 offset-sm-3"> <h1 class="myhead2">Create Folder</h1> <hr> <form enctype="multipart/form-data" method="post"> {% csrf_token %} {{form | …