Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
405 error method is not allowed python django
I am working on shopping cart application in Django(Book Example). When I tried to test it via browser it is responding 405 method not allowed error. As I understand when I am sending request via form(method='post') it is sending http GET request.As I undertand, It is a reason of error(405). Here is HTML form: <form action="{% url 'cart:cart_add' product.id %}" method="POST"> {{ cart_product_form }} {% csrf_token %} <input type="submit" value="Add to cart"> </form> forms.py file: from django import forms PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1,21)] class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int) override = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) views.py file: @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], override_quantity=cd['override']) return redirect('cart:cart_detail') @require_POST def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart:cart_detail') @require_POST def cart_detail(request): cart = Cart(request) return render(request, 'cart/detail.html', {'cart': cart}) -
Form validation is not working in Ajax form submitting
I am building a small Blog App with comment Functionality so, I am trying to prevent bad words in comments. ( If anyone tries to add selected bad words then the error will raise ). BUT when i add text validation in model field and try to enter bad word then it is saving without showing any errors of validation. When i try to save form without ajax then the error is validation successfully showing. BUT error is not showing in ajax. models.py class Comment(models.Model): description = models.CharField(max_length=20000, null=True, blank=True,validators=[validate_is_profane]) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True) views.py def blog_detail(request, pk, slug): data = get_object_or_404(Post, pk=pk) comments = Comment.objects.filter( post=data) context = {'data':data,'comments':comments} return render(request, 'mains/blog_post_detail.html', context) if request.GET.get('action') == 'addComment': if request.GET.get('description') == '' or request.GET.get( 'description') == None: return None else: comment = Comment(description=request.GET.get('description'), post=data, user=request.user) comment.save() return JsonResponse({'comment': model_to_dict(comment)}) blog_post_detail.html {% for comment in comments %} {{comment.comment_date}} <script> document.addEventListener('DOMContentLoaded', function () { window.addEventListener('load', function () { $('#commentReadMore{{comment.id}}').click(function (event) { event.preventDefault() $('#commentDescription{{comment.id}}').html( `{{comment.description}}`) }) }) }) </script> {% endfor %} I have tried many times but still not showing the validation error. Any help would be much Appreciated. Thank You in Advance. -
django use function from other views
I want to use part of the data from an existing function in another view.py for example: result/view.py def result(request,slug) datas = modle.objects.get(slug=slug) somecodes... return render(request,"result.html",data1,data2,data3,data4) And I want part of the data (ex. data1,data2) to use in another view files, how do i do that ? -
text under symbols in the sidebar menu
Very new to CSS and HTML, but right now working on Django one-page project. Under icons, I would like to place some text, but there is an issue with the borders. sample img Right now text wrapping works not very well, I would like to center text under the icon and have at least 3 or 4 straight strings. Maybe there are issues that this text and icons should be in the container, IDK, will be very happy to hear any solution and suggestions for my portfolio project. Thank you! Here is my HTML: <!DOCTYPE html> {% load static %} <html lang="ru"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> <link rel="stylesheet" href="{% static 'style.css' %}"> <script src="https://kit.fontawesome.com/5476287230.js" crossorigin="anonymous"></script> </head> <body> <div class="social-menu"> <ul> <li><a href="https://www.instagram.com/kseniia_ifbb_latvia"><i class="fab fa-instagram"></i></a></li> <li><a href="https://www.tiktok.com/@kseniiasherr"><i class="fab fa-tiktok"></i></a></li> <li><a href="https://www.facebook.com/profile.php?id=100009190064504"><i class="fab fa-facebook"></i></a></li> </ul> </div> <div class="title"> <h1>ЧТО ВЫ ПОЛУЧАЕТЕ?</h1> </div> <div id="background"></div> <div class="icons"> <li><i class="fas fa-utensils"></i></li> <li><i class="fas fa-dumbbell"></i></li> <li><i class="fas fa-clock"></i></li> <li><i class="fas fa-heartbeat"></i></li> </div> <div class="icons-text"> <li><h1>План питания с учетом Ваших вкусовых потребностей</h1></li> <li><h1>Тренировки для любого уровня подготовки</h1></li> <li><h1>Максимально быстрые результаты</h1></li> <li><h1>Тело, о котором Вы могли только мечтать</h1></li> </div> </body> </html> And CSS: body{ background: url(https://images.unsplash.com/photo-1534258936925-c58bed479fcb?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=889&q=80) no-repeat center center fixed; background-size: cover; } … -
django mptt no such column: appname_modelname.lft
models.py -> class Category(MPTTModel): title = models.CharField(max_length=200) description = models.TextField(blank=True, null=True) parent = TreeForeignKey( 'self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) class MPTTMeta: order_insertion_by = ['title'] class Card(BaseModel): categories = TreeManyToManyField(Category, related_name='category_cards', blank=True, default=None) admin.py -> @admin.register(Category) class CategoryAdmin2(DraggableMPTTAdmin, BaseAdmin): list_display = ('tree_actions', 'indented_title',) list_display_links = ('indented_title',) I ran both "python manage.py migrations" and "python manage.py migrate" commands. No error occurs. Migration File -> migrations.CreateModel( name='Category', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_date', models.DateTimeField(auto_now_add=True)), ('modified_date', models.DateTimeField(auto_now=True)), ('title', models.CharField(max_length=200)), ('description', models.TextField(blank=True, null=True)), ('lft', models.PositiveIntegerField(editable=False)), ('rght', models.PositiveIntegerField(editable=False)), ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)), ('level', models.PositiveIntegerField(editable=False)), ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='children', to='w2mmcards.category')), ], options={ 'verbose_name': 'category', 'verbose_name_plural': 'categories', }, ), migrations.AddField( model_name='card', name='categories', field=mptt.fields.TreeManyToManyField(blank=True, default=None, related_name='category_cards', to='w2mmcards.Category'), ), In admin interface, I get this error: OperationalError at /admin/myapp/category/ no such column: myapp_category.lft How to solve it? -
cannot create 'builtin_function_or_method' instances
I want to see the type of a list element but I am not able to see this, it gives this error: "cannot create 'builtin_function_or_method' instances". Normally, it seems to keep dict but I cannot use the dict methods on this variable (like .items). So, I need to learn the type of it. This is the variable : [{'time': '2021-07-03T15:44:40.124358Z', 'application_name': 'TrashTest', 'dev_eui': '45405201a0000009', 'device_name': 'sayac-001', 'f_port': '4', 'value': 338.0}]. I want to use the value parameter only. How can I take the value? Thanks a lot. this is the error and this is the code -
Django - how to get user from built in LoginView
I simply want to grab the user after login but for some reason can't think of the best way to do that while using class based LoginView. I just want to flash a message with the specific user who logged in. I am not sure how to grab the request.user from the built in login view. My very simple view is as follows: class MyLoginView(SuccessMessageMixin, LoginView): template_name = 'registration/login.html' success_message = 'Welcome' -
AttributeError : Can't get attribute 'myfunctionname' on <module '__main__' from '/app/.heroku/python/bin/gunicorn'> : Django Project
I am using a custom module in my Django app, facing issues while deploying in Heroku. This is the content of my custom module- defs.py: import numpy as np def myfunctionname(x): return np.log(x + 1) this file is being called in manage.py as from defspack.defs import myfunctionname procfile : web gunicorn appname.wsgi --log-file - Traceback: 2021-07-06T11:28:32.195664+00:00 app[web.1]: obj = unpickler.load() 2021-07-06T11:28:32.195665+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/pickle.py", line 1212, in load 2021-07-06T11:28:32.195665+00:00 app[web.1]: dispatch[key[0]](self) 2021-07-06T11:28:32.195666+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/pickle.py", line 1537, in load_stack_global 2021-07-06T11:28:32.195667+00:00 app[web.1]: self.append(self.find_class(module, name)) 2021-07-06T11:28:32.195667+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/pickle.py", line 1581, in find_class 2021-07-06T11:28:32.195668+00:00 app[web.1]: return _getattribute(sys.modules[module], name)[0] 2021-07-06T11:28:32.195668+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/pickle.py", line 331, in _getattribute 2021-07-06T11:28:32.195668+00:00 app[web.1]: raise AttributeError("Can't get attribute {!r} on {!r}"2021-07-06T11:28:32.195669+00:00 app[web.1]: AttributeError: Can't get attribute 'myfunctionname' on <module '__main__' from '/app/.heroku/python/bin/gunicorn'> can anyone help me on this -
Django custom __in lookup
I get custom lookup for filtering foreign key field from this answer. from django.db.models import Lookup class EfficientInLookup(Lookup): lookup_name = "ineff" def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + list(rhs_params) return "%s IN (SELECT unnest(ARRAY(%s)))" % (lhs, rhs), params But I have an error in the string lhs, lhs_params = self.process_lhs(compiler, connection) when I am trying use it. Using: queryset = queryset.filter(child__id__ineff=[1,2,3] Error: int() argument must be a string, a bytes-like object or a number, not 'list' How can I write a custom lookup for foreign key fields? -
How to fetch swipe up count from Instagram story insights graph API?
I need to fetch swipe up count which show in the insights of Instagram.As Facebook is not providing swipe up count through their graph API so how can I get that data. Scraping won't work as I already did and I want to fetch those data in python or javascript Thanks in advance for help -
Someone please tell me what is wrong with my code?
I am coding for a complaint management system and so far for creating new complaints the form is kind of made but the complaints that are being made are not getting saved in my admin panel. I have tried everything and I don't understand where i'm going wrong models.py: class Complaints(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) title = models.CharField(max_length=300) description = models.TextField(null=True, blank= True) highpriority = models.CharField(max_length=200, blank=True) document = models.FileField(upload_to='static/documents') def __str__(self): return self.title forms.py: class ComplaintForm(ModelForm): class Meta: model = Complaints highpriority = forms.CharField(label='Priority', widget=forms.RadioSelect(choices=PRIORITY_CHOICES)) fields = ['title', 'description', 'highpriority', 'document'] def clean(self): cleaned_data = super(ComplaintForm, self).clean() title = cleaned_data.get('title') description = cleaned_data.get('description') if not title and not description: raise forms.ValidationError('You have to write something!') views.py: def NewComplaint(request): user = request.user if request.method == 'POST': form = ComplaintForm(request.POST) if form.is_valid(): form.save(commit=False) form.user = user form.save() submitbutton= request.POST.get('Submit') if submitbutton: messages.success(request, 'Submitted!') context = {'form': form} return render(request, 'new.html', context) else: form = ComplaintForm() context = {'form': form} return render(request,'new.html',context) template: <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">New Complaint</h1> <form class="" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-control col-lg-10 comp-title-field">{{form.title}}</div> <p class="desc">Description</p> <button type="button" class="btn btn-secondary preview-btn">Preview</button> <div class="Descr ">{{form.description}}</div> … -
How to make a django custom widget with 2 fields/controls (amount and credit/Debit)
I have one numeric field in my model If the field is negative its debit and if its positive its Credit Now the user has the always enter a positive number and then select Credit or Debit When the data is saved to the field accordingly the sign is assigned The user is not supposed to enter a negative amount How to create a custom widget to achieve this so that I can use it in ModelForm s -
I want the code of previous version of my Django app. How can I get it? I tried git reset --hard but it's not working. It's showing email not found s
I deleted the requirements.txt file and again created a new requirements.txt file using pip freeze > requirements.txt And after deploying, it is showing an application error. So I rolled back to the previous version. But I am not able to get the code of that previous version. I tried with the "git reset --hard eeb02c91" command. But it's not working. It's showing "HEAD is now at eeb02c9 Email not registered error added". Someone, please help me to get the code of the previous version. -
Cannot Install python3-gdal in digitalocean app for django project
Digital ocean introduced apps, which is very fast and easy way to deploy projects. But i've encountered a problem and I wonder if you can help me with it. In my requirements i have added GDAL, but when i try to install it it says that gdal-config is not installed. I have added in my build commands ./manage.py migrate sudo apt-get install python3-gdal python-gdal libgdal-dev But the build commands wont execute before installing the requirements.txt I cannot access the console and I cant install it manually, Have you already encountered such a problem with the dependency libs and how can I solve it? -
Add multiple objects as a list to a model attribute in Django?
I am new to Django and I am working on a project. I want to create a classroom with multiple students which are objects with their own attributes. My classroom model class Classroom(models.Model): name = models.CharField(max_length=31) students = models.ForeignKey('Student',on_delete=models.CASCADE, null=True, related_name='students') def __str__(self): return self.name My student model class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) classroom = models.ForeignKey( Classroom, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Classroom") When I go to the specific URL I see only one student rather than all. Please help. Thanks in advance -
Link an html form to a django form
I created the following html form: <div class="contact-page-form"> {% csrf_token %} <!-- Contact Form --> <form method="get" id="formulaire"> {% csrf_token %} <div class="row clearfix"> <div class="form-group col-lg-12 col-md-12 col-sm-12"> <span class="icon flaticon-user-2"></span> <input type="text" name="username" placeholder="Votre nom" required> </div> <div class="form-group col-lg-12 col-md-12 col-sm-12"> <span class="icon flaticon-big-envelope"></span> <input type="email" name="email" placeholder="Email" required> </div> <div class="form-group col-lg-12 col-md-12 col-sm-12"> <span class="icon flaticon-user-2"></span> <input type="text" name="sujet" placeholder="Sujet" required> </div> <div class="form-group col-lg-12 col-md-12 col-sm-12"> <span class="icon flaticon-user-2"></span> <textarea id="msgtext" name="message" placeholder="Message"></textarea> </div> <div class="form-group col-lg-12 col-md-12 col-sm-12"> <button class="theme-btn submit-btn" name="submit-form">Envoyer <span class="arrow flaticon-right-arrow-1"></span></button> </div> </div> </form> <!-- Contact Form --> </div> I would like to know if it is possible to create a django form in a forms.py file and to link my existing html form to it. if so, how to do it? -
Is there a way to pass foreign key field to test database in django through fixtures
while executing the unit test cases in Django, I tried to load data to test database using fixtures. As the fixtures contains the foreign key field i am getting the column of relation does not exist error. So, can we load the table with foreign key with fixtures while testing the django code -
Integration of python script into django application
I developed an AI application (which includes a knowledge base, nested lists, etc.), written in python and currently using a python interpreter for that. On the other hand, I have a Django application, more like a frontend for the end-user. But now I'm stuck on how to integrate both applications together. -
Ajax Infinite scroll on fixed element does not work. Can I change the window reference to the element?
Let me tell you the problem. Picture 1 I need a fixed element as you can see in picture 1. The context flows there. I use django for backend. I want to use infinite scroll and if I don't use overflow-y: scroll everything works great. I think the problem is tha ajax cannot find height of scrollbar. When scrollbar of window change,as you can see picture2, ajax works great. picture2 How can I fix the problem ? Thank you -
How to generate random users in django template on button click with no refresh
I want a button, on which I can click so that it outputs a random user each time with no refresh. I am using a django user queryset, which should be randomized. So I have this variable which I have passed into my template from views.py in django. all_users {{ all_users }} <button>Generate</button> so now, when I click that generate, it should give a random user from the all users. Without refresh. I think this can be done in javascript, but I'm not sure. This is what I've done. <p id="de">&nbsp;</p> <button id="button" onclick="rndTx">Press</button> <script> function rndEl(){ return arr[~~(rnd()*arr.length)]; } function rndTx(){ var tx = rndEl(); var txt = document.createTextNode(tx); var sp = document.createElement('span'); sp.appendChild(txt); de.innerHTML = ''; de.appendChild(sp).style.color = tx; } rnd = Math.random; arr = {{ all_users }} // using queryset here. tElementById('de'); document.getElementById("button").addEventListener('click',rndTx,false); </script> please let me know how I could do this. Thanks! -
Is Python to preferred as a backend language over Java because it supports live/hot reload?
When developing Java applications I always have to stop and rebuild my application when implementing changes in the backend. If your application is not performance sensitive, should python be preferred as a backend language because not so much time is wasted restarting the application after every small change? -
Django/CKEditor/Javascript Issue including text in textarea
I'm working on a forum with Django that allows users to reply to each other (and quotes the original user). This works perfectly when I do a first reply (I'm using a one line javascript that updates the textarea via grabbing the id and updating the innerHTML with a django template from my view, see html template below) : Issue is, when I attempt to quote an already quoted message, nothing appears in the textarea field. Below are my views and templates: View @login_required def reply_to_post(request, pk, topic_id, post_pk): reply = get_object_or_404(Post, topic_id=topic_id, pk=post_pk) topic = get_object_or_404(Topic, board__pk=pk, pk=topic_id) if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.post = reply post.created_by = request.user post.topic = topic user = reply.created_by title = post.topic post.save() reply.last_update = timezone.now() reply.save() notify.send(request.user, recipient=user, actor=request.user, verb='replied to your post', target=title, nf_type='replied_by_one_user') reverse('home') topic_url = reverse('topic_posts', kwargs={'pk': pk, 'topic_pk': topic_id}) topic_post_url = '{url}?page={page}#{id}'.format( url = topic_url, id=post.pk, page=topic.get_page_count() ) return redirect(topic_post_url) else: form = PostForm return render(request, 'reply_post.html', {'topic': topic, 'form': form, 'reply': reply}) reply_form.html {% load form_tags widget_tweaks %} {% load static %} {% if form.non_field_errors %} <div class="alert alert-danger" role="alert"> {% for error in form.non_field_errors %} <p {% if forloop.last … -
How to change queryset in forms.py django?
I have in my forms.py this code: def __init__(self, *args, **kwargs): super(CountryForm, self).__init__(*args, **kwargs) self.fields['area'].queryset = Geo.objects.filter(Q(category='O') | Q(category='K')) self.fields['district'].queryset = Geo.objects.none() self.fields['district'].widget.attrs['disabled'] = True self.fields['region'].queryset = Geo.objects.none() This none() in queryset don't give me to save my Country form. But I can't delete this 3 fields with none(), because this 2 fields on page gives me a lot of data(31 000) Ofcource it slow down the page. Any ideas how can I specify this queryset Geo.objects.none() but without none() - no data inside? -
(2021) How to login and get page content from Facebook using scrapper API
since Facebook has changed its policies, so now i cannot view or scrap Facebook page or anything without login. I was using scrapper API and everything was working fine but now it redirects me to the login page. Is there any way i can first login with scrapper api then get any page content within a single session? -
Why django is not detecting my table column?
I have a problem. I've created model called "Flower", everything works fine, i can create new "Flowers", i can get data from them etc. The problem is when I want to use column "owner_id" in SQL query I got an error that this column don't exist, despite I can use it to get data from objects (for example flower1.owner_id). I've deleted my sqlite database several times, made new migrations and used migrate but that still not worked.I also changed name of the column and re-created it, but that still doesn't helped. My models.py: from django.db import models from django.contrib.auth.models import User class Flower(models.Model): name = models.CharField(max_length=80) water_time = models.IntegerField() owner_id = models.ForeignKey(User, on_delete=models.CASCADE, default=1) def __str__(self): return self.name My views.py (view, where i want to use it): class workspaceView(generic.DetailView): template_name = 'floris/workspace.html' def get_object(self): with connection.cursor() as cursor: cursor.execute(f'SELECT id,name FROM floris_Flower WHERE owner_id = {self.request.user.id}') row = cursor.fetchall() object = row print(object) if self.request.user.id == object.id: return object else: print('Error') My urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index2, name='index2'), path('login/', views.loginView, name='login'), path('register/', views.register, name='register'), path('addflower/', views.AddPlantView, name='addflower'), path('index.html', views.logout_view, name='logout'), path('workspace/', views.workspaceView.as_view(), name='workspace'), path('profile/<str:username>/', views.ProfileView.as_view(), name='profile'), ] And my error code: …