Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Only the First Button works in Django loop
The div only appears if the first button is clicked. Its works as i wanted but only for the first button in loop. When i manually put display = "block" it appears though on bith loop. What i want is to toggle the class "bg-model" by clicking on the class "editTime". Any help would be appreciated. Thanks in advance... HTML <h4>Appointments</h4> {% if upcomming_appointments %} {% for d in upcomming_appointments %} <li class="list-group-item d-flex justify-content-between align-items-center flex-wrap"> <h6 class="mb-0"> <ion-icon name="medkit"></ion-icon> Appointment with <strong>{{d.PatientName}}</strong><a class="btn btn-info " id="sessionBtn" href="{% url 'medicalReport' d.id %}">Start Session</a> </h6> <span class="text-secondary"> Date: <strong>{{d.appoitmentDate}}</strong> <br> Time: <strong>{{d.appoitmentTime}}</strong><br> Symptoms: <strong>{{d.symptoms}}</strong><br> Comment: <strong>{{d.Comments}}</strong><br> </span> <a id = "changeTime" class="editTime">Change time</a> <a class="btn btn-info " id="logoutBtn" href="{% url 'delete_appointment' d.id %}" onclick="return confirm('Are you sure you want to cancel this appointment? This action is irreversible.')">Cancel Appoitment</a> <div class="bg-modal"> <div class="modal-contents"> <div class="close">+</div> <form method="POST"> <h5>Change Appointment Time</h5> {{d.id}} <input type="hidden" name="SessionID" value="{{d.id}}"> <input type="time" id="timeChange" class="input" placeholder="Time"> <button type="submit" class="loginBtn">Submit</button> </form> </div> </div> </li> JS document.querySelector('.editTime').addEventListener("click", function() { document.querySelector('.bg-modal').style.display = "flex"; }); document.querySelector('.close').addEventListener("click", function() { document.querySelector('.bg-modal').style.display = "none"; }); views.py def doctorProfile(request): upcomming_appointments = Appoitment.objects.all().filter( DoctorEmail=request.user, appoitmentDate__gte=timezone.now()).order_by('appoitmentDate') past_appointments = Appoitment.objects.all().filter( DoctorEmail=request.user, appoitmentDate__lt=timezone.now()).order_by('-appoitmentDate') g = request.user.groups.all()[0].name if g == … -
Django Admin Search field reverse lookup
I have following models: class Policy(models.Model): name = models.CharField(max_length=40) def __str__(self) -> str: return self.name class Meta: verbose_name_plural = 'Policies' class Statement(models.Model): name = models.CharField(max_length=40) policy = models.ForeignKey( to=Policy, on_delete=models.CASCADE, related_name='statements' ) action = models.CharField(max_length=64) resource = models.CharField(max_length=128) and following simple model admin: class PolicyAdmin(admin.ModelAdmin): inlines = [StatementInline] search_fields = [name,] What I want to achieve is to enable search functionality on Policy change list, through which I can search Policy with the name field of Statement model in addition to policy name. -
Django: Use different serializers for different (inherited) models in one endpoint
I have this models (for ilustration only): class Customer(models.Model): created = models.DateTimeField(auto_now_add=True) class Person(Customer): first_name = models.CharField(max_lenght=40) last_name = models.CharField(max_length=40) # More data related to a person class Company(Customer): company_name = models.CharField(max_length=100) # More data related to a company As you can see, I can have two "types" of customers, but they are both "customers" (I think this is a textbook example of inheritance). Everything works fine at the database level, but now I need to create an endpoint that will "dinamically" show the customer data based on which "type" of customer it is. Something like this: [ { "id": 1, "first_name": "John", "last_name": "Doe" }, { "id": 2, "company_name": "Big buck" }, { "id": 3, "first_name": "Jane", "last_name": "Doe" } ] When working within my project, I use things like: customer = Customer.objects.get(pk=100) if hasattr(customer, 'person'): pass # Do some stuff elif hasattr(customer, 'company'): pass # Do some other stuff # Do common stuff related to both customer 'types' So far, I've managed to work around by using different endpoints for "Person" and "Company" customers, but now I need to get both "types" of customers in a single endpoint. And I can't figure out how to write a serializer … -
How to bind models and form json structure?
I'm trying to implement rest api using django rest framework. I want to form a specific JSON, having the ability to receive a nested array with a set of objects. serializers.py class CarListSerializer(serializers.ModelSerializer): # option = serializers.StringRelatedField(many=True) class Meta: model = Car fields = ('id', 'model', 'mark', 'option') models.py class Car(models.Model): model = models.CharField(max_length=200) mark = models.CharField(max_length=200) option = models.ForeignKey('Option', related_name='option', on_delete=models.PROTECT, null=True) class Meta: unique_together = ['model', 'mark', 'option'] class Option(models.Model): color = models.CharField(max_length=200) engine = models.CharField(max_length=200) transmission = models.CharField(max_length=200) Expected Result: [ { "id": 1, "model": "Toyota", "mark": "Prado", "option": [ {'color': 'black', 'engine': '4.2', transmission: 'auto'}, {'color':'white', 'engine': '5.0', transmission: 'auto'} ] }, { "id": 2, "model": "Mazda", "mark": "CX-7", "option": [ {'color': 'white', 'engine': '3.5', transmission: 'auto'}, {'color': 'black', 'engine': '4.2', transmission: 'auto'} ] } ] -
How to copy queryset by splitting field value when calculating Django ORM
I am using django. If there are two or more people in the teacher field, that is, if the special character "/" is included, I want to copy the row by splitting it based on "/". [views.py] counts = Research.objects.values('teacher').annotate(**annotations).values('teacher', *annotations.keys()) The result of the current code is: <QuerySet [{'teacher': 'Helen', 'A': 1, 'R_A': 1}, {'teacher': 'Aron/Cyrus', 'A': 0, 'R_A': 0}, {'teacher': 'Daisy', 'A': 1, 'R_A': 1}, {'teacher': 'Mindy', 'A': 2, 'R_A': 0}]> The result I want to get is: <QuerySet [{'teacher': 'Helen', 'A': 1, 'R_A': 1}, {'teacher': 'Aron', 'A': 4, 'R_A': 2}, {'teacher': 'Cyrus', 'A': 4, 'R_A': 2}, {'teacher': 'Daisy', 'A': 1, 'R_A': 1}, {'teacher': 'Mindy', 'A': 2, 'R_A': 0}]> It looks like an ORM change is required. I've been searching for over 2 hours, but I can't get a solution. Does anyone know how to solve it? -
How can I redirect a user to the dashboard instead of HTTP/something/some page, after a user is successfully loggedin in Django?
http://127.0.0.1:8000/cases instead of redirecting to home pages, it's directly sending us to cases tab. -
how to keep current image file on update form django
I am making an update profile page that conclude change picture, name, and email. everytime I tried to change email or name without changing picture, it erase the picture column. How can I prevent this to happen? I've tried to put value on input file, but then I found out that input file will not read the value and always give back C://fakepath// forms.py : class UpdateForm(forms.Form): name = forms.CharField( max_length=255, required=True, help_text="Required, name" ) email = forms.CharField( max_length=254, help_text="Required. Inform a valid email address." ) avatar = forms.ImageField(required=False) views.py : class Account(LoginRequiredMixin, FormView): model = CustomUser form_class = UpdateForm user = None template_name = 'settings/account.html' def get(self, request, *args, **kwargs): self.user = get_object_or_404(CustomUser, id=kwargs["pk"]) return super(Account, self).get(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.user = get_object_or_404(CustomUser, id=kwargs["pk"]) return super(Account, self).post(request, *args, **kwargs) def form_valid(self, form): self.user.email = form.cleaned_data["email"] self.user.name = form.cleaned_data["name"] self.user.avatar = form.cleaned_data.get('avatar') self.user.save() messages.add_message( self.request, messages.SUCCESS, "Update {} user success".format(self.user.name) ) return super(Account, self).form_valid(form) Templates : <form action="{% url 'Account-list' user.id %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <input accept="image/*" name="avatar" type='file' id="imgInp" /> <label for="" class="field-label">Full Name</label> <input type="text" name="name" id="name" class="field-style" value="{{user.name}}" placeholder="Write name here..."> <label for="" class="field-label">Email Registered</label> <input type="text" name="email" id="email" class="field-style" value="{{user.email}}" … -
can't import six.moves module
import json from six.moves.urllib_parse import urlencode from six.moves.urllib_request import urlopen from django.core.management.base import CommandError def call(method, data, post=False): """ Calls `method` from the DISQUS API with data either in POST or GET. Returns deserialized JSON response. """ url = "%s%s" % ("http://disqus.com/api/", method) if post: # POST request url += "/" data = urlencode(data) else: # GET request url += "?%s" % urlencode(data) data = "" res = json.load(urlopen(url, data)) if not res["succeeded"]: raise CommandError( "'%s' failed: %s\nData: %s" % (method, res["code"], data) ) return res["message"] module) moves Import "six.moves.urllib_parse" could not be resolved from sourcePylancereportMissingModuleSource installed the six module to Python virtual environment six can be imported without problems Occurs from six.moves MissingModuleSource Why can't Import? six.moves -
Spyne, Django change WSDL url
I am using django behind nginx reverse proxy and django sees the server url different than what it actually is hosted on like: Django: http://webserver.com Nginx: https://webserver.com When I try to add the WSDL to SoapUI it automatically defaults to the first http://webserver.com server and then all the requests fail. I have tried the code below, but it did not work: ... app = Application( [EXTWS], tns='soap.views', in_protocol=Soap11(validator='soft'), out_protocol=Soap11(), ) app.transport = "no_transport_at_all" ... wsdl = Wsdl11(app.interface) if os.environ.get("DEBUG"): wsdl.build_interface_document('http://localhost:8000/wsdl/') else: url = f'https://{settings.DOMAIN}/wsdl/' wsdl.build_interface_document(url) Inspirations: here and here -
django user's session key has been changed to another user's session key sometimes
base.py AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] middleware.py class CountVisitorMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) ... return response There are currently social login users and general users. Would using the runserver(not gunicorn or uwsgi) in production be a problem? response = self.get_response(request) <-- Could it be a thread safety issue? Is there anything else i need to check? -
How to overcome Django urlize() method including leading text+. in the url, e.g. x.http://example.com
I am getting an unwanted result from django's urlize method when there is a leading number and period (as might be typed in a numbered list without the expected space) This output surprises me: In [4]: urlize("1.www.test.com") Out[4]: '<a href="http://1.www.test.com">1.www.test.com</a>' It doesn't seem like the parser should include anything before the www prefix unless it's a scheme, but... In [6]: urlize("1.http://test.com") Out[6]: '<a href="http://1.http://test.com">1.http://test.com</a>' What can I do to prevent this? Either by pre-parsing the input or post-parsing afterwards? or is there a better method out there? In [2]: from django.utils.html import urlize In [3]: urlize("www.test.com") Out[3]: '<a href="http://www.test.com">www.test.com</a>' In [4]: urlize("1.www.test.com") Out[4]: '<a href="http://1.www.test.com">1.www.test.com</a>' In [5]: urlize("1.test.com") Out[5]: '<a href="http://1.test.com">1.test.com</a>' In [6]: urlize("1.http://test.com") Out[6]: '<a href="http://1.http://test.com">1.http://test.com</a>' In [7]: urlize("a.http://test.com") Out[7]: '<a href="http://a.http://test.com">a.http://test.com</a>' -
Django framework: unable to load 'services' page
I'm working on a Django project. I think there is some problem with the use of 'services' word in the django project. Please see if you can find some corrections required in the project. The project name is Hello. There is one additional app 'home'. When I navigate to the index, contact, or about page, all of them are working (loading) as expected. But services page is not loading. If I change 'services' to 'service' everywhere, then it works as usual. It's giving the following error: Following are some of the file contents: Hello->urls.py from django.contrib import admin from django.urls import path, include admin.site.site_header = "Harry Ice Cream Admin" admin.site.site_title = "Harry Ice Cream Admin Portal" admin.site.index_title = "Welcome to Harry Ice Creams!" urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), ] home->urls.py from django.contrib import admin from django.urls import path from home import views urlpatterns = [ path('', views.index, name='home'), path('about', views.about, name='about'), path('services', views.services, name='services'), path('contact', views.contact, name='contact'), ] home->views.py from django.shortcuts import render, HttpResponse # Create your views here. def index(request): context = { } return render(request, 'index.html',context) #return HttpResponse("This is homepage") def about(request): context = { } return render(request, 'about.html',context) def services(request): context = { } return … -
Django - Retrive user information with JWT token
MY FUNCTION ONLY SHOWS ACCESS TOKEN API when I hit (user-info)API/login link. I want to show API tokens with user information. http://127.0.0.1:8000/api/login/ link show API with user information # Import libraries from rest_framework.response import Response from rest_framework.views import APIView from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView from base.api.serializers import UserSerializer from base.models import User from rest_framework.permissions import IsAuthenticated, AllowAny class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) # Add custom claims token['username'] = user.username return token # Token Access class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer # Registration class RegisterView(APIView): permission_classes = [AllowAny] def post(self, request): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) # User information class LoginView(APIView): permission_classes = [IsAuthenticated] def get(self, request): user_id = request.user.id user = User.objects.get(id=user_id) serializer = UserSerializer(user) return Response(serializer.data) API Token Access -
How to easily debug Redis and Django/Gunicorn when developing using Docker?
I'm not referring to more sophisticated debugging techniques, but how to get access to the same kind of error messages that are normally directed to terminal tabs? Basically I'm adopting Docker in a Django project also using Redis. In the old way of working I opened a linux terminal tab for gunicorn like this: gunicorn --reload --bind 0.0.0.0:8001 myapp.wsgi:application And this tab kept running Gunicorn and any Python error was shown in this tab so I could see the problem and fix it. I could also open a second tab for the celery woker: celery -A myapp worker --pool=solo -l info The same thing happened, the tab was occupied by Celery and any Python error in a task was shown in the tab and I could see the problem and correct the code. My question is: Using docker is there a way to make each of the containers direct these same errors that would previously go to the screen, to go to log files so that I can debug my code when an error occurs in Python? What is the correct way to handle simple debugging during development using Docker containers? -
DJANGO : How to print the value from a class in the prefetch_related class, which calls another class as a Foreign key?
I am very new to Django and tried various answered questions on this forum. But I could not display the TITLE of the Product. I want to display the TITLE for my product from the DB. From models.py : class Product(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField() unit_price = models.DecimalField(max_digits=6, decimal_places=2) inventory = models.IntegerField() last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT) promotions = models.ManyToManyField(Promotion) class Order(models.Model): PAYMENT_STATUS_PENDING = 'P' PAYMENT_STATUS_COMPLETE = 'C' PAYMENT_STATUS_FAILED = 'F' PAYMENT_STATUS_CHOICES = [ (PAYMENT_STATUS_PENDING, 'Pending'), (PAYMENT_STATUS_COMPLETE, 'Complete'), (PAYMENT_STATUS_FAILED, 'Failed') ] placed_at = models.DateTimeField(auto_now_add=True) payment_status = models.CharField( max_length=1, choices=PAYMENT_STATUS_CHOICES, default=PAYMENT_STATUS_PENDING) customer = models.ForeignKey(Customer, on_delete=models.PROTECT) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.PROTECT) product = models.ForeignKey(Product, on_delete=models.PROTECT) quantity = models.PositiveSmallIntegerField() unit_price = models.DecimalField(max_digits=6, decimal_places=2) From views.py : order = Order.objects.select_related('customer').prefetch_related('orderitem_set__product').order_by('-placed_at')[:5] From hello.html : {% for prod in order %} <li>Order ID : {{ prod.id }} -- Customer {{ prod.customer.first_name }} -- Product {{ prod.orderitem_set.product.title }}</li> I have 2 questions here: In hello.html : How do I display the Product Title? In the views.py : How do I load and display the promotions from the product class in same call? Expected output : Order ID : 408 -- Customer Olin -- Product -- Cheese -- Promotion : … -
Updating a field within another Model's save method with F()
I'm attempting to create a voting system where the score of a given post is separate from the type of votes placed by users. In the event that a user deletes a profile, a given score should not increment/decrement due to their vote being deleted. Therefore scores are only updated by using an F('score') + 1 or F('score') - 1 expression. Within Vote.save(), I'm trying to implement this, yet the Question.score field doesn't update when the Vote is created. How can I get the test to pass where the score in the question goes from 0 to 1? class TestQuestionScoreUpVote(TestCase): '''Verify that a Question's score increments by one point when the Vote is an "up" vote.''' @classmethod def setUpTestData(cls): tag1 = Tag.objects.create(name="Tag1") user = get_user_model().objects.create_user("TestUser") profile = Profile.objects.create(user=user) cls.question = Question.objects.create( title="Question__001", body="Content of Question 001", profile=profile ) cls.question.tags.add(tag1) user_vote = Vote.objects.create( profile=profile, type="upvote", content_object=cls.question ) def test_new_user_vote_on_question(self): self.assertEqual(self.question.score, 1) class Post(Model): body = TextField() date = DateField(default=date.today) comment = ForeignKey('Comment', on_delete=CASCADE, null=True) profile = ForeignKey( 'authors.Profile', on_delete=SET_NULL, null=True, related_name='%(class)ss', related_query_name="%(class)s" ) vote = GenericRelation( 'Vote', related_query_name="%(class)s" ) score = IntegerField(default=0) class Meta: abstract = True class Question(Post): title = CharField(max_length=75) tags = ManyToManyField( 'Tag', related_name="questions", related_query_name="question" ) views = … -
Attribute error 'int' object has no attribute 'items'
Attribute error 'int' object has no attribute 'items' her my Modelserializer def validate(self, validated_data): gameevent = validated_data.get('gameevent') match_round =validated_data.get('match_round') if not match_round : raise serializers.ValidationError("Enter value more than 0 ") if match_round == 1: return match_round round = range(1,match_round) match = Matchscore.objects.filter(gameevent=gameevent,match_round__in=round).values_list('match_round',flat=True) match = set(match) if match : return validated_data else: raise serializers.ValidationError("Enter a valid match_round") -
How do I return multiple and single record using one view Django
So, I am trying to use one view to give multiple and a single record. Is it possible? So in urls.py I have defined path as path('main/actor/<int:pk>', views.getMainActor) In my views file @api_view(['GET']) def getMainActor(request, pk=None): if pk is None: actor = ActorModel.objects.all() serializer = ActorSerializer(actor, many=True) else: actor_single = CheeringCharacter.objects.get(id=pk) serializer = ActorSerializer(actor_single) return Response(serializer.data) The error I am getting is admin/ main/actor/<int:pk> The current path, main/actor/, didn’t match any of these. -
How do I manage Django migrations when commiting changes from local development to remote?
During Django development, I have to create many migrations to get to what I'm looking for. For example, I might change the name of a field and later decide to set it back to what it was. So a lot of my migrations are just toying with the ORM. I assume I don't need them all to show up in the remote repo (which might be a wrong assumption!). I know excluding the migrations via .gitignore is not the right way. Also can't include random ones in commits as they are all linked to one another. So far, I squash my migrations each time I made changes: squashmigrations app_label [start_migration_name] migration_name and then commit. What would be a better solution? -
Python Django load data from text document
I am using python and django to make a website that should be able to load data from a text document and display it. Until now I have converted the data from txt format to html and loaded it to a div like so : <div id='data'> {% include "data.html" %} </div> Unfortunately when I hit refresh after I have modified data.html there is no update. I would like to be able to load the html file on every refresh -
Django-redis for caching time working properly in my PC as Memurai installed but after deploying on heroku error showing 500 in a specific page
I am building a E-commerce website for a client applying OTP verification fir registration for that I have used Django-redis for caching time for OTP expiring also installed Memurai after making debug=false it is working properly but after deploying it on Heroku error showing 500 in page where OTP generate -
How to view data in Django pass to external js
I've been using an id to get all data from external js but the question is I want to display data from the database, but using the template is on external js, I just call an 'id' from external js to my HTML, is somebody know how to read {for data} under external js? views.py def dashboard(request): tasks = task.objects.all() tasks = {'requestsdata':tasks} return render(request, 'dashboard.html',tasks) dashboard.html - I've been using id to fetch all data inside external js <div class="card-body"> <div id="demo2"></div> </div> custom.js External js {% for listofdata in requestsdata%} var kanban2 = new jKanban({ element: '#demo2', gutter: '15px', click: function (el) { alert(el.innerHTML); }, boards: [{ 'id': '_todo', 'title': 'To Do (Item only in Working)', 'class': 'bg-info', 'dragTo': ['_working'], 'item': [{ 'title': ` <a class="kanban-box" href="#"><span class="date">24/7/20</span><span class="badge badge-info f-right">medium</span> <h6>{{listofdata .description}}</h6> //etc. so on ......... `, } ] }, ] }); {% endfor %} -
Valid JSON in Django admin
can you help me figure out what kind of valid data I would need to enter in the Django admin for a schema defined as follow?: REQUIREMENTS_SCHEMA = { "type": "array", "items": { "type": "object", "properties": { "chain": {"type": "string", "enum": BLOCKCHAINS_ENUM}, "asset_type": {"type": "string", "enum": ASSET_TYPES_ENUM}, "asset_address": {"type": "string", "pattern": "^(0x|0X).*$"}, "amount": {"type": "integer", "minimum": 1}, "token_id": {"type": "array", "items": {"type": "integer"}, "minItems": 0}, }, "required": ["chain", "asset_type", "asset_address", "amount"], }, } I tried this [{"type": ["f"], "items": {"type": "x", "properties": {"chain": "ETHEREUM", "asset_type": "ERC20", "asset_address": "0x711Dfd645411B741E6FE3aeaA37d504C0e44B0F9", "amount": 2, "token_id": 2}}}] But im am getting an error -
Django AssertionError No api proxy found for service "memcache"
I'm running a Django app on GAE and I want to use memcache in my views.py to store some data for caching. I have not setup anything for caching in my settings.py and immediately use from google.appengine.api import memcache inside of views.py and pulls/insert data using the .add() and .get() method. This however, results in an AssertionError at / : No api proxy found for service "memcache" What am i missing here? Should I be setting up something inside of settings.py? From my understanding memcache is a built-in feature of GAE and I figured it worked the same way as an API key where we would not need to specify them inside of the settings.py Plus the documentation also does not provide any information on proxy setup or whatsoever. -
How to achieve dynamic filter in django
In my frontend, I have three kinds of filter and when user selects selects those and click on filter then I need to update the results. The problem is user may select any one or two or all the three filters combinedly. But my code just filters only one condition: Here is my code: filter1 = request.POST.getlist("filter1") //Every filters are in arrays filter2 = request.POST.getlist("filter2") //Every filters are in arrays filter3 = request.POST.getlist("filter3") //Every filters are in arrays data = Data.objects.filter(is_approved=True, published=True) //This the model to be filtered if len(filter1) > 0: data = data.filter(intakes__contains=filter1) if len(filter2) > 0: data = data.filter(elevel__contains=filter2) if len(filter3) > 0: data = data.filter(country__in=filter3) How to make this dynamic ? Like it should filter based on more than one selections. Please help