Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django call_command and read from stdin
I've a django management command (MG1) which reads from stdin this way: sys.stdin.read() . I've another django management command (MG2) from which I'd like to call the MG1 command in a way that it can read from stdin. This case stdin can be a file as well, so something like: MG1 < /tmp/file.txt . How can I call the management command (from MG2) this way so it can read the /tmp/file.txt file as stdin? Django: 1.11.16 Python: 2.7.12 . Thanks. -
How can I implement the video recording feature on Agora in a Vuejs project?
I am building a project using Vuejs (frontend) and Django (backend) in which I have integrated Agora-Web-SDK-NG for video calls. Now, I want to add a feature of video recording and recordings will be stored in the cloud. I have researched a lot but couldn't found that Agora-Web-SDK-NG provides this feature and that too in Vuejs. I have read its official documentation too but couldn't found an understanding way to implement. Has anyone ever been implemented this feature in Vuejs? -
django testing 'Object has no meta error' and User has not attribute 'get'
I am trying to Test my views. I have created this Base test class and working with it. I have tried using User like this: user = User.objects.filter(id=1).first(). It shows me the same error. Also, these tests works fine if I remove the self.client part. Can anyone please help me identify the problem? class BaseTest(TestCase): def setUp(self): self.home = reverse('home') self.login = reverse('login') self.signup = reverse('signup') self.admin = User.objects.create_user(pk='1', username='random', password='secret', first_name= 'admin', last_name='user', email='admin@gmail.com') self.adminrank = UserRank.objects.create(user = self.admin, userstatus='Admin') self.agent = User.objects.create_user(pk='2', username='agent', password='secret', first_name= 'agent', last_name='user', email='agent@gmail.com') self.agentrank = UserRank.objects.create(user = self.agent, userstatus='Agent') self.client = User.objects.create_user(pk='3', username='client', password='secret', first_name= 'client', last_name='user', email='client@gmail.com') self.clientrank = UserRank.objects.create(user = self.client, userstatus='Client') self.logincred = { 'username': 'random', 'password': 'secret' } self.agentcred = { 'username': 'agent', 'password': 'secret' } self.clientcred = { 'username': 'client', 'password': 'secret' } self.wrongcred = { 'username': 'client', 'password': 'wrong' } Here are is my view that I am testing: def login(requests): if requests.method == 'POST': username = requests.POST['username'] password = requests.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(requests, user) return redirect('/profile/') else: return JsonResponse({"message": "login failed"}) def profile(requests): userstatus = UserRank.objects.filter(user= requests.user).values('userstatus') # print(userstatus) # ADMIN View if userstatus[0]['userstatus'] == 'Admin': allchecks = requests.POST.get('filter') … -
How to create anagram solver using python? [closed]
I don't understand how to write anagram solver program using python , From where i can get the dictionary of all words? can you provide me some good article on it.basically i am new to python. -
How to implement video calling feature using Django?
I have developed a website but now I want to add video calling feature in my website. Can I use Zoom Api? What will be the best option for me? -
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.