Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch: Reverse for 'RPA_tool' with arguments '('',)' not found. 1 pattern(s) tried: ['admin_tool/RPA_tool/(?P<Policy_Number>[^/]+)/$']
I am trying to create a dynamic URL in my Django App to redirect from the Search Page to RPA_Tool/<Policy_Number> When I attempt to load the search page, I receive the error Reverse for 'RPA_tool' with arguments '('',)' not found. 1 pattern(s) tried: ['admin_tool/RPA_tool/(?P<Policy_Number>[^/]+)/$'] I've tried swapping it to use datadisplay.Policy_ID, and that has successfully redirected to Policy_ID. However, when I change the hyperlink to datadisplay.Policy_Number, I receive the error. here is the HTML: <input type="text" id="myInput" onkeyup="searchTable()" placeholder="Search for Policy.."> <table class = "table"> <tr class="header"> <th>Policy ID</th> <th>Policy Numbers</th> </tr> <tbody id="myTable"> {% for datadisplay in Policies %} <tr> <td>{{datadisplay.Policy_ID}}</td> <td>{{datadisplay.Policy_Number}}</td> <td> <a class="btn btn-sm btn-info" href="{% url 'RPA_tool' datadisplay.Policy_Number %}"> Update </a> </td> </tr> {% endfor %} </tbody> </table> Views.py: def searchPolicies(request): Policies = getPolicyNumbers() myfilter = PoliciesFilter() context = {'myfilter': myfilter} return render(request, 'admin_tool/search.html', {'Policies':Policies, 'myfilter': myfilter}) def RPA_tool(request): if request.method == 'POST': form = RPA_tool_form(request.POST) if form.is_valid(): policyNumber = form.cleaned_data.get('Policy_Number') messages.success(request, f'{policyNumber} Saved') editRPADetails(form) return redirect('/admin_tool/') else: form = RPA_tool_form(initial={'Policy_Number':'Test'}) return render(request, 'admin_tool/RPA_tool.html', {'form':form}) urls.py: from django.urls import path from . import views # from users import views as user_views urlpatterns = [ # path('admin/', admin.site.urls), path('', views.home, name='UW-home'), path('admin_tool/', views.admin_tool, name ='admin_tool'), path('RPA_tool/<str:Policy_Number>/', views.RPA_tool, … -
Page not found at /auth1/Timings/2/ DJANGO
I know that there is somwething wrong with my urls.But unable to figure out.Some one please help in this. models.py class Restaraunt(models.Model): name=models.CharField(max_length=50,blank=True,null=True) class Schedule(models.Model): restaraunt=models.ForeignKey(Restaraunt,on_delete=models.CASCADE,related_name='restaraunt_name') #days=models.CharField(choices=DAYS,max_length=255) opening_time=models.TimeField(auto_now=False,auto_now_add=False) closing_time=models.TimeField(auto_now=False,auto_now_add=False) def __str__(self): return str(self.restaraunt) class Restarasunt(viewsets.ViewSet): def create(self,request): try: name=request.data.get('name') if not name: return Response({"message": "name is rerquired!","success":False}, status=status.HTTP_200_OK ) res_obj=Restaraunt() res_obj.name=name print(res_obj.name) res_obj.save() return Response("Restaurant addedd successfully") except Exception as error: traceback.print_exc() return Response({"message":str(error),"success":False},status = status.HTTP_200_OK) class ScheduleViewSet(viewsets.ViewSet): def create(self,request,pk): try: res_obj=Restaraunt.objects.filter(pk=pk) print('hie',res_obj) data=request.data opening_time=data.get('opening_time') closing_time=data.get('closing_time') sce_obj=Schedule() sce_obj.opening_time=opening_time sce_obj.closing_time=closing_time sce_obj.restaraunt=res_obj sce_obj.save() return Response("") except Exception as error: traceback.print_exc() return Response({"message":str(error),"success":False},status = status.HTTP_200_OK) URLS.PY from rest_framework.routers import DefaultRouter from auth1 import views router=DefaultRouter() router.register(r'retaraunt', views.Restarasunt, basename='Restarasunt') router.register(r'Timings', views.ScheduleViewSet, basename='ScheduleViewSet') urlpatterns = router.urls -
How to display Data in popup modal without using for loop?
I want to display data in the popup, I have a list on products but when a user clicks on the product id then it should be open in popup according to that product id. here is my views.py file... def myview(request): datas=TestForm.objects.all template_name='test.html' context={'datas':datas} return render(request, template_name, context) def myview(request, id): display=TestForm.objects.get(pk=id) template_name='test.html' context={'display':display} return render(request, template_name, context) here is my test.html file... {% for a in datas %} <button type="button" class="btn btn-primary" class="open-modal" data-url="{% url 'myap:list_single' a.id %}" data-toggle="modal" data- target="#exampleModal"> {{a.product_id}} </button> {% endfor %} <!-- Modal --> <div class="extra-div"> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria- labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <tr> <td>{{datas.name}}</td> <td>{{datas.price}}</td> <td>{{datas.category}}</td> </tr> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> here is my jquery which I am writing to display popup according to product id.. var modalDiv = $(".extra-div"); $(".open-modal").on("click", function(){ $.ajax({ url: $(this).attr("data-url") success: function(data) { modalDiv.html(data); $("#exampleModal").modal("show"); } }); }); -
Serializing one to many relationship using ModelSerializer
I am aiming for a nested JSON response. My target output is like so; [ { list_id: <list_id_1>, list_name: <list_name_1>, { item_id: <item_id_1>, item_name: <item_name_1>, }, { item_id: <item_id_2>, item_name: <item_name_2>, } } ] I want to make my output to be a nested JSON. So far this is my progress; models.py class List(models.Model): list_name = models.CharField(max_length=30, blank=True, null=True, default='My List') def __str__(self): return ("List ID: " + str(self.id) + ", " + self.list_name) class Item(models.Model): list = models.ForeignKey('List', related_name='items', on_delete=models.CASCADE) item_name = models.CharField(max_length=30, blank=False, null=False) item_desc = models.CharField(max_length=50, blank=True, null=True) item_category = models.CharField(max_length=20, blank=True, null=True) item_price = models.DecimalField(max_digits=5, decimal_places=2, blank=False, null=False, default=0.00) item_qty = models.IntegerField(blank=False, null=False, default=1) is_complete = models.BooleanField(default=False) def __str__(self): return ("Item ID: " + str(self.id) + ", " + self.item_name) @property def item_tot_price(self): return (self.item_price * self.item_qty) serializers.py class ItemSerializer(serializers.ModelSerializer): list_name = serializers.CharField(read_only=True, source = "list.list_name") class Meta: model = models.Item fields = ['id', 'list', 'list_name', 'item_name', 'item_desc', 'item_category', 'item_price', 'item_qty', 'is_complete', 'item_tot_price'] views.py class ItemListAPIView(generics.ListAPIView): serializer_class = serializers.ItemSerializer def get_queryset(self): """ This APIView should return a list of all the items that are related to a List as determined by the list portion of the URL. """ list = self.kwargs['list'] return models.Item.objects.filter(list__id=list) urls.py urlpatterns = … -
Subclassing a vanilla django view
I'd like to add one line to the LoginView that comes with django. I know how to do this via subclassing, but I have a feeling that I don't need to replicate all of the code in the view that I want to subclass. The only line that I've added is the second last line in this view. 100% of the rest of the code in this view is identical to the django vanilla LoginView. What is the most efficient way to subclass this view and add this one line of code? class CustomLoginView(LoginView): """ Display the login form and handle the login action. """ form_class = AuthenticationForm authentication_form = None redirect_field_name = REDIRECT_FIELD_NAME template_name = 'registration/login.html' redirect_authenticated_user = False extra_context = None @method_decorator(sensitive_post_parameters()) @method_decorator(csrf_protect) @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): if self.redirect_authenticated_user and self.request.user.is_authenticated: redirect_to = self.get_success_url() if redirect_to == self.request.path: raise ValueError( "Redirection loop for authenticated user detected. Check that " "your LOGIN_REDIRECT_URL doesn't point to a login page." ) return HttpResponseRedirect(redirect_to) return super().dispatch(request, *args, **kwargs) def get_success_url(self): url = self.get_redirect_url() return url or resolve_url(settings.LOGIN_REDIRECT_URL) def get_redirect_url(self): """Return the user-originating redirect URL if it's safe.""" redirect_to = self.request.POST.get( self.redirect_field_name, self.request.GET.get(self.redirect_field_name, '') ) url_is_safe = url_has_allowed_host_and_scheme( url=redirect_to, allowed_hosts=self.get_success_url_allowed_hosts(), require_https=self.request.is_secure(), … -
Accessing Django admin on deployed site
During the development of my app I was able to login to the Django back-end via /admin or /api/admin, however I have recently deployed the app and can no longer access it. -
Django: All static files on dedicated server
The django-documentation says Push your local STATIC_ROOT up to the static file server into the directory that’s being served. If I read it correctly, there is no information on how to actually tell Django where to load every single static file. How do you define this location? My other naive idea is to completely avoid Django's collectstatic and hard-code the URLs for .CSS-, .JS-files (images too) in my base-template: <!DOCTYPE html><html> {% load i18n %} <head> <meta charset="utf-8" /> <link rel="stylesheet" type="text/css" href="https://my_server.com/stylesheet.css" /> </head> <body> <header><img src="https://my_server.com/header.png" alt="header" /></header> Benefit: You don't need to collectstatic anymore. Why aren't users encouraged to do it that way? What do you suggest for loading every static file from a dedicated server? -
django-cors-headers not work in for patch method
INSTALLED_APPS = [ # default django apps 'jazzmin', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Optional: Django admin theme (must be before django.contrib.admin) 'rest_framework', 'rest_framework_simplejwt.token_blacklist', 'corsheaders', 'treebeard', 'UserAccount.apps.UseraccountConfig', 'CompanyInfo.apps.CompanyInfoConfig', 'Backup.apps.BackupConfig', 'FinancialPeriod', 'Inventory.apps.InventoryConfig', 'Product.apps.ProductConfig', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = False default_headers = ( "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with", ) CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] django == 3.1 django-cors-headers == 3.5.0 Everything is normal, but just patch method is not work !! all methods work just and just patch method return Access to XMLHttpRequest at ... from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. -
How to edit output in Django ListView before passing to template
So I have a Django ListView that looks like class FirePageView(ListView): model = MyModel template_name = 'page.html' context_object_name = 'my_list' ordering = ['-timestamp'] So can I render a table just fine and everything is working there. However, I want to apply a transformation, for example changing all the timestamps from UTC to EST before sending it to the template. This way the template shows the times in EST but not UTC. How can I edit what the ListView passes into the template? -
Why Django Rest framework is decoding access token even tough classPermissions is empty list
I am a newbie to Django rest framework. What have done so far is as follows: my api view: @api_view(['POST']) @permission_classes([]) def loginUser(request): username=request.data['email'] password=request.data['password'] credentials = { 'email': username, 'password': password } user = authenticate(**credentials) And then in settings.py # https://jpadilla.github.io/django-rest-framework-jwt/ JWT_AUTH = { 'JWT_RESPONSE_PAYLOAD_HANDLER':'authApp.customJWTUtils.jwt_response_payload_handler', 'JWT_VERIFY_EXPIRATION': True, 'JWT_LEEWAY': 1000, 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=30), 'JWT_AUTH_HEADER_PREFIX': 'JWT', 'JWT_AUTH_COOKIE': None, 'JWT_PAYLOAD_HANDLER':'authApp.customJWTUtils.jwt_payload_handler', } Now when I am doing following things in postman Case 1: POST request { "email":"email", "password":"password" } No header in request then it gives me 200 Case 2: But when I send above same post body, along with Access token it gives me 401 un-authorized. Can anyone tell how I can make case 2 give me 200 status -
SQL query "translated" to one that Django will accept, anyone? Please (python)
Can anyone "translate" this MySQL query to Django chain or Q(). This is just an example (but valid) query, but I want to see it with my own eyes, because Django documentation doesn't look very noob friendly in this aspect and I couldn't get those chains and stuff to work. mysql -> SELECT position, COUNT(position) FROM -> (SELECT * FROM log WHERE (aspect LIKE 'es%' OR brand LIKE '%pj%') -> AND tag IN ('in','out')) AS list -> GROUP BY position ORDER BY COUNT(position) DESC; While I think chaining filters would be more convenient for me in the future, this below just seems way more straightforward at the moment. query = "the query from above" cursor.execute(query) [new_list.append([item for item in row ]) for row in cursor] ...or should I just quit() -
How to get table row values in a javascript function from a dynamically created table using for loop in django?
So basically, I am passing a context from views to my template. In my template I am using 'for loop' to view the context in a tabular form and also attaching a button for every table row. When that button is clicked, I want to call a javascript function(that has ajax call). I need to get values of row elements for that particular row to use in my function. My view function: def asset_delivery(request): deliverylist = Delivery.objects.filter(status='Added to Delivery List') context = {'deliverylist': deliverylist} return render(request, 'gecia_ass_del.html', context) So far I tried passing those values as parameters in the following way. My html template table: <table class="table"> <thead style="background-color:DodgerBlue;color:White;"> <tr> <th scope="col">Barcode</th> <th scope="col">Owner</th> <th scope="col">Mobile</th> <th scope="col">Address</th> <th scope="col">Asset Type</th> <th scope="col">Approve Asset Request</th> </tr> </thead> <tbody> {% for i in deliverylist %} <tr> <td id="barcode">{{i.barcode}}</td> <td id="owner">{{i.owner}}</td> <td id="mobile">{{i.mobile}}</td> <td id="address">{{i.address}}</td> <td id="atype">{{i.atype}}</td> <td><button id="approvebutton" onclick="approve({{i.barcode}},{{i.owner}},{{i.mobile}},{{i.address}},{{i.atype}})" style="background-color:#288233; color:white;" class="btn btn-indigo btn-sm m-0">Approve Request</button></td> </tr> {% endfor %} </tbody> </table> The table is displayed perfectly but the button or the onclick or the function call does not seem to work. My javascript function: <script> function approve(barcode2, owner2, mobile2, address2, atype2){ console.log('entered approved'); var today = new Date().getFullYear()+'-'+("0"+(new Date().getMonth()+1)).slice(-2)+'-'+("0"+new Date().getDate()).slice(-2); … -
Mandrill Reply-To header is not received
I need to add a Reply-To header to messages that I'm sending with mandrill app. I've used MailMessage from django.core.mail to create a message. email_msg = EmailMessage( subject=my_subject, body=my_body, from_email=settings.DEFAULT_FROM_EMAIL, to=[email], headers={ "X-MC-Metadata": json.dumps( { ...some metadata } ), "X-MC-Tags": "my_tag", "Reply-To": "my_reply_to_address@gmail.com", }, ) But when I receive the message sent this way there's no Reply-To header and reply sets just from_email as a reply address. -
How can I remove this Error in Django models.py
I created a amount field in models.py, I run python manage.py makemigrations and python manage.py migrate It gave me error ValueError: Field 'amount' expected a number but got ''. then I removed this amount field line from my code and again did makemigrations and migrate command. now again it it showing same error. when I open Django admin page and select my model name which is Orderss . It gives me error that there is no filed name amount class Orders(models.Model): order_id = models.AutoField(primary_key = True) items_json = models.CharField(max_length=5000) name = models.CharField(max_length=20) # amount = models.IntegerField(default=0) email = models.CharField(max_length=20) address = models.CharField(max_length=50) city = models.CharField(max_length=20) state = models.CharField(max_length=20) zip_code = models.IntegerField(max_length=6) phone = models.IntegerField(max_length=12, default="") def __str__(self): return self.name -
i want to compare email and password with the email & password that i saved in my database in django. please guys help me
1.my views.py 2.i want to compare email and password with the email & password that i saved in my database in django. please guys help me Basically i am creating login signup with the help of models and models data def shoplogin(request): if request.method == 'POST': username = request.POST['loginemail'] password = request.POST['loginpass1'] shopLogin = shop_registration.objects.all() username1 = shopLogin.email password1 = shopLogin.pass1 if username == username1 and password == password1: messages.success(request, "Success") print("login seccess") return redirect('createyourshop') else: messages.error(request, "login failed") print("login failed") return redirect('createyourshop') return HttpResponse('shoplogin') 'these are my models tables' #my models.py class shop_registration(models.Model): name = models.CharField(default='', max_length=30) email = models.EmailField(default='', max_length=60) #compare this email to 'loginemail' mobile_number = models.CharField(max_length=12, default='') pass1 = models.CharField(default='', max_length=20) #compare this pass1 to 'loginpass1' pass2 = models.CharField(default='', max_length=20) def __str__(self): return self.name -
How to make a ranged for loop that iterates over elements in a list in Django
I'm fairly new to Django 3, but I could not find any answer that shows the best way to use Django template syntax in order to iterate over the first five elements in a list given in the context. For clarification, what I'm looking for is a way to do this: (given the following list in the context["one", "two", "three", "four", "five", "six"]) I want to display the first five elements in a way similar to this vanilla Python code: for item in range(5): print(list[item]) I would even appreciate it if someone could try and show my how to break a loop in the templates (if it's even possible). Is there a way to do any one of these? -
Controlling modal at django
I want a modal which has information about the dog without refreshing. This is the procedure. Upload the picture click the predict button I want to to run the views.py predict function get the information from the predict function show the information at the opened modal. I tried the ajax but it doesn't work.... -
How to sum variabiles in Jinja template
I want to print sum of two values in jinja in the last table data tag {% for product in invoice.all %} <tr> <td>{{product.quantity}}</td> <td>{{product.unit_price}}</td> <td>{{product.quantity + product.unit_price}}</td> </tr> {% endfor %} What is the proper way of doing this. Thanks in advance -
IntegrityError at /notes/create/ NOT NULL constraint failed: notes_notes.author_id
I am trying to make a notes app. But I am having an error. I am new in django. I am actually practicing what i learn but running through errors and cannot get help from anywhere. i dont know what is missing here in my code. can you guys help me. I shall be very thankful to you. notes/models.py class Notes(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=150) essay = models.TextField() create_date = models.TimeField(default = timezone.now) def __str__(self): return self.title def get_absolute_url(self): return reverse("notes:notes_detail", kwargs={"pk": self.pk}) notes/forms.py class NotesForm(forms.ModelForm): class Meta: model = Notes fields = ("title","essay") widgets ={ 'title' : forms.TextInput(attrs={'class':'form-control'}), 'essay':forms.Textarea(attrs={'class':'editable medium-editor-textarea form-control'}) } def __init__(self,*args, **kwargs): super().__init__(*args, **kwargs) self.fields['title'].label = 'Title' self.fields['essay'].label = 'Text' notes/views.py class NotesCreateView(CreateView): form_class = NotesForm model = Notes template_name = "notes/notes_create.html" def form_valid(self, form,*args, **kwargs): form.instance.username = self.request.user return super(*args, **kwargs).form_valid(form) class NotesDetailView(DetailView): model = Notes context_object_name = 'notes' notes/urls.py app_name = 'notes' urlpatterns = [ path ('create/',views.NotesCreateView.as_view(),name = 'notes_create'), path ('detail/<int:pk>',views.NotesDetailView.as_view(),name = 'notes_detail'), ] notes/notes_create.html {% extends 'base.html' %} {% block content %} <div class='container' style='margin-top:20px'> <div class="box box-warning"> <div class="box-header"> <h3 class="box-title">Note</h3> <p style='margin-top:20px'></p> </div><!-- /.box-header --> <div class="box-body"> <form role="form" method='POST'> {% csrf_token %} {{ form.as_p }} <button type="submit" … -
How can we access data stored in django forms?
I am using the following code to get contact number and email from user: Contact_Number = forms.RegexField(regex="[0-9]",min_length=11,max_length=15) email = forms.EmailField(required=True) Is there any way to access the user contact number, using the user name later on. I am able to excess email using the "user.email" but not the contact number. -
How to post data edit and resubmit the data in python django using Javascript Fetch Function?
In my project, the user enters their post (or comments) in the post field and if he/she wants their re-edit the post, click the edit button and data will present in the Textarea field (using javascript). In Textarea, the user wants to reedit the data and submit it. In My doubt is, when I click the edit button the textarea will present and data also editable but it will not post in the database while I am using the fetch function( my target is without refresh the entire page the data will post using javascript fetch function)and also data-id not passing to the javascript function. Kindly help in this regard. index.html <div class="row"> <div class="col-md-12"> <div class="card shadow-lg"> <div class="card-body"> <div class="row"> <div class="col-md-6"> <h5 class="card-title"><i class="fa fa-user-circle" aria-hidden="true"></i> <a href="{% url 'profile' datas.id %}">{{datas.user_id|capfirst}}</a></h5> </div> <div class=" col-md-6 text-right" > {% if request.user.id == datas.user_id_id %} <!--<button id="edit" value="{{datas.post}}" onclick="edit(this)">Edit</button> --> <button class="btn btn-sm btn-outline-primary" value="{{datas.post}}" onclick="edit(this)">Edit</button> {% endif %} </div> </div> <div id="msg"> <hr> {{datas.post}} <hr> </div> <div class="row"> <div class="col-md-4"><i class="fa fa-thumbs-up"></i></div> <div class="col-md-4"></div> <div class="col-md-4 text-right">{{datas.post_date}}</div> </div> </div> </div> </div> </div> <br> {% endfor %} **inbox.js** function edit(id) { //var body = event.value; var notes = … -
How to display image in modelformset_factory in Django
I have following model where Im using image field: from django.db import models class ActiveManager(models.Manager): def active(self): return self.filter(active=True) class Offer(models.Model): name = models.CharField(max_length=255) url = models.URLField(blank=True) image = models.ImageField(verbose_name='Banner Image', upload_to='offers', blank=True) active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = ActiveManager() def __str__(self): return self.name def get_url(self): return self.url def get_image(self): return self.image.url def is_active(self): return self.active I want to edit multiple forms on the go so I userd modelformset_factory: Here is the view: from django.shortcuts import render, redirect from django.forms import modelformset_factory from .models import Offer # Create your views here. def offers(request): OfferFormSet = modelformset_factory(Offer, fields=( 'name', 'url', 'image', 'active' )) formset = OfferFormSet() if request.method == 'POST': formset = OfferFormSet(request.POST, request.FILES) if formset.is_valid(): formset = formset.save(commit=False) for form in formset: form.save() return redirect('offer:offers') context = {'formset': formset} return render(request, 'offers.html', context) Now in the html Im trying to display the image of already existing instance but I couldn't figure out how to do so, Here is an HTML {% extends 'base.html' %} {% block content %} <style> .form-div{ display: flex; flex-grow: 1; margin: 10px 20px; padding: 20px; border-radius: 10px; box-shadow: 0 0 3px 3px rgba(0, 0, 0, 0.1); } </style> <form method="post" enctype="multipart/form-data"> … -
binascii.Error: Incorrect padding in django ?- when redirected to django adminsitration page
I was doing a project in django. I added crispy template pack and some bootstrap to project after sometime when i tried to redirect to django administration page suddently its showing a padding error [like this][1] if someone happen to have this error please tell how you solved it. [1]: https://i.stack.imgur.com/k1QWx.jpg -
'tuple' object has no attribute '_meta' on post request ajax django
I got a problem with ajax post request in my django view. My have viewed this one json fail in django ('tuple' object has no attribute '_meta') but seem like I can't find the solution from it. Can you spot me the mistake? Django version = 3.1, Python = 3.8.3 # view.py def teacherRegisterView(request): template_name = "app/register.html" if request.is_ajax and request.method == "POST": form = TeacherRegisterForm(request.POST) if form.is_valid(): instance = form.save() ser_instance = serializers.serialize('json', [instance, ]) <- error on this line return JsonResponse({'instance': ser_instance}, status=200) else: return JsonResponse({'error': form.errors}, status=400) return JsonResponse({'error': ""}, status=400 #my script {% block javascript %} <script> $("form-teacher").submit(function (e) { e.preventDefault(); var serializedData = $(this).serialize(); $.ajax({ type: "POST", url: "{% url 'teacher_register' %}", data: serializedData, success: function (response) { $("#form-teacher").trigger("reset"); }, error: function (response) { alert(response["responseJSON"]["error"]); }, }); }); </script> {% endblock %} error from the terminal Internal Server Error: /teacher-register Traceback (most recent call last): File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/muongkimhong/Developments/itc-attendance/attendance/account/views.py", line 53, in teacherRegisterView ser_instance = serializers.serialize('json', [instance, ]) File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/core/serializers/__init__.py", line 128, in serialize s.serialize(queryset, **options) File "/Users/muongkimhong/Developments/itc-attendance/env/lib/python3.8/site-packages/django/core/serializers/base.py", line 94, in serialize concrete_model = obj._meta.concrete_model AttributeError: 'tuple' … -
Only some static files not displaying on Django / Apache stack
Trying to figure out how in the world all my images are loading fine with the exception of a few on one of my templates. Keep in mind, all of this works perfectly in dev mode, but when I moved this to an Apache server, this is what happened. Here is my site that you can see for yourself: http://13.56.18.7/ my file structure: If you look on the Homepage (/ directory) it is missing the main image, and 2 other images directly below that. Also many of the styles are missing. But, all images below this are showing up just fine. Here is the HTML in question: {% extends "base.html" %} {% load static %} {% block contentHome %} <style> .parallax { /* The image used */ background-image: url("{% static 'images/FrontMain-2.png' %}"); /* Set a specific height */ height: 300px; /* Create the parallax scrolling effect */ background-repeat: no-repeat; background-size: cover; } </style> <!-- Container element --> <div class="parallax" style="position: relative;"> <div alt="buttonsDiv" style="right: 35px; bottom: 55px; position: absolute;"> <a href="tel:+1-714-605-2950"><button style="margin-right: 20px;" type="button" class="btn btn-primary btn-lg"><i class="fa fa-phone fa-lg"></i>&nbsp; 714-605-2950</button></a> <a href="{% url 'services_page' %}"> <button type="button" class="btn btn-primary btn-lg"><i class="fa fa-wpforms fa-lg"></i>&nbsp; Contact Form</button></a> </div> </div> This same …