Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, … -
django after redirect adding form.errors to messages doesn't appear in template?
after redirect adding form.errors to messages if form not valid , form.errors doesn't appear in template @login_required(login_url="login") @user_passes_test(user_is_patient_check, login_url='login') def changePasswordPatient(request): if request.method == "POST": form = PasswordChangeForm(request.user,request.POST) if form.is_valid(): user=form.save() update_session_auth_hash(request, user) messages.success(request,'Şifreniz başarıyla güncellendi!') return redirect("changePasswordPatient") else: messages.error(request,form.errors,extra_tags="invalidchangepassword") return redirect("changePasswordPatient") # this part form=PasswordChangeForm(request.user) context={ "form":form, "which_active":"passwordchange" } return render(request,"change-password.html",context) but when I changed if form not valid part like using this(render method).Form errors showing in template.But in this method when I refresh page errors messages still showing.Can anyone help me to fix that? if form.is_valid(): user=form.save() update_session_auth_hash(request, user) # Important! messages.success(request,'Şifreniz başarıyla güncellendi!') return redirect("changePasswordPatient") else: messages.error(request,form.errors,extra_tags="invalidchangepassword") return render(request,"change-password.html",{"form":form,"which_active":"passwordchange"}) change-password.html {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <center><strong>{{ error|escape }}</strong></center> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <center><strong>{{ error|escape }}</strong></center> </div> {% endfor %} {% endif %} -
manage django File Uploads in admin
I am looking for a package or a solution to integrate in my Django Admin that offers the following: upload (one file at a time is fine) multiple files on the same admin page. delete files and have them removed from disk I imagine something like this: I found a couple of file upload libraries for django, mainly from here, but I am not sure with is closest to what I want. I found a couple ones, that bring their own admin module, which I would like to avoid - I want it included in my current admin under the correct model. -
How to hide one part of html code from base.html in django?
I have base.html that loads basically whole site. Inside that base.html I want to hide on home page, but not on others. How to do this? Tried to do like this, but something messed up... This is base.html (This is a part I want to hide in home.html) {% block header_parent %} <!-- ***** Breadcumb Area Start ***** --> <div class="mosh-breadcumb-area" style="background-image: url({% static 'img/core-img/breadcumb.png' %})"> <div class="container h-100"> <div class="row h-100 align-items-center"> <div class="col-12"> <div class="bradcumbContent"> <h2>{{page_title}}</h2> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="{% url 'home' %}">Home</a></li> <li class="breadcrumb-item active" aria-current="page">{{page_title}}</li> </ol> </nav> </div> </div> </div> </div> </div> <!-- ***** Breadcumb Area End ***** --> {% endblock %} Page with header {% extends "base.html" %} {% load static %} {% block content %} {% block header %}{% endblock %} <p>Every other page.</p> {% endblock content %} This is home.html (I don't want to be show part of header here) {% extends "base.html" %} {% load static %} {% block content %} <p>Home</p> {% endblock content %} -
Python split() list as string not number . in Django and chart.js
I take values from device and split like bellow and append array. After that i send the chart.js and visualize data with line chart. But values comes string not number. When i write the value its correct(etc: 17.53 17.70 18.40) but in the chart its take one by one and draws 1 7 5 3 not 17.53 . Draws by one by one. Probally my split method is wrong. Its take as string like a b c and draws a b. What should i do ? temp = client.query('select * from device_frmpayload_data_Temperature order by time desc limit 10') temp_V= temp.get_points(tags={'dev_eui':'000950df9be2733e'}) temp_data = [] for x in temp_V: y = float(str(x).split("'value': ", 1)[1].split("}")[0]) temp_data.append(y) return render(request, 'Events/charts.html', { 'temp_data' : temp_data, }) #chart data part datasets: [{ label: 'temp values', data:'{{temp_data|safe}}', -
Problem to deploy Django app on Apache it load only the default pagina
I'm trying to deploy this Django app on Apache2 server using the WSGI mod. I set up everything and seems that everything works but instead to load my index, Apache load the default Apache pagina. I checked the WSGI configuration to see if I made some mistake serving the static but seems everything is in order. I also checked the error.log from Apache but I couldn't find anything useful. This is the error.log of Apache: [Thu Sep 30 22:28:57.072809 2021] [authz_core:debug] [pid 34291:tid 140219030382336] mod_authz_core.c(817): [client 77.171.127.237:46746] AH01626: authorization result of Require all granted: granted [Thu Sep 30 22:28:57.073467 2021] [authz_core:debug] [pid 34291:tid 140219030382336] mod_authz_core.c(817): [client 77.171.127.237:46746] AH01626: authorization result of <RequireAny>: granted [Thu Sep 30 22:28:57.076377 2021] [deflate:debug] [pid 34291:tid 140219030382336] mod_deflate.c(854): [client 77.171.127.237:46746] AH01384: Zlib: Compressed 10918 to 3120 : URL /index.html [Thu Sep 30 22:28:57.182998 2021] [authz_core:debug] [pid 34291:tid 140219047167744] mod_authz_core.c(817): [client 77.171.127.237:46746] AH01626: authorization result of Require all granted: granted, referer: http:> [Thu Sep 30 22:28:57.183125 2021] [authz_core:debug] [pid 34291:tid 140219047167744] mod_authz_core.c(817): [client 77.171.127.237:46746] AH01626: authorization result of <RequireAny>: granted, referer: http://www.w> [Thu Sep 30 22:28:57.227778 2021] [authz_core:debug] [pid 34291:tid 140219021989632] mod_authz_core.c(817): [client 77.171.127.237:46746] AH01626: authorization result of Require all granted: granted, referer: http:> [Thu Sep … -
Passing Audio Files To Celery Task
I have a music uploading app and believe that it would be smart to pass the files to a celery task to handle uploading. However, when attempting to pass the files, as I will show in my code below, I get a message stating that they are not JSON serializable. What would be the correct way to handle this operation? Everything below uploaded_songs in .views.py is my current code that successfully uploads the audio tracks. It doesn't, however, utilize celery yet. .task.py from django.contrib.auth import get_user_model from Beyond_April_Base_Backend.celery import app from django.contrib.auth.models import User @app.task def upload_songs(songs, user_id): try: user = User.objects.get(pk=user_id) print('user and songs') print(user) print(songs) except User.DoesNotExist: logging.warning("Tried to find non-exisiting user '%s'" % user_id) .views.py class ConcertUploadView(APIView): permission_classes = [permissions.IsAuthenticated] def post(self, request): track_files = request.FILES.getlist('files') current_user = self.request.user upload_songs.delay(track_files, current_user.pk) try: selected_band = Band.objects.get(name=request.data['band']) except ObjectDoesNotExist: print('band not received from form') selected_band = Band.objects.get(name='Band') venue_name = request.data['venue'] concert_date_str = request.data['concertDate'] concert_date_split = concert_date_str.split('(')[0] concert_date = datetime.strptime(concert_date_split, '%a %b %d %Y %H:%M:%S %Z%z ') concert_city = request.data['city'] concert_state = request.data['state'] concert_country = request.data['country'] new_concert = Concert( venue=venue_name, date=concert_date, city=concert_city, state=concert_state, country=concert_country, band=selected_band, user=current_user, ) new_concert.save() i = 0 for song in track_files: audio_metadata = music_tag.load_file(track_files[i].temporary_file_path()) temp_path = … -
how can we fix send_messasge() missing 1 required positional argument: 'message'
Currently, I am working on a notification feature in Django. I am able to run my created code on localhost, development servers but when I deployed the same code production server then It's throwing the below error send_messasge() missing 1 required positional argument: 'message' below is my model.py code. class All_Device_Notification(models.Model): title = models.TextField(default="") description = models.TextField(default="") link = models.TextField(default="") def __str__(self): return self.title def save(self, *args, **kwargs): filtered_users = User.objects.all() devices = FCMDevice.objects.filter(user__in=list(filtered_users)) devices.send_message(title=self.title, body=self.description, click_action=self.link) super(All_Device_Notification, self).save(*args, **kwargs) Here I am not able to understand that if I am compiling the code on the localhost or development server then it was working well but Why am facing the error in the production server? below is my urls.py file url(r'^devices?$', FCMDeviceAuthorizedViewSet.as_view({'post': 'create'}),name='create_fcm_device'), -
Django - how to create proper categories and subcategories
I am currently working on a store made in Django and I have a problem because I have a model for Category as well as Subcategory. The problem is that I don't really know what I did wrong, because in the html file I try to call both categories and subcategories, but in each category all subcategories are displayed, instead of belonging to a specific category. I would like to ask for your help, and check, if files below are correctly written. Thanks in advance models.py from django.db import models from django.urls import reverse # Class model for category class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('selcorshop:product_list_by_category', args=[self.slug]) # Class model for subcategory class Subcategory(models.Model): category = models.ForeignKey(Category, related_name='category', on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) class Meta: ordering = ('name',) verbose_name = 'subcategory' verbose_name_plural = 'subcategories' def __str__(self): return self.name def get_absolute_url(self): return reverse('selcorshop:product_list_by_subcategory', args=[self.slug]) # Class model for product class Product(models.Model): subcategory = models.ForeignKey(Subcategory, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) …