Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Speed Optimization in Django
I am building a Blog App and I am also thinking to implement video posts in it. I am trying to optimize the speed of the Web App in Development and also in Production. I have deployed many sites build in Django in last several months on PythonAnywhere. I've noticed that most of site contains simple functionalities like :- Create, Edit, Image Upload, ListView, DetailView of Blogs , etc. With 500 to 600 lines of Code (python). Talking about Development :- When i open a page that contains 100 to 150 Blogs with Images, then it is taking 2 to 3 seconds to open the page AND then i think this may be Because of more blogs and queries then I checked the page's queries and query's Time using Django-Debug-Toolbar then I deleted all the posts except 1 post after that I saw in debug-toolbar, it is showing Total time to load the Page is 600ms. 4 queries in 6 to 8ms I removed some queries but still same results. I also searched about it then i found a Post of optimizing queries using select_related then I also used it BUT I didn't see any much improvement. I used to … -
how to set default value in django template using ajax
i'm trying to set default value to an input field in django template , i have two models tables class Ticketing(models.Model): Title = models.CharField(max_length=40) b = models.DecimalField(max_digits=5,decimal_places=2) #others class Cancel(models.Model): ticket = models.ForeignKey(Ticketing,on_delete=models.CASCADE,related_name="ticket") title = models.CharField(max_length=40) #others forms.py class CancelForm(forms.ModelForm): class Meta: model = Cancel fields = ['title',] my views.py def create_cancel(request,id): booking_obj = get_object_or_404(Ticketing,id=id) form = CancelForm() if request.method == 'POST': form = CancelForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.admin = request.user obj.booking = booking_obj obj.save() return redirect('cancel:create' ,booking_obj.id) context = { ' booking_obj':booking_obj,'form':form } return render(request,'cancel/create.html',context) urls path('create/<int:id>',create_cancel,name='create'), path('ajax/check-title/<int:id>',create_cancel,name='check_title'), i tried to call back title using ajax but it doesnt work @login_required def check_invoice_paid(request,id): obj = get_object_or_404(Ticketing,id=id) data = { 'title':obj.title } return JsonResponse(data) my template $('select').change(function() { let elm = $(this); data = {}; data[elm.attr("name")] = elm.val(); $.ajax({ url:'{% url 'cancel:check_title' booking_obj.id %}', data:data, success:function(data){ if (data.title){ elm.closest("div.ticket ").find("input.title").val(data.title); } } } ) }) <form action="" method="POST">{% csrf_token %} {{form.errors}} <div id="printDv" class="text-lg"> <p class="p-2 header rounded-lg text-center text-white">Cancel</p> <div class="border border-purple-900 mt-2 rounded-lg p-2 text-center"> <p>no. : {{booking_obj.id}} </p> </div> <div class="ticket border border-purple-900 mt-2 text-center rounded-lg p-2 grid grid-cols-1 md:grid-cols-1 gap-3" dir="ltr" > <p>{{form.title | add_class:'title bg-transparent focus:outline-none w-8/12' }} :title</p> </div> </div> <button class="header … -
Django ListView ignore Order_by in get_Queryset
i'm trying to edit order in a listView through get_queryset() funcion and using order_by() when i try print generated query it's ignore order_by query and uses only the default order in Meta class inside my model class Do you know why that appens? Here my view.py file class TagsListView(ListView): model = Tag paginate_by = 250 ordering = ['-tag'] def get_queryset(self): queryset = Tag.objects.all() queryset.order_by('slug', ) # se presente type nell'url aggiunge il filtro category = self.request.GET.get("category", None) # type = self.kwargs.get('type', None) if category : queryset = queryset.filter( category=category ) search = self.request.GET.get("search", None) if search : queryset = queryset.filter( tag__icontains=search ) print('test ordering') queryset.order_by('slug', 'tag', 'date' ) print(queryset.query.__str__()) return queryset #aggiustare l'url that is my model file # Create your models here. class Tag(models.Model): GENERIC = 0 CONSOL = 1 SOCIETA = 2 SAGA = 3 CAT = 4 ALTRO = 5 CATEGORIES = [ (GENERIC,'Generico'), (CONSOL,'Consol'), (SOCIETA,'Sport'), (SAGA,'Salute'), (CAT,'Categorie'), (ALTRO,'Tempo Libero'), ] tag = models.CharField(max_length=40, unique=True) slug = models.SlugField(max_length=40, unique=True) date = models.DateTimeField(default=timezone.now) category = models.IntegerField(choices=CATEGORIES, blank=True, default=GENERIC) custom = models.CharField(max_length=20, blank=True) class Meta: ordering = ('-date', 'tag') #ordinamento degli elementi pass def __str__(self): #metodo righiesto return self.tag + " - " + self.slug def get_absolute_url(self): return reverse("tags:tag-detail", … -
Not able to connect to django rest server at http://127.0.0.1:8000/
I have used the same code as the tutorial on the drf website When i run python manage.py runserver it gives me this in the terminal Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 10, 2021 - 07:12:08 Django version 3.2.5, using settings 'drftut.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Firefox gives me this error: The connection has timed out The server at 127.0.0.1 is taking too long to respond. The site could be temporarily unavailable or too busy. Try again in a few moments. If you are unable to load any pages, check your computer’s network connection. If your computer or network is protected by a firewall or proxy, make sure that Firefox is permitted to access the Web. I'm also using wsl1 and vscode remote desktop for wsl and im running this inside a python enviroment -
Django rest framework authtoken.views.obtain_auth_token returns ' "detail": "Method \"GET\" not allowed."
projectapp/urls.py from django.urls import path from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ path('token/', obtain_auth_token), ] So when I try to call this using POSTMAN when it's running locally (using runserver) it returns the token and works correctly, but after deploying on cloud using Nginx on Emperor mode (Using POSTMAN to call the API), it returns' { "detail": "Method \"GET\" not allowed." } This was also discussed in here. So basically my client was not sending a POST request. So I read some docs and discussions and found out that when POSTMAN receives a 301 or 302 on POST request, it tries again with GET. So i ran curl on the server with my username and password, it did return a 301, <html> <head><title>301 Moved Permanently</title></head> <body> <center><h1>301 Moved Permanently</h1></center> <hr><center>nginx/1.18.0 (Ubuntu)</center> </body> </html> So my question is, Why is it working in my local server and not in production? And how do I solve the redirect problem so that it accepts POST and i get the token? I'm a newbie in Django and Web Development in particular here is my project/setting.py Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.register.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.register.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.register.password_validation.CommonPasswordValidator', }, … -
Django + Bootstrap navbar button and search field issue
I know that there are similar questions, but I tried and searched hard and didn't find a solution for my problem. I am using Django + bootstrap to complete an exercise which include a navbar. The search button is stubbornly staying below the search field. I would just like to align them, as in this example : Here my code : ''' </div> <div class="collapse navbar-collapse justify-content-center"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <form class="form-inline my-2 my-lg-0 col-3"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> <div class="collapse navbar-collapse justify-content-center" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> </div> </nav> ''' Don't know if it's a naive issue, but I am really struggling and loosing time with it. Many thanks -
how to make dependent model, from one model to another model in Django
I have 3 models and I want to make all of them depend on each other. I have seen this website, and this is a dependent drop-down list in the same HTML template but I have each new HTML page for each model. So, I have one common field in all the models is code. where code field contains a number of codes like eg.: DD1, DD2, DD3, and so on. So, this code is been there for all three models for eg.: Model motor contains the code field, and in the code field there is code like DD1, DD2, DD3, and also in the drum model contain the code field which is DD1, DD2, DD3 and all the three models have same code field and have matching code. So, now I want to make all three models depend on each other with the help of code. Basically, if the user chooses the motor product which having code as DD4 then if the user goes to another page so the user has to get the DD4 code product from other models. I have done coding like this: views.py def addProductMotor(request): user = request.user motor_id = request.GET.get('motor_id') motor_cart = Motor.objects.get(id=motor_id) Cart(user=user, … -
Django change values() dynamically for each record
I'm trying to get values of student records but change the retrieved values upon conditions (parent). Consider having models.py: class Grade(models.Model): code_name = models.CharField(max_length=10) school = models.ForeignKey(School,on_delete=models.CASCADE,blank=False,related_name='grades') class Group(models.Model): code_name = models.CharField(max_length=10) grade = models.ForeignKey(Grade,on_delete=models.CASCADE,blank=False,related_name="groups") student_record = models.OneToOneField(Student,null=True,blank=True,on_delete=models.SET_NULL) class Class(models.Model): code_name = models.CharField(max_length=10) grade = models.ForeignKey(Grade,on_delete=models.CASCADE,blank=False,related_name="classes") student_record = models.OneToOneField(Student,null=True,blank=True,on_delete=models.SET_NULL) class Student(models.Model): male_count = models.PositiveSmallIntegerField() female_count = models.PositiveSmallIntegerField() when I retrieve the student records within a table like below: ____________________________________________ | grade | class or group | males | females | |_______|________________|_______|__________| | | | | | |_______|________________|_______|__________| ** Queryset ** would be something like below: rows = Student.objects.filter(<some condition>).values( '<parent>__grade__codename', '<parent> class or group', # here stands the issue 'male_count', 'female_count', ) I've tried many concepts .. like using Case and When, searched for couple of days and found unanswered questions like this one and tried to make it flat with making a queryset for each (students of classes, students of groups) but still can't make it work. Any Support Will Be Appreciated. -
Django error TypeError: __init__() takes 1 positional argument but 2 were given
I am a bit new to python and I am trying to consume an external API serialized with a serializer class within my Django project and I am getting the below error Traceback (most recent call last): File "lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: __init__() takes 1 positional argument but 2 were given "GET /project/v1/mypath/ HTTP/1.1" 500 56241 see my view below import json import requests from rest_framework import viewsets from rest_framework.response import Response from .config import * from .serializer import * BASE_URL = BASE_URL ACCOUNT_URL = "{}/v2/account".format(BASE_URL) ORDERS_URL = "{}/v2/orders".format(BASE_URL) HEADERS = {'APCA-API-KEY-ID': API_KEY, 'APCA-API-SECRET-KEY': SECRET_KEY} # Create your views here. class AlpacaGetAccountView(viewsets.ModelViewSet): serializer_class = AlpacaAccountSerializer def get_account(self): r = requests.get(ACCOUNT_URL, headers=HEADERS) serializer = AlpacaAccountSerializer(r, many=True) return Response(serializer.data) Honestly, I have no idea where the error is coming from Please advise me on how I can resolve this and where the error is coming from -
How to set nested related fields serializers in Djando Rest Framework?
I'm using Django Rest Framework to build an API where I have the following models of Users making, confirming and showing interest on Events: models.py class User(AbstractBaseUser, PermissionsMixin): user_name = models.CharField(_("user name"), max_length=150, unique=True) slug = AutoSlugField(populate_from='user_name', unique=True) class Event(models.Model): name = models.CharField(max_length=100, blank=False, null=False) owner = models.ForeignKey(User, related_name="owned_events", on_delete=models.SET_NULL, blank=True, null=True) confirmed = models.ManyToManyField(User, related_name="confirmed_events", blank=True) interested = models.ManyToManyField(User, related_name="interested_events", blank=True) to serialize it I used the following code as I found here and at the DRF docs: serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = [ "url", "user_name", "password", ] extra_kwargs = { "password": {"write_only": True} } class EventSerializer(serializers.HyperlinkedModelSerializer): owner = UserSerializer(required=False) confirmed = UserSerializer(required=False, many=True) interested = UserSerializer(required=False, many=True) class Meta: model = Event lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field': 'slug'} } fields = [ "url", "owner", "name", "confirmed", "interested", ] It works just fine like that, but I wanted the UserSerializer to show confirmed and interested events of each user just like each event shows the users confirmed and interested. I changed serializers and got the url of each event, like that: serializers.py with HyperlinkedRelatedField on UserSerializer class UserSerializer(serializers.HyperlinkedModelSerializer): confirmed_events = serializers.HyperlinkedRelatedField( queryset=Event.objects.all(), view_name='event-detail', lookup_field='slug', many=True, required=False ) interested_events = serializers.HyperlinkedRelatedField( queryset=Event.objects.all(), … -
Sort Django users by specific groups on the top
All users of the application are mapped to at least one group. Here is list of available groups: >>>Group.objects.all() <QuerySet [<Group: superuser>, <Group: maintainer>, <Group: admin>, <Group: executive>, <Group: client>, <Group: other>]> When I render all the users in the queryset with .all(), I want to sort them with a specific custom order such that, all the Superusers should be on the top, then Admins, then Executives and then rest of the Users as per below list. group_order_list = ['superuser', 'admin', 'executive', 'client', 'maintainer', 'other'] Wondering, how can I use sorted() function on my queryset: class UserList(generic.ListView): model = User queryset = User.objects.all() template_name = 'users/users.html' paginate_by = 10 -
Django: how to make POST request with form data?
I'm learning Django and am running into an issue posting a piece of data to the database. Here's my code: urls.py urlpatterns = [ path("", views.index, name="index"), ... path("listing/<int:listing_id>", views.display_listing, name="listing") ] Models.py class Bid(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='usr_bids') price = models.DecimalField(max_digits=5, decimal_places=2) class Listing(models.Model): title = models.CharField(max_length=50) bids = models.ManyToManyField(Bid, blank=True, related_name='bids') price = models.DecimalField(max_digits=7, decimal_places=2) closed = models.BooleanField(default=False) Forms.py class BidForm(ModelForm): class Meta: model = Bid fields = ['price'] views.py def display_listing(request, listing_id): listing = Listing.objects.get(pk=listing_id) if not request.user.is_authenticated: return HttpResponseRedirect(reverse('login')) if request.method == "POST": user = User.objects.get(username=request.user) if request.POST.get("button") == "Watchlist": if not user.watchlist.filter(listing=listing): watchlist = Watchlist() watchlist.user = user watchlist.listing = listing watchlist.save() else: user.watchlist.filter(listing=listing).delete() return HttpResponseRedirect(reverse('listing', args=(listing.id, ))) if not listing.closed: if request.POST.get("button") == "Close": listing.closed = True listing.save() else: price = float(request.POST["price"]) bids = listing.bids.all() if user.username != listing.creator.username: if price <= listing.price: return render(request, 'auctions/listing.html',{ 'listing': listing, 'form': BidForm(), 'message': 'Increase your bid.' }) form = BidForm(request.POST) if form.is_valid(): bid = form.save(commit=False) bid.user = user bid.save() listing.bids.add(bid) listing.price = price listing.save() else: return render(request, 'auctions/listing.html', { 'form': form }) return HttpResponseRedirect(reverse('listing', args=(listing.id, ))) else: return render(request, 'auctions/listing.html', { 'listing': listing, 'form': BidForm(), 'comments': listing.comments.all() }) auction/listings.html <div> <form action="{% url 'listing' listing.id … -
Get the value in queryset in Django template
I have used Django to develop a web app. In the View function, I have rendered a queryset list to frontend. view.py: def render_2(request): query_results_book_is_discard = Material.objects.filter(id=course_id).values('is_discard') return render(request, 'main.html', context={'query_results_book_is_discard':query_results_book_is_discard}) In the frontend, the query_results_book_is_discard variable shows the following format : <QuerySet [{'is_discard': True}, {'is_discard': False}, {'is_discard': False}, {'is_discard': False}, {'is_discard': True}, {'is_discard': True}, {'is_discard': False}]> The query_results_book_is_discard variable is in a loop in frontend Django template, I want to use the forloop counter to get the value(True or False) to use if condition to check. I haved tried: {% if query_results_book_is_discard.counter0 != False %} and {% if query_results_book_is_discard.counter0.is_discard != False %} and {% if query_results_book_is_discard.is_discard.counter0 != False %} All failed. How could I get the True or False value in query_results_book_is_discard to use if condition? -
django how to make POST request ONLY using {% url ' x' %} in HTML
Here is my views.py. from django.shortcuts import render, redirect from .models import Todo from .forms import TodoForm from django.views.decorators.http import require_http_methods def index(request): return render(request, 'home.html') def todoPanel(request): form = TodoForm() todo_list = Todo.objects.order_by('id') context = {'form': form, 'tasks': todo_list} return render(request, 'todo_panel.html', context) @require_http_methods def addTask(request): form = TodoForm(request.POST) if form.is_valid(): task = Todo(task=form.cleaned_data['task']) task.save() return redirect('panel') Here is my urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='home'), path('panel/', views.todoPanel, name='panel'), path('addTask', views.addTask, name='addTask') #path('delete_confirm', views.todo_delete, name='delete_confirm') ] and here is my todo_panel.HTML {% extends 'base.html' %} {% block content %} <h1>Todo Panel</h1> <!-- Render the form here--> <form action="{% url 'addTask' %}" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Add"> </form> <!-- Display the todos here --> <ul class="list-group"> {% for task in tasks %} <li class="list-group-item">{{ task }}</li> {% endfor %} </ul> {% endblock content %} I don't want django to redirect me to addTask... I want it to make a POST request. I read the example here https://github.com/PrettyPrinted/django_todo_app and he was able to do it without it redirecting to add. I just want it to make a POST request so it can POST a todo to database. -
Should I Use uWSGI?
I am a newbie to web development. My web application is Django + Nginx. My friend suggested using uWSGI too in case the traffic increases and uWSGI will be able to handle that so the website would not become extra slow. But from what I read, it is Nginx that handles high traffic. So which one? -
NoReverseMatch Error Django Can someone explain how these URL's are failing?
Can someone explain to me how these urls work in django? I'm trying to create a follow/unfollow feature for a twitter clone, the follow is working but when I use the unfollow I am getting the following error. Can someone explain to me why this is failing? I am still learning django and would like to know why this isn't working. NoReverseMatch at /u/fake_account/unfollow/ Reverse for 'foxyprofile' with keyword arguments '{'usersname': 'fake_account'}' not found. 1 pattern(s) tried: ['u/(?P[^/]+)/$'] Here is my code let me know if you need more. foxyprofile.html {% extends 'core/base.html' %} {% load humanize %} {% block content %} <div class="container"> <div class="columns"> <div class="column is-12"> <h1 class="title">{{ user.username }}</h1> <p><a href="{% url 'followers' user.username %}"> Followers: {{ user.foxyprofile.followed_by.count }}</p></a> <p><a href="{% url 'following' user.username %}"> Follows {{ user.foxyprofile.follows.count }}</p></a> <hr /> {% if user != request.user %} {% if request.user.foxyprofile in user.foxyprofile.followed_by.all %} <a href="{% url 'unfollow_foxy' username=user.username %}" class="button is-danger">Unfollow {{ user.username}}</a> {% else %} <a href="{% url 'follow_foxy' user.username %}" class="button is-success">Follow {{ user.username}}</a> {% endif %} {% endif %} </div> </div> <div class="columns"> <div class="column is-8"> <div class="wrapper-fox"> {% for fox in user.foxs.all %} <div class="fox"> <p class="name">{{ fox.created_by.username }}</p> <p>{{ fox.body }}</p> … -
"Authentication credentials were not provided." Thunder client Django Rest
I am trying to restrict dashboard access only, which can be viewed only when the token is passed into the header but... if request.method == "POST": user_name = request.POST['user_name'] name = request.POST['first_name'] lastname = request.POST['last_name'] designation = request.POST['designation'] password = request.POST['password'] email = request.POST['email'] user = MyUser(username=user_name, first_name=name, last_name=lastname) user.set_password(password) user.save() obj = Employee(user=user, first_name=name, last_name=lastname, designation=designation, email=email, isactive=False) obj.save() current_site = get_current_site(request) # mail_subject = 'Activate your account.' # message = render_to_string('Auth/email_template.html', { # 'user': user, # 'domain': current_site.domain, # 'uid': urlsafe_base64_encode(force_bytes(user.id)), # 'token': account_activation_token.make_token(user), # }) # to_email = email # send_mail(mail_subject, message, settings.EMAIL_HOST_USER, [to_email]) obj, create = Token.objects.get_or_create(user=user) return JsonResponse(obj.key, safe=False) login view @csrf_exempt @api_view(['GET', 'POST']) def login_in(request): if request.method == 'POST': name = request.data['first_name'] password = request.data['password'] user = authenticate(username=name, password=password) if user is not None: login(request, user) tok = Token.objects.get(user=request.user) return JsonResponse(tok.key, safe=False) else: print('Not authenticated') return render(request, 'Auth/user.html') Dashboard view @api_view(['GET']) @permission_classes([IsAuthenticated]) def dash_board(request): if request.method == 'GET': print(request.user.is_authenticated) return render(request, 'Auth/dashboard.html', { 'user': request.user, }) Response I am getting from thunder client { "detail": "Authentication credentials were not provided." } I am passing request headers using thunder client in which Authorization header is set to Token d2ed0c39f31bb1c080753bkldd0f4c0ab96b5a07 -
Image url not found in html
I have some images stored in my django db. And i am trying to display all of them on my web. Python file def index(request): if request.method == "GET": result = Video.objects.all() return render(request, "videos/index.html", { "data": result }) HTML file {% for x in data %} <div class="content"> <img src="{{ x.image }}"> <h3>{{ x.title }}</h3> <h3>{{ x.user }}</h3> <video class="embed-responsive embed-responsive-16by9" controls="controls" > <source src="{{ x.video.url }}" type="video/mp4" /> </video> </div> <br /> {% endfor %} Surprisingly, the video is loading, but the image isn't. When I opened the source code on the browser <img src(unknown)> this is what I see. -
How to fix ModuleNotFoundError when I try to run Django framework?
I want to start Django framework learning but whenever I run python manage.py runserver ===> ModuleNotFoundError: No module named 'C:\Users\LENOVO' PS C:\Users\LENOVO\Dev\cfeproj> I dont know what to configure from here, my C drive became a module? Dont know how that happened ={ really frustrating ,i keep failing. Can anyone help me to resolve this issue? -
Consolidate Django migrations into a package
In my django project I have my migrations being created and applied from each app inside migrations folder, however I need all those migrations to be consolidated and migrated from a saperate package outside my app. -
Best way to integrate a Django project into existing program, using same backend logic?
I am very new to Django so I apologize in advance if there are any misconceptions about the framework within this question. I have developed a log analysis program that currently uses the command-line as the user interface using the cmd2 library. I am attaching an image of the project structure with the different Python files. The program is started from log_analyze.py. The commands are parsed in user_interface.py. Other classes like sddc_log.py, get_logs.py, etc. contain logic that is used in the commands for parsing through logs. We currently run this program from VM that our teammates have access to. We are thinking of also creating a web UI for this program so that team members can connect to the VM from the browser to perform log analysis. My question is what would be the best way to organize a Django project that can leverage the existing logic we have in these other Python files and use that information to populate the web UI. Specifically, what would be the proper file structure? Are there any other aspects that I should pay specific attention to? Would this even be a good use case of Django? Thanks for your help in advance. project … -
How do you use Django Login function properly
What I understand so far is that when you're using regular Django you import and use AuthenticationForm and you put the request.POST there and it will retrieve the user you're looking for. But in this case I'm using DRF and some third party authentication system that retrieve the user for me. so in order to test the login function I made this dummy code to test it: @api_view(["GET"]) def login_view(request): if request.method == "GET": #actuall users that exist user = { "id": 1, "email": "test@gmail.com", "name": "melly", "date_joined": "2021-07-09T11:33:44.440889Z" } login(request, user) return Response('test') and it gave me this error Can someone explain to me about this error and why is this happening, thank you! -
Page title with class based function in django
I want to create page titles+subtitles which I wish to control and occasionally modify from the Admin space and pass them to the templates with class based model. Yet, after I enter the inputs in the admin space, the variable I specify in the template provides not value. That is the fields are empty. What do I do wrong? Any advise as to the logic I should use to pass the template? models.py: class Page(models.Model): page_title = models.CharField(max_length=250) page_subtitle = models.TextField() def __str__(self): return self.self template: <h3 class="title mb-0">{{page.page_title}}</h3> <h6 class="title mb-0">{{page.page_title}}</h6> Views: I tried with different views, none of them functioned. TemplateView: class Page(TemplateView): template_name = 'painting_list.html' # the template where I want to display the title def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['page'] = self.Page return context #I also tried it with:# context['page'] = Page.objects.get(id=1) return context DetailView: class Page(generic.DetailView): model = Page context_object_name = 'page' template_name = 'painting_list.html' -
Need help to setup support chat in django-react app using twilio
I need to know should I setup everything in my backend (django) for chat, and call it in my frontend (react)? And what is the best practice to add it in my site. First time, I'm trying and confuse cuz read alot of different blogs. -
vscode django cookiecutter development setup
i am using django cookiecutter with VS code. I am using docker with it. Now whenever i try to code i do not get any linting, snippets recommendation, library detection etc. Any suggestion/recommendation/guide for that problem will be a great help. Thankyou.