Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
upgrading docker compose version in ubuntu linux
my system os is ubuntu ,docker-compose version was 1.25 but imported python-django web app has project has composefile in version was 3.9. how to upgrade my sysytem docker-compose version -
how to implement add another to django model form
I'm trying to implement + button for foreign key select field , if the foreign key doesn't exist instead of going to another page just pop up a form page to add new entry for the foreign key , I've implemented but its full size and dont go to the previous page and shows only a blank page when i submit the form : this is what i tried my models.py class MainGroup(models.Model): admin = models.ForeignKey(UserAccount,on_delete=models.CASCADE) main_type = models.CharField(max_length=40,unique=True) def __str__(self): return self.main_type class Meta: db_table = 'maingroup' class PartGroups(models.Model): admin = models.ForeignKey(UserAccount,on_delete=models.CASCADE) main_type = models.ForeignKey(MainGroup,on_delete=models.PROTECT,related_name='maintypes') part_group = models.CharField(max_length=30) def __str__(self): return self.part_group and this is my forms.py from django.contrib.admin import site as admin_site,widgets class MainGroupForm(forms.ModelForm): class Meta: model = MainGroup fields = ['main_type'] error_messages = { 'main_type':{ 'required':_('some message'), 'unique':_('some message'), } } widgets = { 'main_type':forms.TextInput(attrs={'class':'form-control','placeholder':_('placeholder')}) } class PartGroupForm(forms.ModelForm): main_type = forms.ModelChoiceField(queryset=MainGroup.objects.all(),empty_label=_('label')) def __init__(self, *args, **kwargs): super(PartGroupForm, self).__init__(*args, **kwargs) self.fields['main_type'].widget = ( widgets.RelatedFieldWidgetWrapper( self.fields['main_type'].widget, self.instance._meta.get_field('main_type').remote_field, admin_site, ) ) class Meta: model = PartGroups fields = ['admin','main_type','part_group'] error_messages = { 'main_type':{ 'required':_('some message'), }, 'part_group':{ 'required':_('some message'), } } widgets = { 'part_group':forms.TextInput(attrs={'placeholder':_('group')}) } and this is my views.py @login_required def create_productgroup(request): form = ProductGroupForm() if request.is_ajax() and request.method … -
Firebase cloud messaging app initialization - credentials
I'm trying to learn how to implement push notifications to an PWA app running Django backend and try to use Firebase Cloud Messaging as a push service. I've created a project in the Firebase control panel and a service account + downloaded credentials as a json -file. I installed a library called fcm-django and seems like the migrations went well and I got a new table into my database called fcm_django_fcmdevice. I built a simple test view just to test stuff, not to make actual push notifications yet, but I struggle with authentication. Every time I try to make a request into my endpoint /push/, I get this error: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started. I read that page and installed firebase-admin package into my app. I also run this in my terminal: export GOOGLE_APPLICATION_CREDENTIALS="/path/to/my/credentials.json", but the error is the same every time. I also tried to copy the creds.json into the same dir as my settings.py and did this: from firebase_admin import initialize_app, credentials cred = credentials.Certificate("creds.json") FIREBASE_APP = initialize_app(cred) With this, I get this error: FileNotFoundError: [Errno 2] No such file or … -
Retaining newlines in input form
I realise there are many questions similar to this, but they all seem to answer the flip-side: "How do I display..." I can show that I'm not getting the newlines from the request object environment django 2.2.1, qunicorn 19.9.0 .. running in a docker image build on a python 3.7 base image setup Pre-populate a database record: update api_entitlement set notes= E'line 1\nline2\nline3' where guid='44aa651c-ea98-4990-aa85-d87d21db6043'; .... and confirm the data is there: select * from api_entitlement where guid='44aa651c-ea98-4990-aa85-d87d21db6043'; id | guid | notes -------+--------------------------------------+-------- 14053 | 44aa651c-ea98-4990-aa85-d87d21db6043 | line 1+ | | line2 + | | line3 (1 row) The fragment of template that creates the textarea is thus: <pre id="{{ entitlement.guid }}_notes">{% if entitlement.notes == '—' or entitlement.notes is None %}—{% else %}{{ entitlement.notes }} {% endif %}</pre><textarea id="{{ entitlement.guid }}_notes_new" type="text" class="form-control" value="{% if entitlement.notes == '—' %} -{% else %}{{ entitlement.notes }}{% endif %}" style="display:none">{{ entitlement.notes }}</textarea> (there's some javascript that toggles from display to edit, from the <pre> to the <textarea>) and the code that reads the form is thus: def get(self, request, *args, **kwargs): logger.info(f"notes value is {request.GET}") # # snip irrelevant code # value = request.GET.get('notes') logger.info(f"notes value is {value}") if value != '-' … -
ManyToMany Field serializer in django
I have successfully serialized my Blog model, but in it, there are two ManyToMany Relationships, one is for Category and the other for SubCategory, all these can be one or more. The GET method is working as exactly expected, the issue stays with the POST. Models: ` class Category(models.Model): category_name = models.CharField(max_length=100) sub_category = models.ManyToManyField(SubCategory, blank=True, ) added_on = models.DateTimeField(auto_now=True) icon = models.CharField(default="pi-angle-double-right", max_length=30, help_text="Icons can be picked from https://www.primefaces.org/primevue/showcase-v2/#/icons") def __str__(self) -> str: return self.category_name @property def total_blogs(self): return Blog.objects.filter(category=self).count() class Blog(models.Model): """ Blog table """ colors = [("r", "danger"), ("s", "success"), ("i", "info"), ] title = models.CharField(max_length=250, help_text="Unique, catchy topic of the article", unique=True, null=True, blank=True) body = CKEditor5Field( 'Add a body', help_text="Full body of the article, supports markup", config_name='default', null=True, blank=True) introductory_file = models.ImageField( upload_to="blog_intros", null=True, blank=True, help_text="Cover image to introduce the rest of the blog", validators=[validate_image_file_extension, validate_img_extension]) author = models.ForeignKey(Author, on_delete=models.CASCADE) blog_color = models.CharField( choices=colors, null=True, blank=True, max_length=10) posted_on = models.DateTimeField(auto_now_add=True) upvotes = models.ManyToManyField( User, blank=True, related_name="upvoters") downvotes = models.ManyToManyField( User, blank=True, related_name="downvoters") slug = models.SlugField(unique=True, blank=True, null=True) category = models.ManyToManyField(Category, verbose_name="category") sub_category = models.ManyToManyField( SubCategory, blank=True, verbose_name="subCategory") schedule_to = models.DateField( null=True, help_text="If you are want to schedule the blog to a future date.", blank=True) contributors … -
Get multple related objects from Django ORM
I have such model in Django: from django.db import models class Document(models.Model): name = models.CharField(max_length=256) class Template(models.Model): name = models.CharField(max_length=256) document = models.ForeignKey(Document, on_delete=models.CASCADE) class SharedDocument(models.Model): workspace = models.CharField(max_length=256) document = models.ForeignKey(Document, on_delete=models.CASCADE) I need to get list of templates by workspace in SharedDocument. I was doing this query: >>> shared_documents = SharedDocument.objects.filter(workspace='1').prefetch_related('document') >>> [shared_document.document.template_set.get() for shared_document in shared_documents] But from my prospective it looks a little bit ugly. So the question is: "Is it possible to do what I want by forming query without this part: [shared_document.document.template_set.get() for shared_document in shared_documents]"? To clarify: As a result I want to have a list/QuerySet with Template objects. Regards, Oleg -
UnboundLocalError at /signin/ local variable 'user' referenced before assignment in Django
Function to let the user to login as follows=> Obviously this error pops def login_view(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password =password ) if user is not None: login(request, user) return HttpResponseRedirect(reverse("index")) elif user is None: return render(request, "covi/signin.html", { "message": "Invalid username and/or password." }) else: return render(request, "covi/signin.html") -
Set-Cookie doesn't set cookies, problem with samesite Django & React
I try to store my refresh token which I get from django backend. The log() functions looks like it's working fine, I mean when I click F12 and open the Network tab I get an response login/ which has a Set-Cookie field, f.e. it looks like this: Set-Cookie: refresh_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXVlLjoicmVmcmVzaXIsImV4cCI6MTYzMjU2MTY4OSwianRpIjoiZTg2MjhkMjhmOWJmNPMxYzg4ZjAyNjE3ZDNmMzFmNGUiLCJ1c2VyX2lkIjoiNDU1OTZkNTktNDI1Yy00ZmMxLThlYmUtNWU2YjQzMFRkZjQkIn0.ALfovbSQGIw6Hq6607LXXyhXXcvoUvUUlElCxnvRJfg; expires=Sat, 25 Sep 2021 09:21:29 GMT; HttpOnly; Max-Age=300; Path=/ but there is a problem too with SameSite field: This Set-Cookie header didn't specify a "SameSite" attribute and was defaulted to "SameSite=Lax" and was blocked because it came from a cross-site response which was not the response to a top-level navigation. The Set-Cookie had to have been set with "SameSite=None" to enable cross-site usage I don't get it because I delared the samesite=None in my django view: response = Response(details, status=status.HTTP_200_OK) response.set_cookie('refresh_token', str(refresh), httponly=True, secure=False, samesite=None, max_age=300, path="/", expires=int(SIMPLE_JWT['REFRESH_TOKEN_LIFETIME'].total_seconds())) and the problem is that cookies are not stored in F12 > Application > Cookies > http://localhost:3000 My login function looks like this: export const login = async (data) => { const response = await log(data); if (response.data.access_token) { http.defaults.headers.Authorization = `JWT ${response.data.access_token}`; } else { delete http.defaults.headers.Authorization; } }; log() looks like this: export const log = async (credentials) => { return … -
Isadminuser or Allowyany permission based on the request method in APIView
I have to make a custom permission class based on the request method and the slug that has been passed. I am using APIView to write business logic. The requirements are as follows: 1. Allowany for all the methods except POST. 2. IsAdminUser for POST if slug is abc or Allowany if slug is xyz. My view looks like this: class Example(APIView): permission_classes = [CustomPermission] def get_by_slug(self, slug): return Example.objects.filter(slug=slug).first() def get(self, request, *args, **kwargs): slug = kwargs.get("slug") example = self.get_by_slug(slug) serializer = ABCSerializers(example) return Response(serializer.data) def post(self, request, *args, **kwargs): slug = kwargs.get("slug") setting = self.get_by_slug(slug) if slug == 'abc': ........................................ ///////////////////////////////// For this, I have to define Custompermission which inherits from BasePermission class CustomPermission(BasePermission): """ returns permission based on the request method and slug """ def has_permission(self, request, view): user =request.user if request.method == 'POST' and slugs == 'abc': return True Now, I dont know how to get slug here. The slug here is acquired form **kwargs. But kwargs cant be defined inside has_permission. How can we do this?? -
Django application not working because of uninstalled packages in aws producing 500 internal server error
I have developed a software in python on my system with all the needed packages downloaded and they all worked well. I have also configured aws lightsail to connect apache server following the article in https://aws.amazon.com/getting-started/hands-on/deploy-python-application/ and it worked very well. I have tried to install the needed packages into aws but when I connected it to apache. it was producing error 500 internal server error then on further checking I discorvered that the packages I installed were not installed into proper directory where it was supposed to be located where apache would be able to find it so it was producing error 500. How can I install my python packages into the directory where apache would be able to use it? -
How to pre-populate (Multiple)ChoiceField in Django based on previous user selection
I managed to store and update a selection of categories made by the user to the database. Now I want to pre-populate the MultipleChoiceSelect with this selection once the user queries the form again to update his selection. So my current form will always return all available categories. How can I apply the users personal selection to this? # View @require_POST def save_category_filter(request): # User logged in? if request.user.is_authenticated: # Get the form instance filter_form = SelectCategoryForm(request.POST) # Form validation if filter_form.is_valid(): # Get the cleaned data selection = filter_form.clean() # Check if user already has a filter instance instance_exists = UserCategoryFilter.objects.filter(user=request.user) # If not create, else update if not instance_exists: filter_instance = UserCategoryFilter(user=request.user, categories_selected=selection) filter_instance.save() else: # Update existing instance UserCategoryFilter.objects.filter(user=request.user).update(categories_selected=selection) else: .. # Models class UserCategoryFilter(models.Model): """ Saves the selected category filter by a user """ user = models.ForeignKey(Account, on_delete=models.CASCADE) categories_selected = models.CharField(max_length=2000) class Category(models.Model): """ Model to store all available categories """ poller_category = models.CharField(max_length=30) # Form class SelectCategoryForm(forms.Form): choices = forms.ModelMultipleChoiceField(queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple) This is how the selection of the user is currently saved: -
Django Admin: two ListFilter Spanning multi-valued relationships
I have a Blog model and a Entry model. Entry has a Foreignkey to Blog: One Blog has several Entries. I have two ListFilters for Blog: One for "Entry title", one for "Entry published year". If you filter for entry_title=Lennon and entry_published_year=2008, then I see all Blogs which have entries an entry with title "Lennon" and an (maybe an other) entry with pub-year=2008. That's not what I want. Related docs: https://docs.djangoproject.com/en/3.2/topics/db/queries/#spanning-multi-valued-relationships This is because django does this: qs = qs.filter(title_filter) qs = qs.filter(published_filter) To get the desired result one need to combine both filter() calls into one. How to get both ListFilter into one filter() call? -
how to use titan.email in django to send email to the users
I got titan.email account when i bough AWS hosting How to use this email account to send email to the users in djago EMAIL_HOST='smtp.titan.email' EMAIL_HOST_USER='admin@test.com' EMAIL_HOST_PASSWORD='password' EMAIL_PORT= 465 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_SSL=True I am getting this error while sending email smtplib.SMTPSenderRefused: (504, b'5.5.2 <webmaster@localhost>: Sender address rejected: need fully-qualified address', 'webmaster@localhost') -
My docker container is not working p option
I tried many times for port forwarding. But, return message is connection refused. using official image is working. but using my image is not working. I did many searching and tried. But all failed. T^T What is my problem.? My docker image is exists in hub.docker.com docker pull redukyo/ubuntu:qf_user Please help me! -
how to receive objects in index.html from admin panel?
all bojects have been successfully save in admin dashboard but do not receive dynamic data in index.html page from admin dasboard. please any one can be help me. **views.py** from django.shortcuts import render from .models import home # Create your views here. def home(request): homeobject = home.objects.all() return render(request, 'index.html', {'homes': homeobject}) **models.py** class home(models.Model): HOME_CATEGORY = [ ('SR', 'Service'), ('VL', 'Vlog'), ('CR', 'course'), ] title = models.CharField(max_length=120) description = models.TextField() image = models.ImageField(upload_to='images') home_category = models.CharField(max_length=2, choices=HOME_CATEGORY) **index.html** {% for home in homes %} {{home}} {% endfor %} -
How to resolve this error - "Attribute Error"? [closed]
When am passing the string into another variable, it is giving me error. Please check below error a = 'Market' prompt1=float(input('Please enter your price: ')) ## Place an order print( alice.place_order(transaction_type = TransactionType.Buy, instrument = enter_strike, quantity = enter_quantity, order_type = OrderType.a, product_type = ProductType.Intraday, price = prompt1, trigger_price = None, stop_loss = None, square_off = None, trailing_sl = None, is_amo = False) ) Error Message: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-27-bf8957bdded0> in <module> 14 instrument = enter_strike, 15 quantity = enter_quantity, ---> 16 order_type = OrderType.a, 17 product_type = ProductType.Intraday, 18 price = prompt1, c:\users\ravi\appdata\local\programs\python\python38\lib\enum.py in __getattr__(cls, name) 339 return cls._member_map_[name] 340 except KeyError: --> 341 raise AttributeError(name) from None 342 343 def __getitem__(cls, name): AttributeError: a When am passing the string into another variable, it is giving me error. Please check below error -
Django model fieldsets with lable name from model?
I have a model named "Documents" and now i have two fields on the table namely - type & path Now type will be updated from admin end and path will be updated by users, so too handle this i was using model set form ( as there are more than one fields to be updated at once ) from django.forms import modelformset_factory documentFormset = modelformset_factory(Documents, fields=('document_path',), extra=0) formset = documentFormset(queryset=Documents.objects.filter(type="Request")) So the above gives the required, but now the problem is i need to display the "type" as field name to the respective path field ! For instance: If a row has id | type | path | 1 | Request | | 2 | Certificate | | And when using model formset on the above it gives two forms with "path" as input and its default lable as "Path" So the problem is i need to show "type" value as label name, Certificate : Input(filepath) // need this instead of Type: Input(filepath) So how to change fields label name to name something from the same model -
AttributeError: 'TestModelCreateView' object has no attribute 'object'
I'm overriding get_success_url in my object creation view. Everything else works fine but the tests fail with the error; AttributeError: 'TestModelCreateView' object has no attribute 'object' # View.py from django.views.generic import CreateView class TestModelCreateView( CreateView, BaseFormMixin ): form_class = TestModelForm model = TestModel def get_success_url(self) -> str: return reverse_lazy( "ops:test_model_update", kwargs={"pk": self.object.pk} ) # Test.py def test_model_url(): test_obj:TestModel = baker.make(TestModel, comment=fake.text()) v = TestModelCreateView() call_back_url = v.get_success_url() assert f"/ops/test_model_update/{test_obj.pk}" in call_back_url -
Create project django in pycharm
Creating a project with django in pycharm. Create using the directory on the left (but they are not displayed during creation) I dont have directory like in left photo -
Why does my filtering of queryset on valid pk returns full queryset?
As far as I understand, querysets can always be filtered on. However, if I create this queryset filtering breaks: set_synonyms = Compound.objects.filter(synonyms__name__icontains=query_string) It is a proper queryset: <QuerySet [<Compound: 2-[4-(2-methylpropyl)phenyl]propanoic acid>, <Compound: 2-[4-(2-methylpropyl)phenyl]propanoic acid>, <Compound: 2-[4-(2-methylpropyl)phenyl]propanoic acid>, <Compound: 2-[4-(2-methylpropyl)phenyl]propanoic acid>, '...(remaining elements truncated)...']> and I can get the pk of any element of the queryset, e.g.: pk=set_synonyms.first().pk (pk has the value 76) But when I filter on it, the whole queryset is returned: set_synonyms.filter(pk=pk) just returns the whole queryset set_synonyms. And using set_synonyms.get(pk=pk) raises MultipleObjectsReturned exception (because it returns the whole queryset set_synonyms). Possible relevant information: the relation between Compound and Synonym models is a 1-to-many (1 compound having many synonyms). class Synonym(MixinPubChemCompound, models.Model): """Model definition for synonym naming of compound""" name = models.CharField(max_length=999, db_index=True, null=True) compound = models.ForeignKey( Compound, on_delete=models.CASCADE, related_name='synonyms') retrieved_from = models.ForeignKey( generic_models.Reference, related_name='synonyms', on_delete=models.PROTECT) class Compound(MixinPubChemCompound, models.Model): cid = models.IntegerField(unique=True, db_index=True) iupac_name = models.ForeignKey( IupacName, on_delete=models.PROTECT, unique=False) -
Search bar for django
I have a page where the staff is able to see the staff they have enter, but if the lists get too long, it is hard to find the stuff they wanted, hence, I want to create a search bar and a button so that they can search for the stuff easily and display it in a card form as shown below, how do I do that? This is how my website looks like (in the url it will show q=76464 but it just wont display q=76464) views.py def outgoinggallery(request): user = request.user query = request.GET.get('q') category = request.GET.get('category') if category == None: alloutgoinglru = OutgoingLRU.objects.filter(category__user=user) else: alloutgoinglru = OutgoingLRU.objects.filter( category__name=category, category__user=user) if query: return OutgoingLRU.objects.filter(title__icontains=query) else: return OutgoingLRU.objects.all() categories = Category.objects.filter(user=user) context = {'categories': categories, 'alloutgoinglru': alloutgoinglru} return render(request, 'Outgoing/outgoinggallery.html', context) outgoinggallery.html {% extends "logisticbase.html" %} {% block content %} <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <style> td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; border-radius: 15px; } .image-thumbail { height: 200px; object-fit: cover; } .list-group-item a { text-decoration: none; color: black; } </style> <br> <div style="padding-left:16px"> <div class="row"> <div class="col-md-9"> <div class="row"> <h5>View Outgoing LRU</h5> <div class="col-md-7"> <form method="GET" action="" id="searchform"> <input … -
Django compress string data
I have a django model having: raw_data = models.TextField(_("raw_data"), default='') It just storing some raw data which can be 1K - 200K. I have 50 millions rows. I need to decrease size of data in database. How can I tell what consume most data over all database ? Should I use a string compression before storing the data ? 2.1 I saw here: Text compression in PostgreSQL that it get compressed anyway, is that true ? 2.2 I did some python code compression, I am not sure if changing bytes to string type can cause in lossing data: def shrink_raw_data(username): follower_data = get_string_from_database() text = json.dumps(follower_data).encode('utf-8') # outputs as a bytes # Checking size of text text_size = sys.getsizeof(text) print("\nsize of original text", text_size) # Compressing text compressed = str(zlib.compress(text, 9)) # store String in database # Checking size of text after compression csize = sys.getsizeof(compressed) print("\nsize of compressed text", csize) # Decompressing text decompressed = zlib.decompress(compressed) # Checking size of text after decompression dsize = sys.getsizeof(decompressed) print("\nsize of decompressed text", dsize) print("\nDifference of size= ", text_size - csize) follower_data_reload = json.loads(decompressed) print(follower_data_reload == follower_data) I am not sure about "str(zlib.compress(text, 9))" since my data is stored as string in … -
Why does my ModelForm with CheckboxSelectMultiple widget not validate?
I have a SelectCategoryForm which renders a queryset of Model Category that stores the different categories. The Model UserCategoryFilter stores the filter selected and saved by a user. # Form class SelectCategoryForm(forms.Form): choices = forms.ModelMultipleChoiceField(queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple) # Models class Category(models.Model): poller_category = models.CharField(max_length=30) category_color = models.CharField(max_length=15, blank=True) def __str__(self): return str(self.poller_category) class UserCategoryFilter(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) categories_selected = models.ForeignKey(Category, on_delete=models.CASCADE) # View @require_POST def save_category_filter(request): # User logged in? if request.user.is_authenticated: # Get the form instance filter_form = SelectCategoryForm(request.POST) # Form validation if filter_form.is_valid(): Now when I select some categories in the template and submit, the view validates the form as invalid. -
type object 'ArticleSitemap' has no attribute 'filter' Sitemap
I am working with the Django sitemap framework. Trying to improve SEO stuff for my blog, I have expanded my Article model in models.py and introduced sitemaps.py in one of the Django apps named MArticles. But I have faced an Attribute Error: type object 'ArticleSitemap' has no attribute 'filter'. Below are my python files. In sitemaps.py from django.contrib.sitemaps import Sitemap from .models import Article class ArticleSitemap(Sitemap): changefreq = "weekly" priority = 0.8 def items(self): return Article.modelmanager.all() def lastmodified(self, obj): return obj.last_updated In models.py from django.db import models import datetime from EHub.models import * from django.contrib.auth.models import User from django.utils import timezone from django.urls import reverse from mptt.models import MPTTModel, TreeForeignKey from taggit.managers import TaggableManager from ckeditor_uploader.fields import RichTextUploadingField # Create your models here. class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return str(self.name) class IpModel(models.Model): ip=models.CharField(max_length=100,null=True) def __str__(self): return str(self.ip) class Article(models.Model): options=( ('draft','Draft'), ('published','Published'), ) def get_absolute_url(self): return reverse('MArticles:article_detail',kwargs={'pk':self.id,'slug':self.slug}) class CustomManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status ='published') title=models.CharField(max_length=250,null=True) thumbnail = models.ImageField(upload_to="thumnails/%y",null=True,blank=True) description = RichTextUploadingField(null=True,blank=True, config_name='sourcecode',) author=models.ForeignKey(User,on_delete=models.CASCADE,related_name='blog_posts') slug=models.SlugField(null=True,unique=True) tags=TaggableManager() category = models.ManyToManyField(Category,blank=True) publish_date = models.DateField(default = datetime.date.today) last_updated=models.DateTimeField(default=timezone.now) views=models.ManyToManyField(IpModel,related_name="post_views",blank=True) featured = models.BooleanField(default=False) status=models.CharField(max_length=10,choices=options,default='draft') previous_post = models.ForeignKey('self', related_name='previous', on_delete=models.SET_NULL, blank=True, null=True) next_post = models.ForeignKey('self', related_name='next', on_delete=models.SET_NULL, blank=True, null=True) objects = models.Manager() modelmanager = … -
Something wrong with django json serializer
i try looking for answers but so far to no avail, basically i try to return django model as json however, it seem that the serializer convert it to string instead my code is as follow: view.py from django.shortcuts import render from screener.models import maintable from .models import Messages from django.http import JsonResponse from django.core import serializers from datetime import datetime import json def infiniteScroll(request, room_name): dateFilter=request.GET.get('date') dateFilter=dateFilter[5:len(dateFilter)-4] dateFilter=datetime.strptime(dateFilter, '%d %b %Y %H:%M:%S') data=serializers.serialize('json', reversed(Messages.objects.filter(room=room_name).filter(date_added__lt=dateFilter).order_by('-date_added')[:2])) return JsonResponse(data, safe=False) urls.py from django.contrib import admin from django.urls import path from . import views app_name='chat' urlpatterns = [ path('<str:room_name>/', views.room, name='room'), path('<str:room_name>/hist/', views.infiniteScroll, name='infiniteScroll'), ] when i go to the site http://127.0.0.1:8000/chat/AAPL/hist/?date=Thu,%2023%20Sep%202021%2014:03:42%20GMT the result is a page with string instead: "[{\"model\": \"chat.messages\", \"pk\": 118, \"fields\": {\"username\": \"adiputra12\", \"room\": \"AAPL\", \"content\": \"hello\", \"date_added\": \"2021-09-23T13:54:30.043Z\"}}]" how can I return json instead like shown below: [{'model': 'chat.messages', 'pk': 118, 'fields': {'username': 'adiputra12', 'room': 'AAPL', 'content': 'hello', 'date_added': '2021-09-23T13:54:30.043Z'}]