Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to put responses in an array (DICT in LIST)
Here is the response that I want to have: [ { "id": "e27509e4-0abf-4747-be65-862d6d4092b0", "name": "Price 20200826", "description": "Price 20200826", "is_default": "True" }, { "id": "36484103-cf76-47eb-8bfb-d5c281a5ec04", "name": "price_20200922", "description": "Price 20200922", "is_default": "False" } ] I did this: query = B2CPriceGroup.objects.all().values('id', 'name', 'description', 'is_default') return HttpResponse(query) Got this (not in an array) {'id': UUID('e27509e4-0abf-4747-be65-862d6d4092b0'), 'name': 'Price 20200826', 'description': 'Price 20200826', 'is_default': True} {'id': UUID('36484103-cf76-47eb-8bfb-d5c281a5ec04'), 'name': 'price_20200922', 'description': 'Price 20200922', 'is_default': False} query = B2CPriceGroup.objects.all().values('id', 'name', 'description', 'is_default') return JsonResponse(query, safe = False) Got this TypeError: Object of type QuerySet is not JSON serializable When I did this query = [B2CPriceGroup.objects.all().values('id', 'name', 'description', 'is_default')] return HttpResponse(query) I got this (seem not to be JSON type) <QuerySet [{'id': UUID('e27509e4-0abf-4747-be65-862d6d4092b0'), 'name': 'Price 20200826', Please help, It is necessary to output the exact the same format. -
SOAP how to resolve Requested resource not found?
I have to pass that request to my SOAP server, everything is working without: xmlns="urn:soap_server". I am not sure how to pass that thing threw ny request. Do you have any suggestions? It is my first time with SOAP and I don't know what even that urn exactly is. <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <ota_soap_authorize xmlns="urn:soap_server"> <Code>xxxxx</Code> </ota_soap_authorize> </soap:Body> </soap:Envelope> Python code: from django.views.generic import DetailView # views.py from django.views.decorators.csrf import csrf_exempt from spyne import Unicode, Iterable, XmlAttribute, ComplexModel, \ ServiceBase, Application, rpc, srpc, String from spyne.protocol.soap import Soap11 from spyne.server.django import DjangoApplication NS_B = 'http://www.w3.org/2001/XMLSchema-instance/' class Baz(ComplexModel): __namespace__ = NS_B Thing = Unicode AttrC = XmlAttribute(Unicode) class FooCustomRequest(ComplexModel): AttrA = XmlAttribute(Unicode) AttrB = XmlAttribute(Unicode) Bar = Baz.customize(sub_ns=NS_B) Baz = Unicode class SomeClass(ComplexModel): Code = Unicode class FooService(ServiceBase): @rpc(SomeClass, _returns = Iterable(Unicode), _body_style='bare') def ota_soap_authorize(ctx, req): print(req) print(req.Code) yield 'Hello' soap_app = Application( [FooService], tns='https://www.w3.org/2001/XMLSchema/', in_protocol=Soap11(validator='soft'), out_protocol=Soap11(), ) django_soap_application = DjangoApplication(soap_app) my_soap_application = csrf_exempt(django_soap_application) -
how to write queryset in django for left join with foreign key?
I am trying to write a queryset for two tables in django using left join. Please refer following query which I need to run on django SELECT A.field1, A.field2, B.field2, B.field3 FROM table1 as A LEFT JOIN table2 as B ON A.field1 = B.field2 >>> Foreign key WHERE A.field2 = "xyz" -
Django. How do I add a field to a query?
I have a Room model and I want to add the is_member boolean field to a queryset with rooms. How can i do this? I was thinking of using .annotate (), but that doesn't work for my task. models.py class Room(models.Model): name = models.CharField(max_length=150) members = models.ManyToManyField(User, blank=True) I present the solution like this: rooms = Room.objects.all() user = request.user for room in rooms: members = room.members.all() is_member = user in members user.is_member = is_member Help me please -
Creating Multiple Objects with the Same Uploaded File in Django
I am trying to create an attachment for a ticket and this attachment should be able to created for multiple customers. But when you get the uploaded file and create an object with it, Django automatically close the file. So, it gives I/O operation on closed file error and I can't create another object with that file. Is there any way of doing this? models.py class Customer(models.Model): name = models.CharField(max_length=123) class Ticket(models.Model): ticket_name = models.CharField(max_length=123) customer = models.ForeignKey(Customer, related_name="c", on_delete=models.CASCADE) class Attachment(models.Model): file_name = models.CharField(max_length=123) content = models.FileField(upload_to=/somewhere) ticket = models.ForeignKey(Ticket, related_name="ticket_attachment", on_delete=models.CASCADE,) views.py from models import Customer, Ticket, Attachment class MyView(generic.FormView): def form_valid(self, form): myFile = self.request.FILES.get('attachment') for customer in form.cleaned_data["customer"]: ticket = Ticket.objects.create(ticket_name=form.cleaned_data.get("ticket_name"),customer=customer) Attachment.objects.create(file_name=myFile._name, content=myFile, ticket=ticket) return super().form_valid(form) -
Microservice System Design in Practice (Django) [closed]
I've been learning about system design and came across the microservice architecture. For example, consider an eCommerce platform with the 4 microservices: Search Product list Payment Shipping How would this system design turn into an actual coded product? Would you have 4 APIs (search.website.com/api, product-list.website.com/api, etc.)? In Django, would each of these be separate Django projects? Thanks!! -
Django jsonfield, is it possible to filter with json array value length?
Suppose I have a jsonfield with data json_field = { 'bar': [1,2,3,4] } I'd like to filter data where bar has array length greather than 3 Something like the following, Foo.objects.filter(json_field__bar__length__gt=3) -
Should I use action in the login form templated?
I want to know that if I am using the action in login.html <form > tag and if not using it, In both cases all is good. I am able to successfully login and if there is any error, my views.py showing the respective errors. I think after rendering the template the django automatically send the data back to user_login function in views.py without specifying the action attribute to the <form > tag. I just want to know that when do I need to use action attribute in the <form > tag in django template. My urls.py from django.urls import path from . import views # TEMPLATE URLS! app_name = 'basic_app' urlpatterns = [ path('register/', views.register, name='register'), path('user_login/', views.user_login, name='user_login'), ] views.py def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('index')) else: return HttpResponseRedirect("ACCOUNTS NOT ACTIVE") else: print("Someone tried to login and failed!") print("Username: {} and password: {}".format(username, password)) return HttpResponse("Invalid login details supplied!") else: return render(request, 'basic_app/login.html', {}) login.html {% extends 'basic_app/base.html' %} {% block body_block %} <div class="jumbotron"> <h1>Please Login!</h1> <form method="post" action="{% url 'basic_app:user_login' %}"> {% csrf_token %} <label for="username">Username:</label> <input type="text" … -
Get user profile picture in Microsoft Graph
I would like to retrieve my profile picture using python and display it on profiles.html Here is what I have tried: profiles.html: {% extends "tutorial/layout.html" %} {% block content %} <h1>Profile</h1> <img id="test" src="data:image/gif;base64,{{output_image}}" alt="profile"> {% endblock %} graph_helper.py def get_profiles(token): graph_client = OAuth2Session(token=token) profiles = graph_client.get(f"{graph_url}/me/photo/$value", stream=True) return profiles.raw.read() views.py def profiles(request): token = get_token(request) profiles = get_profiles(token) return render(request, 'tutorial/profiles.html', {"output_image": profiles}) However I receive an error code This site can’t be reachedThe web page at data:image/gif;base64,b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00\x00\x00\x00\xff\xdb\x00C\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\t\t\x08\n\x0c\x14\r\x0c\x0b\x0b\x0c\x19\x12\x13\x0f\x14\x1d\x1a\x1f\x1e\x1d\x1a\x1c\x1c $.' ",#\x1c\x1c(7),01444\x1f'9=82<.342\xff\xdb\x00C\x01\t\t\t\x0c\x0b\x0c\x18\r\r\x182!\x1c!22222222222222222222222222222222222222222222222222\xff\xc0\x00\x11\x08\x01\x00\x00\xc9\x03\x01"\x00\x02\x11\x01\x03\x11\x01\xff\xc4\x00\x1f\x00\x00\x01\x05\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\xff\xc4\x00\xb5\x10\x00\x02\x01\x03\x03\x02\x04\x03\x05\x05\x04\x04\x00\x00\x01}\x01\x02\x03\x00\x04\x11\x05\x12!1A\x06\x13Qa\x07"q\x142\x81\x91\xa1\x08#B\xb1\xc1\x15R\xd1\xf0$3br\x82\t\n\x16\x17\x18\x19\x1a%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz\x83\x84\x85\x86\x87\x88\x89\x8a\x92\x93\x94\x95\x96\x97\x98\x99\x9a\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xe1\xe2\xe3\xe4\x...(+more characters) might be temporarily down or it may have moved permanently to a new web address. ERR_INVALID_URL> -
Im trying to deploy my Django/ python project onto heroku.com
The application works perfectly on local hosting but when I log into my website or try to make an account, it gives me this error. Environment: Request Method: POST Request URL: Django Version: 3.1.3 Python Version: 3.8.6 Installed Applications: ['learning_logs', 'users', 'bootstrap4', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Traceback (most recent call last): File "/app/.heroku/python/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... ^ ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/views/decorators/debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/auth/views.py", line 63, in dispatch return super().dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/views/generic/base.py", line 98, in … -
Convert Remote HTML tempalte to PDF in django
I am trying to convert HTML(hosted on a remote server) to pdf and then save in the Django model. what I tried till now. def convert_html_to_pdf(template, context, filename): response = requests.get(template) template = Template(response.content) html = template.render(Context(context)) f = NamedTemporaryFile() f.name = '/' + user + '/' + str(filename) pdf = pisa.pisaDocument(BytesIO(template.encode('UTF-8')), f) if not pdf.err: return File(f) return False file = pdf_docs.convert_html_to_pdf( template='https://www.example.com/sample.html', context={'name': 'John Smith'}, filename='example.pdf', ) In response, only the template URL is printed on PDF, not the content. -
I want to get only customer id but getting whole customer information
I am trying to show orders by customer id by i am getting this error : TypeError at /orders Field 'id' expected a number but got {'id': 3, 'phone_number': '01622153196', 'email': 'sakibovi@gmail.com', 'password': 'pbkdf2_sha256$216000$H2o5Do81kxI0$2tmMwSnSJHBVBTU9tQ8/tkN7h1ZQpRKrTAKkax1xp2Y=', 'coin': 1200.0}. Actually i want to fetc only customer id but getting whole dictionary. Here in Login Class in views.py i fetch whole customers info like this request.session['customer'] = customer.__dict__ Here is the details : class Login(View): def get(self, request): return render(request, 'signupsignin/signin.html') def post(self, request): phone_number = request.POST.get('phone_number') password = request.POST.get('password') customer = Customer.get_customer(phone_number) error_message = None if customer: match = check_password(password, customer.password) if match: customer.__dict__.pop('_state') request.session['customer'] = customer.__dict__ # request.session['customer'] = customer.id #request.session['customer'] = customer.coin #request.session['phone_number'] = customer.phone_number return redirect('Home') else: error_message = 'Phone number or Password didnt match on our record' else: error_message = 'No Customer Found! Please Registrer First!' print(phone_number, password) context = {'error_message':error_message} return render(request, 'signupsignin/signin.html', context) I think for that reason i am getting the whole informaton of a customer Here is my Views.py for userorders by customer id :: class UserOrders(View): def get(self, request): customer = request.session.get('customer') user_orders = Order.get_orders_by_customer(customer) print(user_orders) args = {'user_orders':user_orders} return render(self.request, 'Home/all_orders.html', args) Here i have a method named get_orders_by_customer() i made this in … -
How can I pass a url parameter to django-tables2?
I have a small app with players and teams. The models are: class Player(models.Model): player_name = models.CharField(max_length=200) position = models.CharField(max_length=200) assigned_team = models.ForeignKey('Team', on_delete=models.SET_NULL, blank=True, null=True) class Team(models.Model): team_name = models.CharField(max_length=200) team_description = models.CharField(max_length=200) This is all working quite well. I have views that obtain querysets that get rendered with django-tables2. I have tables to show all teams, and all players. What I am trying to do is make a table showing all players on a team, and I have not found a way to do that. I want to pass a url parameter (so the address could be something like /viewteam/2), and have this obtain all the players where players.team.id == urlid. I can deal with the URL parameter in the view, but can't see any way to pass it on to the table defined in tables.py What is the right approach for this problem? I know how to pass url parameters to class and function based views -
django.db.migrations.exceptions.NodeNotFoundError when running the server in command prompt
i'm running with this error when running a server. I changed my code directory name before and so earlier i faced the running problem as well. However, it's fixed after changing the name as well in the settings.py, manage.py, and others that might have the old name. I also install the Django, pillow, and psycopg2 again because it told me when trying to run the server in the command prompt. Now, i faced this problem. It says that. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\karen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\karen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check_migrations() File "C:\Users\karen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\base.py", line 459, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\karen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "C:\Users\karen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\migrations\loader.py", line 53, in init self.build_graph() File "C:\Users\karen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\migrations\loader.py", line 255, in build_graph self.graph.validate_consistency() File "C:\Users\karen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\migrations\graph.py", line 195, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\karen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\migrations\graph.py", line 195, in [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\karen\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\migrations\graph.py", line 58, in raise_error … -
ATOMIC_REQUESTS (Django's) equivalent for Flask-SqlAlchemy
My goal is to handle 1 web request that might require 30 to 50 queries/statements under the same transaction and finish it with db.session.commit() This is commonly referred to as ATOMIC_REQUESTS in Django. My problem is that in the course of handling the request, the ORM makes Select Queries. And invariably it calls the Rollback after each Select. SELECT * from table WHERE id = 1 -- INFO sqlalchemy.engine.base.Engine ROLLBACK I've found out that the rollbacks, as the name implies, roll-back the previous channels. So my goal is to be able to work with "ATOMIC REQUESTS" (be able to use 1 transaction for the entire life-cycle of the request) Database: PostgreSQL -
django-ckeditor: How to apply widget to dynamically added forms?
I have a page to edit closed captions in which I am using model formsets (the part of importance here is the text). Originally, I was able to add and remove forms from the formset successfully but, now that I am using django-ckeditor to allow the user to add format to the text, this is not working. This dynamic handling of forms is a bit more complex than the common case, because I need to add and remove forms in between other forms keeping the order, and some may be hidden/marked for deletion. For adding forms, what I do is clone the form that's right next to the insertion point, clear its contents, insert it, and then loop over the subsequent forms to change relevant indexes, which, as I said, worked great. I tried the exact same thing after using django-ckeditor, of course, modifying the new and appropriate element attributes that django-ckeditor added, but I don't think this is the right way to do it. First, there are events related to several elements created by django-ckeditor, that I can't just apply to the clones, and second, the iframe that contains the html document with the text is an actual whole … -
Pre selected in HTML based on context in django template
I need to display a select input field with fixed option <select multiple> <option > area</option> <option > city</option> <option > project</option> <option > address</option> <option > item3</option> <option > item4</option> <option > anotheritem</option> <option > otheritem</option> <option > lastitem</option> <option > itemrandom</option> </select> And I am passing a list in the context which will have item as (area, address, city) one or more or all. I want the option to be pre-selected if any of the value of the options is present in the passed context list. The html page will be rendered from a django view. Using a form is not preferable. -
How to implement Django REST with React
How can I make react scripts properly served from Django? I mean that I want that react will be served from Django view and not separately. what is the best practice for gluing them up together? I need it because I'm developing a Shopify app and in the installation process, the Shopify platform sends a request to my app and waiting for a response in some cases, and right now it's sending it to static react files which not responding as needed. -
Count the number of Likes received by a user for all his posts - Django
I am trying to get the total number of likes given to a user which is in my case the author of the post. I have commented my trial as it didn't work. Here is the models.py class Post(models.Model): title = models.CharField(max_length=100, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author') likes = models.ManyToManyField(User, related_name='liked', blank=True) Here is the views.py that I have tried def total_likes_received(request): total_likes_received = Post.likes.filter(author=request.user).count() return render(request, 'blog/post_detail.html', {'total_likes_received': total_likes_received}) My question is: How to get the total number of likes given for all the posts given to a particular author -
Django,'GET' and'DELETE' are authenticated, but'POST' and'PATCH' are not
First of all, I can't speak English well. test1 account permissions.py (DjangoModelPermissions) class CustomPermissions(permissions.BasePermission): perms_map = { 'GET': ['%(app_label)s.view_%(model_name)s'], 'OPTIONS': [], 'HEAD': [], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } authenticated_users_only = True def get_required_permissions(self, method, model_cls): kwargs = { 'app_label': model_cls._meta.app_label, 'model_name': model_cls._meta.model_name } if method not in self.perms_map: raise exceptions.MethodNotAllowed(method) return [perm % kwargs for perm in self.perms_map[method]] def _queryset(self, view): assert hasattr(view, 'get_queryset') \ or getattr(view, 'queryset', None) is not None, ( 'Cannot apply {} on a view that does not set ' '`.queryset` or have a `.get_queryset()` method.' ).format(self.__class__.__name__) if hasattr(view, 'get_queryset'): queryset = view.get_queryset() assert queryset is not None, ( '{}.get_queryset() returned None'.format(view.__class__.__name__) ) return queryset return view.queryset def has_permission(self, request, view): if getattr(view, '_ignore_model_permissions', False): return True if not request.user or ( not request.user.is_authenticated and self.authenticated_users_only): return False queryset = self._queryset(view) perms = self.get_required_permissions(request.method, queryset.model) return request.user.has_perms(perms) view.py from rest_framework import viewsets, permissions, generics from .serializers import PlayerListSerializer from .models import PlayerList from .permission import CustomPermissions class ListPlayer(generics.ListCreateAPIView): permission_classes = [CustomPermissions, ] queryset = PlayerList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = PlayerListSerializer class AddListPlayer(generics.ListCreateAPIView): permission_classes = [CustomPermissions, ] queryset = PlayerList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = PlayerListSerializer class DetailPlayer(generics.RetrieveUpdateDestroyAPIView): permission_classes = [CustomPermissions, ] queryset = PlayerList.objects.all() serializer_class = PlayerListSerializer … -
Django - Parsing SQL Querys to QuerySet
I'm a beginner with Django and Python but I need some help to parse my sql query to Django query set. I have a database which contains a table called "Temperatura". Models: from django.db import models from datetime import datetime Create your models here. class Temperatura(models.Model): data = models.DateField(default=datetime.now, unique=True) maxima = models.DecimalField(max_digits=5, decimal_places=2) minima = models.DecimalField(max_digits=5, decimal_places=2) estacao = models.CharField(max_length=9) def __str__(self): return str(self) I'd like to make this sql query: select estacao, (avg(maxima) + avg(minima))/2 as TempMedia, max(maxima) as maxima, min(minima) as minima from Temperatura group by estacao -
How to pass dyanmic url to another template in django
I want to create a template that receives a 'link_url' variable and I want to pass it a dynamic URL, like this one: {% url "app:genericlistmodel" model="model_handle" %}. This way I could modularize this template and save a lot of time. Things I've tried that are not working: {% include 'snippet.html' with link_url={% url "gepian:genericlistmodel" model="entrepreneurs" %} %} {% url "gepian:genericlistmodel" model="entrepreneurs" %} {% include 'snippet.html' with link_url=url %} {% include 'snippet.html' with link_url=url "gepian:genericlistmodel" model="entrepreneurs" %} Thanks :) -
Django, allauth "accounts/login" returns wrong email/password on ASANA sign in
created a client_id, secret on asana's side and inserted those as a provider to socialapp then make the changes on settings.py INSTALLED_APPS = [ 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.asana', ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) # auth and allauth settings LOGIN_REDIRECT_URL = '/' SOCIALACCOUNT_QUERY_EMAIL = True ACCOUNT_ADAPTER = "allauth.account.adapter.DefaultAccountAdapter" And urls.py path('accounts/', include('allauth.urls')), But when I go to accounts/login and try to sign in it still returns wrong email/password. Do I missing something here? -
Django on Heroku: ProgrammingError at / relation "theblog_category” does not exist
I already read those other Django Heroku questions and I'm still having an error. I'm appreciating your help. My website is running on localhost:8000. It's working perfectly and no complaints there. My heroku website is running, but my database isn't there on my heroku server. On Heroku: https://data.heroku.com/datastores/... Health: Available 0 of 10,000 Rows In Compliance 8.1 MB Data Size 0 Table(s) I suspect that it's a Django migrations problem, but I can't fix it. I tried the following code: 'heroku run python manage.py migrate' Same error as before. I tried add, commit and push for the heroku server. git add 'theblog/migrations/* git commit -am 'Heroku' git push heroku It was successful, however 'heroku run python manage.py migrate' was not sucessful. Same message as before. Possible, delete the heroku server and I'll try again. On my Heroku website: relation "theblog_category" does not exist Traceback Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (relation "theblog_category" does not exist LINE 1: ..._category"."name", "theblog_category"."name" FROM "theblog_c... ^ ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 165, in _get_response callback, callback_args, callback_kwargs … -
Why Django Rest Framework - Serializer validation doesn't work
I have a simple serializer in my serializers.py and I want to validate one of the fields using validate(self, data) but it doesn't work. My Models.py: class UserRole(models.Model): role = models.CharField(max_length = 100, blank=True, null=True) permission_read = models.BooleanField(null=True) permission_edit = models.BooleanField(null=True) permission_write = models.BooleanField(null=True) permission_delete = models.BooleanField(null=True) superuser = models.BooleanField(null=True) def __str__(self): return self.role My serializers.py: class CreateRoleSerializers(serializers.ModelSerializer): class Meta: model = UserRole exclude = ['superuser'] My views.py: @api_view(['POST']) @permission_classes([IsAuthenticated]) @write_required def user_role_api(request): if request.method == 'POST': json = JSONRenderer().render(request.data) stream = io.BytesIO(json) data = JSONParser().parse(stream) serializer = CreateRoleSerializers(data=data) if serializer.is_valid(): serializer.save(superuser=0) return Response(status=rest_framework.status.HTTP_200_OK) return Response(serializer.errors, status=rest_framework.status.HTTP_400_BAD_REQUEST) I don't know what's wrong with this code. Thanks in advance for the help!