Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
HTTP 405 Method Not Allowed in Django rest framework
I am using Django Rest Framework to create update, delete and create view for blog, but I am getting this error while heading to a specific URL like creating - GET /api/create HTTP 405 Method Not Allowed Allow: OPTIONS, POST Content-Type: application/json Vary: Accept { "detail": "Method \"GET\" not allowed." } this is the view I used @api_view(['POST', ]) def api_create_blog_view(request): user = User.objects.get(id=1) blog = BlogPost.objects.get(author=user) if request.method == 'POST': serializer = BlogPostSerializer(blog, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['PUT', ]) def api_update_blog_view(request, blog_slug): try: blog = BlogPost.objects.get(slug=blog_slug) except blog.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'PUT': serializer = BlogPostSerializer(blog, data=request.data) data = {} if serializer.is_valid(): serializer.save() data['success'] = 'Updated Successfully!' return Response(data=data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py app_name = 'blog' urlpatterns = [ path('create', api_create_blog_view, name='create'), path('<slug:blog_slug>/', api_detail_blog_view, name='detail'), path('<slug:blog_slug>/delete', api_delete_blog_view, name='delete'), path('<slug:blog_slug>/update', api_update_blog_view, name='update'), ] I am using model serializer. class BlogPostSerializer(serializers.ModelSerializer): username = serializers.CharField(read_only=True, source="user.username") class Meta: model = BlogPost fields = ['pk', 'title', 'slug', 'body', 'image', 'date_updated', 'username'] Thank you for reading -
Is it possible to use React in Django project "partially"?
This may be a weird question, and not exactly about programming itself, but let me elaborate anyway. I hope you understand. So I myself am not a professional programmer, only learned Django this year to build the prototype of a web service I'm thinking. Now I'm able to create a basic CRUD application using Django for both front and back end. Then I recently started co-working with a full-stack programmer, who uses React for front-end and Django for back-end. In our project, there are several independent applications, with separate templates/views/models of course, and I decided to take one of them and work on it since we were running out of time. The problem is that I know nothing about React, so I thought I would work on the application purely with Django, and he could work on the rest of the project with React+Django. In this case, is it possible to "work on some parts of the project purely with Django and the rest with React+Django combination"? Or would it cause any problem or error in the entire project? Thank you very much in advance. Please let me know if you need further information. -
Django+Apache | ImportError: No Module named django
I am hosting my django app on Linode with Ubuntu OS and i have configured apache webserver. When I try to access the site i get 500 Internal Server error Apache logs show the following error Traceback (most recent call last): File "/home/mosajan/artistry/artistry/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application<br> ImportError: No module named 'django' Target WSGI script '/home/mosajan/artistry/artistry/wsgi.py' cannot be loaded as Python module. Exception occurred processing WSGI script '/home/mosajan/artistry/artistry/wsgi.py'. wsgi.py import os import sys from django.core.wsgi import get_wsgi_application sys.path.append('home/mosajan/artistry/') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'artistry.settings') application = get_wsgi_application() apache2 conf file artistry.conf Alias /static /home/mosajan/artistry/static <Directory /home/mosajan/artistry/static> Require all granted </Directory> <Directory /home/mosajan/artistry/artistry> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/mosajan/artistry/artistry/wsgi.py WSGIDaemonProcess artistry python-path=/home/mosajan/artistry python-home=/home/mosajan/artistry/venv WSGIProcessGroup artistry WSGIPythonHome /home/mosajan/artistry/venv WSGIPythonPath /hom/mosajan/artistry File structure -
code snippets in styling django template bootstrap
I have to include variables while styling django templates using Bootstrap. <div class="card mb-2 text-white bg-info"> The info part will be changed for each card accordingly. Is there any way similair to this ? <div class="card mb-2 text-white bg-{card.category}"> Please Help -
Django can't recognize view when add transaction.atomic on view function
My django project works fine. But when I add @transaction.atomic on a view function in test_view.py,e.g. @transaction.atomic @csrf_exempt @required_http_methods def test_view(request): Django server can't run correctly with Error: AttributeError: modyle 'xxx.test_view.test_view has not attribute 'test_view Without @transaction.atomic, url can find my view module. What's the problem? -
get data from primary key table in django
i have 2 table a and b class A(models.Model) abc = models.CharField(max_length = 10) class B(models.Model) xyz = models.CharField(max_length = 10) a = models.ForeignKey(A, on_delete = models.CASCADE, related_name = "get_a") not i want to implemnt query on A class and want to print data from A class and B class i try this but did not get result a = A.objects.select_related('get_a') a = A.objects.select_related('a') -
Django-filters: BaseInFilter with a different separator
I'm wanting to be able split text on a value other than a comma within django-filters. I'm currently using django-filter along with a BaseInFilter to allow searching for multiple integer values in a model. This filter separates values based on a comma, and I can't seem to override the function that splits the values. It is likely that I'm misunderstanding where this split is happening. I have tried to override this method in the class BaseCSVWidget def value_from_datadict(self, data, files, name): value = super().value_from_datadict(data, files, name) if value is not None: if value == '': # empty value should parse as an empty list return [] return value.split(',') return None by placing it in my filter with a different separator: class PidnInFilter(BaseInFilter, NumberFilter): def value_from_datadict(self, data, files, name): value = super().value_from_datadict(data, files, name) if value is not None: if value == '': # empty value should parse as an empty list return [] return value.split(' ') return None I've also tried creating my own widget class and overriding there: from django_filters.widgets import BaseCSVWidget class MyWidget(BaseCSVWidget): def value_from_datadict(self, data, files, name): print('value_from_datadict reached') print(data) value = super().value_from_datadict(data, files, name) print(value) if value is not None: if value == '': # empty … -
Django Office365 email Authentication unsuccessfu
I am trying to setup a Django email sending but if fires me authenication error: My mail is godaddy with office365. this is my settings: EMAIL_HOST = 'smtp.office365.com' EMAIL_USE_SSL = False EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'admin@my.....com' EMAIL_HOST_PASSWORD = 'mypassword' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER But it fires me the following error once I try to send an email: -
check permissions before perform_create() method applied
I need to check different types of permissions for different types of actions from request user. For example get permission only need [IsAuthenticated] but when user request perform_create method. I want to implement another permission that is CanCreateProject permissions.py class CanCreateProject(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.user.is_superuser: return True else: return request.user.profile_limitation.can_create_project views.py class ProjectView(ModelViewSet): serializer_class = ProjectSerializer permission_classes = [IsAuthenticated] def get_queryset(self): queryset = Project.objects.all() organization = self.request.user.organization query_set = queryset.filter(organization=organization) return query_set def perform_create(self, serializer): self.permission_classes = [CanCreateProject] ## here project = self.request.data["project_name"] path = self.request.data["project_name"] organization = self.request.data["organization"] serializer.save(project_name=project, project_path=path, organization=organization) How can I run the CanCreateProject method only for perform_create method is requested. -
Database inconsistency between Python and Apache Kafka
So I am using Apache Kafka with Python and Postgres database. I have a model named ImportResultDetail with a foreign key to another model called ImportResult. I create an ImportResult object which is saved to the database, and send its pk as part of a message to the Kafka Producer. When consuming, I try to create an ImportResultDetail object with a fk to that ImportResult object that was created before, but somehow I get an error stating that the said object doesn't exist in the database (although it is there). Below is the stack trace and database entry to better illustrate. Anyone got this kind of problem before, and is aware of said inconsistency and how to fix it? Stack trace Proof that the item exists in db -
How to make a recursive ManyToMany relationship symmetrical with Django
I have read the Django Docs regarding symmetrical=True. I have also read this question asking the same question for an older version of Django but the following code is not working as the Django docs describe. # people.models from django.db import models class Person(models.Model): name = models.CharField(max_length=255) friends = models.ManyToManyField("self", through='Friendship', symmetrical=True, ) def __str__(self): return self.name class Friendship(models.Model): personA = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='personA') personB = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='personB') start = models.DateField(null=True, blank=True) end = models.DateField(null=True, blank=True) def __str__(self): return ' and '.join([str(self.personA), str(self.personB)]) If bill and ted are friends, I would expect bill.friends.all() to included ted, and ted.friends.all() to include bill. This is not what happens. bill's query includes ted, but ted's query does not include bill. >>> from people.models import Person, Friendship >>> bill = Person(name='bill') >>> bill.save() >>> ted = Person(name='ted') >>> ted.save() >>> bill_and_ted = Friendship(personA=bill, personB=ted) >>> bill_and_ted.save() >>> bill.friends.all() <QuerySet [<Person: ted>]> >>> ted.friends.all() <QuerySet []> >>> ted.refresh_from_db() >>> ted.friends.all() <QuerySet []> >>> ted = Person.objects.get(name='ted') >>> ted.friends.all() <QuerySet []> Is this a bug or am I misunderstanding something? -
django how to filter import_export file
How do i filter the CustomerSectionResource models? in my case all data save in the database export in the excel, I just want to select certain data to export in excel. i want to filter just like this Ex. company = FmCustomerUsers.objects.filter(user=request.user.id) obj = FmCustomerSection.objects.filter( fmCustomerID__company_name__in=company.values_list('fmCustomerID__company_name')) how? help me guys.... resources.py class FmCustomerSectionResource(resources.ModelResource): fmCustomerID = fields.Field(attribute='customer', column_name='customer', widget=ForeignKeyWidget(FmCustomer)) class Meta: model = FmCustomerSection fields = ('fmCustomerID', 'section', 'inputdate', 'inputBy', 'modifyDate', 'modifyBy', 'status') views.py from tablib import Dataset from .resources import FmCustomerSectionResource def import_Section(request): if request.method == 'POST': file_format = request.POST['file-format'] company = FmCustomerUsers.objects.filter(user=request.user.id) product_resource = FmCustomerSectionResource.objects.filter( fmCustomerID__company_name__in=company.values_list('fmCustomerID__company_name')) dataset = Dataset() new_city = request.FILES['importData'] if file_format == 'XLS': imported_data = dataset.load(new_city.read(), format='xls') result = product_resource.import_data(dataset, dry_run=True) elif file_format == 'CSV': imported_data = dataset.load(new_city.read(), format='csv') # Testing data import result = product_resource.import_data(dataset, dry_run=True) if not result.has_errors(): # Import now product_resource.import_data(dataset, dry_run=False) return redirect('Section') def export_Section(request): if request.method == 'POST': # Get selected option from form file_format = request.POST['importData'] product_resource = FmCustomerSectionResource() dataset = product_resource.export() if file_format == 'CSV': response = HttpResponse(dataset.csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="exported_data.csv"' return response elif file_format == 'XLS': response = HttpResponse(dataset.xls, content_type='application/xls') response['Content-Disposition'] = 'attachment; filename="exported_data.xls"' return response return redirect('Section') -
Pagination in django API
I need help I am fetching movie data from the movie database so far everything good with the responses. But I am stack on the pagination Because it only returns 20 objects. And I want to return the other results when clicking on pagination buttons. I have tried many ways But the only thing I can achieve is to return the results by passing the parameters in the URL ej. ?page=2 returns another 20 objects ?page=3 returns 20 more objects.And I want to do that but with pagination buttons. I tried using Django pagination but it does not work as it only returns objects from my database and not API. Here is my code in views. Also I am using a small library that I found on github but it does not have a documentation. My code Here: def peliculasPopulares(request): tmdb = TMDb() tmdb.language = 'es' tmdb.api_key = 'my-api' movie = Movie() page = request.GET.get('page') popular = movie.popular(page) return render(request, 'peliculas/populares.html', { 'title': 'populares', 'populares': popular }) -
Page Not Found/No Comment Matches The Given Query
Hi guys i'm a beginner and creating a blog site with comments but after i hit submit it says "No Comment Matches The Given Query" pagenotfound post_create.html views.py post_detail.html urls.py models.py -
Django, How to close DB connection manually to avoid resource occupancy
My Django command has the following features: First, get 1 MyItem from DB. Some processes take a very long time. Finally, save the result in the DB. from django.core.management.base import BaseCommand from my_app.models import MyItem, Result class Command(BaseCommand): def handle(self, id, *args, **kwargs): # Step1. my_item = MyItem.objects.get(id) ## TODO: close DB connection manually. # Step2. # Some processes take a very long time. # Step3. ## TODO: open DB connection manually if needed. Result.objects.bulk_create(results, batch_size=1000) Therefore, I want to release DB Connection after getting MyItem in step 1 for other processing. And I want to open the DB again in step 3. How do I explicitly close the DB Connection? -
How can I use django translation for ES6 template literals?
Is there a way to use the translation for template literals. Here is my code: var x = `<div>Are you sure you want to download ${post_or_comment}?</div>`; I know I could do: var x = '<div>'+gettext('Are you sure you want to download ')+post_or_comment+'?</div>'; But, I think its not the way because, it will be messy for lots of similar situation. -
Custom Template tag setvar scope issue
I created an custom_template_tag.py as this: from django import template register = template.Library() @register.simple_tag def setvar(val=None): return val now in my template I am looping through db and getting the correct data, but when I am trying to use my set variable outside of for loop I get nothing {% for personLiked in Post.likes.filter %} {% if request.user.id == personLiked.id %} {% setvar "True" as is_liked %} {{is_liked}} <--------GETTING VALUE HERE {% endif %} {% endfor %} {{is_liked}} <--------NOT GETTING VALUE HERE Not sure what I am missing since I believe this should be available to the rest of the page. Any suggestions? -
How to solve NOT NULL constraint with django ForeignKey?
As I am new to django I am getting this NOT NULL constraint with django's model ForeignKey. I am trying to add the User as a foreign key to the table Offer my models.py from django.conf import settings class Offer(models.Model): item = models.CharField(max_length=100) stock = models.IntegerField() discount = models.FloatField() user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,) this is how I save it in views.py offer = Offer(item=item,stock=stock,discount=discount) offer.save() How do I solve this -
how i do a filter by url in django in a View and Urls ? similar to this "my_url/sales?filter=date_sale eq 2020-06-20"
I need to filter by date Ex:2020-06-20 or this 2020-06-20 until 2020-06-20 or any date of the user put in request by url and try View class AllMayerViewSet(viewsets.ReadOnlyModelViewSet): queryset = Vendas.objects.filter(cod_cliente=541) serializer_class = VendasSerializer Urls router = routers.SimpleRouter() router.register(r'541/dsadasdas', AllMayerViewSet) urlpatterns = [ url(r'', include(router.urls)), ] Model class Vendas(models.Model): data_venda = models.DateField(db_column='DATA_VENDA') First post!!! -
I have a question about django models. I was creating a django model in visual studio code. It suggested me below code when I type charfield
class message(medels.Model): messageBody= models.CharField(_(""), max_length=1000) In this code what is _("") this? My IDE suggested me that. Please help me to understand it. -
Can I create an (Java/PHP) application that can connect to sqlite3 in django?
Can I create an application (Java/PHP) that can connect to sqlite3 in django? -
Remove anchor name from Django HttpResponseRedirect or redirect
I don't know if it's a bug or a feature, but when I'm on my home page with the contact form anchor (url = http://localhost:8000/#contact) After submitting the form, all of these will redirect including the #contact anchor name and I cannot get rid of it: from django.http import HttpResponseRedirect from django.urls import reverse from django.shortcuts import redirect # Following 3 lines all send back to http://localhost:8000/#contact return HttpResponseRedirect(reverse('homepage')) return redirect(reverse('homepage')) return redirect('/') # As a test, the following line redirects to http://localhost:8000/account/email/#contact return HttpResponseRedirect(reverse('account:email')) I found some people with the opposite issue, trying to add the anchor name, but can't find a related question with my issue -
How to add a Context `OrderItem` to appear in PDF file from Django Admin
Hellooo, I am trying to add a feature to my admin where I can download order details from a PDF file, which has gone successful so far except that only one Model is showing which is Order.Model while there is another one called OrderItems which are the items inside the Model not showing. I am not sure how to add another context for the OrderItem to appear in the PDF.html Here is the models.py class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) class Order(models.Model): items = models.ManyToManyField(OrderItem) Here is the views.py @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response here is the url.py path('admin/order/(<order_id>\d+)/pdf/', views.admin_order_pdf, name='admin_order_pdf') Here is the pdf.html template which is only showing as highlighted Ordered on: {{order.ordered_date}} <----------Showing {% for order_item in order.items.all %} {{ order_item.item.title }} <----------Not Showing {% endfor %} I even tried removing the forloop but still nothing happened Ordered on: {{order.ordered_date}} <----------Showing {{ order_item.item.title }} <----------Not Showing -
How to multiply fields in Django ModelForm?
I am trying to multiply the price and quantity fields from my modelForm to create a total_value field. I would like the value to populate after the user inputs a value for price and quantity. I have tried creating functions in the model to carry out the multiplication, however, I do not understand how to post the data in the template. Sorry I am very new to programming. Below are the links to my code. forms.py models.py views.py template.html -
filtering relational models inside django forms
i have a model which has a foreign key relation with two oder models one of them is 'level'. the view knows in which level you are based on a session variable, and then filter the lessons this is the lesson model: class Lesson(models.Model): level = models.ForeignKey(Level,on_delete=models.CASCADE) subject = models.ForeignKey(Subject,on_delete=models.CASCADE) chapiter = models.CharField(max_length=200) lesson = models.CharField(max_length=200) skill = models.CharField(max_length=200) vacations = models.IntegerField() link = models.URLField(max_length=700,null=True,blank=True) remarques = models.TextField(null=True,blank=True) order = models.IntegerField() created = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now=True) state = models.BooleanField(default=False) now this is my cbv to create a new lesson: class GlobalLessonView(CreateView): model = Lesson form_class = GlobalLessonForm success_url = reverse_lazy('globalform') and this is the form: class GlobalLessonForm(forms.ModelForm): class Meta: model = Lesson fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['subject'].queryset = Subject.objects.none() #change to .all() to see list of all subjects if 'level' in self.data: try: level_id = int(self.data.get('level')) self.fields['subject'].queryset = Subject.objects.extra(where=[db_name+'.scolarité_subject.id in( select subject_id from '+db_name+'.scolarité_levelsubject where level_id='+level_id+')']) except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['subject'].queryset = self.instance.level.subject_set one of the main conditions is to filter level by a session variable but the form does not accept request.session so is there any way …