Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Not redirecting http -> https
I want to redirect almy http request to https i have installed django-sslserver and set SECURE_SSL_REDIRECT = True in settings.py file WHen i run : python manage.py runsslserver localhost:8000 It worka fine But when i try to access my application by entering http://localhost:8000 it is not redirecting to https://localhost:8000 please help..Thanks in advance -
How to use optgroups with Django admin's FilteredSelectMultiple?
I've been using optgroups on my Django Admin page with a SelectWidget, but when I moved to FilteredSelectWidget, they no longer work. What I've noticed is that before the JS for FilteredSelectWidget loads the underlying SelectWidget has the optgroups, but once the JS loads they disappear. For example, if I have a form mixin like so: class SelectMixin(forms.ModelForm): select_field = forms.ModelMultipleChoiceField( queryset=ModelA.objects.all(), required=False, widget=FilteredSelectMultiple("Select Field", is_stacked=False) ) def __init__(self, *args, **kwargs): super(SelectMixin, self).__init__(*args, **kwargs) self.fields['select_field'].choices = (('Group 1' ((1, 'item 1'), (2, 'item 2'))), ('Group 2' ((3, 'item 3'), (4, 'item 4')))) This works when the widget is set to SelectWidget, but when it's set as above it no longer works. Despite the fact that it still generates the correct groupings via the optgroup method. It would appear that the JS of FilteredSelectWidget overwrites them. Has anyone found a way around this? I need a select widget that I can easily deselect with, and the filtering is a nice bonus. -
django - change static to dynamic view retruning only one id in the restframework list
I have written the static code for the django application where user select the time format (DD-MM-YYYY or MM-DD-YYY)date & time that returning the time in such format but im using conditional statement for each time format I want it to be dynamic when there is a additional format is added (YYYY-MM-DD) I don't want to create another conditional statement. I don't want to create any more additional model field in the db.Is there any way to make it dynamic I have tried but couldn't figure out. And also in api I'm converting the time according to selected timezone I could not able to get the date and time for all the user it returning only one user with time.when I use normal django restframework method its returning all the user without time.In detail View im able to get the time for individual user separately API: models.py: from django.db import models import pytz from django.db import models import datetime from django.shortcuts import reverse from django.utils import timezone from datetime import datetime from django.conf import settings from django.utils.text import slugify TIMEZONES = tuple(zip(pytz.all_timezones, pytz.all_timezones)) CHOICES =(('DD-MM-YYYY','DD-MM-YYYY'),('MM-DD-YYYY','MM-DD-YYYY'),('DD-MM-YYYY HH-MM','DD-MM-YYYY HH-MM'), ('MM-DD-YYYY HH-MM','MM-DD-YYYY HH-MM')) class Userbase(models.Model): username = models.CharField('username', max_length=155) slug = models.SlugField(editable=False) email … -
Class 'MyModel' has no 'objects' member
I'm using prospector to run pylint-django, but for some reason it is not interpreting my model classes as part of the Django framework. Running it as follows: DJANGO_SETTINGS_MODULE=myproj.myproj.settings prospector It seems that prospector picks up that the project itself is Django however, as we can see from the final output: Check Information ================= Started: 2021-10-01 05:58:18.025548 Finished: 2021-10-01 05:58:27.211931 Time Taken: 9.19 seconds Formatter: grouped Profiles: default, no_doc_warnings, no_test_warnings, strictness_medium, strictness_high, strictness_veryhigh, no_member_warnings Strictness: None Libraries Used: django Tools Run: dodgy, mccabe, pep8, profile-validator, pyflakes, pylint Messages Found: 53 Throughout my entire project I'm getting errors like: pylint: no-member / Class 'MyModel' has no 'objects' member (col 28) I've tried creating a new django project with the same skeletal structure, but have not yet been able to reproduce, suggesting there is something about my real-world project causing the issue. Any suggestions on what sort of thing might be causing it, and how to debug to try and narrow down the issue? -
Empty tag failed with like button
I am beginner in Django. I am building a simple question and answer site and I am implementing like answer feature so i made a model of Like Answer but it was not working in just if else in template so i added empty tag But button is not liking the answer. models.py class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=900) class Answer(models.Model): question_of = models.ForeignKey(Question, on_delete=modelsCASCADE) answer_by = models.ForeignKey(User, on_delete=models.CASCADE) body = models.CharField(max_length=900) class AnswerLike(models.Model): answer_of = models.ForeignKey(Answer, on_delete=models.CASCADE) liked_by = models.ForeignKey(User, on_delete=models.CASCADE) views.py def question_detail(request, question_id): post = get_object_or_404(Question, pk=question_id) answers = post.answer_set.all() context = {'post':post, 'answers':answers} return render(request, 'question_detail.html', context) def answer_like(request, answer_id): answer = get_object_or_404(Answer, pk=answer_id) if request.GET.get('submit') == 'like': save_like = AnswerLike.objects.create(answer_of=answer, liked_by=request.user) return JsonResponse({'liked':liked}) question_detail.html {{post}} {% for ans in answers %} {{ans.body}} {% for likes in ans.answerlike_set.all %} <form method="GET" class="AnswerLike" action="{% url 'answer_like' ans.id %}"> {% if request.user == likes.liked_by %} <button name='submit' type='submit' value="UnLike">Liked</button> {% else %} <button name='submit' type='submit' value="Like">Not Liked</button> {% endif %} {% empty %} <button name='submit' type='submit' value="Like">Not Liked</button> {% endfor %} </form> {% endfor %} When i save a like from another user from admin then it is liking from request.user but when no-one like … -
Django foreign key relationship with multiple models
I have many different models with different types of fields. I want to use foreign key for multiple models. Like: class Model1(models.Model): title = models.TextField() body = models.TextField() class Model2(models.Model): tag = models.CharField(max_length=200) uploadedDate = models.DateTimeField(auto_now_add=True) class MainModel(models.Model): content = models.ForeignKey([Model1, Model2], on_delete=models.CASCADE) # this will give error How can I do this? -
How to get Image name while updating in react js?
Here I'M trying to create updating feature. I'm getting all the values while editing but i'm not able to get the name of image which was uploaded while creating the post. How can I get the name of image instead of "No File Choosen"? I'm getting data from the backend in this format. setEditInitialState({ id: data.id, meta_title: data.meta_title, blog_name: data.blog_name, blog_category: { value: blogCategories.data?.data.find( (category) => category.id === data.blog_category )?.id || "", label: blogCategories.data?.data.find( (category) => category.id === data.blog_category )?.title || "", }, slug: data.slug, image: data.image, ##Here is the form <div className="form-group"> <label htmlFor="">Image</label> <Input type="file" // className="form-control" // value={values.image} name="image" onChange={(event: any) => setFieldValue("image", event.target?.files[0]) } /> {/* <p>{initialValues.image}</p> */} <FormikValidationError name="image" errors={errors} touched={touched} /> </div> -
How i change status code of jwt token exception while token is invalid or expired.?
I want to know , how i do update status code of jwt authorization while token is invalid vor expiried. -
How to display the results based on what the user search django
I have a web page that shows the details from the database, I have a search bar that will only search based on reception number and part number but whenever I enter the details, it will not display the row of the details in the form of a table. Example shown below: As seen from the URL it manage to show the search=the reception number, but the table still show the whole data that is from the database, instead of just showing the whole row of the data that the user search based on the reception number. How to make it display the data of what the user search based on reception number and part number in a form of a table? views.py @login_required(login_url='login') def gallery(request): search_post = request.GET.get('reception') search_partno = request.GET.get('partno') if search_post: allusername = Photo.objects.filter(Q(reception__icontains=search_post) & Q(partno__icontains=search_partno)) else: allusername = Photo.objects.all().order_by("-Datetime") context = {'allusername': allusername} return render(request, 'photos/gallery.html', context) gallery.html {% extends "logisticbase.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> <script> // Function to download table data into … -
Failed to load PDF File in Cypress
I am testing a react APP that can render PDF fine but as soon as I open it in Cypress, I get this error "Failed to load PDF File". This is an inconvenience because I am trying to test some part of the app that deals with the PDF. Any suggestions? -
Detecting import error when manage.py runserver on Django
I'm working on a project in Python 3.7.4 and Django 3.1.3 In the process of build and deployment, I want to send a notification by detecting an ImportError when running by manage.py runserver. For example, slack message or email. In manage.py, from django.core.management import ... execute_from_command_line(sys.argv) I twisted the import syntax of the views.py file and tried to try-except to the execute_from_command_line(), but I couldn't catch exception. The error is only appearing on the runserver console. Perhaps I think we should modify the utility.execute() within this execute_from_command_line() logic, which is a package modification, so I want to avoid this method. In utility.execute(), def execute(self): """ Given the command-line arguments, figure out which subcommand is being run, create a parser appropriate to that command, and run it. """ try: subcommand = self.argv[1] except IndexError: subcommand = 'help' # Display help if no arguments were given. # Preprocess options to extract --settings and --pythonpath. # These options could affect the commands that are available, so they # must be processed early. parser = CommandParser(usage='%(prog)s subcommand [options] [args]', add_help=False, allow_abbrev=False) parser.add_argument('--settings') parser.add_argument('--pythonpath') parser.add_argument('args', nargs='*') # catch-all try: options, args = parser.parse_known_args(self.argv[2:]) handle_default_options(options) except CommandError: pass # Ignore any option errors at this point. … -
How to accept only the window that the selenium opens? (Django)
I have a Django view function: def bypass_link(request, pk=None): instance = fields.objects.get(pk=pk) link = instance.quote options = webdriver.ChromeOptions() driver = webdriver.Chrome(ChromeDriverManager().install(), options=options) driver.get(link) driver.find_element_by_id("butAgree").click() return redirect(link) template: <td data-label="Quote"> <a href="{% url 'bypass_link' i.id %}" target="_blank">{{ i.link }}</a> </td> urls.py from django.conf.urls import url url(r'^bypass_link/(?P<pk>\d+)/$', views.bypass_link, name="bypass_link"), This opens two links when I click on the hyperlink. When I remove the return redirect(link), this shows the error on the page but the selenium window is working fine. I just want to open the selenium window when clicking on the hyperlink. -
how to store return function value to a variable to use in original function in Django
I have two functions one calls the other to return a value seconds, I believe I have returned successfully however I need to now store it as a variable to use later on but have an error as per the following code: def func2(request): try: user = User now = datetime.datetime.now() startdate = str(user.start_date) startdate = startdate.rpartition('+')[0] startdate = datetime.datetime.fromisoformat(startdate) timedelta = now - startdate seconds = timedelta.seconds print("This is seconds:", seconds) return seconds except Exception as e: pass def func1(request): return func2(request) seconds = return func2(request) ### error - this does not work -
How do I implement a function with Django To add Instance in CustomUser and Staff table The current function not work
i incur some logical problem where my logic function are suppose to fill CustomUser which inherit attribute from Abstractuser table and Staff Table with attribute Address but all in All only create CustomUser ``` List item from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): user_type_data = ((1 ,'HOD'),(2,'Staffs'),(3,'Student')) user_type=models.CharField(default=1,choices=user_type_data,max_length=12) class AdminHog(models.Model): id=models.AutoField(primary_key=True) admin=models.OneToOneField(CustomUser,on_delete=models.CASCADE) create_at=models.DateTimeField(auto_now_add=True,auto_now=False) update_at=models.DateTimeField(auto_now_add=False,auto_now=True) objects=models.Manager() class Staff(models.Model): id=models.AutoField(primary_key=True) admin=models.OneToOneField(CustomUser,on_delete=models.CASCADE) address=models.TextField() create_at=models.DateTimeField(auto_now_add=True,auto_now=False) update_at=models.DateTimeField(auto_now_add=False,auto_now=True) objects=models.Manager() class Course(models.Model): id=models.AutoField(primary_key=True) course_name=models.CharField(max_length=252) create_at=models.DateTimeField(auto_now_add=True,auto_now=False) update_at=models.DateTimeField(auto_now_add=False,auto_now=True) objects=models.Manager() class Subject(models.Model): id=models.AutoField(primary_key=True) subject_name=models.CharField(max_length=252) course_id=models.ForeignKey(Course,on_delete=models.CASCADE) staff_id=models.ForeignKey(Staff,on_delete=models.CASCADE) create_at=models.DateTimeField(auto_now_add=True,auto_now=False) update_at=models.DateTimeField(auto_now_add=False,auto_now=True) objects=models.Manager() class Student(models.Model): id=models.AutoField(primary_key=True) admin=models.OneToOneField(CustomUser,on_delete=models.CASCADE) profile_pic=models.FileField() gender=models.CharField(max_length=255) address=models.TextField() session_start_year=models.DateTimeField() session_end_year=models.DateTimeField() course_id=models.ForeignKey(Course,on_delete=models.DO_NOTHING) create_at=models.DateTimeField(auto_now_add=True,auto_now=False) update_at=models.DateTimeField(auto_now_add=False,auto_now=True) objects=models.Manager() class Attendance(models.Model): id=models.AutoField(primary_key=True) attendance_date=models.DateTimeField(auto_now_add=True) subject_id=models.ForeignKey(Subject,on_delete=models.DO_NOTHING) create_at=models.DateTimeField(auto_now_add=True,auto_now=False) update_at=models.DateTimeField(auto_now_add=False,auto_now=True) objects=models.Manager() class AttendanceReport(models.Model): id=models.AutoField(primary_key=True) student_id=models.ForeignKey(Student,on_delete=models.CASCADE) attendace_id=models.ForeignKey(Attendance,on_delete=models.CASCADE) status=models.BooleanField(default=False) create_at=models.DateTimeField(auto_now_add=True,auto_now=False) update_at=models.DateTimeField(auto_now_add=False,auto_now=True) objects=models.Manager() class LeaveReportStaff(models.Model): id=models.AutoField(primary_key=True) staff_id=models.ForeignKey(Staff,on_delete=models.CASCADE) leave_status=models.BooleanField(default=False) leave_message=models.TextField() leave_date=models.DateTimeField(auto_now_add=True) create_at=models.DateTimeField(auto_now_add=True,auto_now=False) update_at=models.DateTimeField(auto_now_add=False,auto_now=True) objects=models.Manager() class LeaveReportStudent(models.Model): id=models.AutoField(primary_key=True) student_id=models.ForeignKey(Student,on_delete=models.CASCADE) leave_status=models.BooleanField(default=False) leave_message=models.TextField() leave_date=models.DateTimeField(auto_now_add=True) create_at=models.DateTimeField(auto_now_add=True,auto_now=False) update_at=models.DateTimeField(auto_now_add=False,auto_now=True) objects=models.Manager() class FeedbackReportStudent(models.Model): id=models.AutoField(primary_key=True) student_id=models.ForeignKey(Student,on_delete=models.CASCADE) feedback=models.TextField() feedback_reply=models.TextField() create_at=models.DateTimeField(auto_now_add=True,auto_now=False) update_at=models.DateTimeField(auto_now_add=False,auto_now=True) objects=models.Manager() class FeedbackReportStaff(models.Model): id=models.AutoField(primary_key=True) staff_id=models.ForeignKey(Staff,on_delete=models.CASCADE) feedback=models.TextField() feedback_reply=models.TextField() create_at=models.DateTimeField(auto_now_add=True,auto_now=False) update_at=models.DateTimeField(auto_now_add=False,auto_now=True) objects=models.Manager() class NotificationStudent(models.Model): id=models.AutoField(primary_key=True) student_id=models.ForeignKey(Student,on_delete=models.CASCADE) message=models.TextField() create_at=models.DateTimeField(auto_now_add=True,auto_now=False) update_at=models.DateTimeField(auto_now_add=False,auto_now=True) objects=models.Manager() class NotificationStaff(models.Model): id=models.AutoField(primary_key=True) staff_id=models.ForeignKey(Staff,on_delete=models.CASCADE) message=models.TextField() create_at=models.DateTimeField(auto_now_add=True,auto_now=False) update_at=models.DateTimeField(auto_now_add=False,auto_now=True) objects=models.Manager() @receiver(post_save,sender=CustomUser) def Create_user_Dp(sender,instance,created,**kwargs): if created: if instance.user_type_data==1: AdminHog.objects.create(adminhog=instance) if instance.user_type_data==2: Staff.objects.create(adminhog=instance,address="") if instance.user_type_data==3: Student.objects.create(adminhog=instance,address="") @receiver(post_save,sender=CustomUser) def save_user_Dp(sender,instance,**kwargs): if instance.user_type_data==1: instance.adminhog.save() if … -
Does sync_to_async improve performance of django ORM queries?
I suppose this is a very simple question, but after reading a lot of documentation and tips, I still don't get the point. Except for all external things like middleware and SGI type, if my view only consists of a database query and synchronous code to work with the received data, will using async def and sync_to_async for ORM query give me any performance boost? Since at the moment, the ORM queries are still synchronous. async def myview(request): users = await sync_to_async(list)(User.objects.all()) ... vs def myview(request): users = list(User.objects.all()) ... -
How do I implement a function in with Django Investment Website where a user gains dummy cash daily?
I'm testing my skills with Django Investment Website and I'm stuck now, I need to implement a function where a user can gain or watch thier dummy investment increase daily, e.g Invested $10 and their investment start growing from $10 - $20 - $40 etc daily. PLEASE ANY HELP FROM THIS GREAT COMMUNITY WOULD BE HIGHLY APPRECIATED -
my Django website style broken after configure aws S3 storage
My website index.html style broken after I configure aws S3. I added following code in my settings.py: AWS_S3_ACCESS_KEY_ID = "my_key" AWS_S3_SECRET_ACCESS_KEY = "my_key" AWS_STORAGE_BUCKET_NAME = "my_bucket_name" AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_DEFAULT_ACL = "public-read" INSTALLED_APPS = [ 'storages', ] AWS_LOCATION = 'static' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' when I am opening any image url or stylesheet url like this https://mydomain.com.s3.amazonaws.com/static/theme/assets/js/main.js I am seeing below message : <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>HHT43N24VA3Q7QHC</RequestId> <HostId>z5UvXR8RJU5U9H4IY4f2ntuw1dqF6tk4Vts7s+riqaQI5FJT5/H+u8TI8LnMFbH+uAUPwgR8Kp4=</HostId> </Error> should I put anything's in aws Bucket policy and Cross-origin resource sharing (CORS)? -
i have a django app deployed by someone else and this app has two subdomain that are connected to it and each subdomain have a separate dB
hi Guys im some how stuck in a middle of thing. I have vuejs/Django app deployed on Linux and i have two subdomains for this and each subdomain is routing toward same app but different Database. I tried to add a third one following the same steps from adding the subdomain and then running nginx and everything is working fine but when i log in its not routing to the new DB even though i did create a new database and defined it under the DB in base.py file not sure why its routing to an existing database (i did copy the folders of that app but changed the db name) i think its an environment problem but when i go to the new subdomain and cat .env it shows the correct DB any thoughts ? -
Creating a website that can create another websites
I like to create, with django, a website that create another websites and databases. Something like Shopify, by clicking (Create shop), Shopify will create a new website and new database. Do all stores use the same database, or each store has its own database ? I don't know where do I start my search ? What's the name of this technology ? Thanks in advance -
docker django: Why to copy the context into docker image, if we are overwriting it by mounting something in its place in docker compose
I was following the tutorial for docker and django. https://devopstuto-docker.readthedocs.io/en/latest/compose/django/django.html I see the following docker file FROM python:2.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ <---- WHATS THE NEED OF THIS, SINCE WE ARE MOUNTING IT IN DOCKER COMPOSE Docker compose file as version: '3' services: db: image: postgres web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code <---------- WHY TO MOUNT THE CODE HERE. THE IMAGE HAS THE CODE ports: - "8000:8000" depends_on: - db I see the in docker-compose.yml that its mounting the current folder into code - .:/code and in the Dockerfile also we see ADD . /code/ Whats the need of ADD . /code/ if we are anyhow depend on the mounting in docker-compose which is going to overwrite the files -
Django - Handling multiple text fields in same CharField or store a complete table as it is
I have a project where I have to handle Interventions, with that I have a section with a table to store a lot of columns and rows in my database, but I have some problems finding the correct way to do it. The table has the following format/content: The values from the 1st column are fixed. Let me share some ideas I had: Save each row in a single CharField and handling each column parsing each value separated by a character like ";". Save each row associated to another table by a ForeignKey containing the columns info like: class MastCompnentsInfo(models.Model): column_1 = models.CharField(max_length=20, null=True, blank=True) column_2 = models.CharField(max_length=20, null=True, blank=True) .... class Intervention(models.Model): .... t_dat_log = models.ForeignKey('MastCompnentsInfo', related_name='t_dat_log', on_delete=models.DO_NOTHING, null=True, blank=True) t_s_speed_1 = models.ForeignKey('MastCompnentsInfo', related_name='t_s_speed_1', on_delete=models.DO_NOTHING, null=True, blank=True) But I don't like so much this idea, as updating information requires a lot of work, my MastCompnentsInfo model would be a mess with a lot of info and I have no idea how to access each field, individually, from MastCompnentsInfo in the HTML. Another approach was an "OneToMany" relation and put all fixed values from the 1st column in MultiSelectField choices. But like idea 2. I'm with some problems accessing and … -
Paginator DJANGO page range showed
im trying to limit the quantity of pages printed on paginator to 5 so if it is from 1 to 5 show [1, 2, 3, 4, 5, ..], and if im like in page 5 shows [.., 4, 5, 6, 7, ..] something like that Paginator 3 pages so if i have like 100 pages now it shows like this Paginator 100+ pages here is the html <div class="card-footer px-3 border-0 d-flex align-items-center justify-content-between"> <nav aria-label="Page navigation example"> <ul class="pagination mb-0"> {% if page_obj_trans.has_previous %} <li class="page-item"> <a class="page-link" href="{% url 'dashboard'%}?page={{page_obj_trans.previous_page_number}}">Previous</a> </li> {% endif %} {% for a in page_obj_trans.paginator.page_range %} <li class="page-item"> <a class="page-link" href="{% url 'dashboard'%}?page={{a}}">{{a}}</a> </li> {% endfor %} {% if page_obj_trans.has_next %} <li class="page-item"> <a class="page-link" href="{% url 'dashboard'%}?page={{page_obj_trans.next_page_number}}">Next</a> </li> {% endif %} </ul> </nav> </div> -
Django rest framework, ¿What would be the best way to resolve the error, " index list creation error must be integer or chunked, not str" .?
There is a possibility to solve my problem, please. I have 3 molds, of which 2 are related. I am using create on ModelViewSet, which sent the data but I am getting the following error. (list indexes must be integer or chunked, not str) Of course I am trying to create a list of objects, but. ¿How would you develop the syntax? With the use of For? ModelViewSet class CreateApiModelViewSet(viewsets.ModelViewSet): serializer_class = EDFSerializer def get_queryset(self): dano = models.Dano.objects.all() return dano def create(self, request, *args, **kwargs): data = request.data new_evento = models.Evento.objects.create( tabla=data["evento"]["tabla"], usuario=models.Usuario.objects.filter(user_id=data["evento"]["usuario"]).first(), patio=models.Patio.objects.filter(id=data["evento"]["patio"]).first() ) new_evento.save() # New Dano new_dano = models.Dano.objects.create( evento=new_evento, observacion=data["observacion"]) new_dano.save() # Model FotoDano With Error.. :( foto = [] for fotos in foto: for f in data["fotodanodetail"]["foto"][0]: foto_obj = models.FotoDano.objects.get( foto=data["fotodanodetail"]["foto"], dano=new_dano) new_foto_dano.foto.add(foto_obj) # Comment # new_foto_dano = models.FotoDano.objects.create( # #id=data["fotodanodetail"]["id"], # #foto=data["fotodanodetail"]["foto"], # dano=new_dano) # new_foto_dano.save() serializer = EDFSerializer(new_evento) return Response(serializer.data) Serializer # Import Base64 from drf_extra_fields.fields import Base64ImageField class EDFSerializer(serializers.ModelSerializer): fotodanodetail = Base64ImageField(required=False) evento = CrearEventoSerializer() fotodanodetail = FotoDanoFiltroSerializer(many=True) class Meta: model = models.Dano fields = ('evento','observacion','fotodanodetail') Postman -
My Bitnami Django website shows the Bitnami homepage instead of mine. How to change it?
I deployed a website on AWS LIGHTSAIL. I assigned an static IP to that instance and when I enter to it, it shows me the Bitnami homepage. When I run the virtual env in the Django project (python manage.py runserver 0.0.0.0:8000) I have to put the :8000 on my static IP for my website to shows up. What I'm doing wrong? How do I make my website appears on the default port? Thanks! -
Django-Filter Use lookup_choices for custom results
I have a field profit_loss_value_fees and in this field I would like the user to have a drop-down option to show all trades that were a Profit/Loss/Scratch. Profit = Trade.profit_loss_value_fees > 0 Loss = Trade.profit_loss_value_fees < 0 Scratch = Trade.profit_loss_value_fees == 0 What I have done is a result1 which works but I don't get a nice drop-down as mentioned above. It's two empty fields where a user could type in say 1 and 100 and then all trades in that range show. It works but not the desired look. filters.py class StatsPortfolioFilter(django_filters.FilterSet): # Drop down with 3 options (Win, Loss, Scratch) using the Trade Field: profit_loss_value_fees result1 = django_filters.RangeFilter( field_name='profit_loss_value_fees', label='result1', ) What I tried is using the LookupChoiceFilter to create the 3 drop-down options and that worked. The problem is the options do not do anything, obviously. How can I add filters.py class StatsPortfolioFilter(django_filters.FilterSet): # I need something that gives the lookup_choices value # w = Trade.profit_loss_value_fees > 0 # l = Trade.profit_loss_value_fees < 0 # s = Trade.profit_loss_value_fees == 0 # Drop down with 3 options (Win, Loss, Scratch) using the Trade Field: profit_loss_value_fees result = django_filters.LookupChoiceFilter( field_name='profit_loss_value_fees', # field_name focuses on field relatetion label='Result', # field_class=forms.DecimalField, …