Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'NoneType' object has no attribute 'split' in django
I have created nested comment system using django-mptt.(Addding comment,reply to a certain comment,deleting a comment) these functionalities are working fine.But when I am trying to edit particular comment,after editing comment it is not reloading to detail page.In console it showing "AttributeError: 'NoneType' object has no attribute 'split' ". During this error another error is occuring -> TypeError: 'NoneType' object is not subscriptable.Here is my code: models.py: class Comment(MPTTModel): video = models.ForeignKey(Video, on_delete=models.CASCADE, related_name = 'comments') parent = TreeForeignKey('self',on_delete=models.SET_NULL, null=True, blank=True, related_name='children') reply_to = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, related_name='replayers') user = models.ForeignKey(User, on_delete= models.CASCADE) content = models.TextField() created = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) class MPTTMeta: order_insertion_by = ['created'] def __str__(self): return f'{self.content[:20]} by {self.user}' views.py: def edit_comment(request, video_id, comment_id): video = get_object_or_404 (Video, id=video_id) comment = Comment.objects.get(id=comment_id) print(comment) if request.method == 'POST': edit_form = CommentUpdateForm(request.POST,instance=comment) print(edit_form) if edit_form.is_valid(): edit_form.save() messages.success(request, f'Your comment has been updated!') return HttpResponse("") else: return HttpResponse( "The content of the form is incorrect, please fill in again.") else: edit_form = CommentUpdateForm(instance=comment) print(edit_form) context = { 'edit_form': edit_form, 'video_id' : video_id, 'comment_id': comment_id, } return render(request,'comment/edit_comment.html',context=context) main urls.py: urlpatterns = [ path('comment/',include('comment.urls')), ] comment urls.py: from django.urls import path from comment import views app_name = 'comment' urlpatterns = … -
Django Translation Framework and formatted string literals
In the Django Documentation regarding the translation framework, all examples make use of the old style string interpolation: from django.utils.translation import gettext as _ my_string = _('This month has the name %(month)s.') % {'month': get_current_month_name()} Is it also possible to use the newer syntax like f-strings and str.format()-syntax with djangos gettext()? -
How to add a logo to the site index bar using django
Can anyone help me on how to add a logo to the index bar in Django-admin site? -
I am try to implement test series but stuck on add and updating question option
option is depend on question type{Single choice,Multiple choice and file or text options} I have used class based for create question Createview and update question by UpdateView. I Can create question successfully but my data is not render in formsets.Please give you suggestion so i can fixed it. class Questions(models.Model): ques_type = ( ('SCQ', 'Single choice questions'), ('MCQ', 'Multiple choice questions'), ('DQ', 'Descriptive'), ) title = models.TextField(_("Question Title"),null=False,blank=False) file = models.FileField( _("Image / Video"), upload_to='question/file/%Y/%m/%d', null=True, blank=True, help_text='Please upload single video [max 10 mb/ mp4, m4a, m4v, mov]') difficulty_level = models.ForeignKey("DifficultyManager.Difficulty", verbose_name=_( "Difficulty Level"), on_delete=models.SET_NULL, null=True) topics = models.ForeignKey("TopicManager.Topic", verbose_name=_( "Topic"), on_delete=models.SET_NULL, null=True) ques_type = models.CharField( _("Question Type"), max_length=4, choices=ques_type) is_delete = models.BooleanField(_("Delete"), default=False) created_by = models.ForeignKey(User, related_name="questions", blank=True, null=True, on_delete=models.SET_NULL) status = models.BooleanField(_("Status")) create_date = models.DateTimeField( _("Created timestamp"), auto_now_add=True) update_date = models.DateTimeField( _("Last update timestamp"), auto_now=True) objects = QuestionsManager() filetype = models.BooleanField(_("Video"), help_text='if video available',default=False) imagetype = models.BooleanField( _("Image"), help_text='if image available', default=False) def __str__(self): return self.title class QuestionOption(models.Model): question = models.ForeignKey( "Questions", on_delete=models.CASCADE, verbose_name=_("questions")) option = models.CharField(_("Option"), max_length=255) is_right = models.BooleanField(_("Right"), default=False) create_date = models.DateTimeField( _("Created timestamp"), auto_now_add=True) update_date = models.DateTimeField( _("Last update timestamp"), auto_now=True) def __str__(self): return self.question.title class QuestionFile(models.Model): question = models.ForeignKey( "Questions", on_delete=models.CASCADE, verbose_name=_("questions"), null=True) … -
What do I need to do to a function in views.py works?
I'm working on a API and I need to create a function to don't allow the same post format in less than 10 minutes, but i'm just trying to print something in the terminal if the user use the "GET" request method, but it's not working. urls.py: from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'products',views.ProductsViewSet) router.register(r'product-images',views.ProductImagesViewSet) #router.register(r'^products/', views.testIt, basename="TestIt") urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('products/', views.testIt, name = "testIt"), ] views.py: from rest_framework import viewsets from .serializers import ProductsSerializers from .serializers import ProductImagesSerializers from .models import Products from .models import ProductImages from rest_framework import status from rest_framework.throttling import UserRateThrottle from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.decorators import api_view from django.http import JsonResponse class ProductsViewSet(viewsets.ModelViewSet, APIView): queryset = Products.objects.all().order_by('id') serializer_class = ProductsSerializers def testIt(self, request, pk=None): if request.method == 'GET': print('Testando') return Response('Teste!', status = status.HTTP_400_NOT_FOUND) class ProductImagesViewSet(viewsets.ModelViewSet): queryset = ProductImages.objects.all().order_by('id') serializer_class = ProductImagesSerializers I still see the data but it's not returning any message or printing anything when I use the get method. Thank you in advance!! -
Django: Installing gettext via pip
I tried to use Django's internationalization instead of creating an own one. For this I need gettext. But since the internationalization in Django isn't documented well, I had to take a look at some guides. Main problem: After running django-admin makemessages -l en I got the error: CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed.. According to some guides I run pip install python-gettext. But the problem still exists. Trying to run pip install gettext I get the following error: ERROR: Could not find a version that satisfies the requirement gettext (from versions: none) ERROR: No matching distribution found for gettext So how can I install get-text via pip install? Django Version: 3.1.2 -
ValueError: Field 'id' expected a number but got 'DEFAULT VALUE'
When I try to execute python manage.py migrate I get this error: ValueError: Field 'id' expected a number but got 'DEFAULT VALUE'.What could be wrong with my code.Any help pleaseThanks in advance. File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1772, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'DEFAULT VALUE' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 233, in handle fake_initial=fake_initial, File "/home/risper/django_projects/env01/lib/python3.6/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 "/home/risper/django_projects/env01/lib/python3.6/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 "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 112, in database_forwards field, File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 328, in add_field self._remake_table(model, create_field=field) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 189, in _remake_table self.effective_default(create_field) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 303, … -
how to add custom user model to users section of admin panel - django 3.1.1
I have added a custom user model in my django project which was explained here. I defined extra fields in models.py like this: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.CharField(max_length=25, blank=True) address = models.TextField(max_length=500, blank=True) zipcode = models.CharField(max_length=15, blank=True) city = models.CharField(max_length=25, blank=True) country = models.CharField(max_length=25, blank=True) phone = models.CharField(max_length=15) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() in my views.py, the registration goes like this: from django.shortcuts import render, redirect from django.contrib.auth.models import User def update_profile(request, user_id, company, address, zipcode, city, country, phonenumber): user = User.objects.get(pk=user_id) user.profile.company = company user.profile.address = address user.profile.zipcode = zipcode user.profile.city = city user.profile.country = country user.profile.phoneNumber = phonenumber user.save() def register(request): if request.method == 'POST': # Get form values first_name = request.POST['firstname'] last_name = request.POST['lastname'] company = request.POST['company'] address = request.POST['address'] zipcode = request.POST['zipcode'] city = request.POST['city'] country = request.POST['country'] phoneNumber = request.POST['phoneNumber'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] # Check if password match if password == password2: # Check username if User.objects.filter(username=username).exists(): return redirect('register') else: if User.objects.filter(email=email).exists(): return redirect('register') … -
how can i set foreign key set automatically to the user in my person field
this is my views.py @login_required(login_url='/login') def user_edit(request, user_id): if request.method == 'POST': user = User.objects.get(id=user_id) form = ProfileForm(request.POST or None, instance=user) if form.is_valid(): i = form.save(commit=False) i.user = request.user i.save() return redirect('list') else: form = ProfileForm() return render(request, "home/intro.html", {'form': form}) else: return render(request, "home/intro.html") this is my forms.py from django import forms from django.forms import ModelForm from .models import Profile class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = '__all__' this is my models.py from django.contrib.auth.models import User from django.db import models class Profile(models.Model): img = models.ImageField(upload_to='imgs/') about = models.TextField(max_length=255, null=False) phnum = models.IntegerField() uname = models.CharField(max_length=255, null=False) person = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def __str__(self): return self.about how can i set person to that user id that is currently logged in...??? i wanted to save user id to that foreign key so that if i delete user then profile of that user will also be deleted -
Unable to run the new Django site as whenever I tried to do so by running the local host ip:127.0.0.1:8000 it's accessing the old Django Project site [closed]
I am newbie to Django. I had created a simple Django site and ran it I had some issues with it hence abandoned it and now I created a second Django project however when I ran the link 'python manage.py runserver' and trying to access second project via link:'127.0.0.1:8000' it's taking me to the old Django project. Please help me. -
Best way to export multiple PDF files with django as backend and React as frontend
I am currently working on a web application which has django backend (using DRF) and React as frontend. I want to create an API which can export multiple PDF files(of 4-5 pages each). Ofcourse, it will take a long time and doing it in normal HTTP request/response cycle will timeout. What is the best way/architecture to incorporate this in the backend? PS: I already have celery working for several other apis(time consuming background tasks) but in this case, I want response (i.e pdf files) from the celery to reach frontend. I am not sure how to do that. Any other method which is ideal for such scenario is appreciated. Thanks in advance!! -
how to increase disk size of RabbitMQ with celery in Django
I am using RabbitMQ as broker with Celery in my django project. But problem is that Celery task get stuck. I am getting OCR of pdf file in that task and normally it works fine but if I upload file more than 1 MB celery task takes alot of time as it seems like it gets stuck. I read online and found that its happening because disk size of RabbitMQ is less. So my question is how I can assign RabbitMQ more disk space I have read official docs and more solutions related to that but still I am unable to understand. Because there isn't any default setting file of RabbitMQ. If you know please explain briefly how I can set it up and increase its size -
AttributeError: 'HttpResponseSeeOther' object has no attribute 'url'
I'm looking to test for a 303 See Other status code when a User attempts to login. Django does not have a built in class to handle this status code, so I constructed a sub class of HttpResponse. from http import HTTPStatus from django.http import HttpResponse class HttpResponseSeeOther(HttpResponse): '''Represents a 303 status code''' status_code = HTTPStatus.SEE_OTHER Next, I constructed a TestCase to test a View's response when it is passed valid form data. However, the test raises this error: AttributeError: 'HttpResponseSeeOther' object has no attribute 'url' . Going over the Django docs, I cannot see any reference to a Response object having an URL attribute. How can I go about addressing this error so that a server returns a 200 OK response after a successful 303 See Other redirect? test_views.py class TestUserLoginPage(TestCase): @classmethod def setUpTestData(cls): User.objects.create_user(username="User", password="password") cls.login_creds = { 'username': 'User', 'password': 'password' } def test_successful_login_redirect(self): response = self.client.post( reverse("login"), data=self.login_creds, follow=True ) self.assertRedirects(response, reverse("photos:main_gallery"), status_code=303) self.assertTemplateUsed(response, "photos/main_gallery.html") views.py class LoginPage(View): def get(self, request): form = UserAuthenticationForm() return render(request, 'login.html', context={'form': form}) def post(self, request): import pdb; pdb.set_trace() form = UserAuthenticationForm(request, request.POST) if form.is_valid(): messages.success(request, f"Welcome {request.user}!") return HttpResponseSeeOther(reverse("photos:main_gallery")) messages.info(request, "Login Failed. Username not registered.") form = UserAuthenticationForm() return … -
How to show OrderItem in Order in Django Admin.py
I am trying to show the orderitemsadmin in the orderadmin using TabularInline but I keep getting the following error. AttributeError: 'OrderItemAdmin' object has no attribute 'urls' This is a Django e-commerce project and I am trying to facilitating the admin viewing the orders and their items. Here is the admin.py class OrderItemAdmin(admin.TabularInline): list_display = ['item', 'quantity', 'ordered'] model = OrderItem raw_id_fields = ['item'] class OrderAdmin(admin.ModelAdmin): list_display = ['user', 'ordered', 'ordered_date', 'coupon', 'payment', 'shipping_address', 'status', 'refund_requested', 'refund_granted', 'ref_code'] list_display_links = [ 'user', 'shipping_address', 'payment', 'coupon' ] list_editable = ['status'] list_filter = ['ordered', 'ordered_date', 'refund_requested', 'refund_granted', 'status'] search_fields = [ 'user__username', 'ref_code' ] actions = [make_refund_accepted] inlines = [ OrderItemAdmin, ] Here is the models.py class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, ------------------------------------------------------ status = models.CharField(max_length=50, choices=[('pending', 'Pending'), ('ofd', 'Out For Delivery'), ('recieved', 'Recieved')], default='pending') def __str__(self): return self.user.username -
Django - can I add a form on changelist_view?
I have a model admin with a simple custom change view page, can I add a form on it? class MyModelAdmin(admin.ModelAdmin): change_list_template = 'custom_template.html' def changelist_view(self, request, extra_content=None): # How do I link the form to this view ? # logic of handling data from the form return super(MyModelAdmin, self).changelist_view(request, extra_context=None) -
Django WebSocket Multiple Send
i try realize multiple send in websockets. In synchronous and only 1 to 1 work but if i try send message 1 to many or asynchronous 1 to 1 i don't see notification. Can you help please with code or rewrite this code. I'm not an expert in websockets, but I'm trying to write something. consumers.py class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): if self.scope["user"].is_anonymous: await self.close() else: self.group_name = "user_id_" + str(self.scope["user"].id) for group in self.group_name: self.channel_layer.group_add( group, self.channel_name) await self.accept() async def disconnect(self, close_code): await self.close() async def notify(self, event): await self.send(text_data=json.dumps(event["text"])) notify.py def send_notification(data, user, req_user, email): channel_layer = get_channel_layer() group_name = 'user_id_{0}'.format(user.id) async_to_sync(channel_layer.group_send)(group_name, { "type": "notify", "text": data, }, ) if email: send_mail(subject='Message', message=f"{data}", from_email=req_user.email, recipient_list=[user.email]) notify = Notification.objects.create(sender=req_user, message=data) notify.receivers.add(user) notify.save() Execute function send_notification('notify_text', user=[User.objects.get(username='applicant1'), applicant1 = User.objects.get(username='applicant0')], req_user=user_id,email=False) template <script> var loc = window.location var wsStart = "ws://" if (loc.protocol === "https:"){ wsStart = "wss://" } var webSocketEndpoint = wsStart + loc.host + '/notifications/' // ws : wss // Websocket URL, Same on as mentioned in the routing.py var socket = new WebSocket(webSocketEndpoint) // Creating a new Web Socket Connection // Socket On receive message Functionality socket.onmessage = function(e){ console.log('message', e) $("body").append("<h3>"+e.data+"</h3>") // Can write any … -
Django Filtering Foreign Key Item
I have problem using fk in django. I want to make a fk field that the parent's queryset has been filtered. I have app called user that has costumized User model in model.py class User(AbstractUser): username = models.CharField(max_length=50, unique=True) email = models.EmailField(_('email address'), unique=True) phone = models.IntegerField(_('phone number'), unique=True, blank=True, null=True) this User has ManyToMany Relationship with Group queryset: maker, checker, signer >>> print(Group.objects.all()) <QuerySet [<Group: maker>, <Group: checker>, <Group: signer>]> In other app called cleaning I have cln_daily model that has foreignkey relationship with that User model based on their group. class cln_daily(models.Model): . . user_maker = models.ForeignKey(User,verbose_name="Maker's Signature",on_delete=models.CASCADE, related_name="makerSignature", blank=True, null=True,) user_checker = models.ForeignKey(User, verbose_name="Checker's Signature",on_delete=models.CASCADE, related_name="checkerSignature", blank=True, null=True) user_signer = models.ForeignKey(User, verbose_name="Signer's Signature",on_delete=models.CASCADE, related_name="signerSignature", blank=True, null=True) So what I mean is user_maker queryset has users that only belong to group maker. user_checker has users that only belong to group checker and user_signer queryset has users that only belong to group signer. How to express filtered User model in that model.py? -
Use regroup with datetimefield
I want to regroup a queryset in my template : {% regroup events by date as events_group %} {% for event in events_group %} <div class="time-label"> <span class="bg-danger"> {{ event.grouper }} It's works but the "date" is a datetimefield. I want to group my results per day. Today the results are displayed like : 10 Oct 2020 16:59 event1 10 Oct 2020 16:55 event2 10 Oct 2020 16:54 event3 09 Oct 2020 12:59 event4 09 Oct 2020 11:59 event5 I want : 10 Oct 2020 event1 event2 event3 09 Oct 2020 event4 event5 How to do this ? -
convert Django raw sql return into object
my sql Django raw query returns : [ (datetime.date(1998, 10, 8), 'swe', 'tam', 'images/3.jpg', 190, 'female', 1), (datetime.date(2020, 10, 8), 'Sal', 'ws', '1_qvQ9V4k.jpg', 122, 'male', 4) ] I want to convert the below format .how to do that. <QuerySet [<player: Sal>, <player: lee>, <player: swe>, <player: pol>, <player: Pak>, <player: Ask>, <player: sal>]> becuase i want to use it for my custom filter function : myFilter = RankFilter(request.GET, queryset=player_features.objects.all().order_by('-ranking_points')) -
Django Python DetailView not working as expected. I get an issue when I try and view a specific note
Advice required. would someone point me in the right direction? Using Django 3.1.1 with Pycharm Community 2020.2 I'm working with ListView to show all To-Do notes on one page allTasks.html {% extends "app/base.html" %} {% load static %} {% block content %} <body> <div class="section"> <div class="container" id="heading"> <h3>List of all Tasks to-date</h3> </div> <div class="container"> <ul id="taskcontainer"> {% for i in obj %} <li> <div class="row"> <div class="col-md-12"> <div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-inblock"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-primary">{{ i.name }}</strong> <h6 class="mb-0">{{ i.date }}</h6> <div class="mb-1 text-muted">Team {{ i.team_project }}</div> <p class="card-text mb-auto">{{ i.notes }}</p> <p class="card-text mb-auto">Priority: {{ i.urgency }}</p> <strong class="d-inline-block mb-2 text-danger">Completed? {{ i.completed }}</strong> <span> <a href="{% url 'task-detail' task.id %}" class="link">View</a> <a href="#" class="link">Edit</a> </span> </div> </div> </div> </div> </li> {% endfor %} </ul> </div> </div> </body> From here I go into DetailView to each individual note task_detail.html {% extends "app/base.html" %} {% load static %} {% block content %} <br> <div class="row"> <div class="col-md-12"> <div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-inblock"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-primary">{{ object.name }}</strong> <h6 class="mb-0">{{ object.date }}</h6> <div … -
Object of type QuerySet is not JSON serializable Django with AngularJS
I have a Django project where am using AngularJs as frontend. I have a very simple search where user will search a code and if the code matches from the db table it will show it. Am pretty new with angularjs what i tried is fetching objects as an array. ** my view ** @csrf_exempt def hscodesearch(request): chaptercode = '' hs4code = '' chapter_description = '' chapter_description1 = '' if (request.method == 'POST'): data = json.loads(request.body) s_t = data.get('hs_search') hs_content = { "chaptercode": chaptercode, "chapter_description": chapter_description, "chapter_description1": chapter_description1, "search_test": s_t, "hs4code": hs4code, } result = [hs_content] return HttpResponse(json.dumps({"status": 1, "data": result}), content_type='application/json') my controller.js mainApp.controller('hsController', function($scope, $http, $compile, $timeout, $location) { $scope.data = {}; $scope.init = function() { console.log("angular loaded!") } $scope.data.form = { hs_search: "", result: "", }; $scope.data.formStyle = { hs_search: "" }; $scope.submitForm = function() { //console.log($scope.data.form) var error = 0; if(!$scope.data.form.hs_search) { $scope.data.formStyle.hs_search = "is_invalid"; error++; } else { $scope.data.formStyle.hs_search = ""; } if(error==0) { var jsonCall = $http({ method: 'POST', url:'/theapp/hs-code-search', data: $scope.data.form, headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'} }); jsonCall.success(function(data, status, headers, config) { if(data.status==1) { $scope.data.form.result = data.data console.log($scope.data.form.result) } }); jsonCall.error(function(data, status, headers, config) { if(data.status==0) { $.growl.error({ message: data.error}); } }); console.log($scope.data.form) } … -
Django rest framework, DELETE request responds with "Method \"GET\" not allowed." to every valid request
Here is my code for DELETE method for a "comment" model (views.py): class CommentDelete(DestroyAPIView): queryset = Comment.objects.all() serializer_class = CommentSerializer in urlpatterns it looks like this (urls.py): ... path('delete/', views.CommentDelete.as_view()), ... For some reason when I make a direct DELETE request, the result is "Method \"GET\" not allowed." I'm also using swagger, and it gets even more weird there. There is a DELETE option but it doesn't provide any parameter field even after I've specified it in views.py (lookup_field = 'id'). When I run it, it gives me an expected error: Expected view CommentDelete to be called with a URL keyword argument named "id". -
Nested foreign key serializer with customized response in Django not working
Part of models.py class Supporting_organizationSerializer(serializers.ModelSerializer): name = serializers.CharField(required=True) image_name = serializers.CharField(required=False) class Challenge(models.Model): title = models.CharField(max_length= 1000, blank=False) supporting_organization = models.ForeignKey(Supporting_organization, related_name="supporting_organizationId",on_delete=models.CASCADE,blank=True) class Challenge_progressLog_detail (models.Model): challenge = models.ForeignKey(Challenge, related_name="challengeCreationId",on_delete=models.CASCADE) latitude = models.DecimalField(max_digits=9, decimal_places=6,default=0.0) longitude = models.DecimalField(max_digits=9, decimal_places=6,default=0.0) location_address = models.TextField(default='') photo_description = models.TextField(default='') part of serializers.py: class Supporting_organizationSerializer(serializers.ModelSerializer): name = serializers.CharField(required=True) class Meta: model = Supporting_organization fields = '__all__' class ChallengeSerializer(serializers.ModelSerializer): supporting_organization = serializers.RelatedField(source='supporting_organizationId', read_only=True) class Meta: model = Challenge fields = '__all__' class Challenge_progressLog_detail_Serializer(serializers.ModelSerializer): challenge = serializers.RelatedField(source='challengeCreationId', read_only=True) class Meta: model = Challenge_progressLog_detail fields = '__all__' I want the Challenge_progressLog_detail_Serializer to return a nested object detail which will havechallenge detail with respective supporting organization. The categorization is straightforward, having a list of challenge progress log detail in the first level, challenge types in the second, and supporting organization items in the third level. Problem is that Challenge_progressLog_detail_Serializer only returns the first and second level only i.e. only the challenge detail is shown. But I want the full nested list of Challenge_progressLog_detail with Challenge Detail, And supporting organization detail items. I used below serializer class in in challenge_progresslog_detail ==> serializer.py file for get customized response in list. Apart from I used rest_framework serializer. class challengeListSerializer(serializers.ModelSerializer): challenge_id = serializers.SerializerMethodField() challenge_title = … -
Git db.sqlite and wsgi.py file keep reverting on pull
I have a python/django/wagtail project that I built locally using db.sqlite3. I did an initial push with everything to github, and then pulled it to my server. I made a change to the wsgi file and did some work in the cms which updated the database. I made some changes locally. I changed my .gitignore to exclude db.sqlite3 and wsgi.py. git add ., git commit, git push origin master. then, on the server, sudo git pull origin master. db.sqlite3 reverts back to before I made the cms changes and the wsgi.py reverts back to pointing to my dev settings. I made the changes back to the cms but now I need to do another update when I have made even more cms changes and I do not want to overwrite the database again. wsgi.py is a small fix but still. My .gitignore # Created by https://www.toptal.com/developers/gitignore/api/django # Edit at https://www.toptal.com/developers/gitignore?templates=django ### Django ### *.log *.pot *.pyc __pycache__/ local_settings.py db.sqlite3 db.sqlite3-journal media wsgi.py # If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ # in your Git repository. Update and uncomment the following line accordingly. # <django-project-name>/staticfiles/ ### Django.Python Stack ### # Byte-compiled … -
Crispy form does not work with specific form field and button
I am trying to use crispy-forms but ran into the following two problems. This is the form.py from django import forms from menu.models import Item class TableCheckInForm(forms.Form): guest_count = forms.IntegerField(min_value =0) # item = forms.ModelChoiceField(queryset=Item.objects.all()) item = forms.IntegerField(min_value =0) and the template: {% extends "base.html" %} {% load crispy_forms_tags %} {% block title %}Table{% endblock %} {% block content %} <div class="table_order_form"> <h1>Order</h1> <form action="{% url 'table_order_view' %}" method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" class = "button table_order">PLACE ORDER</button> </form> </div> {% endblock %} And of course in the settings.py, I have declared: crispy_forms and CRISPY_TEMPLATE_PACK = 'bootstrap4' Problem 1: in forms.py, if the field item is a ModelChoiceField (the commented line), the form is out of whack, not "crispy" at all. But if I replace it with a usual form field such as IntegerField, the form is nicely formatted. Problem 2: in the template, I place a button right below the form, but when rendered, the button appears in parallel with the form, to its top right, and out of whack. Looking for some advice. Thanks.