Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check and see if an output contains the desired elements from any list or not?
I am trying to write tests for a particular app in django using the python's unittest library. def test_permissions_for_admin(self): admin = Group.objects.get(name='Administrator') permisisons = admin.permissions.all() admin_permissions = ['add_ipaddress', 'change_ipaddress', 'delete_ipaddress', 'view_ipaddress', 'add_subnet', 'change_subnet', 'delete_subnet', 'view_subnet'] for p in permissions: print(p.codename) for p in permissions: self.assertIn(p.codename, admin_permissions) The Above code prints this, OUTPUT: change_emailaddress delete_emailaddress view_emailaddress add_ipaddress change_ipaddress delete_ipaddress view_ipaddress add_subnet change_subnet delete_subnet view_subnet view_group change_organization change_organizationowner add_organizationuser change_organizationuser delete_organizationuser view_organizationuser add_user change_user delete_user view_user Whereas What I am trying to check is that, all the permissions present from the variable admin_permissions are present in this output or not. I have tried using the assertIn, assertEqual, & assertTrue methods but it doesn't seem to work here. Is there anything else I could look for or any method present which I am not aware of to solve such kind of issues. -
Removing a string character in list Python
I have the data in a dictionary format, as below; i want to remove the '" 'character in list. how can i achieve that? Any help, would be much appreciated. { "test2": [ [ "'testdesc...', ' fdfd', ' dsgdgdfgdfg'" ] ] } I tried something like this in my views, but it won't reflect any changes. views.py : for record in data: test_list = [] test_list.append(record['description']) record['test2'] = [x.split(' " ') for x in test_list] -
How to get the total number of Likes related to an Author and user it to send notifications when reaching a certain number
I have a notification system in my Django project, when a user likes a Post the author of the post receives a notification that a post is liked and when this like is unliked the notification is deleted. Now I am trying to add a functionality in the notification system to get the total number of likes for all the posts created by an author and send a notification to the author when the total of likes reaches a certain number, instead I set a function that when a post reaches a certain number of likes a notification is sent. I have been trying to accomplish this but I am getting several errors. I am going to comment on my trials so in the below codes. As per the last trial I have made I am receiving: TypeError: total_likes_received() takes 1 positional argument but 2 were given Here is the Post model class Post(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='author') num_likes = models.IntegerField(default=0, verbose_name='No. of Likes') likes = models.ManyToManyField(User, related_name='liked', blank=True) Here is the Like model class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=8) def total_likes_received(self): return self.filter(post__author=Post.author).count() #The number of Likes received … -
calculate signal after first calculate signal is done
i have two signals, first calculate total per line and second is total of all lines. with the example i have now, first only do correct, second one = 0. until i update the invoice for example, then it s updated too. i want to start first one then automaticaly second one do the job correctly. def invoiceitem_pre_save(sender, instance, *args, **kwargs): instance.calculate(save=False) print('invoiceitem saved') pre_save.connect(invoiceitem_pre_save, sender=InvoiceItem) def invoice_pre_save(sender, instance, *args, **kwargs): instance.calcul(save=False) print('invoice saved') pre_save.connect(invoice_pre_save, sender=Invoice) -
Django-mptt not listing names in templates
i am using django-mptt library to build a category tree. when i put the code below in my template i get this error. index.html {% load mptt_tags %}{% load mptt_tags %} <ul class="root"> {% recursetree nodes %} <li> {{ node.name }} {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> this is the error i get. VariableDoesNotExist at / Failed lookup for key [nodes] in [{'True': True, 'False': False, 'None': None}, {}, {}, {'listing': <TreeQuerySet [<Category: Clothes>, <Category: Children Clothes>, <Category: Mens Clothes>, <Category: Womens Clothes>, <Category: Electronics>, <Category: Foods>]>}] view.py def index(request): listing=Category.objects.all() context={ 'listing':listing } return render(request,'catalog/index.html',context) -
Django/Angular: Empty Object Being Sent
I am sending a request using angular, I tried setting the Content-Type to "application/json", it said- "unsupported media type", I changed it to "form-data", it stopped giving the error but the request results in an empty object even though when I console log the object before sending, it shows the correct JSON object. What could be going wrong? How do I fix it? I have two headers, since I am trying to send a file object as well, and for that I thought I'd use two requests, one only for the file and other for the rest since they might need different headers. Angular:- serivce.ts id : "" base_url = "http://127.0.0.1:8000/details/" create_url = this.base_url + 'create/' token = localStorage.getItem('token') httpHeaderNormal = new HttpHeaders({ 'Content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW', 'Authorization': `Bearer: ${this.token}` }) httpHeaders = new HttpHeaders({ 'Content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW', 'Authorization': `Bearer: ${this.token}` }); constructor(private http: HttpClient, private activatedRoute: ActivatedRoute, private injector: Injector) { }; getDetail(id: number): Observable<any> { console.log(id); return this.http.get(this.base_url + id + "/", { headers: this.httpHeaderNormal }) } updateDetail(detail, id, fileToUpload): Observable<any> { const endpoint = this.base_url + id + "/"; if (fileToUpload) { const formData: FormData = new FormData(); formData.append('logo', fileToUpload, fileToUpload.name); console.log(formData); this.http.put(endpoint, formData).subscribe( res => { console.log(res); … -
String model references must be of the form 'app_label.ModelName' error while adding a Foreign Key field to model
I have an app customer inside company/sales/ with app_label as 'company.sales.customer'. This app contains a model Customer in models.py. I want this model to be linked as a foreign key in another app 'orders'. models.py of 'orders': from django.db import models class Order(models.Model): party = models.ForeignKey('company.sales.customer.Customer', on_delete=models.CASCADE) --other fields-- apps.py of 'customer': from django.apps import AppConfig class CustomerConfig(AppConfig): name = 'company.sales.customer' label = 'company.sales.customer' settings.py : INSTALLED_APPS = [ ----, 'company.sales.customer' ] -
I cannot output the value of the foreign key via jsonresponse serealize
I want to get json serialized the name of the products insted of the id ones. I tried to add natural_keys method on the parent model with no luck. I can receive the json data good but in this way: [{"model": "ocompra.compradetail", "pk": 1, "fields": {"producto": 238, "precio": "620.00", "cantidad": 1}}, {"model": "ocompra.compradetail", "pk": 2, "fields": {"producto": 17, "precio": "65.00", "cantidad": 2}}] Any suggestions will be much appreciated! Thanks, views.py def detalle(request): template_name = "ocompra/compra_ok.html" contexto={} data={} if request.method=="GET": cat = CompraDetail.objects.all().order_by("codigo") contexto={"obj":cat} if request.method=="POST": codigos=request.POST.getlist("codigos[]")#Codigo/s de la Orden de Compra codigos= [int(x) for x in codigos]#Convierte la lista en integer items_detalle = CompraDetail.objects.filter(compra__in=codigos).select_related('producto') for item in items_detalle: print(item.producto.nombre, item.cantidad, item.precio, item.subtotal) #data['success'] = True #print (data) return JsonResponse(serializers.serialize('json', items_detalle,fields=('producto', 'cantidad','precio'), use_natural_foreign_keys=True), safe=False) #return JsonResponse(data) return render(request,template_name,contexto) models.py from django.db import models from django.utils.timezone import datetime from articulos.models import Articulos # Create your models here. class CompraHead(models.Model): numero=models.AutoField(primary_key=True) cliente= models.CharField(max_length=200,default="Consumidor Final") direccion=models.CharField(max_length=100,null=True,blank=True) telefono=models.CharField(max_length=50,null=True,blank=True) fecha=models.DateField(default=datetime.now) observaciones=models.CharField(max_length=400) subtotal=models.DecimalField(default=0.00,max_digits=9,decimal_places=2) descuento=models.IntegerField(default=0.0) total=models.DecimalField(default=0.00,max_digits=9,decimal_places=2) class CompraDetail(models.Model): compra=models.ForeignKey(CompraHead,on_delete=models.CASCADE) producto=models.ForeignKey(Articulos,on_delete=models.CASCADE) precio= models.DecimalField(max_digits=10,decimal_places=2) cantidad=models.IntegerField(default=0) subtotal=models.DecimalField(default=0.00,max_digits=9,decimal_places=2) def natural_key(self): return (self.producto.nombre) js var token = '{{csrf_token}}'; var data = JSON.stringify({"codigos":codigos}); data = {"codigos[]":codigos}; console.log(data); $.ajax({ headers: { "X-CSRFToken": token }, "url": '/ocompra/detalle/', "type": "POST", "dataType": "json", data: data, success: function(data){ // … -
object is not iterable error in Django Rest Framework
I am new to django rest framework, I am trying to build a simple movie API. I created 3 models Movie, Cast and Reviews, after applying migrations I added values in tables in django admin. When I start the server the api works fine until I again add values in Cast table or reviews table it gives me error like: "'Cast' object is not iterable". And its also not showing the Movie table data. What am I doing wrong. Here is My code: models.py from django.db import models # Create your models here. class Cast(models.Model): actor = models.CharField(max_length=225) producer = models.CharField(max_length=225) director = models.CharField(max_length=225) screenwriter = models.CharField(max_length=225) class Reviews(models.Model): name = models.CharField(max_length=225) comment = models.CharField(max_length=225) class Movies(models.Model): name = models.CharField(max_length=225) genre = models.CharField(max_length=225) ratings = models.IntegerField() cast = models.ForeignKey(Cast, on_delete=models.CASCADE) review = models.ForeignKey(Reviews, on_delete=models.CASCADE) serializer.py from .models import Movies, Reviews,Cast from rest_framework import serializers class CastSerializer(serializers.ModelSerializer): class Meta: model = Cast fields = ('actor', 'producer', 'director', 'screenwriter') class ReviewsSerializer(serializers.ModelSerializer): class Meta: model = Reviews fields = ('name', 'comment') class MoviesSerializer(serializers.ModelSerializer): cast = CastSerializer(many=True) review = ReviewsSerializer(many=True) class Meta: model = Movies fields = ('name', 'genre', 'ratings', 'cast' , 'review') views.py from django.shortcuts import get_object_or_404 from .serializers import MoviesSerializer, ReviewsSerializer, CastSerializer … -
Make multilevel nested list from csv in Python
I have a csv with the following row structure (9 columns): Nr - A1 x - A1 y - A2 x - A2 y - B1 x - B1 y - B2 x - B2 y see also Picture: Picture of csv structure What I need is to read this file into an array that has a 3 level hierarchy like this: [[[A1 x, A1 y],[A2 x, A2 y]],[[B1 x, B1 y],[B2 x, B2 y]]] so that I can Shuffle the A-pairs within each other and the B-pairs within each other without removing their relationship to each other (so that there is always one y and one x, not tow xx and two yy). Shuffle all the order of A-pairs and B-pairs altogether without changing their inner structure (so that one time all the A-pairs start all B-pairs follow and one time the other way around). My current code to read in the csv is like that each row is read in and then I tried to make separate arrays out of that, but all of that resulted in way too much post processing of the retrieved values. I think, there might be a better way to read the csv … -
How to add a specefied number of characters in django form
so I am trying to build a django form for accepting orders for my ecommerce website. I want the user to enter their zip code, but it should be of only 6 characters, not more, not less. How can I achieve this? Here is my form so far: class OrderForm(forms.Form): name = forms.CharField(max_length=30) email = forms.EmailField() address = forms.CharField(widget=forms.Textarea()) zip_code = forms.CharField(max_length=6) The max_length attribute allows the user to enter less than 6 characters, which is not what I want. Any help would be appreciated. -
Reverse for 'bid' with no arguments not found. 1 pattern(s) tried: ['dasboard/orders/add/(?P<pk>[0-9]+)$']
I'm trying to set the the status of a model object to "Off" based on passed id, How do I achieve this. Here is my views.py def bid(request, id): if request.method == 'POST': bid = Order.objects.get(id=id) bid.status = "Off" # change field bid.save() return HttpResponseRedirect('/dashboard') urls.py path('dashboard/orders/add/<int:id>', bid, name='bid') html <a href="{% url 'order_detail' order.id %}" style="text-decoration: none; color:white;" class="orders_made"> -
How can I add a constraint to a Django model that forces two fields to match?
I need to add a constraint to my Company model that makes sure that if state is defined that country is also defined and that state__country matches country. My Models from django.db.models import F, Q class Country(models.Model): name = models.CharField(max_length=100, unique=True) abbr = models.CharField(max_length=3, unique=True) class State(models.Model): name = models.CharField(max_length=100, unique=True) abbr = models.CharField(max_length=2, unique=True) country = models.ForeignKey( Country, on_delete=models.PROTECT, to_field="abbr", default="US" ) class Company(models.Model): name = models.CharField(max_length=250, blank=True) state = models.ForeignKey( State, on_delete=models.SET_NULL, null=True, blank=True, related_name="companies", ) country = models.ForeignKey( Country, on_delete=models.SET_NULL, null=True, blank=True, related_name="companies", ) class Meta: constraints = [ models.CheckConstraint( # This causes an error: check=(Q(state__isnull=True) | Q(state__country=F("country"))), name="state_and_country_must_match", ), ] When I run the migration, I get the following error caused by Q(state__country=F("country")): django.core.exceptions.FieldError: Joined field references are not permitted in this query So, what's the correct way to write this? By the way, another option would be to for country to be None if state is defined, but I'd rather not do that as I'd like to be able to get all companies in a country using country.companies. -
save with signals on same model on django
I would like to merge these methods on figure_1 so i can get the figure_2 and use signals to save the results on the same model. something is wrong so results are not saved on the model figure_1 : class Invoice(models.Model): date = models.DateField(default=timezone.now) amount_gtotal = models.DecimalField(max_digits=20, decimal_places=2, default=0) amount_gtax = models.DecimalField(max_digits=20, decimal_places=2, default=0) amount_gamount = models.DecimalField(max_digits=20, decimal_places=2, default=0) def amount_gtotal(self): items = self.invoiceitem_set.all() amount_gtotal = 0.00 for item in items: amount_gtotal += item.price * item.quantity return amount_gtotal def amount_gtax(self): items = self.invoiceitem_set.all() amount_gtax = 0 for item in items: amount_gtax += item.price_sell * item.quantity * item.vat return amount_gtax def amount_gamount(self): amount_gamount = self.amount_gtotal() + self.amount_gtax() return amount_gamount figure_2 : def calculate(self): invoiceitems = self.invoiceitem_set.all() amount_gtotal = 0 amount_gtax = 0 amount_gamount = 0 for invoiceitem in invoiceitems: amount_gtotal += item.price * item.quantity amount_gtax += item.price_sell * item.quantity * item.vat amount_gamount += amount_gtotal + amount_gtax totals = { 'amount_gtotal': amount_gtotal, 'amount_gtax': amount_gtax, 'amount_gamount': amount_gamount, } for k,v in totals.items(): setattr(self, k, v) if save == True: self.save() return totals def invoice_pre_save(sender, instance, *args, **kwargs): instance.calculate() pre_save.connect(invoice_pre_save, sender=Invoice) class InvoiceItem(models.Model): invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.PROTECT) price_sell = models.DecimalField(max_digits=20, decimal_places=2) quantity = models.DecimalField(max_digits=20, decimal_places=2) vat = models.DecimalField(max_digits=5, decimal_places=2) I … -
how to show output text from db just in one line in django templates
In my Django project, I want to read some text from my PostgreSQL DB and show them just like emails that are shown in the inbox. i.e, each output shouldn't have any line-breaks(enters) or other tags. I've wrote something like this so far: <div> <p style="font-size: 15px;">{{ contact.message |safe|truncatewords:15|cut:"\n" }}</p> </div> I also tested |striptags tag instead of |cut:"\n". It removes line breaks, but some other problems come with it since I'm using CKEditor richtextfield and the text has some markups. how to show just 1 line of text ( up to a few words, 15 for example) without any linebreaks and HTML tags? any help is appreciated. -
Why does Django not find the slug?
An error is output when trying to move to a category: If there is not enough data to answer, write down what you need to add to the question. Thank you in advance NoReverseMatch at /1928/december_rush/ Reverse for 'category_list' with keyword '{'card': , 'category': 'backend'}' not found. 1 pattern(s) tried: ['1928/(?P[-a-zA-Z0-9_]+)/(?P[-a-zA-Z0-9_]+)/$'] class Card(models.Model): """ Карточка для выбора блога о сайте """ STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField('Заголовок', max_length=100) text = models.TextField('Текст') slug = models.SlugField('Url', max_length=150) status = models.CharField('Стаутс публикации', choices=STATUS_CHOICES, default='draft', max_length=15) published = PublishedManager() objects = models.Manager() def get_absolute_url(self): return reverse('blog:post_list', kwargs={'card':self.slug}) def __str__(self): return self.title class Meta: db_table = 'Cards' verbose_name = 'Карточка' verbose_name_plural = 'Карточки' class Category(models.Model): """ Категории постов """ STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField('Заголовок', max_length=100) slug = models.SlugField('url') status = models.CharField(', choices=STATUS_CHOICES,default='draft', max_length=15) published = PublishedManager() objects = models.Manager() def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:category_list', kwargs={'card':Card.slug, 'category':self.slug}) class Meta: verbose_name = 'Категория' verbose_name_plural = 'Категории' class Post(models.Model): """ Страница поста """ STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField('Заголовок', max_length=150) slug = models.SlugField('Url', max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, related_name='blog_posts', verbose_name='Автор') text = models.TextField('Текст') created = models.DateTimeField('Дата создания', auto_now=True) … -
How to use context object to make query in Class based View?
I am trying to understand class based views and having difficulty to with variables. class TeacherView(generic.DetailView): model = Teacher context_object_name = 'the_object' template_name = urls['Teacher_detail'] # I declared an array and called urls to store template paths I want to use the Teacher variable that I am going to use in the template to make queries. Example: Homeworks.objects.filter(Teacher = Teacher_of_this_view) and pass also this Homeworks array to my template and use. Can someone atleast please tell me what to check exactly ? I got lost with functions like get_object(), get_context_object() etc. Thanks in advance -
How Django Default Model Form Validation Works?
I have create a model with email and username where email is my (pk). Both have arguements 'unique=True' in model fields. Then i have created form. My form when validates the data it always checks the uniqueness of the username but not the uniqueness of the email field. I don't know why? Since, i have mentioned unique=True why its not checking for the email data uniqueness. I have overided the clean_email() method in user registration to fix this issue but not in profile update form. I can fix this using same method but want to know why this is happening. I am still learning django a beautifull framework of python. Please help me understand this issue. models.py class MyAccountManager(BaseUserManager): def create_user(self,email,username,password=None): if not email: raise ValueError("Users Must Have email Address") if not username: raise ValueError("Users Must Have username") user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,username,password): user = self.create_user( email = self.normalize_email(email), username=username, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user # //////////////////////////////////////////////////////////// def get_profile_image_filepath(self,filename): return f'profile_images/{self.pk}/{filename}' #pk= primary key def get_default_profile_image(): return "img/default_profile/default.png" class KeepSafeUserModel(AbstractBaseUser): first_name = models.CharField(verbose_name='first_name',max_length=30,default="") last_name = models.CharField(verbose_name='last_name',max_length=30,default="") email= models.TextField(verbose_name='email',max_length=60,unique=True,primary_key=True) username = models.CharField(max_length=30,unique=True) date_joined = models.DateTimeField(verbose_name="date … -
How to set Django queryset to GKE memcached
Somehow I thought, pymemcached should work out of the box like django cache. But what I am realizing is it doesn't. Going through the docs, there are methods like set_multi, get_multi. This should work well with django dictionaries(key/value pairs). Given that Django querysets are not tranditionally dictionaries, what would be the method to use with pymemcached. Here is how am using it for the moment: if not settings.DEBUG: from pymemcache.client.base import Client NODE_NAME = os.environ['NODE_NAME'] client = Client((NODE_NAME, 5000)) class ProductsListCacheAPIView(ListAPIView): model = Product serializer_class = TestProductSerializer filter_backends= [SearchFilter, OrderingFilter] permission_classes = [AllowAny] search_fields = ['product_title', 'product_description', 'user__first_name', 'product_type', 'product_price', 'product_city'] pagination_class = ProductPageNumberPagination def get_queryset(self, *args, **kwargs): query = self.request.GET.get("search") lookups = () ..... queryset_list = queryset_list.filter(lookups).distinct() cache_key = 'my_api_marketplace_cache' data = client.get(cache_key) if data is None: print('Getting marketplace fresh from database!') data = queryset_list client.set(cache_key, queryset_list, cache_time) return data This doesn't work ofcourse. Seems unlike django cache from django.core.cache import cache (django.core.cache.backends.memcached.PyLibMCCache) The set method seems to work only with strings for pymemcached. How can I use pymemcached here to cache django querysets? -
How can i list Parent categories only with django-mptt?
I want to list only the parent Categories in one page and the other sub-categories in another page. models.py class Category(MPTTModel): name=models.CharField(max_length=50) slug=models.SlugField(max_length=50, unique=True, help_text='Uniue Value product page url, created from name.') is_active=models.BooleanField(default=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) parent=TreeForeignKey('self',on_delete=models.CASCADE,null=True,blank=True, related_name='children') class MPTTMeta: order_insertion_by=['name'] views.py def index(request): listing=Category.objects.all() context={ 'listing':listing } return render(request,'catalog/index.html',context) -
Why is fetch API translating IP address into localhost:8000?
I am trying to make an api and front end app in the same django project. The front end app uses React which makes a call using fetch to the django api app using the url: http://server_ip/api/v0/codex. When I check in the browser it looks like this is getting translated (somehow) into http://localhost:8000/api/v0/codex. This causes an error because (from what I understand) the browser is looking for the file on the local machine (my personal computer) not the remote server. This is verified by the fact that if I run the django dev server on my personal computer the request goes through. I am using nginx and gunicorn for servers (on remote cloud server used for deployment). gunicorn is running on localhost:8000. gninx does a proxy_pass to http://localhost:8000. What is going on? How does the fetch API work with localhost? What can I do to get around this issue? -
Django with filtered join
I have an inner join: SELECT c.name, b.name FROM company c INNER JOIN branch b ON b.company_id = c.id WHERE c.id = 5 AND b.employees > 10; That I got 3 registers. How do I make this query in Django to returns only 3 registers? c = Company.objects.prefetch_related("comp_branches").filter(id=5, comp_branches__employees__gt=10) c[0].comp_branches.all() # returns 5 registers -
Test view queryset in django
I am trying to validate my views in Django and I have a problem. How to check queryset filter in test. This is my view class UpcomingEvents(generics.ListAPIView): queryset = Event.objects.filter(enabled=True, start_date__gt=datetime.datetime.now()).order_by('start_date') serializer_class = EventSerializer pagination_class = Paginator How can I check if enable is true or start date> now in test without creating objects? -
Understanding definition of Django's model class
If we create a new model as follows, from django.db import models class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) and run the database migrations, then I understand that the corresponding table is created with column names and field types, and I understand that we can do the following: >>> from myapp.models import Book >>> book = Book(title="Matilda", author="Roald Dahl") >>> book.save() >>> print book.title Matilda However I am struggling a little to understand the python code in the class definition, just in terms of how I understood classes to work, and was hoping someone could help my understanding with the following questions: In the definition of the class Book, title seems to be a class attribute. This class attribute is set to an instance of the CharField class? In which case when we create an instance of the Book class, if we do not pass in an argument, would title be set to this same instance of CharField? When we pass in title='Matilda' on creating this instance of Book, is this then overriding the attribute title? How do we know that Book takes in title as an argument? I hope these make sense. Thank you for any help. Lizzie -
Getting No Response While using js function in html
I'm working on a practice project trying to create Social media clone using python and javascript everything is going well but just stuck on an error so here's my code first html <form onsubmit="createComment('{{p.id}}')" > <input id="comment_text{{p.id}}" type="text" placeholder="Write an Answer"> <input type="submit"> </form> js function createComment(f){ alert('c') fetch('/comment', { method : 'POST', body : JSON.stringify({ post_id : f, comment_text : document.querySelector(`#comment_text${f}`).value }) }) .then(response => response.json()) .then(data => { alert('succes') }) } django models class Comments(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="commenter") text = models.TextField(max_length=250) time_comment = models.DateTimeField(auto_now_add=True) class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_post") likes = models.ManyToManyField(User, related_name="likes") timestamp = models.DateTimeField(auto_now_add=True) text = models.TextField(max_length=1000) img = models.ImageField(upload_to="post", blank=True, null=True) comment = models.ManyToManyField(Comments,related_name="post_comments") url & view @csrf_exempt def new_comment(request): data = json.loads(request.body) print(data) post = Post.objects.get(id=data['post_id']) comment = Comments( user= request.user, text=data['comment']) comment.save() post.comment.add(comment.id) return JsonResponse({'message' : 'Succes'}, status=201) URL path("comment", views.new_comment, name="comment") I have some other function to create new post and edit which work similar and they are working well and I have checked my django views and url are fine I can do it without fetch method