Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I add an image in a bootstrap card?
I am trying to a attach an image in a specific area in a card, but I don't know how to. I am sorry if it's a very silly question, I am a total beginner in terms of html. So can anyone please show me how to do it? It would have been really useful. Thanks in advande! I am using Django. For example, If I want to add an image in that specific blue outlined area, what should I do? My code {% for fixture in fixtures %} <div class="card bg-light"> <div class="card-header" style="color:red;" > Featured </div> <div class="card-body"> <h5 class="card-title" style="color:black;">{{ fixture.home_team }} vs {{ fixture.away_team }}</h5> <p class="card-text" style="color:black;">{{ fixture.description }}</p> <form style="color:black;"> <h5><label for="watching">Watching?</label> <input type="checkbox" id="watching" name="watching" value="watching"> </h5> </form> </div> </div> {% endfor %} -
Why filter() doesn't invokes in angular 11+Django rest framework?
In my current project which is using angular11 and Python Django+django rest framework so i was trying to create a filter feature in department component but it doesn't woeks as expected. when i am trying to filter so department table doesn't shows filtered record as o/p. before filter search [![enter image description here][1]][1] after filter serach result [![enter image description here][2]][2] this is my humble request that plzz review my code and if possible then help me to solve this problem asap. component.ts import { Component, OnInit } from '@angular/core'; import { SharedService } from "src/app/shared.service"; @Component({ selector: 'app-dep-show', templateUrl: './dep-show.component.html', styleUrls: ['./dep-show.component.css'] }) export class DepShowComponent implements OnInit { constructor(private service:SharedService) { } DepartmentList:any=[]; DepartmentIdFilter:string=""; DepartmentNameFilter:string=""; DepartmentListWithoutFilter:any=[]; ngOnInit(): void { this.refreshDepList(); } refreshDepList(){ this.service.getDeptList().subscribe((data)=>{ this.DepartmentList=data; }); } FilterFn(){ var DepartmentIdFilter1=this.DepartmentIdFilter; var DepartmentNameFilter1=this.DepartmentNameFilter; console.warn("filter called") // console.warn(el) this.DepartmentList=this.DepartmentListWithoutFilter.filter(function (el:any){ return el.DepartmentId.toString.toLowerCase().includes( DepartmentIdFilter1.toString().trim().toLowerCase() )&& el.DepartmentName.toString.toLowerCase().includes( DepartmentNameFilter1.toString().trim().toLowerCase() ) }); } }``` ``` <thead> <tr> <th scope="col"> <div class="d-flex flex-row"> <input [(ngModel)]="DepartmentIdFilter" class="form-control" (keyup)="FilterFn()" placeholder="filter"> </div> Department Id</th> <th scope="col"> <div class="d-flex flex-row"> <input [(ngModel)]="DepartmentNameFilter" class="form-control" (keyup)="FilterFn()" placeholder="filter"> </div> Department Name</th> <th scope="col">Options</th> </tr> </thead> ``` [1]: https://i.stack.imgur.com/L7Cag.jpg [2]: https://i.stack.imgur.com/Ckvxv.jpg if anybody can tell my mistake in this code or can suggest me … -
Django order record by serializer Method Field
I am confused about how can I order records by serializer method here Is my serializer serializer.py here is my data from API data from api here is my viewset kindly tell me is there any way I can order record by avg which is coming from serializer method field -
Django Channels Private Chat server
I am new to Django channels and the ASGI application itself, so I am a bit confused about how to go while building a private chatting app. There isn't much tutorial for private chats all are for chat rooms and broadcasting I have few thoughts in mind about how I can make a Private chat, but I am not sure which approach to take. My first thought is to not use the channel layer and handle each connection separately. By that I mean every time a user comes to the chatting app it will open a connection with the name chat__{userid} and if user_A sends a message to user_B it will first check if user_A is authorized to send a message to user_B then call send method on user_B, after a message is sent send back the confirmation to the user_A. there is a problem with the above implementation what if a user opens a different tab, how should I handle that. To establish a connection between users using channel_layers, if both are online while they are chatting with one another, but the problem arises when the user is chatting with multiple users do I need to open multiple WebSocket … -
'datetime.datetime' object is not callable django celery beat
I have Django Celery and Beat on my Docker based setup. My settings are divided into their concerned environment. base.py holds the common configurations that are required by both staging.py and production.py. In my common.py I am initialising a variable something like this from datetime import datetime import pytz est_timezone = datetime.now(pytz.timezone('EST')) This is the traceback I get for it celery-beat_1 | [2021-04-09 10:59:46,845: CRITICAL/MainProcess] beat raised exception <class 'TypeError'>: TypeError("'datetime.datetime' object is not callable") you can put the above snippet in a shell and it works well, so I have no idea what's going on. -
Django: logging: Formatter how to access request.build_absolute_uri()
I am planning to use custom logging formatter in DJango. And add the url to the record object using request.build_absolute_uri() The following is what i want to do # SQL formatter to be used for the handler used in logging "django.db.backends" class CustomFormatter(logging.Formatter): def format(self, record): record.absolute_path = request.build_absolute_uri() # <-- how to access request here return super(CustomFormatter, self).format(record) and later use as 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(absolute_path)s \n%(message)s' }, } How to access request inside the Custom logging -
how to handle multiple models in django restframework
I am a beginer in django restframework.My question is how to update profile which contain the following fields "Name, Email, Mobile, Gender, Educationalqualification, college, specialization, country,state,city" and these fields are in diffenet models ie, models.py class LearnerAddress(Address): learner = models.ForeignKey(Learner, on_delete=models.CASCADE) class Learner(BaseModel, Timestamps, SoftDelete): created_from_choices = ( ('web', 'Web'), ('ios', 'iOS'), ('android', 'Android'), ) gender_choices = ( ('male', 'Male'), ('female', 'Female'), ('other', 'Other'), ('not_specified', 'Not Specified') ) user = models.OneToOneField(User, on_delete=models.CASCADE) created_from = models.CharField(max_length=20, choices=created_from_choices, default='web', null=False) phone_verification_date = models.DateTimeField(verbose_name="Phone verification Date", null=True) email_verification_date = models.DateTimeField(verbose_name="Email verification Date", null=True) is_email_verified = models.BooleanField(default=False) is_phone_verified = models.BooleanField(default=False) is_guest = models.BooleanField(default=False) # photo = models.ImageField(upload_to=None, height_field=None, width_field=None,Learner null=True, blank=True) gender = models.CharField(max_length=20, choices=gender_choices, default='not_specified', null=False) class LearnerQualification(BaseModel, Timestamps, SoftDelete): qualification = models.ForeignKey(EducationalQualification, max_length=50, null=False, on_delete=models.CASCADE) specialization = models.ForeignKey(Specialization, max_length=50, null=False, on_delete=models.CASCADE) college = models.ForeignKey(College, max_length=50, null=False, on_delete=models.CASCADE) year = models.IntegerField(null=False) remarks = models.CharField(max_length=100, null=False) learner = models.ForeignKey(Learner, on_delete=models.CASCADE, related_name="learner_qualifications", null=True) -
Django in Python using sessions
print("Your answers") opn1 = request.session.get('no1') print(opn1) opn2 = request.session.get('no2') print(opn2) opn3 = request.session.get('no3') print(opn3) opn4 = request.session.get('n1') print(opn4) opn5 = request.session.get('no5') print(opn5) print("Correct Answers") print("1. Silicon") print("2. 1000 bytes") print("3. Microsoft Office XP") print("4. Param") print("5. 1000,000,000 bytes") So i have got answers from the users using session and i have displayed the correct answers but i wanted to know the condition to validate -
SyntaxError: invalid syntax in django
I get this error when run the code. Any help is appreciated class Logout(generics.CreateAPIView): permission_classes = [IsAuthenticated] def get(self, request, *args, **kwargs): response = self.http_method_not_allowed(request, *args, **kwargs) return response def post(self, request, *args, **kwargs): return self.logout(request) def logout(self, request): try: request.user.auth_token.delete() except(AttributeError, ObjectDoesNotExist) as e: logger.exception(e) logger.debug("Can't logout", exc_info=True) raise e response = Response({"detail": "Successfully logged out."}, status=status.HTTP_200_OK) return response except (AttributeError, ObjectDoesNotExist) as e: ^ SyntaxError: invalid syntax -
How to remove null from serializer.data when return response in django
I want to remove null from serializer.data before return final response to the end users. Here is my code: def list_order_by_status(request): order = Order.objects.all() serializer = ListOrderSerializer(order, many=True, context={"status": request.data['status']}) return Response(serializer.data) Here is my reponse: 0: {…} 1: null 2: {…} -
django: how middleware know something to execute before view is called and something after view is called
I am going through the django middle ware. I am not able to understand how does the middleware know somecode to be run before the view is called and some code to be run after the view is called. the following image will show more clearly what i am asking -
Django REST Framework - How to generalize this serizlier method?
I have a Question model in my app, as well as an Answer model. I also have a QuestionSerializer and an AnswerSerializer. I'm dealing with overriding the update method of my QuestionSerializer: since I can send both my question and answers data in a single PUT request, I need my serializer to handle nested updates. Here's the code I came up with: def update(self, instance, validated_data): # get data about answers answers_data = validated_data.pop("answers") # update question instance instance = super(QuestionSerializer, self).update( instance, validated_data ) answers = instance.answers.all() # get all answers for this question # update each answer or create it if it didn't exist for answer_data in answers_data: try: answer = Answer.objects.get(pk=answer_data["id"]) save_id = answer_data["id"] except Answer.DoesNotExist: answer = Answer(question=instance) answer.save() save_id = answer.pk del answer_data["id"] # get rid of frontend generated id used to determine whether the question already existed serializer = AnswerSerializer( answer, data=answer_data, context=self.context ) serializer.is_valid(raise_exception=True) serializer.update(instance=answer, validated_data=answer_data) # remove answer from the list of those still to process answers = answers.exclude(pk=save_id) # remove any answers for which data wasn't sent (i.e. user deleted them) for answer in answers: answer.delete() return instance Basically, for each new answer my frontend generates a random id (a very … -
Is there a way to populate fields that are programmatically added in the Django Form class?
I have a Form with overridden init() because I programmatically create fields based of the models that have another model as foreign key. My form class looks like this: class ProductSpecForm(forms.Form): def __init__(self, *args, **kwargs): category = kwargs.pop('category', None) super(ProductSpecForm, self).__init__(*args, **kwargs) specs = category.categoryspec_set.all() for spec in specs: value = None self.fields[spec.name] = forms.CharField( max_length=50, required=True, label=spec.label(), initial=value ) It works fine when I render it in the template. The problem is when I validate it. It shows me that fields are empty even though I initialize it with request.POST in my view: if request.method == 'POST': spec_form = ProductSpecForm(request.POST, category=category) if spec_form.is_valid(): ... else: print(spec_form.errors) In my opinion, it doesn't work to populate the fields because when I initialize the object with the super().init(), the added fields does not exist yet. When I call the super().init() at the bottom of my overridden init() it does not even work in the template because it does not read the fields at all. Can I somehow call the method that only populates the form object after I initialize all my fields in my init()? -
How can accept and reject order in Django
I want to accept and reject the order. If order will accept it show be saved in db, if order is rejected it show be del, but i am trying but nothing happened View.py class OrderDecision_View(TemplateView): template_name = 'purchase/allOrders.html' def get(self, request, *args, **kwargs): allOrders = Order.objects.all() args = {'allOrders': allOrders} return render(request, self.template_name, args) def post(self, request): orderId = self.request.GET.get('order_id') statusAccept = self.request.GET.get('acceptButton') statusReject = self.request.GET.get('rejectButton') if statusAccept: try: orderDecision = OrderRequest( order_id=orderId, order_status=statusAccept, ) orderDecision.save() return redirect('orderDecision') except Exception as e: return HttpResponse('failed{}'.format(e)) if statusReject: remove = Order.objects.get(pk=statusReject.id) delete(remove) Template {% block content %} {% for allorder in allOrders %} {{ allorder.id }} {{ allorder.orderProduct.product.name }} {{ allorder.orderProduct.quantity }} <button type="submit" name="acceptButton" value="accept"><a href="{% url 'orderDecision' %}?order_id={{ allorder.id }}">Accept</a></button> <button type="submit" name="rejectButton" value="reject"><a href="{% url 'orderDecision'%}?order_id={{ allorder.id }}"> Reject</a></button> {% endfor %} {% endblock % } -
Django Api Json format change
I have my json output in the given format the main body of the article is inside one key only. what i want to do is separate out them based on diffrent paragraphs Current output Output i Want Not exactly in the same format but in a way it can atleast separate out between tags -
django switch Language doesn't work (i18n)
I follow the teaching on the internet . Why do I always fail to translate successfully? Please help me see where I am missing. My {% trans "test" %} never translates. Then I click on other languages in html and it will go to http://127.0.0.1:8000/i18n/setlang/. I don't know where i went wrong . Django ver 3.2 settings.py MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.i18n', ... ], }, }, ] LANGUAGES = ( ('en-us', 'English (United States)',), ('zh-tw', '繁體中文(台灣)') ) LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True LOCALE_PATHS = [Path(BASE_DIR, "locale")] USE_TZ = True projects.urls.py urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( path('', include('App.urls', namespace='app')), ) App.urls.py app_name = 'App' urlpatterns = [ path('index/', views.I18_Test.as_view(), name='index'), ] locale en_us #: templates/hello.html:12 msgid "test" msgstr "EEE" #: templates/hello.html:19 msgid "Language" msgstr "En" zh_tw #: templates/hello.html:12 msgid "test" msgstr "TTT" #: templates/hello.html:19 msgid "Language" msgstr "TW" html {% load i18n %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head> <body> {% trans "test" %} <nav class="navbar navbar-expand-lg navbar-light navbar-suspend" id="base-navbar"> <div class="container"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item … -
How does Django find if i a user is authenticated?
I'm building a SPA that uses Django on the backend for authentication, and i'm using Session Authentication. In order to check if a user is authenticated, the SPA sends Django a standard request to an endpoint that will simply return request.user.is_authenticated. This works because the sessionid cookie is always sent from the client to the Django app. In another part of the SPA app, for some reason the cookie is not being sent with the request, so Django always returns False even when the user is logged in. The solution i found is to send the sessionid cookie in the POST request body, but this will still return False. Since that didn't work either, i had this idea: if the sessionid cookie is not in the cookies but it is in the request's body, set the cookie manually from the view: def checkAuth(request): if request.method == 'POST': session_cookies = json.loads(request.body.decode('utf-8')) request.COOKIES['sessionid'] = session_cookies['sessionid'] request.COOKIES['csrftoken'] = session_cookies['csrftoken'] print(request.COOKIES) response = {'state': str(request.user.is_authenticated), 'username': str(request.user)} return JsonResponse(response, safe=False) Here i see the cookies being set in the view: {'sessionid': 'somecookie', 'csrftoken': 'sometoken'} But request.user.is_authenticated still returns False. Why is that? Is there any way i can solve this? -
How to make django project licensable?
I have a django project that is deployed at the customer site and managed by their employees. This on-premise installation consist of various components like nginx, uwsgi, postgres, task schedulers, etc which are packaged and deployed on a server within customer's VPC. The entire project is an enterprise edition consisting of complex workflows and features specific to the business use-case. Now, my task is to make this piece of software licensable by pricing certain pages, reports, features, modules etc as per the agreement with the client. The project contains role based access control as well as a provision to turn features on/off based upon some config settings in the django project. I wish to make this project licensable by allowing customer to subscribe for the features they required and provide them with some sort of activation/license key that they can add it to their deployed project. The challenge is that the code is exposed to the customer since it is deployed at their site and someone can crack the code to turn on unpaid features. Can anyone please guide me on best practices for the same? Reagrds -
Django deployment error deango.core.exceptions.ImproperlyConfigured
Hey i have an django application which is working fine locally but its not working when it is hosted on a web showing below error django.core.exceptions.ImproperlyConfigured: Error loading pyodbc module: /lib/x86_64-linux-gnu/libm.so.6: version `GLIBC_2.29' not found (required by /home/site/wwwroot/antenv/lib/python3.7/site-packages/pyodbc.cpython-37m-x86_64-linux-gnu.so) Did i miss anything at the time of hosting? -
How to use the form values inside form_valid function in django
I would like to know how to use the inputted values into a form in the form_valid function in my view. First of all, here is the view: class OrganisorStudentUpdateView(OrganisorAndLoginRequiredMixin, generic.UpdateView): # some code form_class = OrganisorStudentUpdateModelForm # some code def form_valid(self, form, *args, **kwargs): # some variables from form print(form.instance.weekday.all()) # some extra mathematical code using the values of form.instance.weekday.all() # update some of the other form fields print(form.instance.weekday.all()) return super().form_valid(form, *args, **kwargs) weekday in form.instance.weekday.all() is a many to many field in the form that is linked to another model. The problem is that I need to click the update button twice in order to do the mathematical code with the values from weekday. Here is a simple example. My current values for the weekday form field is the "Monday", "Wednesday", "Friday" checkboxes checked. When I update the form without changing anything, the following is printed: <QuerySet [<Weekday: Monday>, <Weekday: Wednesday>, <Weekday: Friday>]> <QuerySet [<Weekday: Monday>, <Weekday: Wednesday>, <Weekday: Friday>]> Then, I will change my values for weekday to "Tuesday" and "Thursday". I updated. I got this: <QuerySet [<Weekday: Monday>, <Weekday: Wednesday>, <Weekday: Friday>]> <QuerySet [<Weekday: Monday>, <Weekday: Wednesday>, <Weekday: Friday>]> This is not what I want, as … -
C++ server and django as client connection
I have wanted to make my a socket connection between my django client and c++ server.As press button on my django webpage it will reflect in my client -
HTML page running in Django does not look the same on two different machines
I am not very experienced (read as: next to no experience) with Django and HTML, but I am trying to make a web page with some buttons and CSS animations. I am working together with a partner, and while working together, we noticed that the elements positioned around on the page appear in very different positions between the two of us. What shows up on my end: What shows up on their end (which is what we are trying to get at, positioning the images over the bubbles correctly): I am mostly interested on why it happens that we have the exact same files but our pages, both opened in Chrome, same screen ratios etc, look different. Also why it happens that I make changes to the CSS file and the page does not change at all; and I'm talking changes such as removing all positioning of the images, which should align them to the up left corner, but they sit in place(yes I did save, reload the page, restart the server etc). -
Django - querying multiple values using foreign keys
I am new to Django and trying to understand the model relationships. I have two models: class Author(models.Model): author_name = models.Charfield(max_length = 15) class Books(models.Model): book_name = models.CharField(max_length = 15) authors = models.ForeignKey(Author) In my views.py I am accessing the records like this: class BooksViewSet(APIView): def get(self, request): data = Books.objects.all() Now suppose I have multiple books with multiple authors, how do I create an API which would include all the authors of the books? I think I need to filter out the values but am not exactly sure how it is done. Currently, I get only one author using the above views.py. Sorry if I missed the obvious. Thanks for your time in advance. -
How to insert an image in a specific area in a bootstrap crad?
I am trying a attach an image in a specific area in a card, but I don't know how to. I am sorry if it's a silly question, I am a beginner in terms of html. So can anyone please show me how to do it? I am using Django. For example, If I want to add an image in that specific blue outlined area, what should I do? My code {% for fixture in fixtures %} <div class="card bg-light"> <div class="card-header" style="color:red;" > Featured </div> <div class="card-body"> <h5 class="card-title" style="color:black;">{{ fixture.home_team }} vs {{ fixture.away_team }}</h5> <p class="card-text" style="color:black;">{{ fixture.description }}</p> <form style="color:black;"> <h5><label for="watching">Watching?</label> <input type="checkbox" id="watching" name="watching" value="watching"> </h5> </form> </div> </div> {% endfor %} -
Input fields are makred always RED in Djano UserRegistrationForm
I am creating a User authentication system in Django. The first page I set is to Register a new user. For that, my views.py is below: views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from .forms import UserRegisterForm from django.contrib import messages # To give an alert when a valid data is received # Create your views here. def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created!') return redirect('login') else: form = UserRegisterForm(request.POST) return render(request, 'Agent/register.html', {'form': form}) and the html file is given below: register.html {% extends "client_management_system/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted "> Already Have An Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a> </small> </div> </div> {% endblock content %} and the URL pattern for register page is given below: from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from Agent import views as agent_views urlpatterns = [ path('admin/', admin.site.urls), path('', include('client_management_system.urls')), …