Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I get information from my ubuntu server?
I have a ubuntu server. This serve crawling data by apache2, python3 and django. And I start to make android with android studio. I want to get data in android app from my server. How can I get information from my ubuntu server? -
django rest framework filter_backends class called before permission_classes class
I have a DRF view-set with a custom permission and filter. In DRF's official docs it says: Permission checks are always run at the very start of the view, before any other code is allowed to proceed. But I have noticed that my filter_backend class is called before permission_class. Here is my code: # my permission from rest_framework import permissions class CompanyAccessPermission(permissions.BasePermission): message = 'Detail of company not allowed.' def has_object_permission(self, request, view, obj): print("permission") return request.user in obj.users.all() # my filter from rest_framework import filters class IsCompanyOwnerFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): print("filter") return queryset.filter(users__in=[request.user]) # my view from rest_framework import mixins, viewsets from rest_framework.permissions import IsAuthenticated from api import filters, permissions, serializers from core import models class CompanyViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.RetrieveModelMixin): permission_classes = (IsAuthenticated, permissions.CompanyAccessPermission) filter_backends = [filters.IsCompanyOwnerFilterBackend] queryset = models.Company.objects.all() serializer_class = serializers.CompanySerializer So when I want to retrieve a Company object the output is as follows: > filter > permission I was expecting the opposite of that. I also looked at the source code of DRF class GenericViewSet(ViewSetMixin, generics.GenericAPIView). It seems like the permission class (called in views.APIView) is called before the filter backend class (called in generics.GenericAPIViewi which inherits views.APIView). What am I missing? -
Django dynamic links using multiple fields
I have a url set up dynamically for a project using: path('project/<int:pk>', ProjectView.as_view(), name='project') How can I make this so I can use two parameters, something like this: path('project/<int:pk>/<int:category', ProjectView.as_view(), name='project') So I need to set up links to each category, so the user will see only the updates from Project A category 1 of 7. -
"Error 0x80070057: The parameter is incorrect" when unzipping files
I created a function to create multiple report pdfs with weasyprint, zip them together and download the zip file. When trying to extract the folder on Windows 10 with the in-house zip program i get this error: "An unexpected error is keeping you from copying the file. [...] Error 0x80070057" I can skip the error and the files get extracted. In the best case scenario I'd like to prevent this error though. def get_all_shareholder_reports(request): current_shareholders = list(models.objects.all()) zip_buffer = io.BytesIO() with zipfile.ZipFile(zip_buffer, "a") as zip_file: for shareholder in current_shareholders: pdf_file_handle = io.BytesIO() context_dict = get_report_details(pk=shareholder.shareholder_id) html_string = render_to_string('tempalte.html', context_dict) html_handler = HTML(string=html_string, base_url=request.build_absolute_uri()) html_handler.write_pdf(target=pdf_file_handle) pdf_file_handle.seek(0) pdf_string = pdf_file_handle.getvalue() pdf_file_name = 'Shareholder_Report_' + pdf_file_name = 'Shareholder_Report_{}_{}_{}.pdf'.format(context_dict['shareholder'].forename, context_dict['shareholder'].surname, datetime.datetime.now().strftime( "%d_%m_%Y_%H:%M:%S")) zip_file.writestr(zinfo_or_arcname=pdf_file_name, data=pdf_string) zip_buffer.seek(0) response = HttpResponse(zip_buffer.getvalue(), content_type="application/x-zip-compressed") response['Content-Disposition'] = 'attachment; filename=%s' % 'myzip.zip' return response -
How do I check if a many-to-many relationship exists in a Django template?
In this code example, "teaches_for" is the name of a many-to-many field that relates a Performer model to a School model. I want to include this particular block only if at least one relationship between a Performer and a Teacher model exists. Here's my non-working code: {% if performer.teaches_for.exists %} <h3>{{performer.first_name}} teaches at these schools...</h3> <ul> {% for school in performer.teaches_for.all %} <li><a href="/schools/{{school.id}}">{{ school.name }}</a></li> {% endfor %} </ul> {% endif %} The line that's wrong is {% if performer.teaches_for.exists %}. What can I replace it with which will be True if at least one relationship exists, but False otherwise? -
Django - Getting value from dropdown menu + button
I've done some searching already. I have a program which will do some analysis based on a given country. The HTML form is: <p>Select a country:</p> <select form="countrySelection" id="countrySelect" required> <option value=""></option> <option value="BELGIUM">Belgium</option> <option value="FRANCE">France</option> <option value="ITALY">Italy</option> </select> <form action="/analysis" id="countrySelection" method="GET"> <br> <input class="button" name="countrySubmit" type="submit" value="Start"> </form> In my urls.py I have: path('', views.index, name='index'), path('analysis/', views.run, name='run'), I want to get the value of the dropdown menu (BELGIUM/FRANCE/ITALY) upon clicking the button and then send it to the view run: def run(request): country = ... [...] return HttpResponse("Completed.") I have tried to use "request.GET.get('country') and other methods with no luck. -
How to upload and retrieve multiple photos in Django
I have a gallery page in which i want to display all actor/actress/movie/event photos.I get the photos on daily basis. I want to store the images in static media section. Here I have 2 questions. 1) What is best method to store and retrieve the gallery images in django? (Each movie/event/actor/actress may have multiple images) 2) How the folder structure should be in terms of SEO? like date/actor/{1,2,3} or eventname/{1,2,3} Using image filed I was able to upload and display single image. None of the articles showing how to upload multiple images. -
How to implement views.py in django for the structure multiple slug
I have path('<bloger_slug>-<category_slug>-products/', product_list, name='product_list'), how to make views.py for this url -
'WSGIRequest' object is not subscriptable in django
I'm getting this error in the below function in my views.py file. I don't know what 'WSGIRequest' is or why it's throwing an error. Here the settings.MEDIA_ROOT means it will list all the files in that directory def run_existing_query(request): context = {} print(settings.MEDIA_ROOT) context["download"] = "" context["list_of_queries"] = os.listdir(settings.MEDIA_ROOT) if request.method == "POST": MODULE_DIR = 'settings.MEDIA_ROOT' py_file = glob.glob(os.path.join(MODULE_DIR, request['selected_query']+'.py')) module_name = pathlib.Path(py_file).stem module = importlib.import_module(module_name) qe = module.QueryExecutor() #Query executor is Class name context["download"] = "Hello" return render(request, "run_existing.html", context) Why am I getting this error? -
How to copy a model instance to another model based on attribute value in Django
I want to copy a model instance from my Tasks class into my CompletedTasks class if and only if the progress attribute in my Tasks object is set to "completed". The I want to delete the object from the Tasks class. How do i set it up to automatically do this when a user edits a task and inputs completed for progress I tried a few different methods, but I am not exactly sure how to go about this. The function completedTasks(self,id) below is what I currently have, but it doesn't do anything. class Tasks(models.Model): progress = models.ForeignKey(Progress, max_length=20, on_delete=models.CASCADE) def completedTasks(self, id): instance = Tasks.objects.get(pk = id) if(instance.progress == "completed"): temp = CompletedTasks() temp = instance temp.save() instance.delete() class CompletedTasks(Tasks): -
why Django suit is not loading style
so i have installed django suit theme from their documentation as instructed but when i load their theme its not loading the style and its looking just like a skeleton a pic of the admin panel theme any one knows how can i fix it or even a recommendation of a better theme would be accepted my project apps.py: from suit.apps import DjangoSuitConfig class SuitConfig(DjangoSuitConfig): layout = 'horizontal' -
Periodically refresh placeholder and canvas tag in Django template
I have a template that, among other things, displays a current market price through a placeholder, i.e., {{ market.current_price }}, and an accompanying price graph using ChartJS, rendered in the template in a canvas tag, <canvas id="myChart"></canvas>. My question: since the market price changes as different users engage with the underlying market, is there a straightforward way to periodically (say, every 10 seconds) refresh the placeholder and chart in the template, to make sure each user is looking at the most recent price/graph? I'm trying to avoid having to refresh the entire page, if at all possible. If it makes any difference, the chart is rendered through Ajax, as follows: {% block jquery %} var endpoint = "{% url 'chart_data' market.id %}" var defaultData = [] var labels = [] $.ajax({ method: "GET", url: endpoint, success: function(data){ defaultData = data.prices price_array_length = defaultData.length + 1 labels = data.price_dates var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: labels, datasets : [{ label: 'Market price', data: defaultData, backgroundColor: [ 'rgba(54, 162, 235, 0.2)', ], borderColor: [ 'rgba(54, 162, 235, 1)', ], borderWidth: 2 }] }, options: { scales: { yAxes: [{ ticks: { suggestedMin: 0, … -
MP4/AVI videos are not playing on safari browser : Django 2
I create one web application using django 2.1 and python3 and in my requirements is upload video and play video and its absolutely working excellent dynamically and static in all browser except safari browser I have already tried everything in html tag (video,autoplay,muted,loop playsinline,controls,type="video/mp4") etc... everything but still not playing video in safari browser. my all python logic view + model files code is perfect and working and getting excellent output in all browser except safari browser. I have already checked all inspect elements and path,all videos path are placed in right place. <html> <head> <meta charset="utf-8"> </head> <body> <div class="left-video-div"> <video autoplay muted loop playsinline controls width="320" height="240" class="video-background "> <source src="{% static "sample_test01.mp4" %}" type="video/mp4"> </video> <video autoplay muted loop playsinline controls width="320" height="240" class="video-background "> <source src="{% static "sample_test02.mp4" %}" type="video/mp4"> </video> <video autoplay muted loop playsinline controls width="320" height="240" class="video-background "> <source src="{% static "sample_test03.mp4" %}" type="video/mp4"> </video> <video autoplay muted loop playsinline controls width="320" height="240" class="video-background "> <source src="/media/static/clips/userid_420/2019-07-15_182035.991933_Test_Video_02.mp4" type="video/mp4"> </video> </div> <p><strong>Note:</strong> The video tag is not supported in Internet Explorer 8 and earlier versions.</p> </body> </html> I expect the output all static and dynamic video playing in safari browser but its not working. -
provide me solution for toaster notification box in ajax
I am trying to use toaster function in ajax to display notification ,but it is not working .please help me since I knew little about js. please give me proper code. -
could not install the packages using pipenv when using docker
I am setting up a project using cookiecutter-django with pipenv instead. I am trying to use docker however I am getting the error as ERROR: Service 'django' failed to build: The command '/bin/sh -c pipenv install' returned a non-zero code: 1. To run the docker i used the following command docker-compose -f local.yml up -d Here is my docker file local.yml version: '3' volumes: local_postgres_data: {} local_postgres_data_backups: {} services: django: &django build: context: . dockerfile: ./compose/local/django/Dockerfile image: tryavel_local_django depends_on: - postgres - mailhog volumes: - .:/app env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: tryavel_production_postgres volumes: - local_postgres_data:/var/lib/postgresql/data - local_postgres_data_backups:/backups env_file: - ./.envs/.local/.postgres mailhog: image: mailhog/mailhog:v1.0.0 ports: - "8025:8025" redis: image: redis:5.0 celeryworker: <<: *django image: tryavel_local_celeryworker depends_on: - redis - postgres - mailhog ports: [] command: /start-celeryworker celerybeat: <<: *django image: tryavel_local_celerybeat depends_on: - redis - postgres - mailhog ports: [] command: /start-celerybeat flower: <<: *django image: tryavel_local_flower ports: - "5555:5555" command: /start-flower compose/local/django/Dockerfile FROM python:3.7-alpine ENV PYTHONUNBUFFERED 1 RUN apk update \ # psycopg2 dependencies && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev \ # Pillow dependencies && apk add jpeg-dev zlib-dev freetype-dev lcms2-dev … -
Django Oauth2 Configuration
I have two databases for one for separate django project and another for open edx project and I want to connect it with Oauth2, but not able to get the user status like user is super user or staff user from open edx database. can someone help me with this problem? -
Update Form Not Submitting
I am trying to update the fields of a model using fbv and I created different forms for those fields too. But still, I cannot submit the form no matter what. I think the problem is with image field and the form does not render to be valid. Is there a sloution for it? models.py class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True) role = models.CharField(max_length=50, choices=Roles) verified =models.BooleanField(default = False,blank=True) photo = models.ImageField(upload_to='images', blank=True, default='default/testimonial2.jpg') slug = models.SlugField(unique=False, blank=True) def save(self, *args, **kwargs): self.slug = slugify(self.user.username) super(UserProfile, self).save(*args, **kwargs) def __str__(self): return self.user.username def get_absolute_url(self): if (self.verified==True): return reverse("NewApp:mail", kwargs={'pk': self.pk}) else: return reverse("NewApp:userlist") views.py def UserUpdateView(request,slug): object = User.objects.get(username=request.user) user_form = UserUpdateForm(instance=object) obj = UserProfile.objects.get(slug=request.user) profile_form = UserProfileForm(instance=obj) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() return redirect('NewApp:logindex') return render(request, 'NewApp/userprofile_form.html', {'user_form': user_form, 'profile_form': profile_form,}) -
how does django-rest-auth handle the expiration of facebook access tokens
I am using django-rest-auth for authentication for my django rest server and I am using the access token given by facebook to login. django-rest-auth in turn gives me a key to use for authentication on the server. My question arouse when I realized that the access keys that are given by facebook expire, so I am having trouble finding out if the new access key given by facebook will result in the same key given by django-rest-auth or if I need to build a system to handle this fact -
Charts not displayed in django admin view?
I am trying to display some charts in my admin view( by extending admin/base.html) and I want to use a template instead of libraries such as charts.Js to display them. I want my view to be like the following (https://colorlib.com/polygon/cooladmin/index.html). Github repo here (https://github.com/puikinsh/CoolAdmin). However, in my case no charts are being displayed. I have integrated all files and folders( containing static files) and set all dependencies correctly andhe main.js(contains code for charts) are also working. Extract from main.html(includes links) <div id="content-main" class="main-content container-fluid"> <div class="section__content section__content--p30"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="overview-wrap"> <h2 class="title-1">overview</h2> <button class="au-btn au-btn-icon au-btn--blue"> <i class="zmdi zmdi-plus"></i>add item</button> </div> </div> </div> <div class="row m-t-25"> <div class="col-sm-6 col-lg-3"> <div class="overview-item overview-item--c1"> <div class="overview__inner"> <div class="overview-box clearfix"> <div class="icon"> <i class="zmdi zmdi-account-o"></i> </div> <div class="text"> <h2>10368</h2> <span>members online</span> </div> </div> <div class="overview-chart"> <canvas id="widgetChart1"></canvas> </div> </div> </div> </div> </div> </div> </div> </div> <!-- Jquery JS--> <script src={% static 'hfs_admin/vendor/jquery-3.2.1.min.js' %}""></script> <!-- Bootstrap JS--> <script src={% static 'hfs_admin/vendor/bootstrap-4.1/popper.min.js' %}""></script> <script src={% static 'hfs_admin/vendor/bootstrap-4.1/bootstrap.min.js' %}""></script> <!-- Vendor JS --> <script src={% static 'hfs_admin/vendor/slick/slick.min.js' %}""> </script> <script src={% static 'hfs_admin/vendor/wow/wow.min.js' %}""></script> <script src={% static 'hfs_admin/vendor/animsition/animsition.min.js' %}""></script> <script src={% static 'hfs_admin/vendor/bootstrap-progressbar/bootstrap-progressbar.min.js' %}""> </script> <script src={% static 'hfs_admin/vendor/counter-up/jquery.waypoints.min.js' %}""></script> <script … -
Users cannot update profile info
I'm trying to let users change their profile information but instead of changing the existing profile, form.save() saves it as a new entry under the same user. (example, bio would say 'What's up', they go to edit and no visible info is changed but another set of info is put in my userprofile table.) I tried using SQL commands and it returned something about an error near 'IT', which isn't in my code. I've tried getting my user.profile and then trying to edit the info through that (i.e user.profile.sex = form.cleaned_data['sex']). I've looked through the docs and the only thing I found that makes sense is Model.save(force_update=True) but where would I put it in my view and how could I link it to the user? View with the SQL I tried... @login_required def edit_prof(request): if request.method == 'POST': form = EPIF(request.POST, instance=request.user) if form.is_valid(): user_id = request.user.id conn = sqlite3.connect('db.sqlite3') cur = conn.cursor() sex = form.cleaned_data['sex'] dob = form.cleaned_data['dob'] r_stat = form.cleaned_data['relationship_stat'] locale = form.cleaned_data['location'] bio = form.cleaned_data['bio'] cur.execute(''' UPDATE profs_customuserprofile SET sex = {}, dob = {}, relationship_stat = {}, location = {}, bio = {} WHERE ID = {}; '''.format(sex, dob, r_stat, locale, bio, user_id)) content = form.save(commit=False) … -
Server error 500 when deploy django to Heroku
I got following server error 500 when deploying django app to heroku. I have worked on this problem for 2 days to fix, but have no idea to solve the problems. I assume djangorestframework cause this problems because it has favicon.ico which leads "GET /favicon.ico HTTP/1.1" 404 77" but no idea. Does anyone detect issues? Thank you for your support in advance!! 2019-07-23T12:03:44.622777+00:00 app[api]: Release v23 created by user atnihs-do-21@hotmail.co.jp 2019-07-23T12:03:51.865737+00:00 heroku[web.1]: Starting process with command `gunicorn alumate.wsgi --log-file -` 2019-07-23T12:03:55.314454+00:00 heroku[web.1]: State changed from starting to up 2019-07-23T12:03:55.130912+00:00 app[web.1]: [2019-07-23 12:03:55 +0000] [4] [INFO] Starting gunicorn 19.9.0 2019-07-23T12:03:55.132168+00:00 app[web.1]: [2019-07-23 12:03:55 +0000] [4] [INFO] Listening at: http://0.0.0.0:20191 (4) 2019-07-23T12:03:55.132311+00:00 app[web.1]: [2019-07-23 12:03:55 +0000] [4] [INFO] Using worker: sync 2019-07-23T12:03:55.138103+00:00 app[web.1]: [2019-07-23 12:03:55 +0000] [10] [INFO] Booting worker with pid: 10 2019-07-23T12:03:55.150027+00:00 app[web.1]: [2019-07-23 12:03:55 +0000] [11] [INFO] Booting worker with pid: 11 2019-07-23T12:03:55.000000+00:00 app[api]: Build succeeded 2019-07-23T12:04:30.649490+00:00 heroku[router]: at=info method=GET path="/" host=alumate.herokuapp.com request_id=0f1e339a-08fc-4b93-9c1b-1db28b675f76 fwd="210.150.77.215" dyno=web.1 connect=1ms service=835ms status=500 bytes=234 protocol=https 2019-07-23T12:04:30.649933+00:00 app[web.1]: 10.99.197.226 - - [23/Jul/2019:12:04:30 +0000] "GET / HTTP/1.1" 500 27 "https://dashboard.heroku.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36" 2019-07-23T12:04:31.116073+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=alumate.herokuapp.com request_id=381749d5-0137-4017-bd1b-8bb8cb6feef1 fwd="210.150.77.215" dyno=web.1 connect=0ms service=186ms status=404 bytes=258 protocol=https … -
i'm having problem of accessing object in array with template language
{% for number in appliers|length|times %} {% if connector|get_by_index:number == commission.id %} {{appliers|get_by_index:number}} {% endif %} {% endfor %} i have made custom_template filter and it have worked great but the problem is that i can't access appliers[number]'s class variables. I tried accessing by {{appliers|get_by_index:number.email}} and it wouldn't work... please can any one can tell me how to solve this? -
How to delete all the files associated with the users when I delete the user
I am trying to make an web application in Django.Here I have created different fields in user model including profile picture and other pictures.When I delete a user,the files associated with the user doesn't get deleted.I want to delete the files,profile picture and other pictures when I delete the user. I am using django2.2 and I have customized my own user model and admin panel. In my user model I have added 'Profile Picture' field and 'CV' field. When I add a user in my model the profile picture are stored in 'Media/"%username/"' directory.I want to delete the files associated with the user when I delete the user.So I have written 'on_delete=..' in the () of username but it gives an error.So is there any possible way to do it? import .. import os def user_directory_path(instance, filename): return os.path.join('media', instance.username, filename) class User(AbstractBaseUser): username = models.CharField(max_length=200, unique=True, on_delete = os.remove(str(user_directory_path))) profile_photo = models.ImageField(default='media/download(1).png', upload_to = user_directory_path) cv = models.FileField(upload_to = user_directory_path) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) moderator = models.BooleanField(default=False) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) I wanted to delete the files this way username = models.CharField(max_length=200, unique=True, on_delete = os.remove(str(user_directory_path))) but some errors come -
Django Media Files during development
How can I serve media files during development? The 'image' attribute has no file associated with it. When I try to upload a new file, I get this error: SuspiciousFileOperation at /admin/accounts/userprofile/4/change/ The joined path (/media/me.jpg) is located outside of the base path component (/home/django/django_project/static-serve/media) models.py image = models.ImageField(upload_to='/media',blank=True) urls.py ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py MEDIA_ROOT = '/home/django/django_project/static-serve/media/' MEDIA_URL = 'media/' -
Python Django - Show all assigned objects on the web page
I am developing web app for tracking orders. And I would like to display all orders which were created by a user via detailView. models.py class Order(models.Model): ... user = models.ForeignKey(MyUser, on_delete=models.CASCADE) order_number = models.CharField(max_length=150) class MyUser(models.Model): eid = models.CharField(max_length=7) name = models.CharField(max_length=150) surname = models.CharField(max_length=150) views.py class UserDetailView(generic.DetailView): model = MyUser template_name = "database/user_detail.html" def get_queryset(self): return Order.objects.all().order_by("-id") user_detail.html {% extends "base.html" %} {% block content %} <body> <h1> {{ user.eid }} {{ user.name }} {{ user.surname }} </h1> {% for order in orders %} order.order_number {% endfor %} {% endblock %} With this code I receive error: page not found: No Order found matching the query. If i delete the def get_queryset() in the views.py, it shows only the users eid and name. Not sure how I can get all the assigned orders to the particular user.