Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AJAX way of handling filters in a Django based ecommerce application is not working upon copy pasting the url in new tab
So I ran into this problem two days back and still haven't got a proper solution. I would highly Appreciate any help in here. Let me explain the scenario first, so the idea is I have one django based ecommerce site and I want to render the product showcase page through ajax call (without reloading) and same time also update the url as the selected filters for example (http://vps.vanijyam.com:8000/customerlist?category=category_1). I want to achieve similar to this site - shutterstock. My Scenario - http://vps.vanijyam.com:8000/customerlist this page to showcase all the available products and also have the filters option and pagination. Now when I change the page or apply some filter I am e.g. http://vps.vanijyam.com:8000/customerlist?category_slug=category_1 then it is working, but when I refresh the page it is not.. the reason behind this the way I am handling this ajax call in the backend. def customer_categories(request): # Get attributes from request url current_page = request.GET.get('page' ,'1') category_slug = request.GET.get('category_slug') sortby_filter = request.GET.get('sortby_filter') price_filter = request.GET.get('price_filter') search_query= request.GET.get('term') line_filter_min = request.GET.get('price_min') line_filter_max = request.GET.get('price_max') # Set limit and offset for queryset limit = REQUEST_PER_PAGE * int(current_page) offset = limit - REQUEST_PER_PAGE categories = Category.objects.all() # products = Product.objects.filter(available=True)[offset:limit] # limiting products based on current_page … -
Why psycopg2 keep spitting out this error?
I'm very newbie at deploying stuff to somewhere. I'm working on deploying django rest api and react app to my ec2 instance. The instance is Ubuntu 20.04.2 LTS focal. This is my project scheme backend \-backend(folder) \-core(folder) \-todos(folder) \-uploads(folder) \-users(folder) \-db.sqlite3 \-Dockerfile \-manage.py \-Pipfile \-Pipfie.lock frontend \-assets(folder) \-public(folder) \-src(folder) \-Dockerfile \-gulpfile.js \-package-lock.json \-package.json \-tailwind.config.json webserver \-nginx-proxy.conf docker-compose.yml I made an dockerfile for the django rest api, and this is what it looks like. backend/Dockerfile FROM python:3.7-slim ENV PYTHONUNBUFFERED 1 ... ARGs and ENVs ... RUN mkdir /backend WORKDIR /backend RUN pip3 install pipenv COPY . /backend/ RUN pipenv install --python 3.7 RUN python manage.py makemigrations RUN python manage.py migrate But when I'm trying to do sudo docker-compose up at my ec2 instance, it spits out the error at RUN pipenv install. It spits out the error while locking Pipfile.lock. This is what error looks like. [InstallError]: File "/usr/local/lib/python3.7/site-packages/pipenv/cli/command.py", line 253, in install [InstallError]: site_packages=state.site_packages [InstallError]: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 2063, in do_install [InstallError]: keep_outdated=keep_outdated [InstallError]: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 1312, in do_init [InstallError]: pypi_mirror=pypi_mirror, [InstallError]: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 900, in do_install_dependencies [InstallError]: retry_list, procs, failed_deps_queue, requirements_dir, **install_kwargs [InstallError]: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 796, in batch_install [InstallError]: _cleanup_procs(procs, failed_deps_queue, retry=retry) [InstallError]: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line … -
How to receive notifications from PostgreSQL table in Python
I'm using psycopg2 for Postgres in python and want notifications and row data when the DateTime column data matched with the current time from the Postgres table. I can do this with a scheduler that is run on x seconds interval and get the rows that are matched with the current time, but it is the worst solution. So, I have to get Listen/Notify in Postgres which is notified when some new changes occurred in the table. Is it possible to get this scenario from Listen/Notify? An alternative solution will be appreciated. -
django: im trying to add checked value and line through to a completed task in to-do list app
Im trying to add checked value and line through to a completed task in to-do list app, i have a div element that have the class completed which is styled in css to strikethrough and a checked attribute in the checkbox element. So inside my html template, i created a for loop to loop through all the todos and check if a todo with attribute completed(an attribute of todo object in model.py) is true, then if it is, the todo(attribute of todo object in model.py) should be place within the element with the class completed and the checked checkbox. And if it is not true, it should be placed within the elements without the completed and checked class. but it rendered the html and it didnt apply the effect to it, despite the fact that there are some todo which their (completed) attribute is set to true in the admin panel This is my html template: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'Todoapp/css/style.css' %}"> <link rel="stylesheet" href="{% static 'Todoapp/fontawesome/css/all.min.css' %}"> <title>Todo</title> </head> <body> <div class="container"> <div class="wrapper"> <div> <div class="header"> <h3><i class="fa fa-tasks fa-white … -
Passing a Django Statement or Accessing specific query set index
I am trying to return the number of threads and posts that belong to that specific forum. The structure is like this: Category -> Forum -> Thread. I want to query the database for all threads and posts that belong to that Forum. This is my current code: Models.py class Forum(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='forums') def __str__(self): return self.name class Thread(models.Model): name = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) thread_forum = models.ForeignKey(Forum, on_delete=models.CASCADE) def __str__(self): return self.name class Post(models.Model): post_body = models.TextField(blank=True, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE) post_date = models.DateTimeField(auto_now_add=True) post_thread = models.ForeignKey(Thread, on_delete=models.CASCADE) def __str__(self): return str(self.id) + ' | ' + str(self.author) Views.py class HomeView(ListView): context_object_name = 'name' template_name = 'index.html' queryset = Category.objects.all() def get_context_data(self, *args, **kwargs): context = super(HomeView, self).get_context_data(*args, **kwargs) context['thread_count'] = Thread.objects.all().count() context['post_count'] = Post.objects.all().count() context['user_count'] = User.objects.all().count() context['categorys'] = Category.objects.all() context['newest_user'] = User.objects.latest('username') return context index.html {% for forum in category.forums.all %} <div class="container-fluid category-forums clearfix"> <!-- 3 red --> <div class="container-fluid category-forums-wrap d-flex align-items-center"> <!-- 4 green --> <div class="container-fluid forum-details-wrapper clearfix"> <div class="container-fluid forum-details-container"> <p class="forum-name"><a href="{% url 'threadlist' forum.pk %}">{{ forum.name }}</a> </p> <p class="forum-desc">{{ forum.description }}</p> <div class="sub-forum-container container clearfix"> … -
how to create multiple/different types of signup forms in `django-allauth` for respective multiple/different types of users
I have searched high and low and none of the solutions I have found work. Using django-allauth how can I create and use multiple types of signup forms specific to respective multiple types of users? Here are some posts that I've looked at: Suggest using SignupForm which @pennersr advises against, and Same solution and same problem, and response related to customizing a form but not multiple from @pennersr, and suggested link from @pennersr that provides some helpful info but again not specific to multiple forms, and lastly this thread Does anyone have the solution to this? Is it possible? I have one form, view and template that works as intended. The following works for 1 django-allauth signup form settings.py #assign to custom form ACCOUNT_SIGNUP_FORM_CLASS = 'users.forms.GeneralSignupForm' forms.py #django-allauth extends SignupForm by default so the following forms are simply adding additional fields that SignupForm does not include class GeneralSignupForm(forms.Form): first_name = forms.CharField(max_length=255, help_text="Your first name") last_name = forms.CharField(max_length=150, help_text="Your last name") phone = forms.CharField(max_length=150) def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.phone = self.cleaned_data['phone'] user.save() views.py class GeneralSignupView(SignupView): template_name = 'account/signup.html' form_class = GeneralSignupForm redirect_field_name = 'next' view_name = 'signup' success_url = None def get_context_data(self, **kwargs): data = … -
I want to make cards responsive. but in django
image 1 image 2 the cards goes horizontally i want it to go down vertically when the card goes off screen. This is a project of django so im looping over a div but the card is going off the screen horizontally i want it to go vertically when the card goes off the screen. PYTHON CODE [HTML] ` <div class="container"> {% for project in projects %} <div class="items"> <h2>{{project}}</h2> <div class="purl"> <p>{{project.description}}</p> </div> <div class="purl1"> <a href='{{project.url}}'>{{project.url}}</a> </div> <div class='buttons'> <a class='btn' href='{% url "update" project.id %}'>Edit</a> <a style='background-color:#f25042' class='btn' href='{% url "delete" project.id %}'>Delete</a> </div> </div> {% endfor %} </div> ` CSS ` .container{ display:flex; } .purl{ text-overflow: hidden; padding-right:.1em; } .purl1{ max-width:20em; margin-right:14px; } .items{ border-radius: 8px; padding:1em 1.5em .5em 1.4em; box-shadow: 0px 0px 17px 0px black; margin:5% 1em 2em .5em; width:100%; } .items h2{ color:#fffffe; } .items p{ color:#94a1b2; } a{ text-decoration: none; color:#7f5af0; } a:hover{ text-decoration: none; color:#fffffe; } .buttons{ display:flex; } .btn{ float:left; text-align: center; font-size:17px; font-weight:bold; padding:.5em; margin:2em 1em .5em 1em ; width:3.5em; border:none; border-radius: 8px; background-color: #2cb67d; color:#fffffe; font-family: 'Noto Sans', sans-serif; } .btn:hover{ background-color: #3dd696; cursor: pointer; } @media only screen and (max-width: 800px) { .container{ margin-left:10%; display:block; } .items{ width:60%; … -
Python Django OpenCV TensorFlow deploy current = current[int(bit)]
I want to deploy a project to azure that contains tensorflow and opencv however i'm getting this error below, i hope someone can help me, i already added the path of the video_feed at urls.py on project Exception while resolving variable 'name' in template 'unknown'. Traceback (most recent call last): File "/antenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/antenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 165, in _get_response callback, callback_args, callback_kwargs = self.resolve_request(request) File "/antenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 288, in resolve_request resolver_match = resolver.resolve(request.path_info) File "/antenv/lib/python3.8/site-packages/django/urls/resolvers.py", line 576, in resolve raise Resolver404({'tried': tried, 'path': new_path}) django.urls.exceptions.Resolver404: {'tried': [[<URLResolver <URLPattern list> (admin:admin) 'admin/'>], [<URLResolver <module 'streamapp.urls' from '/home/site/wwwroot/streamapp/urls.py'> (None:None) ''>, <URLPattern '' [name='index']>], [<URLResolver <module 'streamapp.urls' from '/home/site/wwwroot/streamapp/urls.py'> (None:None) ''>, <URLPattern 'video_feed' [name='video_feed']>], [<URLResolver <module 'streamapp.urls' from '/home/site/wwwroot/streamapp/urls.py'> (None:None) ''>, <URLPattern 'video' [name='video']>], [<URLPattern 'video_feed' [name='video_feed']>]], 'path': 'robots933456.txt'} During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/antenv/lib/python3.8/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] TypeError: 'URLResolver' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/antenv/lib/python3.8/site-packages/django/template/base.py", line 837, in _resolve_lookup current = getattr(current, bit) AttributeError: 'URLResolver' object has no attribute 'name' During handling of the above exception, another exception … -
Getting 'undefined' when accessing item in an array returned from Django Rest Framework via AJAX
I am trying to access data in an array returned from an AJAX GET Request to Django Rest Framework. However, I keep getting undefined, I can console log the data and see what I am trying to target with my index numbers but I am having no luck. I also tried using JSON.parse() but this just threw an error. For visualisation here is what the console.log prints:https://ibb.co/9y8CBw9 Here's what I've got for my Javascript: document.querySelector('#userLists').addEventListener('click', function(event) { if (event.target.dataset.name) { var listname = event.target.dataset.name console.log(listname); getTableData() } }) const getTableData = function(){ $.ajax({ type: 'GET', url: '/api/uservenue/', data: {}, success: function (data) { data.forEach(item => { console.log(item.venue) }) fillTable(data) } }); }; function fillTable(data) { console.log(data) const table = document.getElementById("dashboardTableBody"); let row = table.insertRow(); let name = row.insertCell(0); name.innerHTML = data[0][1]; } Here is my serializers from DRF: class mapCafesSerializer(serializers.ModelSerializer): class Meta: model = mapCafes fields = ['id', 'cafe_name', 'cafe_address', 'description'] class UserVenueSerializer(serializers.ModelSerializer): venue = mapCafesSerializer() class Meta: model = UserVenue fields = ['id', 'list', 'venue'] And these are the pertinent models: class UserVenue(models.Model): venue = models.ForeignKey(mapCafes, on_delete=models.PROTECT) list = models.ForeignKey(UserList, on_delete=models.PROTECT) class mapCafes(models.Model): id = models.BigAutoField(primary_key=True) cafe_name = models.CharField(max_length=200) cafe_address = models.CharField(max_length=200) cafe_long = models.FloatField() cafe_lat = models.FloatField() geolocation … -
How do I make highly scalable chat app with django?
I am currently using ajax , on set interval page would refresh giving a real time feel but i fear on long run if if it scale will clients have the problem, as page refresh every second I think it may overload server, which is the best option for a real time chat app using django, except redis(not free and it has limit) The app should be scalable upto 1000 concurrent connections Server is vps with 4 core 4gb ram and 4tb bandwidth -
How do I fix the ssl module for my Digital Ocean droplet?
I have completed a project I have been working on for quite a while that is a Django-React app. My Django-React app only works with Python 3.6. I have been following a guide to deploy my Django-React app to a Digital Ocean droplet server. I have been following the guide found at this link. I am using a video to guide me, so this is why this guide is using some slightly older versions of Ubuntu, etc., but this shouldn't be an issue. When I follow this guide, I come into the issue that I am automatically using the newest version of Python. It took me many hours but I was eventually able to download Python version 3.6 onto this server... I have been able to get through most of the guide I linked. I have gotten to the point where I create my virtual environment, but in my case I use pipenv instead of virtualenv because this is what I'm used to. So I will explain my problem with the following details: I enter my virtual environment with pipenv shell. I run django-admin --version: The command-line responds: 3.1.6. I run python3.6 -V: The command-line responds: Python 3.6.0. I run … -
Django REST framework ModelSetView POST not allowed
I am trying to learn how to use Django REST framework. I want to make a very simple API using ModelViewSet. I've followed the docs but it's not exactly clear to me if ModelViewSet provides an automatic mapping from its create to POST when doing router.register(r"polls", QuestionViewSet, basename="polls") I keep trying my endpoint: curl --location --request POST 'http://localhost:8005/polls/' \ --header 'Content-Type: application/json' \ --data-raw '{ "question_text": "how it do", "pub_date": "01-01-2021" }' But it returns: {"detail":"Method \"POST\" not allowed."} Models: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) Serailizer and ModelViewSet: class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ["id", "question_text", "pub_date"] class QuestionViewSet(viewsets.ModelViewSet): queryset = Question.objects.all() serializer_class = QuestionSerializer() Routers: from django.conf.urls import re_path, url, include from django.urls import path from rest_framework import routers from .question import QuestionViewSet router = routers.DefaultRouter() router.register(r"polls", QuestionViewSet, basename="polls") urlpatterns = router.urls -
name 'InMemoryUploadedFile' is not defined in django model?
So basically I have a django model which has a filefield. I'd like to resize images that get submitted and I have this code here to do that def save(self, *args, **kwargs): img = Image.open(self.media) output = BytesIO() original_width, original_height = img.size aspect_ratio = round(original_width / original_height) desired_height = 100 desired_width = desired_height * aspect_ratio img = img.resize((desired_width, desired_height)) img.save(output, format='JPEG', quality=90) output.seek(0) self.image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.image.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) super(Post, self).save(*args, **kwargs) The error im getting is "name 'InMemoryUploadedFile' is not defined". How do I fix this? Also a side question. The model also takes in videos. How would I resize a video? This is just a side question the InMemoryUploaded is the main question. Thank you! -
How can I make my graphene-python API respond faster?
I've built a python/daphne/django/graphene server, and did everything I could to optimize my queries -- cached db queries in Redis so that they are basically free, and eventually came to find that even with a very small graph schema I still see a >200ms overhead inside of graphql-core, evidently parsing my query. I come from a REST-api-centric worldview, and in this case the stack decisions were out of my hands. I'm just trying to make it work. Queries that a normal django view should return in ~20ms still take ~250ms. Given that I'm consistently sending the same few queries, it would be fantastic to skip the repetitive parsing of the same query over and over again. So, I'm curious what the Python graphql people do, to make their service perform, and to begin with, I'd like to know: Should I just expect to live with that query overhead? Can I improve by doing something like switching from Daphne to Uvicorn, or even mod_wsgi (am not doing any async stuff) Is there any way to circumvent repeated parsing of the same query? thanks for your time and assistance. -
Cannot saving form in django
So i'm using the auth.models.user to create user model and by default it's passing ('first_name', 'last_name', 'username', 'email', 'password1', 'password2'). and the forms.py: class UserSignUpForm(UserCreationForm): class Meta: fields = ('first_name','last_name','username', 'email', 'password1', 'password2') model = user def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = 'Username' self.fields['email'].label = "Email Address" i try to allowing user to edit their personal information from all avaliable fields in UserSignUpForm, except the password fields. so i created this views.py (function based view): def edit_account(request): user = request.user form = UserSignUpForm(instance=user) if request.method == 'POST': form = UserSignUpForm(request.POST, instance=user,) if form.is_valid(): form = UserSignUpForm(instance=user) form.save() messages.success(request, 'Your account has been updated.') return redirect('/dashboard/profile/') context = {'editform':form} return render(request, 'accounts/updateaccounts.html', context) tried submit the specific field form like{{editform.first_name}} after passsing it in the html page (because i dont want to user be able edit their password) but it still not update/saving the new user data. is there any method so it can be save? thanks -
Pandas & Jango - How to create a DataFrame filter from multiple user inputs without using string executable
I am building a website where users can graph data in a dataframe and apply filters to this data to only plot information they are interested in, as shown below Right now I am having trouble figuring out a way to take the filters a user inputs in the fields above and using those inputs to filter the dataframe. Since the user can create an unbounded number of filters, I decided to use a for loop to build an executable string that contains all of the filters in one variable that is shown below column = (value selected in "Select Parameter", which corresponds to a column in the dataframe) boolean = (value selected in "Select Condition" e.g., >, <, >= ect.... user_input = (value user inputs into field e.g., 2019 and Diabetes) executable = 'df = df[df[' + column1 + '] ' + boolean1 + user_input1 + ' and ' + 'df[' + column2 + '] ' + boolean2 + user_input2 + ' and '..... exec(executable) While this method works, it leaves my code very vulnerable to injection. Is there a better way of doing this? -
Error in importing a module in rest_framework, while creating rest API using Django framework
I created a web application using Djanjo framework, and then when I am trying to create a REST API, after configuring all the relevant files such as models.py, admin.py, serializers.py, views.py, and settings.py. It shows an error while importinng the model from rest_framework. The traceback is as follows: *Traceback (most recent call last): File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\urls\resolvers.py", line 399, in check for pattern in self.url_patterns: File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\urls\resolvers.py", line 584, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\urls\resolvers.py", line 577, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen … -
django - How to get parameters from "def save" function
Is there a way to get parameters from the "save" function? Even if I shoot debug, models.py def save(self, *args, **kwargs): super().save(*args, **kwargs) in postman url http://127.0.0.1:8000/photo?file_h=200&file_w=800 I have to save using "file_h=200&file_w=800". Adding "request" gives me an error. -
decoding to str: need a bytes-like object, HttpResponse found when using Render function in Django
I'm trying to return a error page if a file is not found, by using the render shortcut after the FileNotFoundError and it doesn't work. In view.py I have: return render(request, "encyclopedia/entry.html", { "entry":util.get_entry(request, title) }) In util.py I have: def get_entry(request, title): """ Retrieves an encyclopedia entry by its title. If no such entry exists, the function returns error page. """ try: f = default_storage.open(f"entries/{title}.md") return f.read().decode("utf-8") except FileNotFoundError: context = {} context['title_name']="Title name" return render(request,'encyclopedia/error.html',context,content_type='text/html') #return "The page '"+str(title)+"'"+" was not found." I want to return a html page but it gives me this error Type error: decoding to str: need a bytes-like object, HttpResponse found I'm a beginner and I'm really stuck on this code and I don't know how to change the type to a 'byte-like object' -
In DjangoRestFramework, is it expected that a MultipleChoiceField default attribute is ignored? [duplicate]
I have the following request serializer using a MultipleChoiceField class CompletedOrderStatusDefault: requires_context = False def __call__(self, serializer_field): # -----> this code is never hit?! return [OrderStatus.COMPLETED] class OrderListRequestSerializer(serializers.Serializer): ... order_statuses = serializers.MultipleChoiceField( required=False, default=CompletedOrderStatusDefault, choices=AllowedOrderStatus.ALLOWED, ) the code in the call is never hit during a request and the value for the field is instead an empty set. Is this a bug I should raise or am I wrong to expect that the default is used for this MultipleChoiceField? if so, how should the default be set when the parameter is unspecified in an incoming request? -
python sorted(regex expr with for loop if statement)
I'm having tough time understanding def list_entries function . what does _, mean? and inside sorted() there is a regex expr which means replace .md with empty string and then it runs a for loop? it's possible to run a for loop in sorted after regex expression? and lastly if statement checking if it file ends with .md? I just want to know how this is all put together into sorted() Thank you for your help. import re from django.core.files.base import ContentFile from django.core.files.storage import default_storage def list_entries(): _, filenames = default_storage.listdir("entries") return list(sorted(re.sub(r"\.md$", "", filename)for filename in filenames if filename.endswith(".md"))) -
Adding a button to export to a csv/xlsx file on Wagtail Dashboard
I am attempting the solution mentioned in this stack overflow post (Adding a button to Wagtail Dashboard) however the solution might be outdated, or at least it doesn't work for me and I'm unsure why. Goal: Be able to export a object's data to csv First, the button HTML code had to be slightly adjusted to be formatted correctly like so: {% extends "modeladmin/index.html" %} {% block header_extra %} <div class="right"> <div class="addbutton" style="margin-left: 2em;"> {% include "modeladmin/includes/button.html" with button=view.button_helper.export_button %} <a href="#" class="button bicolor icon icon-download">My button</a> </div> </div> {{ block.super }}{% comment %}Display the original buttons {% endcomment %} {% endblock %} and then I copied and pasted the views and helper functions: from django.contrib.auth.decorators import login_required from django.urls import reverse from django.utils.decorators import method_decorator from django.utils.functional import cached_property from django.utils.translation import ugettext as _ from wagtail.contrib.modeladmin.helpers import AdminURLHelper, ButtonHelper from wagtail.contrib.modeladmin.views import IndexView class ExportButtonHelper(ButtonHelper): """ This helper constructs all the necessary attributes to create a button. There is a lot of boilerplate just for the classnames to be right :( """ export_button_classnames = ['icon', 'icon-download'] def export_button(self, classnames_add=None, classnames_exclude=None): if classnames_add is None: classnames_add = [] if classnames_exclude is None: classnames_exclude = [] classnames = self.export_button_classnames … -
Django issue running manage.py on Mac
I am trying to run a project in atom using a virtual environment and I keep getting an error in regards to the manage.py file. File "manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax I've searched for solutions all over and most people seem to resolve it by using python3 manage.py runserver in the virtual environment instead of python manage.py runserver but that did not work for me. Any suggestions on this? -
Render html tags in Django send email
I found a tutorial on how to send email with Django. This works as intended. However, when I apply html tags, it is being read as a string. Probably because of render_to_string function, but any ideas how to proceed on this? This is my view to send email: current_site = get_current_site(request) mail_message = render_to_string('send/email_template.html', { 'name' : name, 'domain':current_site.domain, }) And this is my email template: {% autoescape off %} <html> Hi {{ name }}, <div class="form-control">......</div> </html> {% endautoescape %} As for the result, it is this: <html> Hi Name, <div class="form-control">......</div> </html> -
How to use Django's APIRequestFactory with an array of objects?
I have the following test def test_bulk_post(my_faker,factory): snippets = [{'code':'print(True)'},{'code':'print(True)'},{'code':'print(True)'}] assert factory.post('/snippets/',snippets) == True I am trying to extend the snippets app in the tutorial to accept multiple code objects in a single post request. Right now this gives me: /venv/lib/python3.8/site-packages/django/test/client.py(244)encode_multipart() *** AttributeError: 'list' object has no attribute 'items' so its not expecting a list.. But I want to give it one. How do I do that?