Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python django image upload is not working
Python Django image upload is not working when I am adding data and click on submit button not give a any response and also not upload any data in the database. models.py fisrst of all i add model file. # Create your models here. from django.db import models class Car(models.Model): carname=models.CharField(max_length=50) carmodel = models.CharField(max_length=50) carimage = models.ImageField(upload_to='images/') price=models.CharField(max_length=15) average=models.CharField(max_length=20) gear=models.CharField(max_length=200) passengers = models.CharField(max_length=200) type=models.CharField(max_length=200) Insurance=models.CharField(max_length=200) class Meta: db_table="car" forms.py then i create a form.py. from django import forms from carapp.models import Car class CarForm(forms.ModelForm): class Meta: model=Car fields="__all__" also add this two line in settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py then i give a path of method. from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static from carapp import carviews urlpatterns = [ path('admin/', admin.site.urls), #this is for admin user path('savecar',carviews.savecar), path('showcar', carviews.showcar) ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) carviews.py then I created an API method. from django.shortcuts import render,redirect from carapp.forms import CarForm from carapp.models import Car from django.core.paginator import Paginator, EmptyPage, InvalidPage def savecar(request): if request.method == "POST": form= CarForm(request.POST) if form.is_valid(): try: form.save() return redirect("/showcar") except: pass else: … -
Django Forms ignoring USE_L10N configuration
It looks like my django application is not respecting the settings configuration USE_L10N=True In [1]: from django import forms In [2]: class SomeForm(forms.Form): ...: some_date = forms.DateField(required=False) ...: In [3]: form = SomeForm(data=dict(some_date='28/05/2020')); form.errors Out[3]: {'some_date': ['Enter a valid date.']} In [4]: from django.conf import settings In [5]: settings.USE_L10N Out[5]: True In [6]: import locale In [7]: locale.getlocale() Out[7]: ('pt_BR', 'UTF-8') In [8]: form = SomeForm(data=dict(some_date='05/28/2020')); form.errors Out[8]: {} If I use MM/DD/YYYY or YYYY/MM/DD it works. Shouldn't django be using this pt-BR format instead? What can be wrong? Thank you in advance! -
How to get form field value using jQuery, Ajax and Django
I have a html form which has four inputs. Two of them got through a form passed from Django view and two of them through previous page view through Django variable. This html form is as follow: <form method="POST" id="post_form" class="post_form" action="" enctype="multipart/form-data" formnovalidate > {% csrf_token %} <!-- category --> <div class="form-group"> <input type="hidden" id="category" name="category" value="{{category}}"> </div> <!-- subcategory --> <div class="form-group"> <input type="hidden" id="sub_category" name="sub_category" value=" {{sub_category}}"> </div> <!-- post form field --> {% for field in form %} {% if field.name == 'title' %} <div class="form-group"> <label>{{ field.label_tag }} </label> <input type="text" class="form-control" id="title" placeholder="title" name="title"> </div> {% endif %} {% if field.name == 'content' %} <div class="form-group"> <label>{{ field.label_tag }}</label> <textarea class="form-control" id="content" placeholder="description" name="content"></textarea> </div> {% endif %} <!-- end of form --> {% endfor %} <button type="submit" class="btn btn-primary">Submit</button> </form> the jQuery code as follow: <!-- to submit the post and post images forms --> <script type="text/javascript"> // to submit the form and prevent the default submission $(document).on('submit', '#post_form', function(e) { e.preventDefault(); var formData = new FormData(this); formData.append("category",$("#category").val()); formData.append("sub_category",$("#sub_category").val()); formData.append("titel",$("#title").val()); formData.append("content",$("#content").val()); alert(formData['category']); $.ajax({ type:'POST', url: "{% url 'create_post' %}", data: formData, processData: false, cache:false, contentType: false, csrfmiddlewaretoken:'{{ csrf_token }}', success: function(data) { if … -
Extract the month from DateField in Django template
Want to extract the month and year from template template_1.html <form method = 'POST'> <input type ='month' name = 'searchmonth'> <input type = 'submit' value = 'Search'> </form> template_2.html {% for i in record %} {% if i.record_patient_number == number %} {{ month = i.record_date.getMonth() }} {% if month == searchrecordmonth %} *something* {% endif %} {% endif %} {% endfor %} All variable are include in views.py In this search month is not able to extract and record_date is save in models.py and as a record_date = models.DateField(blank = True , null = True) -
Django / Apache returns HTTP 500 Randomly
I have been dealing with a rather strange issue lately. My backend has httpd + mod wsgi + Django setup. I have a class-based view as follows: class ExtrasView(View): def get(self, request): path = settings.BASE_DIR + "/data.json" with open(path, encoding='utf-8') as f: data = json.loads(f.read()) return JsonResponse(data) The get request to the above view works perfectly 9 out of 10 times. However, randomly this view would give a response with status 500. Based on the apache log, it seems that the response body length is correct i.e. the length of data in the file. This is verified by apache access logs. Does anyone have an idea why this might be happening? I have checked the error logs and there's nothing in the errorlog. The error log does print tracebacks in case of exceptions or other syntax errors, just in this case it doesn't print anything so I'm clueless. Needless to say, the file being read is a static file that 100% exists. The data in the file is huge, it's length is about 30-40k characters. Would this cause an issue? If yes, then why does it work 9 out of 10 times? Any comments are welcome. -
Gunicorn not working on Amazon ec2 server
I am trying to deploy a django website on an aws ec2 instance (ubuntu 18.04) following this tutorial that is consistent with other online resources. Everything is working fine but there is some issue with gunicorn. The worker doesn't seem to boot. I figured there was something wrong with my installation and I tried uninstalling and installing with different commands- inisde my virtualenv with pip install gunicorn and sudo -H pip install gunicorn I even physically deleted all gunicorn files and reinstalled gunicorn but its always the same. Where have I gone wrong? p.s: I had initially done sudo apt-get -
Add Cash on Delivery Payment on Saleor Project
I'm totally new to django, but I've found this open source e-commerce app named Saleor so I've built a complete front-end depending on it, but the problem I'm having now is in the checkout level where I can't find a Cash on Delivery payment method and I can't complete the checkout without adding a payment method, the business need doesn't require a credit-card or any online payment method. after googling I found this plugin django-payments-code, tried to install it on the project but I got this error ModuleNotFoundError: No module named 'payments', I'm running out of time and I really appreciate any help might be provided. -
django xhtml2pdf not getting image
I am trying to render html to pdf, it really works great ! only there is an issue and that is the template getting image: I am using python xhtml2pdf library for pdf render this is my method for render pdf: def render_pdf(template_src, context_dict): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return HttpResponse('Unable to process the request, We had some errors<pre>%s</pre>' % escape(html)) and this is my views.py below: def test_view(request): context = { 'test': 'a test string' } return render_pdf('test.html', context) and this my test.html {% load static %} <p>hello test </p> <img src="{% static 'ok.jpg' %}"> It gets image if i render with django default render method But the image not getting when i render for pdf. I heard of this solution with link_callback method with this documatin: https://xhtml2pdf.readthedocs.io/en/latest/usage.html I am not getting where to include this or how can i achive this. Can anyone help me in this case? -
DJango read static file Json
I am learning django, I would like to read a json file but I do not kown where to put it cause I cannot display. Here is the structure of my project: src=>templates=> Main=> home.html src=>Myproject=> settings.py src=>Myproject=>urls.py here the html: {% load static %} <lottie-player src= src="{% static "./myfile.json" %}" background="transparent" speed="1" style="width: 700px; height: 700px;" loop autoplay > </lottie-player> </div> Hereis the main urls.py if settings.DEBUG: import debug_toolbar urlpatterns += [ path('__debug__/', include(debug_toolbar.urls)), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Here is my setting : STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, "static_project") ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "static_root") #every time a user upload folder, it will be inside the static_cdn folder and the root "media root" MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "media_root") Thanks for your help -
Django specify which database to use for module
In my Django project I have a couple of applications, one of them is email_lists and this application does a lot of data handling reading data from the Model Customers. In my production environment I have two databases: default and read-replica. I would like all queries in a particular module to be made against the replica-set database. I can do that if I explicitly tell the query to do so: def get_customers(self): if settings.ENV == 'production': customers = Customer.objects.using('read-replica').filter() else: customers = Customer.objects.filter() but this module has more than 100 queries to the Customer and other models. I also have queries to relations like: def get_value(self, customer): target_sessions = customer.sessions.filter(status='open') carts = Cart.objects.filter(session__in=target_sessions) the idea is that I want to avoid writing: if settings.ENV == 'production': instance = Model.objects.using('read-replica').filter() else: instance = Model.objects.filter() for every query. There are other places in my project that do need to read from default database so it can't be a global setting. I just need this module or file to read using the replica. Is this possible in Django, are there any shortcuts ? Thanks -
django-using same route in url path
I was working on a project and I am a beginner in Django. I am passing user.id from template to URL for tow things i.e one for profile update and one for a password reset. But it is going to only one URL whether I am clicking on profile update or password reset. I think the issue is I can not use the same routes in two URL paths. here is my url.py: urlpatterns = [ path('signup', views.signup, name='signup'), path('login', views.login, name='login'), path('logout', views.logout, name='logout'), path('<int:user_id>/', views.chgprofile, name='chgprofile'), path('<int:user_id>/', views.chgpassword, name='chgpassword'), ] here is my template code which shows the two buttons: <a class="btn btn-sm btn-outline-primary" href="{% url 'chgpassword' user.id %}">change password</a> <a class="btn btn-sm btn-outline-primary" href="{% url 'chgprofile' user.id %}">update profile</a> -
Django setting models.DateField() with a datetime object
I'm debugging some failing test after we recently upgraded from django 1.11 to 2.2, and i've noticed a behaviour that i havent been aware before. consider the following code from datetime import date, datetime, timedelta class User(models.Model): birthday = DateField() user = User.objects.create(birthday=date.today()) # setting the DateField object with datetime yesterday_datetime = datetime.now() - timedelta(days=1) user.birthday = yesterday_datetime user.save() user.refresh_from_db() print(user.birthday) # returns date.today() I've always assumed that when a DateField object has been populated with a datetime object, that the date aspect of the datetime object is taken and saved. It seems like this is not the case, and the field isnt updated / saved to the db. Is this a django 2+ behaviour or has this been the default for quite some time? Can anyone share their experience with this edge case? -
Django name magic in serializers.py file for HyperlinkedModelSerializer?
so I was trying to debug a problem where for a particular view using a HyperlinkedModelSerializer, one level of data was being returned as ints not urls. Ie, I was getting { "id": 4, "title": "asdf", "photos": [ 4 ], }, where I should have been getting { "id": 4, "title": "asdf", "photos": [ "http://localhost:8000/pics/4/" ], }, What was really weird, is the exact same viewset function works when I move it to the serializers.py file, but returns the wrong data when it lives in views.py. The function is as follows: class MemberMenuItemsViewSet(AuthModelViewSet): """ all items available from this maker (from all menus) """ serializer_class = MenuItemSerializer queryset = MenuItem.objects.all() def get_queryset(self): #def get(self, request, *args, **kwargs): member_id = self.kwargs.get('member_id') return MenuItem.objects.filter( menu__owner_id=member_id).order_by('-updated_at') I have solved my problem for now by moving this function to the serializers.py file and adjusting the call to it in urls.py ; but it is baffling why moving the function here instead of in views.py, should make any difference. I've tested it several times with consistent results, and my conclusion is there is some name magic going on? Or somewhere that I have not realized the serializers.py file is being pre-processed? Its no longer a … -
Connection refused while using MongoDB with Django
I'm using 2 databases for my Django project and they're in the settings as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'AppDB', 'USER': 'genericpiratename', 'PASSWORD':'pass', 'HOST': 'mypirateapp-postgres.ja6as4d8ss54.ap-south-1.rds.amazonaws.com', 'PORT': '5432', }, 'mongoDB' : { 'ENGINE': 'djongo', 'NAME': 'pirateapp', 'USER': 'uncommonpiratename', 'PASSWORD': 'dbpass', 'HOST': 'mongodb+srv://uncommonpiratename:dbpass@cluster1-8zu5ge.mongodb.net/test', } } The first database is a hosted PostgreSQL database and the second one is also a hosted MongoDB database. I used the mongodb atlas to host the cluster and compass to create the database pirateapp. I also allowed database access for both the databases from all IPs. I've used the following routers for the databases: class PrimaryRouter: def db_for_read(self, model, **hints): return 'default' def db_for_write(self, model, **hints): return 'default' def allow_relation(self, obj1, obj2, **hints): db_list = ('default') if obj1._state.db in db_list and obj2._state.db in db_list: return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): return True class DirectionsRouter: route_app_labels = {'tressureHunter'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'mongoDB' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'mongoDB' return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in … -
Is there any multiple pagination on the same page but in different tabs in django?
I have tabs in django template displaying the tour packages category. For single page I am able to implement pagination in django but I am unknown regarding the pagination based on tabs. will please anyone suggest me any ideas how to filter in django views based on tabbed heading ? In single page I am using like this Models.py enterdef blog(request): blog_list = Blog.objects.filter(blog_verification=True) paginator = Paginator(blog_list, 6) # Show 6 blogs per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = {'blogs': page_obj, 'packages': Packages.objects.all()} return render(request, 'user/blog.html', context) Templates <div class="pagination"> <span class="step-links"> {% if blogs.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ blogs.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ blogs.number }} of {{ blogs.paginator.num_pages }}. </span> {% if blogs.has_next %} <a href="?page={{ blogs.next_page_number }}">next</a> <a href="?page={{ blogs.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> </div> -
Exit a view function without triggering an error from Twilio, after unsubscribing a phone number? - Django
def sms(request): if request.method == "POST": umessage_body = str(request.POST['Body']).isupper() if umessage_body == STOP or umessage_body == STOPALL or umessage_body == UNSUBSCRIBE or umessage_body == CANCEL or umessage_body == END or umessage_body == QUIT: new_unsubscriber = Unsubscriber(phone_number=request.POST['From']) return elif umessage_body == START or umessage_body == YES or umessage_body == UNSTOP: Unsubscriber.objects.filter(phone_number=request.POST['From']).delete() return If user types one of the unsubscribe words such as STOP, I should add the phone number to my Unsubscriber model as a record, and then exit the sms function. How do I exit the sms function without triggering an error? Currently I get the error 21610 - Attempt to send to unsubscribed recipient from Twilio. -
Django - prefetch_related GenericForeignKey results and sort them
I have the below structure, where content modules, which are subclassed from a common model, are attached to pages via a 'page module' model that references them via a GenericForeignKey: class SitePage(models.Model): title = models.CharField() # [etc..] class PageModule(models.Model): page = models.ForeignKey(SitePage, db_index=True, on_delete=models.CASCADE) module_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) module_id = models.PositiveIntegerField() module_object = GenericForeignKey("module_type", "module_id") class CommonModule(models.Model): published_time = models.DateTimeField() class SingleImage(CommonModule): title = models.CharField() # [etc..] class Article(CommonModule): title = models.CharField() # [etc..] At the moment, populating pages from this results in a LOT of SQL queries. I want to fetch all the module contents (i.e. all the SingleImage and Article instances) for a given page in the most database-efficient manner. I can't just do a straight prefetch_related because it "must be restricted to a homogeneous set of results", and I'm fetching multiple content types. I can get each module type individually: image_modules = PageModule.objects.filter(page=whatever_page, module_type=ContentType.objects.get_for_model(SingleImage)).prefetch_related('module_object_') article_modules = PageModule.objects.filter(page=whatever_page, module_type=ContentType.objects.get_for_model(Article)).prefetch_related('module_object') all_modules = image_modules | article_modules But I need to sort them: all_modules.order_by('module_object__published_time') and I can't because: "Field 'module_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying" ... and I don't think I can add the recommended GenericRelation field to all the content … -
React: How to send a multipart/form-data to a database
I am currently setting up a file upload with React for the frontend and Django for the backend. More specifically, I want to pass a file + some data to my database via an API. But while uploading the file I get the error: "The submitted data was not a file. Check the encoding type on the form." models.py (Django) class Story (models.Model): title = models.CharField(max_length=100,blank=False) content = models.TextField(blank=False) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) audio = models.FileField(default='SOME STRING', upload_to='audio_stories/',null=True, validators=[validate_file_extension_audio]) def __str__(self): return self.title def get_absolute_url(self): return reverse('story-detail', kwargs={'pk': self.pk}) serializers.py (Django) class StorySerializer(serializers.ModelSerializer): class Meta: model = Story fields = '__all__' A MultiPartParser is used to pass file + data. api.py (Django) class StoryViewSet(viewsets.ModelViewSet) (Django): serializer_class = StorySerializer parser_classes = (MultipartJsonParser, parsers.JSONParser) queryset = Story.objects.all() permission_classes = [ permissions.IsAuthenticated ] def perform_create(self, serializer): serializer.save(author=self.request.user) utils.py (Django) class MultipartJsonParser(parsers.MultiPartParser): def parse(self, stream, media_type=None, parser_context=None): result = super().parse( stream, media_type=media_type, parser_context=parser_context ) data = {} # find the data field and parse it data = json.loads(result.data["data"]) qdict = QueryDict('', mutable=True) qdict.update(data) return parsers.DataAndFiles(qdict, result.files) In actions story.js (React) import axios from "axios"; import { tokenConfig } from './auth'; import { createMessage, returnErrors } from "./messages"; import {ADD_STORY} from "./types"; const apiBase … -
The If equal not working in Django Template
I am able to fetch these two values in the Django HTML template : {{ user.get_username }} {{post.user}} But when I use them further to compare their values in an IF condition, it doesn't work. {%if user.is_authenticated%} <h3> {{ user.get_username }}</h3> <h3> {{post.user}} </h3> {%ifequal user.get_username post.user%} <form action="{%url 'post_delete' post.id %}" method="POST"> {%csrf_token%} <button type="submit">Delete</button> </form> {%endifequal%} {%endif%} {%endfor%} I've also tried {% if user.get_username == post.user %} as well, but it didn't help either. Please help. I need the delete button only against the posts of logged in user. -
NOT NULL constraint failed: posts_comment.post_id django
I have the basics of a blogs app (I have been following Corey Schafer's tutorial, part 10, if that matters) and I am trying to post and display comments on the post that other users have wrote that only relate to that post. Similar to that of a comment section on Facebook or YouTube. Currently I'm displaying all comments in the database on every post because I don't know how to filter the results to only show comments for the specific post and I also don't know how to post comments to a specific post, that's where I get the error. My code is below: Models.py class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(default=timezone.now) product = models.ForeignKey(Product, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('core:post-detail', kwargs={'pk': self.pk}) class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.user.username Views.py class PostDetailView(DetailView): model = Post context_object_name = 'posts' def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context['comment'] = Comment.objects.all() return context class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = ['content'] def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) urls.py (This is the urls.py file in … -
How to connect to pymongo with django
my DB connection is DATABASES = { 'default': { 'ENGINE': 'djongo', 'ENFORCE_SCHEMA': True, 'NAME': 'taxiapp', 'HOST':'127.0.0.1', 'PORT': xxxx, } } my SSH ADDRESS x.x.x.x SSH USERNAME 'admin' SSH PORT 0000 SSH AUTH method password and USER PASSWORD 0000 currently I am getting pymongo.errors.ServerSelectionTimeoutError: 127.0.0.1:xxxx: [Errno 111] Connection refused How to define SSH details in my settings.py file ??? -
how to simply add somthing to manytomany field in django REST with a request
i'm new in django rest. i want to be able to add things to "members" field. how serializers.py and views.py should look like? class Group(models.Model): since = models.DateTimeField(auto_now_add=True) groupid = models.CharField(max_length=20, blank=False, null=False, validators=[alphanumeric], unique=True, default='') #groupid only contains alphanumerical characters title = models.CharField(max_length=100, blank=True, default='No Name') describtion = models.TextField(blank=True) invite_only = models.BooleanField(default=False) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name='Created by', blank=True, null=True, related_name="%(app_label)s_%(class)s_created", on_delete=models.SET_NULL) members = models.ManyToManyField(settings.AUTH_USER_MODEL,blank=True) #upper field should be modified. because right now, it's pointing to django's default superuser model class Meta: ordering = ['since'] def __str__(self): return self.title -
Why does this form not save?
the code below is a simple register for an account now when I submit this form it redirects me to the home page and this means that my form is valid and works but when I check my Admin page I see that account is not registered and I get no error. therefor I can understand here that my code is already working but it hasn't been saved. so, how can I save member through FormView? thanks in advance views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.views.generic import TemplateView, View from django.views.generic.edit import FormView from .forms import UserForm from django.urls import reverse_lazy class IndexView(TemplateView): template_name = "accounts/index.html" class ProfileView(FormView): template_name = "accounts/register.html" form_class = UserForm success_url = reverse_lazy("accounts:index") def form_valid(self, form): print("the user has registered") return super().form_valid(form) forms.py from django import forms from .models import User class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label="Confirm Password", widget=forms.PasswordInput) class Meta: model = User fields = '__all__' exclude = ('staff', 'active', 'admin', 'last_login') def clean_password2(self): password = self.cleaned_data['password'] password2 = self.cleaned_data['password2'] if password and password2 and password != password2: raise forms.ValidationError("Passwords don't match") return password2 def clean_email(self): email = self.cleaned_data['email'] qs = User.objects.filter(email=email) if qs.exists(): raise forms.ValidationError("email is taken") … -
How can i manage featured option if new article is create then old featured is expired and it show in without featured list?
i have two type of list's one is with featured boolean second is without featured. How can i manage featured option if new article is create then old featured is get expired and it's show in without featured list? example is here.. views.py articles = Article.status_objects.filter(featured=True)[:1] articleslist = Article.status_objects.all().exclude(featured=True)[:2] -
Django adds square brackets and quotes to charfield input
recently I encountered a rather weird problem with my Django forms. I am currently working on my todo list project. Everything works fine, except that whenever I add a new task, its title seems to be saved in database with additional square brackets and quotes around it. It looks like one-element list, but it is a string. I kinda solved it by displaying the silced version of the string from the database, but it still shows for example while editing a task. Hope anyone has some idea what might be going on? models.py: from django.db import models class Task(models.Model): title = models.CharField(max_length=35) completed = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) # added_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) author = models.CharField(max_length=50, default='') def __str__(self): return self.title forms.py: from django import forms from .models import * class TaskForm(forms.ModelForm): class Meta: model = Task fields = '__all__' widgets = { 'title': forms.TextInput(attrs={'class': 'new_task_text', 'placeholder': 'Add new task'}), } class TaskEditForm(forms.ModelForm): class Meta: model = Task fields = ['title', 'completed'] widgets = { 'title': forms.TextInput(attrs={'class': 'new_task_text'}), } views.py: from django.shortcuts import render, redirect from .forms import * from django.contrib.auth.decorators import login_required @login_required def list_homepage(request): tasks = Task.objects.filter(author=request.user.username) for task in tasks: if "['" and "']" in task.title: task.title …