Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I add 2 or more different forms in the same template?
I am new to Django and was working on a page where I need to allow the user to place a bid on an item, leave a comment or add/remove this item from his watchlist so I thought I would need to have a form for each of these tasks, but all I found about multiple forms was formsets and that's not what I need. So my question is how can I have more than 1 form in a template or what are the alternative ways to do this? Thanks in advance -
NoReverseMatch at /update/
I'm using the author name for posts in the url. I get this error after clicking on the submit button when updating the post or creating a new post: Reverse for 'post-detail' with keyword arguments '{'id': 2, 'author': 'john'}' not found. 1 pattern(s) tried: ['(?P<author>[^/]+)\\/(?P<pk>[0-9]+)\\/$'] models.py class Post(models.Model): title = models.CharField(max_length=100, blank="true") content =models.TextField(default="Enter details", verbose_name="Content") date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'id' : self.pk, 'author': self.author.username}) Views.py class PostUpdateView(LoginRequiredMixin, UpdateView): model = Post fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user ##author = current logged in user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False urls.py urlpatterns = [ path('<str:author>/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('<str:author>/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('<str:author>/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), ] -
DetailView is missing a QuerySet Error. shouldnt it work with the primary key?
Quite new to this super nice django thing. Trying my best... trying http://127.0.0.1:8000/angebot/1/ in my browser is supposed to show me the queryset with the primary key 1 from model Testkunde do i need to define a queryset in the detailview ?? normally with model = Testkunde this should be done ?? would really appreciate any help ! thanks in advance! views.py class TestkundeDetailView(DetailView): model = Testkunde template_name = 'angebot/detail.html' context_object_name = 'testkunde_list' urls.py urlpatterns = [ #path('', angebot_views.testkunde_list, name='testkunde_list'), path('', angebot_views.TestkundeListView.as_view(), name='angebot-list'), path('<int:pk>/', angebot_views.DetailView.as_view(), name='angebot-detail'), ] models.py class Testkunde(models.Model): auswahl = ( ('Ausw1', 'Ausw2'), ('Ausw2', 'ausw2'), ('Ausw3', 'ausw3'), ) vname = models.CharField(max_length=250,default='vname') nname = models.TextField(default='default') tel = models.CharField(max_length=250,default='0664') ausw = models.CharField(max_length=10,choices=auswahl,default="Ausw1") datum = models.DateTimeField(default=timezone.now) def __str__(self): return self.vname def get_absolute_url(self): return reverse('angebot:testkunde_list',) Error: ImproperlyConfigured at /angebot/1/ DetailView is missing a QuerySet. Define DetailView.model, DetailView.queryset, or override DetailView.get_queryset(). Request Method: GET Request URL: http://127.0.0.1:8000/angebot/1/ Django Version: 3.0.8 Exception Type: ImproperlyConfigured Exception Value: DetailView is missing a QuerySet. Define DetailView.model, DetailView.queryset, or override DetailView.get_queryset(). Exception Location: C:\Users\berni\PycharmProjects\django_project\venv\lib\site-packages\django\views\generic\detail.py in get_queryset, line 73 Python Executable: C:\Users\berni\PycharmProjects\django_project\venv\Scripts\python.exe Python Version: 3.7.7 Python Path: ['C:\Users\berni\PycharmProjects\django_project\django_project', 'C:\Users\berni\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\berni\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\berni\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\berni\AppData\Local\Programs\Python\Python37', 'C:\Users\berni\PycharmProjects\django_project\venv', 'C:\Users\berni\PycharmProjects\django_project\venv\lib\site-packages'] Server time: Fri, 27 Nov 2020 08:19:51 +0000 I've been searching but can't find the … -
How to customize form (html) with fixed heading title and fixed footer with validation forms buttons?
I develop Django apps and need to customize standard form for data entry that fit the structure in attached image bellow. You can also see my current code that "do the job" but would like to know if it is the good way to do that or if there is better practices. I have define css classes for my fixed heading-title, fixed footer-bottom and for my 2 buttons "Save" and "Cancel" html <nav class="navbar navbar-expand-md navbar-dark bg-info fixed-top" style="padding-top: 50px;">...</nav> <!-- content form for field data entry --> <div class="box row-full" id="heading-title"> <h3>Nouveau projet</h3> </div> <div class='container' style="margin-top:200px;margin-bottom:200px"> <form id="projecteditform" method="POST" class="post-form"> {% csrf_token %} {{ form|crispy }} <button id="ajouter_projet" class="btn btn-info .fixed-save" type="submit" style="width: 100px; z-index:2">Valider</button> <a data-modal data-target="" class="btn btn-dark .fixed-cancel" href="{% url 'project:index_projet' %}" style="width: 100px; z-index:2">Annuler</a> </form> </div> <div class="box row-full" id="footer-buttons"></div> <!-- end content form for field data entry --> <footer class="page-footer font-small blue fixed-bottom" style="background-color:white; z-index:1">...</footer> css .box { width: 100px; max-height: 60px; color: white; } #heading-title { position: fixed; padding-top: 20px; top: 100px; color:black; background: white; } #footer-buttons { position: fixed; bottom: 50px; background: white; } .row-full{ width: 100vw; position: relative; margin-left: -50vw; text-align: center; height: 100px; left: 50%; } .fixed-save{ position: fixed; … -
Django does not use index on ordering
I'm trying to optimize a query in Django (version 1.11) that I use in a prefetch. So I have a StaffProfile model that has a relation to Wages like this: class Wages(Model): # ... staff = models.ForeignKey('StaffProfile', on_delete=models.CASCADE, null=True) title = models.CharField(_('Title'), max_length=50) class StaffProfile(Model): # ... objects = StaffProfileManager.from_queryset(StaffQuerySet)() The StaffQuerySet has a dedicated method: class StaffQuerySet(QuerySet): def my_prefetch( ) -> QuerySet: return self.prefetch_related( Prefetch( 'wages_set', queryset=Wages.objects.filter( # ... ).order_by( Upper('title') ), to_attr='prefetched_wages' ), ) What I noticed is that When I run this query: Wages.objects.all().order_by(Upper('title')) my database (PostgreSQL) obviously sorts the results (below is the output from the EXPLAIN run on the generated SQL): Sort (cost=21.31..21.86 rows=220 width=166) Sort Key: (upper((title)::text)) -> Seq Scan on staff_wages (cost=0.00..12.75 rows=220 width=166) So I've tried to set an index on the title field. In order to achieve this I've created a migration: class Migration(migrations.Migration): dependencies = [ ('staff', '0020_merge_20201116_0929'), ] operations = [ migrations.RunSQL( sql='CREATE INDEX "staff_wages_title_upper_idx" ON "staff_wages" (UPPER("title"));', reverse_sql='DROP INDEX "staff_wages_title_upper_idx";' ) ] I've run it and I see it was created in the database. However, when I now run my query, the EXPLAIN gives exactly the same output, whereas I expected it to use my index. What am … -
Is there any inbuilt function in django to clean the data in a request.POST dictionary key?
All the inbuilt cleaning methods seem to be only for the Django Forms. I find editing the style of those forms complex and that's why I just prefer create traditional HTML forms and later supply the data from request.POST to the required Django Model. Is there any inbuilt workaround for cleaning such data in Django or I'll have to write a function myself? -
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