Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display correct json data using django
Am trying to display database record as json arrays. if I run the code below views.py from django.core import serializers from django.http import HttpResponse def read(request): members = Member.objects.all() print("success") jsondata = serializers.serialize('json', members) return HttpResponse(jsondata, content_type='application/json') models.py from django.db import models class Member(models.Model): firstname = models.CharField(max_length=40) lastname = models.CharField(max_length=40) def __str__(self): return self.firstname + " " + self.lastname am getting json response as per below [ {"model": "crud.member", "pk": 1, "fields": {"firstname": "Thor", "lastname": "Odinson"}}, {"model": "crud.member", "pk": 6, "fields": {"firstname": "sdd", "lastname": "rrrrr"}} ] My Requirements: Here is what I want. I want to get my json responses in the following manner below [ {"firstname": "Thorr", "lastname": "Odinson"}, {"firstname": "Ann", "lastname": "bell"} ] To this effect, If I try using JsonResponse() method as per code below, am getting error 'QuerySet' object is not callable def read(request): #response_data = {} response_data = [] members = Member.objects.all() return JsonResponse(response_data, members) print("success") -
Django ListView which includes forms
Lately I am moving from method based views to the class based views in Django. I feel that I couldn't find a good solution to use ListView together with forms. Below code in new view works but pagination does not work. Where I am doing wrong? Also, what do you think new view? Is there another and cleaner way to do that? Old method based view: def list_orders(request): if request.method == 'POST': form = billing_forms.OrdersForm(request.POST) object_list = orders.list_orders_by_date( owner=request.user, year=form.data.get('year'), month=form.data.get('month') ) else: form = billing_forms.OrdersForm() object_list = billing_orders.list_orders(owner=request.user) page = request.GET.get('page', 1) paginator = Paginator(objects_list, 10) try: object_list = paginator.page(page) except PageNotAnInteger: object_list = paginator.page(1) except EmptyPage: object_list = paginator.page(paginator.num_pages) return shortcuts.render(request, 'billing/orders.html', { 'object_list': object_list, 'form': form, }) New class based view: class OrdersListView(ListView, BaseLoginRequiredMixin): template_name = 'billing/orders.html' paginate_by = 10 def get(self, request, *args, **kwargs): form = billing_forms.OrdersForm() object_list = billing_orders.list_orders(owner=request.user) return shortcuts.render(request, self.template_name, {'form': form, 'object_list': object_list}) def post(self, request, *args, **kwargs): form = billing_forms.OrdersForm(request.POST) object_list = billing_orders.list_orders_by_date( owner=request.user, year=form.data.get('year'), month=form.data.get('month'), ) return shortcuts.render(request, self.template_name, {'form': form, 'object_list': object_list}) -
Django postgres model changes
After changing a model attribute from "owner" to "user" im getting this error message: column app_modelName.user_id does not exist LINE 1: SELECT "app_modelName"."id",... when trying to make a request to the endpoint. The migrations went through, and also deleting the migrations and doing fake migrations didn't help. When I looked up the table in my Postgresql is discovered that the column is still named owner_id and not user_id. Any idea how I can change that ? -
django booleanfield is None instead of False
i' ve a new application with the following model definition: class Sth(models.Model): .... is_cue = models.BooleanField(default=True) . Querying in shell i got the following: Sth.objects.filter().values_list('is_clue', flat=True) <QuerySet [None, True, None]> . Instead of False i can see there None . In previous versions of Django i used to get only False and True values. What might cause this change? In the database with older and current versions i can see 0 and 1 in the db. The versions i' m using are: django: 2.1.7 python: 3.5.3 debian: 9.7 mysql-server: 5.5.9999+default mariadb: mariadb-server-10.1 10.1.37-0+deb9u1 . -
raise TypeError('view must be a callable or a list/tuple in the case of include() | question-2
iam learning django . i see these error in terminal : raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). these error is too long . i see many question like this. But none of answer can solved my issu ! -
API View, how filter objects by already logged user
I have API view which show me objects filtered by id and everything is ok but I cant change this view to filter by already logged user, model have ForeignKey related to User and I want for this View to show only objects that are related to already logged user. This is my view for id which work: class CreateComment(APIView): def get_object(self, id): try: return Product.objects.get(id=id) except Product.DoesNotExist: raise Http404 def get(self,request, id): product = self.get_object(id) serializer = ProductSerializer(product) return Response(serializer.data) def post(self, request, id): serializer = CommentSerializer(data=request.data) if serializer.is_valid(): serializer.save(nick=request.user, product=self.get_object(id)) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I tried to do something like this: def get_object(self): try: return Product.objects.filter(user=request.user) except Product.DoesNotExist: raise Http404 def get(self): product = self.get_object() serializer = ProductSerializer(product) return Response(serializer.data) And something like this: def get(self, request): product = Product.objects.filter(user=request.user) serializer = ProductSerializer(product) return Response(serializer.data) But nothing work -
i have a problem in django program i want to have a detail url with id numbers (im still a noob)
Hello im trying to get this homework done but my brain is blowing ... so i want this server to to have and url detail so i can type the id of the text but it wouldn't work . this is the index.html : {% if myquotes %} <ul> {% for quote in myquotes %} <li> <a href="{%url 'detail' quote.id %}"> {{ quote.text }} {{ "-" }} {{ quote.author }} </a> </li> {% endfor %} </ul> {% endif %} <p>there are no quotes.</p> <br><br> <h1>add a quote</h1> <form action="{% url 'add' %}" method="post"> {% csrf_token %} <input type="text" name="quote" value="" placeholder="add a quote"> `enter code here`<input type="submit" value="Add"> </form> And this is the detail.html : <h1>{{ ourquote.id }}</h1> <h1>{{ ourquote.text }}</h1> <h1>{{ ourquote.author }}</h1> I dont really know the problem is here or what but i need to know where is it this is the image of the error msgenter image description here and this is the image of the files that i have -
Django: ordering a queryset by dictionary added values
I´m trying to sort a queryset of dictionaries to which I added some calculated values. The process class Inventario(models.Model): codigo_kinemed = models.CharField(max_length=100) existencias = models.IntegerField(help_text="Existencias ", blank=True, null=True) valor_coste = models.IntegerField(help_text="Existencias ", blank=True, null=True) valor_venta = models.IntegerField(help_text="Existencias ", blank=True, null=True) fecha = models.DateField(help_text="Fecha de toma de datos", blank=True, null=True) def __str__(self): return str(self.codigo_kinemed) I get a queyset from that. inventario_diferencia = Inventario.objects.filter(fecha=ultima_fecha_cargada.fecha).values() That returns a queryset of dictionaries. Then I iterate over that queryset and calculate some new fields. for este in inventario_diferencia: este['stock_valor_venta'] = este['existencias'] * este['valor_venta'] I can print that calculated field with no problem in the template. {{ inventario_diferencia.stock_valor_venta }} Ordering I want to sort that queryset by the new stock_valor_ventavalue I added. When I try the usual querset inventario_diferencia.order_by('stock_valor_venta') I get: Cannot resolve keyword 'diferencia_mes' into field. Choices are: codigo_kinemed, existencias, fecha, id, valor_coste, valor_venta Those are the model´s original values, so no option to order by the new value. When I try to sort it like a dictionary inventario_diferencia = sorted(inventario_diferencia, key=lambda t: t.diferencia_mes) I get 'dict' object has no attribute 'diferencia_mes' Documentation In the Django doc https://docs.djangoproject.com/en/2.1/ref/models/querysets/#values states the following: values(*fields, **expressions) Returns a QuerySet that returns dictionaries, rather than model instances, when used … -
Python manage.py getting constant error in Visual Studio Code editor
When I run anything in the Visual Studio Code terminal with 'python manage.py ...' I get the error below with "invalid syntax." This happens with: startapp migrate runserver etc., but only in the Visual Studio Code terminal. When I run the exact same commands in the mac iTerm, they work just fine. Why won't these 'manage.py' commands work in the Visual Studio Code terminal? python manage.py migrate File "manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax -
How to set a var inside a Django template
I want to set some vars from a dict in a Django template. I access a dict items and values, but when try to set some value from that, does not work It's work: {% for key, value in v.items %} {% if key == 'title' %}<tr>{{ value }}</tr>{% endif%} {% if key == 'name' %}<tr>{{ value }}</tr>{% endif%} {% endfor %} It doesn't work: {% for key, value in v.items %} {% if key == 'title' %}{% with title as value %}{%$ endwith %}{% endif%} {% if key == 'name' %}{% with name as value %}{%$ endwith %}{% endif%} {% endfor%} <tr>{{ title }}</tr><tr>{{ name }}</tr> I want to set a VAR inside a django template from a dict value! -
Whats wrong with this url?
I am trying to acces the following url with django. But i get the following error: Result Using the URLconf defined in WebAPI.urls, Django tried these URL patterns, in this order: admin/ airports/ ^$ [name='index'] airports/ ^carriers/(?P<code>[A-Z]{3})/$ [name='carriers'] airports/ ^carriers/(?P<a_code>[A-Z]{3})/(?P<c_code>[A-Z]{2})/$ [name='details'] carriers/ The current path, airports/carriers/ATL/9E, didn't match any of these. I can not see what is wrong with the "airports/ ^carriers/(?P[A-Z]{3})/(?P[A-Z]{2})/$ [name='details']" part. BTW: all the other urls work. -
how to fix circular import in django?
I'm trying to create an api that uploads an image with an email to the database. But I'm getting an error "raise ImproperlyConfigured(msg.format(name=self.urlconf_name))" Is the problem in my urls.py? https://imgur.com/OjPUhOv.jpg This is how my structure looks https://imgur.com/TW6pKPn.jpg This is the error for urls.py- from django.contrib import admin from django.urls import path,include from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('',include('user.urls')), path('api/',include('api_test.urls')) # path('articles/',include('articles.urls')) ] for api_test/urls.py from django.urls import path,include from django.conf import settings from . import views from rest_framework import routers router = routers.DefaultRouter() router.register('image_test',views.api_test,base_name='image_test') urlpatterns = [ # path('/',views.api_test), path('',include(routers.url)), ] for views.py class api_test(viewsets.ModelViewSet): queryset = fineDB.objects.all() serializer_class = fineSerializer ##for serializers.py from rest_framework import serializers from .models import fineDB class fineSerializer(serializers.ModelSerializer): image = serializers.ImageField(max_length=None,use_url=True) class Meta: model = fineDB fields = {'email','image'} -
django1.11 Custom authentication backend problem --return a unknown URL begin with /user/xxx?
I try to use the custom Authentication Backend in Django 1.11 to build the function (log-in with the user's email rather than the regular log-in with username. And both username and useremail are saved in the same user object in database). With the following code, I can successfully login with username(I input correct username value in HTML form's username blank) and password as a pair. But while I use the email value from HTML form input, It popups the Error as below in the background debug window: error "Not Found: /user/login/ ; "POST /user/login/ HTTP/1.1" 404 " . I am very curious because there is never "user/login" at all in my whole urls.py and users.views.py. how does it come from? Before this inquiry for help, I look up in Django official doc(version 1.11) and other suggestive comments in our stack overflow, but it still has no proper answer with this. Hope your guys save me out and give your ideas. Btw, I also check on 1.11 Django Docs, it said that " Do not forget to test for the is_active attribute of the user in your own backend permission methods. Changed in Django 1.10: In older versions, the ModelBackend allowed … -
How to eliminate id path parameter in swagger-ui in DRF-YASG for DRF and DJANGO
I'm using DRF-YASG to document API in Swagger and want to customizing/eliminating some fields shown in parameters I'm running the project with Django 2.1.7, DRF 3.9.2 and DRF-YASG 1.14.0. So, I want to eliminate the ID which is shown in swagger-ui (like a 'string' and 'path'), cause I have it in the body request through Schema, but swagger-ui shows the id (automatically generated field) in parameters. In the screen below, you can see the problem: https://user-images.githubusercontent.com/5421182/54859641-70359d00-4cee-11e9-9b12-79ab57d12495.png Here, my code... request_category_put = openapi.Schema(type=openapi.TYPE_OBJECT, required=['id','name'], properties={ 'id': openapi.Schema(type=openapi.TYPE_INTEGER, title='Id', readOnly=True, description='Id of the category'), ### <-- I have the ID here. 'name': openapi.Schema(type=openapi.TYPE_STRING, title='Category', maxLength=200, minLength=1, description='Name of the category') }, example={ 'id' : 1, 'name' : 'Business', } ) class CategoryDetail(APIView): permission_classes = (IsAuthenticatedOrReadOnly,) @swagger_auto_schema( manual_parameters=[authorization], request_body=request_category_put, responses = { '200' : response_category, '400': 'Bad Request', '404': 'Not found' }, security=[security_endpoint], operation_id='Update category', operation_description='Update a specific category.', ) def put(self, request, pk, format=None): category = get_object_or_404(Category, pk=pk) serializer = CategorySerializer(category, data=request.data) if serializer.is_valid(): serializer.save(modified_by=self.request.user) return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) When I add the field in manual_parameters in @swagger_auto_schema, only change the attributes of this... but the field still is there. -
Django - Execute for loop twice - once without saving and once with saving?
Right now I am trying to confirm a CSV Upload with all the information that is about to be saved in the database. So basically something like: "The following entries are about to be updated/created. Do you want to continue". With my current code I let the user know which entries where updated/created or duplicates. But this happens after it is already saved in the DB. I would like the user to check whether or not the changes he made are correct and only then save it to the database. Here is my views.py (only the part that is relevant) csv_file = request.FILES['file'] csv_file.seek(0) decoded_file = csv_file.read().decode('utf-8').splitlines() row_count = len(decoded_file) #print("d_file: ", decoded_file) reader = csv.reader(decoded_file) liste = list() s = False for row in reader: count += 1 try: datet = datetime.now().date() datum = datet.strftime("%d.%m.%Y") row[7] = datum row[8] = str(request.user) #d = [row[0], row[1], row[2], row[3], row[4]] dataset1 = CSV5.objects.filter(gebaeudebereich=row[0], gebaeudenummer=row[1], ebene=row[2], raum=row[3], dose=row[4])#.values_list("gebaeudebereich", "gebaeudenummer", # "ebene", "raum", "dose") dataset2 = CSV5.objects.filter(switch_ip=row[5], switch_port=row[6]).values_list("switch_ip", "switch_port") ds1 = CSV5.objects.values_list("gebaeudebereich", "gebaeudenummer", "ebene", "raum", "dose") ds2 = CSV5.objects.values_list("switch_ip", "switch_port") #print("ds1: ", ds1) print("dataset1: ", dataset1) print("dataset2: ", dataset2) print("dataset1: ", dataset1.exists()) print("dataset2: ", dataset2.exists()) if (dataset1.exists() and not dataset2.exists()): #instance = get_object_or_404(CSV5, … -
Django, raise forms.ValidationError in BaseModelFormSet not working
I am using BaseModelFormSet and passed it to modelformset_factory in views.And inside BaseModelFormSet function i override clean() to make formset validation to rise validation error.The problem is that when I try to fill the formset with a wrong data, validation error is not showing at all I have tried to render from in template manually with non field errors but did not work and went through documentation https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#overriding-clean-on-a-modelformset forms.py class MyModelFormSet(BaseModelFormSet): def clean(self): super().clean() if any(self.errors) return for form in self.forms: debit = form.cleaned_data['debit'] if debit == 100: raise forms.ValidationError('debit is 100!') return debit views.py def postpage(request): journalLineFormSet = modelformset_factory(journalLine,exclude=('journalNumber',),extra=2,can_delete=True,formset=MyModelFormSet,max_num=2,validate_max=True) if request.method == 'POST': mainform = journalForm(request.POST) subform = journalLineFormSet(request.POST) if mainform.is_valid() and subform.is_valid(): instances = subform.save(commit=False) for instance in instances: instance.save() mainform.save() return HttpResponseRedirect('/myacc/posted/') else: ##linesform = linesform(queryset=journal.objects.all().none()) mainform = journalForm() subform = journalLineFormSet(queryset=journalLine.objects.all().none()) #prefix used if you want to set a cumstom prefix to from name return render(request,'myacc/post.html',{'mainform': mainform, 'subform': subform}) -
How to get data from django rest framework request field
I have 2 models: Printer and Check models.py class Printer(models.Model): name = models.CharField(...) api_key = models.CharField(...) check_type = models.CharField(...) point_id = models.IntegerField() class Check(models.Model): printer_id = models.ForeignKey(Printer, on_delete=models.CASCADE) type = models.CharField(...) order = JSONField(...) status = models.CharField(...) pdf_file = models.FileField(...) I am building API using Django REST Framework. And I am getting POST request that should look this way: request "/create_checks/" { "id": 123456, "price": 780, "items": [ { "name": "pizza", "quantity": 2, "unit_price": 250 }, { "name": "rolls", "quantity": 1, "unit_price": 280 } ], "address": "some address", "client": { "name": "John", "phone": his phone }, "point_id": 1 } Every point(place where food is cooking) has two printers. I need to create two Check objects so one "check" prints for kitchen and one for client. For that I am going to use "point_id" from request and create two Check views.py @api_view(['POST']) def create_checks(request): queryset = Check.objects.all() orderid = #order_id from request point = #point_id from request jsonorder = #request body converted to json printers = Printer.objects.filter(point_id=point) kitchencheck = Check(printer_id=Printer.objects.get(name=printers[0].name), type="kitchen", order=jsonorder,status="new") clientcheck = Check(printer_id=Printer.objects.get(name=printers[1].name), type="client", order=jsonorder,status="new") kitchencheck.save() clientcheck.save() return Response({"Success": "Checks created successfully"}, status=status.HTTP_200_OK) 1. How do I get order_id and point_id from request? 2. How can I conver request … -
is_active is not changing when custom user logged out
I am working on custom user model, but the logout feature is not synchronized with root password. is_active(here activated) variable is not changing to False when I logout and the superuser logged in Django admin gets logout when logout button is pressed in the front end user. How to fix this. models.py class Users(AbstractBaseUser, PermissionsMixin): objects = UserManager() mobile_no = models.IntegerField(_('MobNumber'), null=True, blank=True,unique=True) email = models.EmailField(_('Email'), max_length=75, null=False, blank=False) first_name = models.CharField(_('FirstName'), max_length=50, null=True, blank=True) last_name = models.CharField(_('LastName'), max_length=70, null=True, blank=True) role = models.CharField(_('Role'), max_length=70, null=True, blank=True) location = models.CharField(_('Location'), max_length=70, null=True, blank=True) date_time = models.DateTimeField(_('DateTime'), auto_now=True, null=True, blank=True) activated = models.BooleanField(_('activated'), default=False) is_admin = models.BooleanField(_('is_admin'), default=False) is_itstaff = models.BooleanField(_('is_staff'), default=False) def __unicode__(self): return str(self.mobile_no) def __str__(self): return str(self.mobile_no) def get_full_name(self): return self.first_name + " " + self.last_name class Meta: ordering = ['-id'] @property def is_staff(self): return self.is_admin def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return self.is_admin USERNAME_FIELD = 'mobile_no' REQUIRED_FIELDS = ['role'] views.py @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('login')) -
Django Like View for Post
I want to create a like view for my post model but I couldn't make it. class PostLikeRedirectView(generic.RedirectView): def get_redirect_url(self, *args, **kwargs): slug = self.kwargs.get("slug") print(slug) obj = get_object_or_404(Post, slug=slug) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated(): if user in obj.likes.all(): obj.likes.remove(user) else: obj.likes.add(user) return url_ I am getting this error. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/posts/first-post-30/like/ Raised by: app_posts.views.PostLikeRedirectView No Post matches the given query. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Also, slug variable return None. My Post Model: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=250) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(User, blank=True, related_name='post_likes') slug = models.SlugField(max_length=200, blank=True, unique=True) class Meta: ordering = ('date_posted',) def __str__(self): return self.title def get_absolute_url(self): return reverse('posts:post_detail', kwargs={'title': self.slug}) def save(self, *args, **kwargs): super(Post, self).save(*args, **kwargs) if not self.slug: self.slug = slugify(self.title) + "-" + str(self.id) self.save() -
How to check if many-to-many related field contain all of given values
I have two django models with ManyToMany relationship: class Tag(models.Model): name = models.CharField(max_length=128, unique=True) class Bookmark(models.Model): # .... tags = models.ManyToManyField(Tag) I would like to write a filter_backends that given a list of tag names returns only those bookmarks that have assigned all of those tags. Example: Given bookmark_a with tags==['foo', 'bar', 'baz'] And bookmark_b with tags==['foo', 'baz'] Then calling url .../bookmarks/?tags=foo,bar will return only bookmark_a -
Why does `user.has_perm(Model, obj)` return False although `user.has_perm(Model)` returns True?
In a Django project and application just created with django-admin startproject and ./manage.py startapp, I've created this model: class Book(models.Model): author = models.CharField(max_length=50) Then I run this code with ./manage.py shell: from django.contrib.auth.models import Permission, User from django.test import TestCase from myapp.models import Book myuser = User.objects.create_user(username="myuser") myuser.user_permissions.add(Permission.objects.get(codename="change_book")) mybook = Book(author="Joe Author") mybook.save() myuser.has_perm("myapp.change_book")) # The result is True myuser.has_perm("myapp.change_book", mybook)) # The result is False Why is this? The user does have permission to edit mybook, doesn't he? How is has_perm() supposed to work? Is this documented somewhere? -
Multiple file upload DRF
I have a requirement which I would like to allow multiple files to be uploaded within the same post request to create an object. I currently have a method of doing this, but after looking at some other examples it doesn't appear to be intended way to do it. models.py class Analyzer(models.Model): name = models.CharField(max_length=100, editable=False, unique=True) class Atomic(models.Model): name = models.CharField(max_length=20, unique=True) class Submission(models.Model): class Meta: ordering = ['-updated_at'] issued_at = models.DateTimeField(auto_now_add=True, editable=False) completed = models.BooleanField(default=False) analyzers = models.ManyToManyField(Analyzer, related_name='submissions') atomic = models.ForeignKey(Atomic, verbose_name='Atomic datatype', related_name='submission', on_delete=models.CASCADE) class BinaryFile(models.Model): class Meta: verbose_name = 'Binary file' verbose_name_plural = 'Binary files' def __str__(self): return self.file.name submission = models.ForeignKey(Submission, on_delete=models.CASCADE, related_name='binary_files') file = models.FileField(upload_to='uploads/binary/') serializers.py class BinaryFileSerializer(serializers.ModelSerializer): class Meta: model = models.BinaryFile fields = '__all__' class SubmissionCreateSerializer(serializers.ModelSerializer): class Meta: model = models.Submission fields = ['id', 'completed', 'atomic', 'analyzers', 'binary_files'] id = serializers.ReadOnlyField() completed = serializers.ReadOnlyField() atomic = serializers.PrimaryKeyRelatedField(many=False, queryset=models.Atomic.objects.all() analyzers = serializers.PrimaryKeyRelatedField(many=True, queryset=models.Analyzer.objects.all() binary_files = BinaryFileSerializer(required=True, many=True) def validate(self, data): # # I dont really like manually taking invalidated input!! data['binary_files'] = self.initial_data.getlist('binary_files') return data def create(self, validated_data): submission = models.Submission.objects.create( atomic=validated_data['atomic'] ) submission.analyzers.set(validated_data['analyzers']) # # Serialize the files - this seems too late to be doing this! for file in validated_data['binary_files']: … -
How to find out the this heritence relationship on the case? seems no ancestor but it did
I am work with a django practice, on a book. the example in book used a Drop-in replacement of Django admin named xadmin.an ERROR caused: Media object has no attribute add_js I check the old version and current version of django, this 'add_js' method has delete, and the self._js also repalced to self._js_lists = [js] and there is a method @property def _js(self):with a . and it didn't provide a method to change this attr, it only been assigned in __init__ So I guess I shoudn't just do this: media._js_lists.append(js) So,I try to find out heritance relations in my on own code and find a way to assign my js.then this code confused me: It seems just only one Ancestor:BaseOwnerAdmin,but then i add : for base in self.__class__.__bases__: print(base.__name__) in def media(self): it printed: blogpostAdmin ListAdminView ModelAdminView CommAdminView BaseAdminView BaseAdminObject View object blogpostAdmin ListAdminView ModelAdminView CommAdminView BaseAdminView BaseAdminObject View object It really confuse me now,how the hell these ancestor came out? I am both new in django and program,but I really want to improve myself.so,I will very appriciate if any one tell me what is happen in those codes! this is my code from the book: blog/adminx.py import xadmin from … -
I have a question related to basics of django
How does the CreatePostView in views.py link to the post_form.html. It does not have "template_name" in it still how does the createpostview links to the post_form.html? Please look into the following codes that i have added below, and let me know if you can help, Thankyou! Views.py from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from django.utils import timezone from .models import Post, Comment from .forms import PostForm, CommentForm from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView) from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin # Create your views here. class AboutView(TemplateView): template_name = 'blog/about.html' class PostListView(ListView): model = Post def get_queryset(self): return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') class PostDetailView(DetailView): model = Post class CreatePostView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' form_class = PostForm model = Post class PostUpdateView(LoginRequiredMixin,UpdateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' form_class = PostForm model = Post urls.py from django.urls import path from . import views urlpatterns = [ path('',views.PostListView.as_view(),name='post_list'), path('about/',views.AboutView.as_view(),name='about'), path('post/<int:pk>', views.PostDetailView.as_view(), name='post_detail'), path('post/new/', views.CreatePostView.as_view(), name='post_new'), path('post/<int:pk>/edit/', views.PostUpdateView.as_view(), name='post_edit'), path('drafts/', views.DraftListView.as_view(), name='post_draft_list'), path('post/<int:pk>/remove/', views.PostDeleteView.as_view(), name='post_remove'), path('post/<int:pk>/publish/', views.post_publish, name='post_publish'), path('post/<int:pk>/comment/', views.add_comment_to_post, name='add_comment_to_post'), path('comment/<int:pk>/approve/', views.comment_approve, name='comment_approve'), path('comment/<int:pk>/remove/', views.comment_remove, name='comment_remove'), ] post_form.html {% extends 'blog/base.html' %} {% block content %} <h1>New post</h1> <form method="POST" class="post-form"> {% csrf_token %} {{form.as_p}} <button type="submit" class="save … -
Getting response from django rest endpoint (Search bar)
I'm new to django and need to make search bar in my django-react project. Need to take data from input, send it to django and, as response, receive new queryset. I'm using axios and django-rest framework. From input field within React "Search" component I'm intending to send data via axios like: getQuery = () => { axios.get(`http://localhost:8000/api/SearchPost?q=${this.state.query}`) .then(res => { this.setState({ data: res.data }); input in React: handelChange = (e) => { this.setState({ query: this.search.value}, () => { this.getQuery() }) } render() { return ( <form> <input placeholder="Search..." name="q" ref={input => this.search = input} method="get" onChange={this.handelChange} /> </form> my view.py in django is: class SearchPost(generics.ListCreateAPIView): serializer_class = ModelSerializer def search(request): query = request.GET.get("q") if query: queryset = Model.objects.filter( Q(category_icontains=query)| Q(title_icontains=query)| Q(creator_icontains=query) ).distinct() in urls.py: path('api/SearchPost', views.SearchPost.as_view()), but, as a response I'm reciving nothing. Things I'm asking myself is: 1) Am I sending axios request to the right endpoint? 2) Should I return something in my view.py "SearchPost" class? Any advices are welcome, thank you.