Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: convert cURL to python requests
I have cURL code that I need to convert to python code using requests library. I want to use this inside django backend software. I tried several ways but I am getting some erros. Can someone help me with this? Here is the cURL code: curl -XPOST -H 'cache-control: no-cache' -H 'content-type: application/json' -H 'X-Client-Id: asdf1234' -H 'X-Client-Secret: qwer9876' -d '{ "planId":"BASIC", "planName":"Basic subscription plan", "amount":12, "intervalType":"week", "intervals":2,"description":"This is the standard plan for our services"}' 'https://test.cashfree.com/api/v2/subscription-plans' -
Errors when running tests in parallel
Multiple issues arise when I try to run tests in parallel. According to the docs, "test_" is prepended to the database name specified in DATABASES. I used the name "postgres", so the database created when running tests is called test_postgres. When running tests in parallel, the following databases are created (which is expected): test_postgres_1, test_postgres_2, test_postgres_3, and test_postgres_4. When running all tests with the --parallel=4 option, however, every test fails with the following message: django.db.utils.OperationalError: FATAL: database "postgres_x" does not exist where x can be 1, 2, 3 or 4. I can see that the following databases have been created: test_postgres_x where x can be 1, 2, 3 or 4. Where's "postgres_x" coming from? Why isn't "test_" being prepended to these? Furthermore, if I manually create the expected databases postgres_x (x = 1 to 4), the migrations applied to the "main" database aren't applied to the clones. This results in errors like this: django.db.utils.ProgrammingError: relation "users_user" does not exist. Roughly 1/4 tests pass when using 4 cores. Lastly, if I try to migrate postgres_x by using migrate --database=postgres_x, I get: django.db.utils.ConnectionDoesNotExist: The connection postgres_x doesn't exist. I have ensured that all tests are isolated just so I can run them … -
Django: search bar is unable to hide fields
Tonight, I was looking into the W3C Filter/Search table, and I thought it would be a pretty nice addition to my Django project. So, I decided to add a search bar like that one. It seems to work, but... There's only a single problem: once I apply a filter to the search bar, it is unable to hide fields from my table. It may sound like a stupid question, but I was wondering what could I do to actually filter the data displayed on my table, using the JS I took from the W3C. I'm kind of stuck with this problem. HTML: <!-- script is used in base.html --> {% extends 'base.html' %} {% block content %} <header> <h2>Character list</h2> </header> <nav class="nav nav-pills nav-justified"> <br> <input class="search-bar" type="text" id="searchbar_id" onkeyup="search()" placeholder="Search for a character..." title="Type in a character name"> <a class="nav-item nav-link" href="{% url 'new_character' %}">New Character</a> <a class="nav-item nav-link" href="{% url 'guilds' %}">Guild List</a> {% if not request.user.is_authenticated %} <a class="nav-item nav-link" href="{% url 'login' %}">Sign in</a> <a class="nav-item nav-link" href="{% url 'signup' %}">Sign up</a> {% else %} <a class="nav-item nav-link" href="{% url 'logout' %}">Sign out</a> {% endif %} </nav> <div class="container"> {% if characters %} <br> <table … -
Get 5 random instances from a queryset in Django
I have this view function that renders the first 5 articles in my Articles model def home_page(request): qs = Article.objects.all()[:5] context = {'article_list': qs} return render(request, "home.html", context) How do i edit it to output any random 5? I've tried this solution, but it didn't work. I don't know what I'm doing wrong. Any help will be greatly appreciated. Thanks -
Extracting questions from doc file using python
I have a Django project in which I want the user to upload a docx file containing questions of MCQ/Fill in The Blanks type. I want to extract these questions and store individual questions in the database. I have set up the database, but couldn't find anything to extract the questions from the docx file. I can read the docx file using textract (https://textract.readthedocs.io/en/stable/), which gives me a list of strings. But how do I check whether a string is a question or an option or just an instruction? Do I have to make specific rules to extract the questions, or is there any library in Python that can help me solve this problem? -
Why doesn't 'encode("utf-8", 'ignore').decode("utf-8")' strip non-UTF8 chars in Python 3?
I'm using Python 3.7 and Django 2.0. I want to strip out non-UTF-8 characters from a string, that I'm obtaining by reading this CSV file. I tried this ... web_site = row['website'].strip().encode("utf-8", 'ignore').decode("utf-8") but this doesn't seem to be doing the job, since I have a resulting string that looks like ... web_site: "wbez.org<200e>" Whatever this "<200e>" thing is, is evidently non-UTF-8 string, because when I try and insert this into a MySQL database (deployed as a docker image), I get the following error ... web_1 | django.db.utils.OperationalError: Problem installing fixture '/app/maps/fixtures/seed_data.yaml': Could not load maps.Coop(pk=191): (1366, "Incorrect string value: '\\xE2\\x80\\x8E' for column 'web_site' at row 1") -
Google Cloud Storage 429 PATCH Too many requests
I'm sorry if this isn't the place to ask, desperately looking for advice. We have a Django 2.2 project using django-storages and GCS for a long time, about an hour ago we started to receive this error constantly, apparently, there is a rate of 1 per second, per file, however only one upload is being made, also we haven't deployed new code related to this, every section of our site where user uploads file we get this error. We don't consume directly the API, we only execute "save" on our models. Any ideas on how can we debug this? This is an example of a complete error: 429 PATCH https://www.googleapis.com/storage/v1/b/at_private_storage/o/dany8%2Fdocumentos%2Faaa16962-fe3e-4242-b479-12d4d4d84ea7.xml?projection=full&predefinedAcl=publicRead: The rate of change requests to the object at_private_storage/dany8/documentos/aaa16962-fe3e-4242-b479-12d4d4d84ea7.xml exceeds the rate limit. Please reduce the rate of create, update, and delete requests. -
Dynamically including/excluding fields from Meta class of a Django ModelForm
Let's say I have a form such as: from django import forms class Foo(forms.ModelForm): class Meta: model = SomeModel fields = ('field1', 'field2', 'field3') How can I include or exclude fields based on some condition? -
Uploading Image in Django: 'utf-8' codec can't decode byte 0x89 in position 246: invalid start byte
I'm trying to upload images in my api using pure json, but when i tried to upload image in request.Files and the token in request.body, I face this error: UnicodeDecodeError at /api/auth/set-profile-image/ 'utf-8' codec can't decode byte 0x89 in position 246: invalid start byte and it says: Unicode error hint The string that could not be encoded/decoded was: " �PNG but i'm sending JPG! :D View.py @csrf_exempt def set_profile_image(request): if request.method == 'POST': request_info = json.loads(request.body) token = request_info.get('token') img = request.FILES['image'] if token is not None and img is not None: user = User.objects.filter(token=token) if user.exists(): user = user.get() form = UploadImage(request.POST, request.FILES['image']) if form.is_valid(): user.profile_image = form.cleaned_data['image'] user.save() response = { 'status_code': 200, 'image_set': True, 'image_url': user.profile_image.url } Form.py from django import forms class UploadImage(forms.Form): image = forms.ImageField() and my test code is: import requests data = { 'token': 'helloworld1--_aFsV-ZVG9lVpi0KSydrx3pG3TSMPqqHVKWD2Yc8bE' } url = 'http://localhost:8000/api/auth/set-profile-image/' with open('test.jpg', 'rb') as img: response = requests.post( url=url, data=data, files={ 'image': img } ) # print(response.text) f = open('test.html', 'wb') f.write(response.content) f.close() I'm using ImageField as my db field in models.py Warmest Regards, Poor Maintenance guy who's stuck in others code! -
need help guys , table gigpost_category has no column named titled
i'm trying to make a simple blog and i'm facing this problem.. so when i try to add a model in my admin panel it shows me this error? here is the code models.py from django.db import models from django.utils import timezone from django.conf import settings # Create your models here. class Category(models.Model): titled=models.CharField(max_length=100,default='') class Meta: abstract=True def __str__(self): return self.title class Gigpost(models.Model): title=models.CharField(default='',max_length=100,blank=False) user=models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=False) categories=models.OneToOneField(Category,on_delete=models.PROTECT,default='',blank=False) published_at=models.DateTimeField(auto_now_add=True) description=models.TextField(default='',max_length=None,blank=False) mainphoto=models.ImageField(default='') photo=models.ImageField() def __str__(self): return self.title class Comment_area(models.Model): user=models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=False) comment=models.TextField(max_length=None,default='') commented_at=models.DateTimeField(auto_now_add=True) admin.py from django.contrib import admin from .models import Gigpost , Category # Register your models here. admin.site.register(Gigpost) admin.site.register(Category) the error message : OperationalError at /admin/gigpost/category/add/ table gigpost_category has no column named titled Request Method: POST Request URL: http://127.0.0.1:8000/admin/gigpost/category/add/ Django Version: 2.2.5 Exception Type: OperationalError Exception Value: table gigpost_category has no column named titled thanks for helping genius people :D -
How to avoid + signs getting replaced with spaces in GET parameters (Django)?
I've found myself in need of passing email addresses in GET parameters, but I noticed + signs get replaced by spaces, so that an URL like example.com?param=myemail+alias@example.com will, when captured through something like request.GET.get("param", None), yield myemail alias@example.com. For now I opted for the arguably crude and risky way of replace()ing spaces with + signs but I'd like to know: is there a better way to pass email addresses in GET parameters (that will work with Django 3+)? -
Cart and Cart Item relations in Django Rest Framework
models.py class Cart(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="cart") create_date = models.DateTimeField(auto_now_add=True) class Item(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE,related_name='items') product = models.ForeignKey(Product, on_delete=models.CASCADE,related_name='product') quantity = models.IntegerField(default=1) serializers.py class CartSerializer(serializers.ModelSerializer): class Meta: model = Cart fields = ['user','status'] class ItemSerializer(serializers.ModelSerializer): cart = CartSerializer() class Meta: model = Item fields = ['cart', 'product', 'quantity'] urls.py urlpatterns = [ path('add/', AddItem.as_view(),name='add'), ] views.py class AddItem(CreateAPIView): serializer_class = ItemSerializer permission_classes = [IsAuthenticated] How can I connect the "cart" in Item without asking it directly in Django Rest Framework? I'm sending {"product":1,"quantity":1}, however it asks for "cart" to be sent. I can't figure out how to make DRF automatically resolve it as it's connected to the cart. -
How to push a docker-compose to openshift from windows
So I'm trying to deploy a docker-compose with Django, Nginx and Postgresql. When I run it trough the docker-compose everything is working, but is I execute docker-compose push is not mapping the containers, so I read that I should be using something like Kompose to push it, but the thing is that Kompose convert or push is not available in windows. Do you guys know any workaround with this? How can I push the containers and map everything usind windows to openshift. Any help would be greatly appreciated. Thanks -
Django: call method after clicking button
I was searching for this answer but none met my expectation. So, In my template I have some content and wanted to add button (which later will add to favorites). After clicking I want to call method from my views.py and redirect to other view. my views.py def home(request): //logic here return render(request,'file.html') def function_to_call(request): ///logic here return render(request,'second_file.html') file.html <form action="{% url 'function_to_call' %}"> <button id="submit" type="button" value="Click" /> </form> and in my urls.py url(r'^function_to_call/',views.function_to_call,name='function_to_call'), Unfortunately, after clicking on button, nothing happens -
Django Admin link to member list on event list
I have two simple models. class Event(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=30) class Member(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) event = models.ForeignKey(Event, on_delete=models.CASCADE) Now in Event I have list of events and when we choose one of them, next step is Edit of this Event. It's working good, but I need on these events list link/action to members yet. Is it possible to quick do it. -
Saving string to SQLite many times consumes a ridiculous amount of disk space?
Through my front-end I allow users to edit posts with an auto-save-function. Every update of the post is saved to the DB. On edit the instance from the last save is updated via a PUT request. The amount of space this is consuming however is quite ridiculous. Disregarding, if the updated string gets longer or shorter the space only goes up. My local SQLite file has now more than 500MB. The relevant view in django is verbose but pretty standard I'd say: class PostDetail(APIView): permission_classes = [ permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly, IsOwnerOrPublishedOnly] def get_queryset(self): queryset = Post.objects.all() is_published = self.request.query_params.get('is_published', None) if is_published and is_published == 'false': queryset.filter(is_published=False) if is_published and is_published == 'true': queryset.filter(is_published=True) return queryset def get_object(self): obj = get_object_or_404(self.get_queryset(), uuid=self.kwargs.get('post_uuid', None)) self.check_object_permissions(self.request, obj) return obj def put( self, request, post_uuid, format=None): post = self.get_object() serializer = PostUpdateSerializer(post, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_500_INTERNAL_SERVER_ERROR) I can't really wrap my head around how to debug this? This is why I'm turning to SO. Any tips? -
Django - Comment user name
Im working on a django project, and I have a model that looks like this: class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1,on_delete=models.CASCADE) slug = models.SlugField(unique=True,null=True, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') parent = models.ForeignKey("self", null=True, blank=True,on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) objects = CommentManager() def __str__(self): return str(self.user.username) I use this serializer: class CommentDetailSerializer(ModelSerializer): user = SerializerMethodField() replies = SerializerMethodField() class Meta: model = Comment fields = [ 'user', 'content', 'replies', 'timestamp' ] def get_user(self,obj): return str(obj.user.username) def get_replies(self,obj): if obj.is_parent: return CommentChildSerializer(obj.children(),many=True).data for this view: class CommentDetailApiView(RetrieveAPIView): queryset = Comment.objects.all() serializer_class = CommentDetailSerializer lookup_field = 'slug' if I console.log(JSON.stringify(data)); I get this output. {"user":"abc","title":"blabla","content":"blablabla","comments":[{"user":1,"content":"cool post","timestamp":"2020-02-18T00:07:29.932850Z"}] How do I get the comment user username instead of its id? Thank you -
Strange beaver when use order_by with conditions Cannot resolve keyword '-pub_date into field
This code work fine, except it's not the result that i want. For each Case it's order goes by to old one to new one def get_queryset(self, *args, **kwargs): return super(PublishedManager, self).get_queryset().filter( pub_date__lte=timezone.now(), status="published").order_by( Case(When(status_ranking='1', then='pub_date')).asc(), Case(When(status_ranking='2', then='pub_date')).asc(), Case(When(status_ranking='3', then='pub_date')).asc(), Case(When(status_ranking='4', then='pub_date')).asc() ) Whenever i use this method, i got the error; Cannot resolve keyword '-pub_date into field def get_queryset(self, *args, **kwargs): return super(PublishedManager, self).get_queryset().filter( pub_date__lte=timezone.now(), status="published").order_by( Case(When(status_ranking='1', then='-pub_date')).asc(), Case(When(status_ranking='2', then='-pub_date')).asc(), Case(When(status_ranking='3', then='-pub_date')).asc(), Case(When(status_ranking='4', then='-pub_date')).asc() ) -
How can i add eye views feature to my blog post in django? [closed]
Blog post with eye views feature -
Django SQLite3 development DB is more than 500MB. Analyse what is taking up the space?
I am developing a django application. I am storing lang strings in the database but besides that, I am not storing much else in there. In production I am also replacing the SQLite with Postgres. But I really want to figure out, what is taking up all the space in the DB but I don't really now how to analyse the database tables to see memory consumption? -
Little help boxes for sign up form
I created a signup page for my website with Django. In this form, I want to put little boxes or ballons next to input fields. For example, when user click or hover the box next to password input field, it should be written that "The password should be 8 letter and includes 1 uppercase" etc. How can I do it? signup.html <!DOCTYPE html> <html lang="en"> {% load static %} <link rel="stylesheet" href="{% static 'css/signup.css' %}"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="radio" id="toggle--signup" name="toggle" class="ghost" /> <! –– <img class="logo framed" src="https://www.tumblr.com/images/logo/logo_large.png?v=7ea0eb57dd627a95f82be5bde0c43d59" alt="Tumblr logo" /> ––> <form class="form form--signup framed" method="post"> {% csrf_token %} <h1 class=" text--centered">PHARSYS</h1> <h2 class="text text--centered text--omega">Join Us!</h2> <input type="text" placeholder="Username" name="username" maxlength="150" autofocus required id="id_username" class="input input--top"> <input type="text" placeholder="First name" name="first_name" maxlength="30" id="id_first_name" class="input"> <input type="text" placeholder="Last name" name="last_name" maxlength="30" id="id_last_name" class="input"> <input type="email" placeholder="Email" class="input" name="email" maxlength="254" id="id_email"/> <input type="password" placeholder="Password" class="input" name="password1" required id="id_password1"> <input type="password" placeholder="Confirm password" class="input" name="password2" required id="id_password2"> <select class="input" name="user_type" required id="id_user_type"> <option value="" selected>User Type</option> <option value="pharmacist">Pharmacist</option> <option value="manager">Medical Repository Manager</option> </select> <button type="submit" class="input input--submit">Sign Up!</button> <a class="text text--small text--centered" href="/users/login">I am already a member</a> </form> <div class="fullscreen-bg"></div> </body> </html> -
groups attribute using django-tenant-users
I am using wagtail as part of a multi-tenant setup using django-tenant-schemas and django-tenant-users. Whenever I specify my custom user model that extends django-tenant-users's UserProfile, as required by django-tenant-users, wagtail breaks the application because it is trying to access the groups attribute, which UserProfile does not have. Are applications that need access to groups incompatible with django-tenant-users? Is there a way around this? Output: File "/home/cirrus-admin/cirrus/cirrus_core/cirrus_core/urls.py", line 25, in <module> from wagtail.admin import urls as wagtailadmin_urls File "/home/cirrus-admin/.local/share/virtualenvs/cirrus_core-QNhT-Vzg/lib/python3.7/site-packages/wagtail/admin/urls/__init__.py", line 12, in <module> from wagtail.admin.urls import password_reset as wagtailadmin_password_reset_urls File "/home/cirrus-admin/.local/share/virtualenvs/cirrus_core-QNhT-Vzg/lib/python3.7/site-packages/wagtail/admin/urls/password_reset.py", line 3, in <module> from wagtail.admin.views import account File "/home/cirrus-admin/.local/share/virtualenvs/cirrus_core-QNhT-Vzg/lib/python3.7/site-packages/wagtail/admin/views/account.py", line 14, in <module> from wagtail.users.forms import ( File "/home/cirrus-admin/.local/share/virtualenvs/cirrus_core-QNhT-Vzg/lib/python3.7/site-packages/wagtail/users/forms.py", line 178, in <module> class UserCreationForm(UserForm): File "/home/cirrus-admin/.local/share/virtualenvs/cirrus_core-QNhT-Vzg/lib/python3.7/site-packages/django/forms/models.py", line 266, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (groups) specified for User -
Django mptt recursetree with get_cached_trees in template
In View: context['categories'] = = models.Category.objects.all().get_cached_trees() In template: {% load mptt_tags %} <ul> {% recursetree categories %} <li> {{ node.name }} {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> As a result, it render only first level of queryset. If remove get_cached_trees it works. How to render all tree with get_cached_trees? -
Django - can not publish post
I have a problem, I'm just making a simple blog. I wanted to have possibility to save my posts as a drafts before I publish them. I follow step by step video, I have almost everything same and there is still some problem - publish function doesn't work. Do you have some ideas why? models.py from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class Post(models.Model): autor = models.ForeignKey('auth.User', on_delete=models.CASCADE) tytuł = models.CharField(max_length = 200) tekst = models.TextField() create_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def get_absolute_url(self): return reverse("post_detail", kwargs={'pk':self.pk}) def __str__(self): return self.title views.py(that function) @login_required def post_publish(request, pk): post = get_object_or_404(models.Post, pk=pk) post.publish() return redirect('post_detail', pk=pk) and if statement in html file: {% if post.published_date %} <div class="date postdate"> {{ post.published_date }} </div> {% else %} <a class="btn btn-outline-dark" href="{% url 'post_publish' pk=post.pk %}">Publish</a> {% endif %} urls.py from django.urls import path, re_path from . import views urlpatterns = [ path('', views.IndexView.as_view(), name="index"), path('about/', views.AboutView.as_view(), name="about"), path('posts/', views.PostListView.as_view(), name="post_list"), re_path(r'posts/(?P<pk>\d+)/', views.PostDetailView.as_view(), name="post_detail"), path('posts/new/', views.CreatePostView.as_view(), name="post_new"), re_path(r'posts/(?P<pk>\d+)/edit/', views.PostUpdateView.as_view(), name="post_edit"), re_path(r'posts/(?P<pk>\d+)/remove/', views.PostDeleteView.as_view(), name="post_remove"), path('drafts/', views.DraftListView.as_view(), name="post_draft_list"), re_path(r'posts/(?P<pk>\d+)/publish/', views.post_publish, name="post_publish") ] Everything is good as far as … -
FileNotFoundError: [WinError 3]
I'm trying to add an image to django [logo.jpg] which is inside a folder called static. I have created but, I'm getting an error WinError 3] The system cannot find the path specified: 'C:\Users\vo\Desktop\firefire\firefire\static' I'm using windows 10 STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'firefire/static/') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/'