Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting 'str' object has no attribute 'get' when using django template tags
template {{ show_details.message|get_value:"data_errors"}} template_tags.py @register.filter def get_value(dictionary, key): print("DICTIONARY",dictionary,"KEYYY",key) #output for this is ('DICTIONARY','','KEYYY',u'data_errors') return dictionary.get('key') AttributeError: 'str' object has no attribute 'get' -
django rest api framework "list" obj has no attribute values
I trying to pass some files through djangorest framework and while trying to do so, I am facing error 'list' object has no attribute 'name' my views.py from django.shortcuts import render from rest_framework import serializers from rest_framework import viewsets from rest_framework import status from rest_framework.response import Response from restfilesupload.serializers import FileSerializer class FileUploadViewSet(viewsets.ViewSet): def create(self, request): serializer_class = FileSerializer(data=request.data) if request.method == 'POST': if 'file' not in request.FILES or not serializer_class.is_valid(): return Response(status=status.HTTP_400_BAD_REQUEST) else: handle_uploaded_file(request.FILES.getlist("file")) return Response(status=status.HTTP_201_CREATED) def handle_uploaded_file(f): with open(f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) class Meta: fields = ['pk' , 'file'] my serializers.py from rest_framework import serializers class FileSerializer(serializers.Serializer): file = serializers.FileField(max_length=None, allow_empty_file=False) -
Update item that contains file without file reupload in RetrieveUpdateAPIView
class Item: name = models.CharField(...) document = models.FileField(...) class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__' class UpdateItemAPIView(RetrieveUpdateAPIView): authentication_classes = (SessionAuthentication, ) permission_classes = (IsAuthenticated, ) serializer_class = ItemSerializer parser_classes = (MultiPartParser, FormParser) In GET response I see "photo": "127.0.0.1:8000/media/items/11/01/2021/file_name.pdf" What should I put as a value when I want to update Item but photo file is the same? If I put a path to the file that I grab from GET response, I see a validation error that it is not a file. Vue.js var formData = new FormData(); formData.append("photo", this.photo); for (var key in data) { formData.append(key, data[key]); } this.$http .put(`/api/item/update/${this.itemID}/`, formData, { headers: { "X-CSRFToken": this.getCookie("csrftoken"), "Content-Type": "multipart/form-data" } }) -
I am trying to create drop down menu in django but my code is showing only text box ? Help Appricated
I have defined modles.py, view.py, and forms.py but unable to get the drop-down menu. at initial, I have created moodle.py using os_choice and later on a substitute in the operating_system. further, I have created forms and I am using crispy forms to render in front page. likewise, I have defined this in views.py but when I see it on the font page it shows only a text file, not a drop-down with choices. Here is my model.py code: from django.db import models from django.utils.encoding import smart_text from multiselectfield import MultiSelectField # Create your models here. class ResultQuery(models.Model): os_choice = ( ('Windows 10', 'Windows 10'), ('Windows 8', 'Windows 8'), ('Linux', 'Linux'), ) operating_system = models.CharField(max_length=30, blank=True, null=True, choices=os_choice) level = models.CharField(max_length=30) program = models.CharField(max_length=30) semester = models.CharField(max_length=20) exam_year = models.IntegerField() institute = models.CharField(max_length=4) reg_no = models.CharField(max_length=50) symbol_num = models.IntegerField() student_name = models.CharField(max_length=50) dob = models.DateField() sgpa = models.TextField() result = models.CharField(max_length=40) name = models.CharField(max_length=30) subject1_code=models.CharField(max_length=40) subject1_title=models.CharField(max_length=40) subject1_credit_hour=models.TextField() subject1_grade_point=models.TextField() subject1_grade=models.TextField() subject1_remarks=models.CharField(max_length=20, null=True, blank=True) subject2_code = models.CharField(max_length=40) subject2_title = models.CharField(max_length=40) subject2_credit_hour = models.TextField() subject2_grade_point = models.TextField() subject2_grade = models.TextField() subject2_remarks = models.CharField(max_length=20, null=True, blank=True) subject3_code = models.CharField(max_length=40) subject3_title = models.CharField(max_length=40) subject3_credit_hour = models.TextField() subject3_grade_point = models.TextField() subject3_grade = models.TextField() subject3_remarks = models.CharField(max_length=20, null=True, … -
How to use filter_horizontal with TabularInline and .through?
My models are class Test(models.Model): name = models.CharField(max_length=255) class Testrelated(models.Model): name = models.CharField(max_length=255) tests = models.ManyToManyField(Test, related_name='tests') And admin: class TestrelatedInline(admin.TabularInline): extra = 0 model = models.Test.tests.through filter_horizontal = ('name') class TestAdmin(admin.ModelAdmin): list_display = ('id', 'name') search_fields = ('name',) inlines = [ TestrelatedInline, ] The problem is that .through has no the model fields. So I can not refer to any field using filter_horizontal. <class 'app.admin.TestrelatedInline'>: (admin.E019) The value of 'filter_horizontal[0]' refers to 'name', which is not an attribute of 'app.Testrelated_tests'. I have created a test stand https://gitlab.com/marataziat/testdjangoproject. -
Creating a waiting room Django
I would like to create something like FaceTime on a website based of the tastes of the users. I thought about creating a waiting room where all users will be. Then a matching algorithm will try to pair two of the users and take them to a private room where they will be able to chat. I have made a simple music controller with the following tutorials: https://youtube.com/playlist?list=PLzMcBGfZo4-kCLWnGmK0jUBmGLaJxvi4j The problem is that I don’t know how to create a room by default. A room which is always active and where I can put my users in it :/ PS: I use Django with python and rest framework for the backend. Thanks -
Not working Import tool and template override at the same time for same model
Trying to use both import tool and Django admin template override on the same model. However, it not working same time . Is there a particular solution for this? -
djongo aggregate in python django
i`m using mongodb(3.6) in python(3.8.5) django(3.1.5). and i have used djonjo(1.3.3) for mongodb connection. when i have run aggregate query with model.objects.aggregate({'$graphLookup': { 'from': 'categories_categories', 'startWith': 'id', 'connectFromField': 'sub_category', 'as': 'SubCategory' } }) so i am getting error QuerySet.aggregate() received non-expression(s): {'$graphLookup': {'from': 'categories_categories', 'startWith': 'id', 'connectFromField': 'sub_category', 'as': 'SubCategory'}}. -
How to create multiple instances in DRF?
I have a list of data coming in a request, and after filtering taken out data that needs creation, I'm passing it to the serializer create method, but I'm getting this error: AssertionError: The `.create()` method does not support writable nested fields by default. Write an explicit `.create()` method for serializer `apps.some_app.serializers.SomeSerializer`, or set `read_only=True` on nested serializer fields. My view looks like this: class MyViewSet(ModelViewSet): # Other functions in ModelViewset @action(methods=['post'], url_path='publish', url_name='publish', detail=False) def publish_data(self, request, *args, **kwargs): new_data = util_to_filter_data(request.data) serializer = self.serializer_class(data=new_data, many=True) if serializer.is_valid(raise_exception=True): serializer.create(serializer.validated_data) return Response() I understood the error, that I am passing nested fileds in the create method. But, when I am directly calling my Viewset with single POST request, it is created successfully, even though it too contains nested fields. What am I doing wrong here? -
Angular 8 , angular chosen not working after build
Currently I am developing website using django and angular 8. for dropdown I have used angular-chosen and I have configured it in angular side using angular-chosen package. On Angular side dropdown working properly with angular-chosen and I am able to get expected results as shown in SS below. But after build into my django application, angular chosen not able to load.I have attached screenshot as below. I have done same configuration as have been suggested in below plunker. https://embed.plnkr.co/plunk/N5KF1d I have tried a lot to find solution but not able to. So guys please let me know if anyone have solution for it. Thanks. -
How to add or remove fields from a serializer based on a condition?
I'm creating a simple Todo app and I want to provide an api for it. A todo task maybe completed or not. if it's not completed yet, then the field Todo.date_completed will be null. I want to let the same serializer send the field date_completed if it's not null. One solution would be to let date_created be a SerializerMethodField and send some string like "Not completed yet" in case it's not completed. But that's not really helpful since the client will be asking for the tasks that're not completed anyways... Another solution would be like here, I've rewritten the same class (Meta) twice just to remove the value from rest_framework import serializers from todo.models import Todo class TodosSerializer(serializers.ModelSerializer): date_created = serializers.ReadOnlyField() date_completed = serializers.ReadOnlyField() class Meta: model = Todo fields = ['title', 'memo', 'date_created', 'date_completed', 'is_important'] class PendingTodosSerializer(TodosSerializer): class Meta: model = Todo fields = ['title', 'memo', 'date_created', 'is_important'] How to let the field date_completed be sent only in case it's not null? And one extra question, in case there is no way, can I somehow remove the field date_completed from PendingTodosSSerializer.Meta without rewriting the entire class again so that I don't have to copy and paste the code? -
How do I set the duration of the output of a job in Elastic Transcoder using Django?
I want to automate using Amazon's Elastic Transcoder to trim a video file in Django. My code so far is: def trim_video(key, new_key, duration): pipeline_id = 'XXXXXXXXXXXX-XXXXXX' region = 'XXXXXXXX' transcoder_client = boto.elastictranscoder.connect_to_region(region) create_job_result=transcoder_client.create_job(**{ 'pipeline_id': pipeline_id, 'input_name': {'Key': key}, 'output': { 'Key': new_key, "PresetId": 'XXXXXXXXXXXXX-XXXXXX' } }) print('Job has been created. The output key will be ' + new_key) This code will cause the file to be transcoded but will not trim it. What do I add in order to trim the video? -
how to add two different tables data in one table through button in django without form
urls.py path('books/<int:book_id>/',addfavourite,name='addfavourite') This is the model table. models.py class Library(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) book = models.ForeignKey(Book,on_delete=models.CASCADE,related_name='library') def __int__(self): return self.library_id views.py def addfavourite(request, pk): userid = auth.get_user(request) bookdetail = get_object_or_404(Book, pk=pk) if request.user.is_authenticated: favourite = Library() favourite = Library.objects.create(user=userid,book=bookdetail) favourite.save() else: return reverse('books.html') The button to add data as no user value is needed. <button type="submit" href="{% url 'addfavourite' bookdetail.pk %}" class="button"> I am not getting error but the data is not created in table. -
Problems on through model with Django Rest Framework
This happens when I list to Recipe objects. Trying to do as here, I get no errors, but the response I'm getting is as the following: # response of Recipe.objects.all() [ { "user": 1, "name": "sandwich", "ingredients": [ {}, {} ], "created": "2021-01-11T00:47:04.932071-03:00", "modified": "2021-01-11T00:47:04.932167-03:00" } ] When the models are: class Recipe(models.Model): user = models.ForeignKey('users.User', on_delete=models.CASCADE, null=False) name = models.CharField(blank=False, max_length=50) ingredients = models.ManyToManyField('recipes.Ingredient', through='recipes.IngredientComposition') # some other fields... class Ingredient(BaseModel): name = models.CharField(blank=False, max_length=25, unique=True error_messages={'unique': 'Ingredient already exists'}) class IngredientComposition(models.Model): ingredient = models.ForeignKey('Ingredient', on_delete=models.CASCADE, null=False) recipe = models.ForeignKey('recipes.Recipe', on_delete=models.CASCADE, null=False) quantity = models.DecimalField(max_digits=21, decimal_places=3, null=False, default=1) And their serializers: class RecipeSerializer(serializers.ModelSerializer): ingredients = IngredientCompositionSerializer(read_only=True, many=True) class Meta: model = Recipe fields = ['user', 'name', 'ingredients', 'created', 'modified'] class IngredientSerializer(serializers.ModelSerializer): class Meta: model = Ingredient fields = ['name', 'created', 'modified'] class IngredientCompositionSerializer(serializers.HyperlinkedModelSerializer): name = serializers.ReadOnlyField(source='ingredient.name') class Meta: model = IngredientComposition fields = ['name', 'quantity'] The expected response is: [ { "user": 1, "name": "sandwich", "ingredients": [ {"name": "bread", "quantity", 2.0}, {"name": "cheese", "quantity", 3.0} ], "created": "2021-01-11T00:47:04.932071-03:00", "modified": "2021-01-11T00:47:04.932167-03:00" } ] What am I missing? -
how to handle authentication error in angular based on data returned from django rest-framework
a login may result in authentication failed by Django due to 'Invalid credentials', 'Account disabled' , 'Email is not verified' , the code looks as below if not user: raise AuthenticationFailed('Invalid credentials, try again') if not user.is_active: raise AuthenticationFailed('Account disabled, contact admin') if not user.is_verified: raise AuthenticationFailed('Email is not verified') I am getting three different responses in three different conditions but 401 status code in all three cases. my login request sends from angular as follow, if (this.loginForm.dirty && this.loginForm.valid) { this.httpService.doLogin(this.loginForm.value).subscribe(data=>{ console.log() if(data['email'] && data['tokens']){ //codes gets executed if everything goes well and authenticate well. ... ... }else{ console.log('data load fail', data) } },error=>{ //line 1 this.toastr.error('Invalid Credentials or email not verified', 'Login Error',); }) }else{ this.toastr.warning('Info!', 'Invalid data provided.'); } } the problem is in all three above authentication fail, my codes come to line 1, and I am not able to toast the failing reason properly although I get the response but HTTP 401 takes me to line 1. I want to toast according to the response so that the user understand what is the issue, ex: if the email is not verified I must toast email not verified if account disabled I must toast account disabled … -
TodayArchiveview is not detected in urls.py(Django)
I created several date-based views in Django, and while views for year and month function as expected, the view to display today is not detected. For instance, if I try to get http://127.0.0.1:8000/blog/archive/2021/jan or http://127.0.0.1:8000/blog/archive/2021/jan/07/ the views will be displayed, http://127.0.0.1:8000/blog/archive/today/ will fail. I understand that the problem must be with urls.py configuration, but I just cannot find it in documentation. urls.py from django.urls import path, re_path from blog import views app_name = 'blog' urlpatterns = [ # Example: /blog/ path('', views.PostListView.as_view(), name='index'), # Example: /blog/post/ (same as /blog/) path('post/', views.PostListView.as_view(), name='post_list'), # Example: /blog/post/django-example/ re_path(r'^post/(?P<slug>[-\w]+)/$', views.PostDetailView.as_view(), name='post_detail'), # Example: /blog/archive/ path('archive/', views.PostArchiveView.as_view(), name='post_archive'), # Example: /blog/archive/2019/ path('archive/<int:year>/', views.PostYearArchiveView.as_view(), name='post_year_archive'), # Example: /blog/archive/2019/nov/ path('archive/<int:year>/<str:month>/', views.PostMonthArchiveView.as_view(month_format = '%b'), name='post_month_archive'), # Example: /blog/archive/2019/nov/10/ path('archive/<int:year>/<str:month>/<int:day>/', views.PostDayArchiveView.as_view(), name='post_day_archive'), # Example: /blog/archive/today/ path('archive/today/', views.PostTodayArchiveView.as_view(), name='post_today_archive'), ] views.py from django.shortcuts import render # Create your views here. from django.views.generic import ListView, DetailView, ArchiveIndexView, YearArchiveView, MonthArchiveView, \ DayArchiveView, TodayArchiveView from blog.models import Post class PostListView(ListView): model = Post template_name = 'blog/post_all.html' context_object_name = 'posts' paginate_by = 2 class PostDetailView(DetailView): model = Post class PostArchiveView(ArchiveIndexView): model = Post date_field = 'modify_dt' class PostYearArchiveView(YearArchiveView): model = Post date_field = 'modify_dt' make_object_list = True class PostMonthArchiveView(MonthArchiveView): model = Post date_field … -
Django blog comments
I can't get to add the new comment in the list of existing commetns on a post. Here's the model: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') body = models.TextField() commented_by = models.ForeignKey(User, on_delete=models.CASCADE) commented_on = models.DateTimeField(auto_now_add=True) def __str__(self): return f'Commented by {self.commented_by} on {self.post}.' Here's the view: def post_detail(request, id): post = Post.objects.get(id=id) comments = post.comments.all().order_by('-commented_on') total_comments = post.comments.all().count() form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST, instance=post) if form.is_valid(): instance = form.save(commit=False) instance.post = post instance.save() context = { 'post' : post, 'comments' : comments, 'form' : form, 'total_comments' : total_comments, } return render(request, 'blog/detail.html', context) -
Django Error NoReverseMatch at /new_bid/1 Reverse for 'addwatchlist' with arguments '('',)' not found
I am somewhat new to Django. I'm encountering an error that I find very odd. The site allows a user to place a bid (enter a number amount) on an item, similar to ebay. When I enter the number, I get the error "NoReverseMatch at /new_bid/1 Reverse for 'addwatchlist' with arguments '('',)' not found. 1 pattern(s) tried: ['addwatchlist/(?P[0-9]+)$'] This is odd because that area of the code (new_bid in views.py) has nothing to do with the addwatchlist. The addwatchlist in views.py adds this particular item to a list, for that user. It's just so a user can keep track of any items on the site they want to watch. The watchlist function works completely - I can add an item to my watchlist and it's fine. I don't know why this function is interacting with my other function, new_bid, which adds a bid for the item. I know this error usually is related to the url or the way the html template calls the url but I really don't know why they two are interacting. Is it because they both use "id": listingid ? Any help is appreciated! urls.py for relevant urls: urlpatterns = [ path("addwatchlist/<int:listingid>", views.addwatchlist, name="addwatchlist"), path("new_bid/<int:listingid>", views.new_bid, … -
Autumate bigo live apk from windows
In the clip below there is a software on the left giving command to Bigo live apk I want to know what should I learn in order to be able to make similar software as the clip the software has two features login to Bigo live with multi accounts and the accounts can auto chat. https://www.youtube.com/watch?v=7wqGxlZWKqQ -
Suddenly getting Validation Error when trying to perform db migration in Django
For weeks I have had no issues making db migrations, and running models. I added a few fields and then I got Validation Error so I removed the fields, but the error remains. I am not sure what the issue is or how to fix it. I've looked into the db entries and there are no NA entries. I removed from the current field any default="NA" but I continue to get the error. What is the source of the error? How can I fix it? Operations to perform: Apply all migrations: admin, animals, auth, contenttypes, sessions Running migrations: Applying animals.0025_auto_20210111_0214...Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/usr/Desktop/animalDirectoryTemplate/.venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/usr/Desktop/animalDirectoryTemplate/.venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/usr/Desktop/animalDirectoryTemplate/.venv/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Users/usr/Desktop/animalDirectoryTemplate/.venv/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Users/usr/Desktop/animalDirectoryTemplate/.venv/lib/python3.7/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/Users/usr/Desktop/animalDirectoryTemplate/.venv/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 245, in handle fake_initial=fake_initial, File "/Users/usr/Desktop/animalDirectoryTemplate/.venv/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/usr/Desktop/animalDirectoryTemplate/.venv/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Users/usr/Desktop/animalDirectoryTemplate/.venv/lib/python3.7/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = … -
django dumpdata command throws doesnot exist error
I am trying to add some default/fixed values to postgres database and came across fixtures. My model is like this app/models.py class Category(models.Model): category = models.CharField(max_length=255) def __str__(self): return self.category app/fixtures/category.json [ { "model": "core.category", "pk": 1, "fields": { "category": "foo" } ] However, I am getting the following error when I run manage.py dumpdata [CommandError: Unable to serialize database: cursor "_django_curs_139823939079496_sync_1" does not exist -
Data accessing by double reverse filter with multiple interdependent model
I am working with some models in Django. my models.py: class Industry(models.Model): user = models.OneToOneField(myCustomeUser, null=True, blank=True, on_delete=models.CASCADE, related_name='industry_releted_user') name = models.CharField(max_length=200, blank=True) gmail = models.EmailField(null=True, blank=False, unique=True) owner = models.CharField(max_length=200, blank=True) license = models.IntegerField(null=True, unique=True) industry_extrafield = models.TextField(blank=True) def __str__(self): return self.name class Industry_Report(models.Model): industry = models.ForeignKey(Industry, null=True, blank=True, on_delete=models.CASCADE) extra1 = models.CharField(max_length=200, blank=True, null=True) extra2 = models.CharField(max_length=200, blank=True, null=True) extra3 = models.CharField(max_length=200, blank=True, null=True) extra4 = models.CharField(max_length=200, blank=True, null=True) def __str__(self): return self.industry.name class report_tableA(models.Model): industry_report = models.ForeignKey(Industry_Report, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=False, null=True) father_name = models.CharField(max_length=200, blank=False, null=True) mother_name = models.CharField(max_length=200, blank=False, null=True) rank = models.CharField(max_length=20, blank=False, null=True) nid = models.IntegerField(blank=False, unique=True) phone_number = models.IntegerField(blank=False, null=True) gmail = models.EmailField(null=True, blank=True, unique=True) Now I am trying to access all those data of report_tableA which are interrelated to Industry's object from the Industry model's DetailView. my views.py: class industryDetails(DetailView): model = Industry template_name = 'app/industryDetails.html' def get_queryset(self): return Industry.objects.filter(user=self.request.user) def get_object(self): return get_object_or_404(Industry, user=self.request.user) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) Industry_Report_obj = self.object.industry_report_set.all() context['Industry_Report'] = Industry_Report_obj report_tableA_obj = self.object.industry_report_set.report_tablea_set.all() context['report_tableA'] = report_tableA_obj return context Actually, I try to implement a kind of double reverse approach doc for relationship field. But it won't work and say Queryset not … -
Error code when trying to create new django project
I am trying to create a new django app. After creating an initial "mysite" project, I tried to create an application labeled "polls" from my windows command line. However, when I put in py manage.py startapp polls, I get this error message: C:\Users\22may> py manage.py startapp polls C:\Users\22may\AppData\Local\Programs\Python\Python39\python.exe: can't open file 'C:\Users\22may\manage.py': [Errno 2] No such file or directory From my understanding, I need to reestablish the project's address. How would I go about this? The current address is: C:\Users\22may\mysite\manage.py Thanks! -
Is it secure to create API in django without rest framework
I've created an app in my django project which works same like API. But for post requests, logins I'm doing something like this. request "GET"(url: example.com/api/get) this returns a csrftoken which is then used by my applications as cookie. request "POST"(url: example.com/api/login), Here frontend application logs in the user. The csrftoken from example.com/api/get is used in cookies and same is used as csrfmiddlewaretoken in post data. My question here is, it is secure to create API like this and use instead of Django RestFramework. Any suggestion will be appreciated.THANK YOU -
How to store information from javascript into a Django model?
I currently have an app which uses HTML/CSS/JQuery. As of right now all my data is saved in Jquery (and therefore not saved between sessions), but I am learning Django and want to learn how I would save that JQuery data into Django models. So how do javascript and django communicate in order to save information from one to the other?