Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter product by its Attribute in Django - Django?
I'm working on a Django Ecommerce project where product has several attributes like. size, color( A single product can have multiple attributes with different size and color). No i'm trying to filter products using django_filters but unable to filter by its attributes. Below are the codes(models) for your reference. Request you to kindly look in to and help. Thanks in advance. Product Model: class Product(models.Model): variations = ( ('None', 'None'), ('Size', 'Size'), ) name = models.CharField(max_length=200, unique=True) store = models.ManyToManyField(Store) slug = models.SlugField(null=True, blank=True, unique=True, max_length=500) sku = models.CharField(max_length=30, null=True) tax = models.IntegerField(null=True, blank=True) stock = models.CharField(max_length=10, null=True) variations = models.CharField(choices=variations, max_length=20) short_description = models.CharField(max_length=500, null=True) details = RichTextUploadingField(null=True, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) discounted_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) image = models.ImageField(upload_to='product/images', default='product.png', null=True, blank=True) image_one = models.ImageField(upload_to='product/images', null=True, blank=True) image_two = models.ImageField(upload_to='product/images', null=True, blank=True) image_three = models.ImageField(upload_to='product/images', null=True, blank=True) image_four = models.ImageField(upload_to='product/images', null=True, blank=True) image_five = models.ImageField(upload_to='product/images', null=True, blank=True) tags = models.ManyToManyField(Tags) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True, related_name='products') status = models.CharField(max_length=20, choices=(('Active', 'Active'), ('Inactive', 'Inactive'))) brand = models.ForeignKey(Brand, on_delete=models.PROTECT, blank=True, null=True) offer = models.ForeignKey(Offer, on_delete=models.CASCADE, null=True, blank=True) # This is used only for filtration Product attribute model class ProductAttribute(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) size = models.ForeignKey(Size, on_delete=models.CASCADE, … -
django set_cookie does not set cookie in browser
I am writng a drf app, that sets cookie. I set cookie like this: serializer = TitleSerializer(result.titles, many=True) response = JsonResponse(serializer.data, safe=False) response.set_cookie("country_code", code) return response But when I check request for cookies like this: if 'country_code' in request.COOKIES: print(request.COOKIES['country_code']) I get nothing. I checked response object in browser console and it has them in headers: Set-Cookie country_code=unknown; Path=/ and in cookies: country_code path "/" value "unknown" But when I go to inspect>storage>cookies there is nothing there. Should I set cookies by hand in js or am I doing something wrong in django part? I just googled how to set cookies in django and it seemed like browser should set and send cookies automaticly, so I was curious what I'm doing wrong. -
Django .exclude() returns empty queryset
I have a problem with .exclude() when making a QuerySet. My models involved are: Profession class Profession(models.Model): profession_name = models.CharField(max_length=20) equipment = models.ManyToManyField(Equipment, blank=True) ability = models.ManyToManyField(Ability, blank=True) skill = models.ManyToManyField(Skill, blank=True) skill_advanced = models.ManyToManyField(SkillAdvanced, blank=True) Ability class Ability(models.Model): ability_name = models.CharField(max_length=35) When I create QuerySet with: self.prof_abilities = Profession.objects.filter(profession_name="Acolyte").values('ability') I get: <QuerySet [{'ability': 2}, {'ability': 69}, {'ability': 81}, {'ability': 86}, {'ability': 23}]> But I would like to exclude some values, so I use this instead: self.prof_abilities = Profession.objects.filter(profession_name="Acolyte").exclude(ability__in=[2, 23, 81, 86]).values('ability') But the outcome is an empty QuerySet: <QuerySet []>. I've tried various tweeks like .exclude(ability__id__in=[2, 23, 81, 86]) or .exclude(ability__ability_name__in=['Foo name', 'Bar name'] but with no success. I'm new to Django so if this is something obvious, I would also appreciate some pointers where to read more on my mistake. -
Django rest framework post request returns 200 but data is not saved in the database
when post request is sent to the api, api returns Ok as the response but no data is inserted into the database. views.py @api_view(['POST']) def createTicketList(request): serializer = TicketListSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) serializer.py class TicketListSerializer(serializers.ModelSerializer): class Meta: model = TicketListTable fields = '__all__' def create(self, validated_data): return TicketListTable(**validated_data) models.py class TicketListTable(models.Model): ticketListName = models.CharField(max_length=50) ticketListCreated = models.DateTimeField() ticketListUpdates = models.DateTimeField() def __str__(self): return self.ticketListName class Meta: app_label = "backend" db_table = "TicketListTable" postman api postman api post request -
django getting distinct records in table seems to choose random row
I have a table that contains the pricing data for the cards and I am trying to get the pricing data for distinct cards by card_id but this seems to select the row at random. I would like to get the latest datetime pricing data for each card card_id. Table: id nonfoil foil datetime card_id "fb7fbcdc" 0.20 0.49 "2021-10-11 10:03:51.943603+01" "00302342" "d0d6f491" 0.10 0.49 "2021-10-11 10:01:09.916438+01" "00302342" "bfdca73b" 0.03 0.04 "2021-10-11 10:03:51.907601+01" "012e0b83" "33c7aeae" 0.10 0.04 "2021-10-11 10:01:09.875894+01" "012e0b83" "94ca3324" 0.10 0.04 "2021-10-11 10:01:09.961261+01" "0307f37b" "2e992a8d" 0.03 0.04 "2021-10-11 10:03:51.988602+01" "0307f37b" I currently am getting the pricing data using the following code: pricing_cards.objects.filter(card_id__rarity='mythic').values_list('nonfoil', flat=True).distinct('card_id'), For example this is returning: id nonfoil foil datetime card_id "d0d6f491" 0.10 0.49 "2021-10-11 10:01:09.916438+01" "00302342" "bfdca73b" 0.03 0.04 "2021-10-11 10:03:51.907601+01" "012e0b83" "94ca3324" 0.10 0.04 "2021-10-11 10:01:09.961261+01" "0307f37b" But I would like it to return: id nonfoil foil datetime card_id "fb7fbcdc" 0.20 0.49 "2021-10-11 10:03:51.943603+01" "00302342" "bfdca73b" 0.03 0.04 "2021-10-11 10:03:51.907601+01" "012e0b83" "94ca3324" 0.10 0.04 "2021-10-11 10:01:09.961261+01" "0307f37b" -
Working fine in localhost but page not found when live online in Django
Below are urls.py and views.py part. It was working properly in local host but but return page not found 404 after deployment online. #urls.py from django.urls import path from . import views urlpatterns = [ path('', views.store, name='store'), path('cook/', views.cook, name='cook'), ] #views.py from django.http import HttpResponse def cook(request): return HttpResponse('This is a test message') -
SQL server - Login timeout expired (0) (SQLDriverConnect)
I have created docker container for django application and i wanted to connect with MSSQL in my local machine from the docker but I couldn't able to connect it. I have tried changing the host in the connection string but still its reflecting the same Error which i get when i tried docker-compose up as ERROR-log: conn = Database.connect(connstr, web_1 | pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') settings.py -host i have tried with other ip as well but failed to connect when running in local also DATABASES = { "default": { "ENGINE": "sql_server.pyodbc", "NAME": "dbnew", "USER": "user1", "PASSWORD": "user@1233", # "Integrated Security":"SSPI", "HOST": "172.19.179.179", "PORT": "", "OPTIONS": { "driver": "ODBC Driver 17 for SQL Server", }, }, } dockerfile FROM python:3.8 ENV PYTHONUNBUFFERED 1 WORKDIR /code #before install pyodbc , we need unixodbc-dev # RUN apt-get install multiarch-support # install msodbcsql17 # RUN su RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - RUN curl https://packages.microsoft.com/config/debian/9/prod.list > /etc/apt/sources.list.d/mssql-release.list RUN exit RUN wget http://archive.ubuntu.com/ubuntu/pool/main/g/glibc/multiarch-support_2.27-3ubuntu1.4_amd64.deb RUN apt-get install ./multiarch-support_2.27-3ubuntu1.4_amd64.deb RUN apt-get update # RUN ACCEPT_EULA=Y apt-get install -y msodbcsql17 # RUN 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc # RUN source ~/.bashrc # optional: for unixODBC development headers RUN ACCEPT_EULA=Y … -
Django does not call the function and does not output information from the database
I started learning django recently and am writing a website for a tutor. I need to add output to topics that are entered into the database through the admin panel. But he doesn't take them out. Although the profile data is displayed perfectly. views.py class TopicListView(ListView): model = Topic template_name = 'video/video.html' context_object_name = 'top' def video(request): top = Topic.objects.all() context = {'top': top} return render(request, 'video/video.html', context) video.html {% load static %} <!DOCTYPE html> <html> <head> <link rel="icon" href="../static/images/favicon.jpg" type="image/x-icon"> <link rel="shortcut icon" href="../static/images/favicon.jpg" type="image/x-icon"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Материалы</title> <link rel="stylesheet" href="{% static 'profiles/css/style.css' %}" type="text/css" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script> </head> <body> {% if user.is_authenticated %} <div class="top"> <a href="/">Главная</a> <a class="active" href="video">Материалы</a> <a href="question">Тесты</a> <a href="accounts/logout"> Выйти</a> </div> {% for post in top %} <div> <h3>{{ post.name_topic }}</h3> </div> {% endfor %} {% else %} <p>Ввойдите в профиль, чтобы увидеть эту страницу</p> <div class="button"> <a href="accounts/login">Log in</a> </div> {% endif %} </body> </html> -
problem with same template's name in different app folder in django
I create two folder app1 and app2 by the command startapp. Then I create folder templates in both app1 and app2. In both templates i create a.html but with the different html content. In the views.py of app1 I create a function to render to a.html and when I visit the url of that function, I get the content of a.html of app2 instead of app1. So what happend here? How could I get exactly the html file from app1? My django ver 3.2.8 and python ver 3.9.6 Thanks in advanced. -
I want to get django rest choices key instead of Value
When i select choice for degree type it returns the value of the choice but i want to get key. For example when i select UNFINISHED_BACHELOR from choices it returns Unfinished Bachelor's degree but i want get UNFINISHED_BACHELOR class CandidateEducation(models.Model): class DegreeType(models.TextChoices): HIGH_SCHOOL = "High School" UNFINISHED_BACHELOR = "Unfinished Bachelor's degree" TWO_YEAR = "Two-year degree" degree_type = models.CharField( max_length=100, choices=DegreeType.choices, null=True, blank=True ) degree_title = models.CharField(max_length=100, null=True, blank=True) institution = models.CharField(max_length=100, null=True, blank=True) class CandidateEducationList(generics.ListCreateAPIView): serializer_class = CandidateEducationSerializer queryset = CandidateEducation.objects.all() class CandidateEducationSerializer(serializers.ModelSerializer): class Meta: model = CandidateEducation fields = "__all__" Result: [ { "id": 6, "degree_type": "Unfinished Bachelor's degree", ----> Error "degree_title": "ABC", "institution": "aaa", } ] Expected [ { "id": 6, "degree_type": "UNFINISHED_BACHELOR", "degree_title": "ABC", "institution": "aaa", } ] -
MultiValueDictKeyError at /change-part/. In python django
So i try to make a upload image system, and i make two different type of image, there are static and dynamic and i try to make a different act/function for thoose type, so i made a two if one like this, if len(request.FILES['img_dinamic']) != 0: part = WebPart.objects.get(part=partToChange) if len(part.dinamic_image) > 0: os.remove(part.dinamic_image.path) img_dinamic = request.FILES['img_dinamic'] else: img_dinamic = "" and the other one is like this if len(request.FILES['img_static']) != 0: img_static = request.FILES['img_static'] else: img_static = "" and when i try to run the system, it appears some error like this MultiValueDictKeyError at /change-part/ 'img_static' any body can help me ? -
Proxy is not reachable from foreign IP's ( Unable to receive SOCKS5 sub-negotiation response )
I just create a new socks5 proxy server ( i use Danete as a server ) in Iran I mean I use the server inside my country and I have an EC2 instance in the us-east-2 region. what I need is to transport some traffic from my AWS EC2 instance to my proxy server in Iran. but now I face some issues the first issue is proxy just work when my request is from ip's in Iran and in this case it works just fine but when I turn on my VPN ( nordvpn USA region ) or make a request from AWS EC2 or any IP from outside of my country I face this error curl: (7) Unable to receive SOCKS5 sub-negotiation response. I have a Django app and need to use this proxy and when i run my Django app in server to user proxy I face this issue requests.exceptions.ProxyError: HTTPSConnectionPool(host='my host', port=443): Max retries exceeded with url: /services/CompositeSmsGateway?wsdl (Caused by ProxyError('Cannot connect to proxy.', RemoteDisconnected('Remote end closed connection without response'))) in my celery worker. I already search the entire internet for a solution but there is no solution for this. This is my dante.conf internal: eth0 port … -
How to update a model inside an exception of a view function and make the transaction commit to the database?
We are trying to create a model to control the number of Access attempts of a user, and then make a call to a function that might throw an exception when, for example, the credentials are not valid. If there is an exception, update the model by incrementing the attempts by one, otherwise update the model in a different way. Everytime we are in the exception branch the model doesn't get created, nor updated. We have tried using s1 = transaction.savepoint() transaction.savepoint_commit(s1) and @transaction.non_atomic_requests but the result gets discarded anyway. There is no way to avoid the exception logic. Django version: Django==2.2.24 access_attempt.py from django.db import models from django.utils.translation import gettext_lazy as _ class AccessAttempt(models.Model): username = models.CharField(_("Username"), max_length=255, null=True, db_index=True) failures_since_start = models.PositiveIntegerField(_("Failed Logins")) validate_jwt_auth.py from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from .models.access_attempt import AccessAttempt from rest_framework import status from rest_framework.exceptions import AuthenticationFailed @transaction.non_atomic_requests def obtain_tokens(request, credentials): attempt = AccessAttempt.objects.filter(username=credentials['username']).first() if attempt is None: attempt = AccessAttempt.objects.create( username=credentials['username'], failures_since_start=0 ) attempt.save() failures = attempt.failures_since_start print(failures) if failures > 5: return {'message': "Failed too many times"}, status.HTTP_403_FORBIDDEN try: with transaction.atomic(): payload = TokenObtainPairSerializer(context={'request':request}).validate(credentials) attempt.failures_since_start=0 attempt.save() return payload, status.HTTP_200_OK except AuthenticationFailed: attempt.failures_since_start += 1 attempt.save() print(attempt.failures_since_start) return {'message': "Unauthorized"}, status.HTTP_401_UNAUTHORIZED views.py def generate_auth(request): … -
Django heroku internal server error after deploying
I have deployed my django app to heroku and I am getting Internal Server Error in the website. settings.py : 'ALLOWED_HOSTS = ['http://127.0.0.1:8000/','https://stripetestdjango.herokuapp.com/', 'localhost'] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] MEDIA_URL = '/images/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) MEDIA_ROOT = BASE_DIR / 'static/images' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' if os.getcwd() == '/app': DEBUG = False The heroku log shows the below: I have .env file. How to push that to server as well as I am deploying using heroku. I guess the error is it is not able to find my .env file. Please feel free to ask for more details if needed. -
Django load only neccessary data from database
I have a problem with django I struggle with for a long time now. I created a chat, and its working basically. But when i send a message, the other client has to refresh his page to see the new message. I tried to send a JsonRequest every 10 seconds, and to reload the messages, but it reloads all messages. So is there a (simple) way to pass to the Frontend only those messages which are not already there? Thanks in advance. views.py def updatechat(response): id = response.GET.get("target_id") target_user = Client.objects.get(id=id) user = Client.objects.get(id = response.user.id) order = user.chatpost_set.filter(partner = target_user.id) return render(response, "main/chat.html", {"order": order}) chat.html target_id = new_id setInterval(function(){ $.ajax({ type: "GET", url: "{% url 'updatechat' %}", data: {"target_id": target_id} }) .done(function(response){ $('#chatdiv').append(response); }); }, 10000) urls.py path("updatechat", views.updatechat, name="updatechat") -
Casting inside a django query
I have a model with two properties class Player(models.Model): username = models.CharField(max_length=200, unique=True) score = models.CharField(max_length=50) I want the score to remain a CharField but now I want to average the scores of all players through a simple query like this Player.objects.aggregate(Avg('score')) This will not work because "score" is a CharField and needs to be cast to a float first. How do I go about typecasting it on the fly? Thank you in advance. -
Reverse accessor for 'base.MentorInfo.groups' clashes with reverse accessor for 'base.StudentInfo.groups'
Here is the models.py file that I have been using. I am trying to create a login model to be implemented using phone auth as well as social auth. from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import AbstractUser from taggit.managers import TaggableManager from django.core.validators import RegexValidator # Create your models here. class StudentInfo(AbstractUser): firstname = models.CharField(max_length=200) lastname = models.CharField(max_length=200) email = models.EmailField(("Email Address"),max_length=200, unique=True, ) password = models.CharField(('Password'),max_length=255) phone = RegexValidator( regex =r'^\+?1?\d{9,12}$', message ="Phone number must be entered in the format: '+999999999'. Up to 12 digits allowed.") USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['firstname','phone'] def __str__(self): return "{}".format(self.email) def create_user(self, email, password=None): user=self.model( email=self.normalize_email(email) , ) user.set_password(password) user.save(using=self.db) return user class MentorInfo(AbstractUser): firstname = models.CharField(max_length=200) lastname = models.CharField(max_length=200) email = models.EmailField(("Email Address"),max_length=200, unique=True, ) password = models.CharField(('Password'),max_length=255) phone = RegexValidator( regex =r'^\+?1?\d{9,12}$', message ="Phone number must be entered in the format: '+999999999'. Up to 12 digits allowed.") USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['firstname','phone'] def __str__(self): return "{}".format(self.email) def create_user(self, email, password=None): user=self.model( email=self.normalize_email(email) , ) user.set_password(password) user.save(using=self.db) return user class LiveProject(models.Model): title = models.CharField(max_length=255) time= models.PositiveIntegerField() role=models.TextField(max_length=255) overview=models.TextField() #task description category=models.CharField(max_length=255) companybackground=models.TextField() video=models.URLField() bandwidth=models.TextField() #expected deliverable tags= TaggableManager() sample=models.URLField() upload=models.FileField("Upload Soln", upload_to=None, max_length=200) image=models.ImageField() textresource=models.CharField(max_length=200) textlink=models.URLField() learnoverview=models.CharField(max_length=100) … -
How to set model default value to a result bring returned by a function?
I've got a function inside my model which generates a random value for the model field and I need to set that value as a default for the model field. I've got the following model class Info(TimeStampedModel): info_id = models.UUIDField(primary_key=True) generated_url = models.TextField( null=False, blank=False, default=random ) def random(self): return 'customer.random.domain.com.' + ("".join(random.choices(string.ascii_uppercase + string.digits, k=5))) I wish the default value for the generated_url to be coming from the method inside the model named as random. but I get the following exception at Runtime: TypeError: random() missing 1 required positional argument: 'self' If I add parenthesis at the end of the function name as generated_url = models.TextField( null=False, blank=False, default=random() ) Then in that case I get a compile time error as the same: TypeError: random() missing 1 required positional argument: 'self' -
I get an error while using this command i don't know why?
ALTER USER kalyan CREATEDB; ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATEDB' at line 1 -
generate pdf not working in single function
I am getting table data from the database and I added a button in HTML and I trying to get pdf by clicking on the button but it's not working. when I am using a separate function in view one for rendering data and another for generates pdf then time it's working but I want to use in single function for generating pdf and render my table. views.py def render_to_pdf(request, template_name, context_dict={}, filename="document"): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="'+filename+'".pdf"' template = get_template(template_name) html = template.render(context_dict) pisa_status = pisa.CreatePDF( html, dest=response, link_callback=context_dict) if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response def training_completed_attendance(request): xyz=trainingMaster.objects.filter(status='Active').order_by('code') context={ 'xyz':xyz, } if request.POST.get('pdf_download'): pdf= utils.render_to_pdf(request, 'dashboard/generate_pdf.html', context, filename='training conpleted') return HttpResponse(pdf, content_type='application/pdf') return render(request,'dashboard/training_completed_report.html',context) html <table class="table table-bordered text-center" border="1" id="table1"> <form method='post'> {% csrf_token %} <button type="submit" name='pdf_download'>Download</button> </form> <tr> <th>Male</th> <th>Female</th> <th>Total</th> </tr> </tr> {% for x in xyz %} <td style="width: 13%; text-align: center; " class="table-cell-label">{{x.male}}</td> <td style="width: 13%; text-align: center; " class="table-cell-label">{{x.female}}</td> <td style="width: 13%; text-align: center; " class="table-cell-label">{{x.total}}</td> {% endfor %} -
AUTH_USER_MODEL refers to model 'user.User' that has not been installed
I am creating a new project in django with a structure like the following: trakkiamultitennant __init__.py asgi.py settings.py urls.py wsgi.py users migrations __init__.py admin.py apps.py models.py serializers.py tests.py urls.py views.py I have updated the app in settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'users', ] AUTH_USER_MODEL = 'user.User' Models.py class User(AbstractUser): is_company = models.BooleanField(default=False) is_employee = models.BooleanField(default=False) is_client = models.BooleanField(default=False) @property def full_name(self): return self.first_name + " " + self.last_name class Company(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(max_length=500, default=0) phone = models.CharField(max_length=50, default=0) address = models.CharField(max_length=500, default=0) gstin = models.CharField(max_length=50, default=0) but when I try to makemigrations it gives me the following error: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'user.User' that has not been installed What am I missing? -
Django DRF Update field with GET method
I have a object table it has a available field which is True by default. I want to make this available field false when API calls through GET method. -
Defining path to image in django
I have a user input some information on a form, and this is used to generate an image that I wish to display on a webpage, however I am unable to work out how I should define the path to the image. I have a user input some information on a form, and this is used to generate an image: make_image.py sns_plot = sns.heatmap(data_from_user) fig = sns_plot.get_figure() fig.savefig(f"{outputs_dir}/{patient.patient_id}/output.png") #patient.patient_id is a also generated by the form I then write some html again based on user inputs and wish to add a link to the image created write_html.py #this is some prewritten html with open(f"{data_dir}/recommendations/{treatment}.html", "r") as file: data = file.read() # here I want to add the image image = f'<img src="output.png" alt = “User generated image”>’ data=data+image #Here i save the amended html with open( f"{outputs_dir}/{patient.patient_id}/treatments/{treatment}{order}.html", "w" ) as file: file.write(data) I am using django and this is my view views.py class TreatmentTemplateView(TemplateView): template_name = "../templates/patient/treatment_detail.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["patient_id"] = self.kwargs["patient_id"] result = find_treatment(context["patient_id"]) context = result[0] context["patient"] = result[1] return context This view puts integrates the html generated in the functions above, the text side of things works fine, it is just … -
Search for user first name and last name together in django
I have a web page where it display the user's details such as their first name and last name, username, email etc. But I only can search either the user's first name or the last name in the search bar, how do I make it so that the user is able to type both the user's first name and last name and display the details out? This is how my web page looks like as shown in the picture below (Ex: The staff name display is admin (First name) and Tan (Last name): views.py @login_required() def allstaff(request): search_post = request.GET.get('q') if (search_post is not None) and search_post: allusername = User.objects.filter(Q(first_name__icontains=search_post) | Q(last_name__icontains=search_post) | Q( username__icontains=search_post) | Q(email__icontains=search_post)) if not allusername: allusername = User.objects.all().order_by("-date_joined") else: allusername = User.objects.all().order_by("-date_joined") page = request.GET.get('page') paginator = Paginator(allusername, 3) try: allusername = paginator.page(page) except PageNotAnInteger: allusername = paginator.page(1) except EmptyPage: allusername = paginator.page(paginator.num_pages) context = {'allusername': allusername, 'query': search_post} return render(request, 'allstaff.html', context) allstaff.html {% extends "home.html" %} {% block content %} <style> table { border-collapse:separate; border:solid black 1px; border-radius:6px; -moz-border-radius:6px; } td, th { border-left:solid black 1px; border-top:solid black 1px; } th { border-top: none; } td:first-child, th:first-child { border-left: none; } </style> <div … -
init function inside serializer class in django rest framework
This is a question of comprehension rather than code issue. I came across a code snippet of other person who has used init function inside the serializer class. I had to write update code on it. I wrote overriding the update method inside that serializer class which is as follows: class ProfileInfoApiview(UpdateAPIView): serializer_class = ProfileInfoSerializer def get_object(self): return self.request.user My serializer that i have wrote: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["name", "mobile","user_type"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) print("iam init") for field in self.fields: self.fields[field].required = True def update(self, instance, validated_data): print("iam update") user = instance user_type = validated_data.get("user_type") if user_type: if user_type == "student": Student.objects.create(user=user) if user_type == "parent": Parent.objects.create(user=user) if user_type == "teacher": Teacher.objects.create(user=user) instance.save() super(ProfileSerializer,self).update(instance,validated_data) return instance The confusion here is the init function that was written above. I just wrote the update function. The init was there already. Even if I remove the init function it works as expected and even I keep it there, it works fine. The print command is working that means init is working. But what is its use there?? If it does something why it is working when I removed it?? When is the init function called …