Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework drf-yasg disable alphabetical urlpatterns endpoints
How to disable alphabetical or sort endpoints like in URLs file Example I have my profile app urls and main urls # profile app urls.py router = routers.DefaultRouter() router.register('profile', views.ProfileViewSet) router.register('profile_two', views.ProfileViewSetTwo) router.register('contats', views.ContactsViewSet) urlpatterns = [ path('', include(router.urls)) ] # main urls.py schema_view = get_schema_view( openapi.Info( default_version='v1', ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path('api/', include('profile.urls')), path('', schema_view.with_ui( 'swagger', cache_timeout=0), name='schema-swagger-ui') ] I want the endpoints to be ordered as in the profile app, but drf-yasg sorts alphabetical Any ideas or suggestions? -
Is passing `user_id` in every view is good ( safe ) or bad?
I am Building a BlogApp and I was afraid of thinking about the passing user_id in every view is Bad or Not. Because i am passing user_id in almost every of my views like :- views.py 1. def new_blog_post(request,user_id): 2. def open_blog_post(request,user_id): 3. def all_blog_posts(request,user_id): 4. def user_profile(request,user_id): 5. def delete_blog_post(request,user_id): Above -----^ are all the views in my app. I am passing user_id in all my views and others. Question Is it good to having user_id in every view ? What have i tried I tried in many websites and searched about it BUT i found nothing on this Topic. Any help would be Appreciated. Thank You in Advance -
How to do a multiplication based on a ForeignKey in django
Hello guys i have this 2 models in django, and has you can see im overriding the save() method because i want the atribute valor_a_receber to be based on a basic multiplication with a foreignkey value Here is my source code: from django.db import models from accounts.models import Vendedor class Comissao(models.Model): porcentagem = models.FloatField() def __str__(self): return str(self.porcentagem) class Venda(models.Model): vendedor = models.ForeignKey(Vendedor, on_delete=models.DO_NOTHING) comissao_venda = models.ForeignKey(Comissao, null=True, on_delete=models.DO_NOTHING) data_venda = models.DateField(auto_now_add=True) valor_venda = models.FloatField() descricao_venda = models.CharField(max_length=60) valor_a_receber = models.FloatField(blank=True, null=True) def save(self, *args, **kwargs): self.valor_a_receber = (self.comissao_venda * self.valor_venda) super().save(*args, **kwargs) def __str__(self): return str(self.vendedor) Any Help is appreciated! -
How can you change Django loop body using javascript?
i was wondering if there is a way i can change the body of for loop in django using javascript each time i press a button. in my case i want to display matches this week and when i press next i want to change the list using javascript and then pass it django template in the regroup part, i want to change the matches list. i know how to write the code to make the new list and the previous and next buttons using javascript but i don't know how to pass it to django template or maybe another way could be to write django code in javascript, anyone can help with either way? in views.py , matches return a list of dictionaries from today to 6 days later def home(request): start = datetime.now().date() end = today + timedelta(6) matches = request_games(today, after_week) return render(request, "sporty/home.html",{ "matches": matches, "start" : start, "end": end }) in home.html {% extends "sporty/layout.html" %} {% load static %} {% block body %} <div class="box"> {{start}},{{end}} {% regroup matches by date as date_list %} {% for date in date_list %} <div class="the_date"> {{date.grouper}} </div> {% for match in date.list %} <div class="match_container"> <div class="status"> … -
Pyhton Django allow upload only videos or other specified extensions
I want to allow django file modol only allow user for upload only specified extensions (mp4, mpg, etc....) How can I do it ? Model.py: class Video(models.Model): my_video = models.FileField(upload_to='uploaded_video/') title = models.CharField(max_length=180) date = models.DateTimeField(auto_now=True) view.py def upload(request): if request.method == 'POST': get_file = request.FILES['up_video'] orginal_file_name = get_file.name fs = FileSystemStorage() fs.save(orginal_file_name, get_file) form = VideoForm(request.POST, request.FILES) form.save() -
Call a function using value from variable
I want to get a model in django using the current url for example a = resolve(request.path_info).url_name context = { 'example' : a.objects.all } here the retrieved url name is available in models This obivously won't work but this is what I want to accomplish -
django use 2 different databases
I want to use django to make a dashboard. The thing is, I want to have one DB for data (that will be displayed on the dashboard) and one DB for Django operations (all the automatic tables Django creates) I saw this answer but when I type manage.py migrate --database=data_db_name then django creates all its automatic table also on that DB, and I dont want that. I only want this DB to be with the data to be displayed on the dashboard. Is it possible? if so, how can I do it? Thanks -
Django, sending a pdf as attatchment breaks with error
I am trying to send a generated pdf file as an email and I get an AttributeEror. The pdf generation routine works fine when I try to show the file in the browser through the response object. It breaks when I try to use it as an attachment. This is how I render: pdflib.py import cStringIO as StringIO from xhtml2pdf import pisa from django.template.loader import get_template from django.template import TemplateDoesNotExist from django.template import Context from django.http import HttpResponse from cgi import escape def render_to_pdf(template_src, context_dict): try: template = get_template(template_src) except TemplateDoesNotExist: template = get_template("pdf_default.html") context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result, encoding="UTF-8") if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return HttpResponse('We had some errors<pre>%s</pre>' % escape(html)) and this is how I try to send: pdf = render_to_pdf(template, {}) { msg.attach("test_result.pdf", pdf,'application/pdf') msg.content_subtype = "html" msg.send() And this is what I get: Traceback: File "/home/chris/.virtualenvs/vitadmin/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/chris/.virtualenvs/vitadmin/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 22. return view_func(request, *args, **kwargs) File "/mnt/c/Users/xpant/Dropbox/workspace/vitadmin/customer/views.py" in email_guide 81. msg.send() File "/home/chris/.virtualenvs/vitadmin/local/lib/python2.7/site-packages/django/core/mail/message.py" in send 303. return self.get_connection(fail_silently).send_messages([self]) File "/home/chris/.virtualenvs/vitadmin/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py" in send_messages 107. sent = self._send(message) File "/home/chris/.virtualenvs/vitadmin/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py" in _send 121. message = email_message.message() File "/home/chris/.virtualenvs/vitadmin/local/lib/python2.7/site-packages/django/core/mail/message.py" in message 267. … -
What is the best way to create make profile for user in Django? When i am extending AbstractUser in models
I am totally confused here. I am working with Django and Django rest framework. I want to create profile for users but i am not understanding. Here is the code I am trying. Thanks for help. from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. from django.conf import settings class CustomUser(AbstractUser): pass class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) bio = models.CharField(max_length=480, blank=True) city = models.CharField(max_length=40) avatar = models.ImageField(null=True, blank=True) def __str__(self): return self.user.username Please help me, Is this a right way to implement this? -
How to load `task_kwargs` from `TaskResult` model in `django_celery_results`?
I'm using django_celery_results to save results of some celery tasks. Each task gets kwargs as input which at the end gets saved in task_kwargs field of TaskResult. Im having trouble loading those kwargs later from the way they get saved in DB. For example this is one entry: "{'config_file_path': '/path/to/configs/some_config.json'}" Simple example of accessing the field value: tkwargs = TaskResult.objects.get(id=1).task_kwargs for which i get the above string. What is a straightforward way to get task_kwargs as a python dictionary instead of that string? -
Django Rest Framework and React Linkedin Social Authentication OAuth2Error
I am building web app with Django Rest Framework as backend and React as frontend. using below libraries Django==3.1.5 djangorestframework==3.12.2 dj-rest-auth==2.1.3 django-allauth==0.44.0 I am trying to implement Linkedin authentication but getting bellow error as mentioned OAuth2Error at /api/v1/appname/linkedin/ Error retrieving access token: b'{"error":"invalid_request","error_description":"Unable to retrieve access token: appid/redirect uri/code verifier does not match authorization code. Or authorization code expired. Or external member binding exists"}' Backend code in django rest framework class LinkedInLoginView(CustomLoginView): """ LinkedIn login """ adapter_class = LinkedInOAuth2Adapter callback_url = "CALL_BACK_URL" client_class = OAuth2Client and frontend code like <LinkedIn clientId="CLIENT_ID" callback={callbackLinkedIn} scope={["r_liteprofile", "r_emailaddress"]} text={rendertext()} className='ant-btn LinkdinIcon ant-btn-link' redirect_uri="CALL_BACK_URL" render={renderProps => ( <Button type="link" className="LinkdinIcon" onClick={renderProps.onClick}> <LinkdinIcon /></Button>)} and CALL_BACK_URL which is already added under redirect urls in linkedin developers. We have Backend running in different domain and frontend is running on different domain. Can anybody please help me to understand what would be CALL_BACK_URL in backend and what would be in frontend ? If anybody can share some reference links or code would be appreciated. -
Django Didn't ask for password_reset_confirm template
I am following Corey Schafer Video lecture >> Password Reset Email urls.py from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('profile/', user_views.profile, name='profile'), path('register/', user_views.register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='users/password_reset.html'), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='users/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) AND CREATED 3 HTML FILE for these routes but as per his lecture >> then he hit button (request reset password) he's getting error like noReverseMatch Reverse for 'password_reset_confirm' bla bla bla then he created another route to handle this which is ('password-reset-confirm///') but in my case when i hit button request reset pasword it throw me to this route "password-reset/done/" (with no error ,no email has been sent ) settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = config.EMAIL EMAIL_HOST_PASSWORD = config.PASS -
I want to accept parameter from url in django rest framework and save it in model
Creating a role based application using django rest framework. I want to add user based on their roles.I am getting role from url path("create-profile/<str:role>",views.create_profile), I want to add this role to groups field. def create_profile(request,role): serializer = CreateProfileSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(parent_id = request.user.username) return Response("Profile Created Successfully.") If I am trying to use below code before or after serializer.save() serializer.groups.add(Group.objects.get(name = role)) Its giving me below error AttributeError: 'CreateProfileSerializer' object has no attribute 'groups' I have also tried to pass keyword argument as I did for parent_id it is also not working. -
Pass extra context to template
I am trying to output a list of movies generated from a search result but when those movies are shown, I also want to show either an "add to list" or "remove from list" button depending on if the user already has that movie in their list. I have already been able to show all the movies but I am having trouble getting the user.id and movie.imdb_id into the extra context in my views.py {% for movie in object_list %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ movie.director }}</a> <small class="text-muted">{{ movie.country }}</small> </div> <h2><a class="article-title" href="{% url 'movie-detail' movie.imdb_id %}">{{ movie.title }}</a></h2> <p class="article-content">{{ movie.duration }}</p> {% if user.is_authenticated %} <button>Remove From List</button> <button>Add to List</button> {% endif %} </div> </article> {% endfor %} views.py class SearchResultsView(ListView): model = Movie template_name = "search/results.html" paginate_by = 5 def get_queryset(self): query = self.request.GET.get('q') object_list = Movie.objects.filter(Q(title__icontains=query)) return object_list def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['query'] = self.request.GET.get('q') return context I want to put a line like SavedMovie.objects.filter(user_id=user.id).filter(movie_imdb_id=object.imdb_id).exists() and make it run for each movie in object_list but I don't know how to do that in views.py and how to show it in the template -
Conditional statements in Djago_tables2 class definition
I am trying to change formatting of my table rows based on one of my object values. I know how to pass row attributes to my template, but don't know how to use current record when deciding how should my row look like in class definition. See below: class OrderTable(tables.Table): my_id = tables.Column(verbose_name="Order number") status = tables.Column(verbose_name="Order status") class Meta: model = Order row_attrs = { "class": lambda record: record.status } This is what I did read in django_tables2 docs. However- When trying to add some 'if's' it seems to return lambda function object instead of value: class OrderTable(tables.Table): my_id = tables.Column(verbose_name="Order number") status = tables.Column(verbose_name="Order status") class Meta: model = Order print(lambda record: record.status) if lambda record: record.status = '0': row_attrs = { "class": "table-success" } else: row_attrs = { "class": "" } What prints in my log is: <function ZamTable.Meta.<lambda> at 0x000001F7743CE430> I also do not know how to create my own function using 'record' attribute. What should I pass to my newly created function? class OrderTable(tables.Table): my_id = tables.Column(verbose_name="Order number") status = tables.Column(verbose_name="Order status") class Meta: model = Order def check_status(record): record = record.status return record status = check_status(???) if status = '0': row_attrs = { "class": … -
Modify AJAX call ONLY to avoid Django TypeError: is not JSON serializable?
I'm trying to make an AJAX call to a Django backend service (an installation of Apache Hue, though I think that's irrelevant to this question) and always getting the error below, even though I'm submitting exactly the same request body as the web interface makes, and that works. So I'm trying to work out what's wrong in the AJAX request, I believe if I can get that correct, it will work. Error: Exception Type: TypeError at /hue/notebook/api/execute/hive/ Exception Value: <desktop.appmanager.DesktopModuleInfo object at 0x2f37250> is not JSON serializable The other answers on SO and elsewhere I've seen for this error message all talk about modifying the Django code in some way. I can't do that as it's installed in a shared corporate environment. As the web interface requests work, it must be possible to do an AJAX call that replicates these but I can't seem to get it right. The web interface posts this formdata: snippet: {"id":"0329123d-c43b-b03e-8f8d-917e201e3f0d","type":"hive","status":"running","statementType":"text","statement":"SELECT 3;","aceCursorPosition":{"column":9,"row":0},"statementPath":"","associatedDocumentUuid":null,"properties":{"files":[],"functions":[],"arguments":[],"settings":[]},"result":{"id":"b811aebf-9e9b-0707-8dbc-8a9d58a239cb","type":"table","handle":{"has_more_statements":false,"statement_id":0,"statements_count":1,"previous_statement_hash":"f985bc4dd58ed59865bf4921631d1e7243c51bae06789de8d9020f2c"}},"database":"default","wasBatchExecuted":false} Which is accepted by the server. However when I try and replicate that with the following AJAX call I get the JSON error (ignore ID values being different, it's the format): $.ajax({ url: "notebook/api/execute/hive/", type: 'POST', data: {"snippet": {"id":"0329123d-c43b-b03e-8f8d-917e201e3f0d","type":"hive","status":"running","statementType":"text","statement":"SELECT 3;","aceCursorPosition":{"column":9,"row":0},"statementPath":"","associatedDocumentUuid":null,"properties":{"files":[],"functions":[],"arguments":[],"settings":[]},"result":{"id":"b811aebf-9e9b-0707-8dbc-8a9d58a239cb","type":"table","handle":{"has_more_statements":false,"statement_id":0,"statements_count":1,"previous_statement_hash":"f985bc4dd58ed59865bf4921631d1e7243c51bae06789de8d9020f2c"}},"database":"default","wasBatchExecuted":false}}, success: function(data) { … -
Django, SMTP AUTH extension not supported by server on different machine
I have encountered interesting problem. I have lets just say, that kind of EMAIL settings: EMAIL_HOST = "my.email.host" EMAIL_HOST_USER = "my@user.com" EMAIL_HOST_PASSWORD = "my_password" FROM_EMAIL = "From <my@user.com>" EMAIL_PORT = 25 EMAIL_USE_TLS = False When I try to send some kind of email from my local computer: from django.core.mail import EmailMessage msg = EmailMessage("Subject", "Test", to=['example@mail.com']) msg.send() I successfully send this email message. However, when I host this django application on my remote server, code above gives this error: File "<console>", line 1, in <module> File "/home/example_project/envs/example_project/lib/python3.7/site-packages/django/core/mail/message.py", line 276, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/example_project/envs/example_project/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/home/example_project/envs/example_project/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 69, in open self.connection.login(self.username, self.password) File "/usr/lib/python3.7/smtplib.py", line 697, in login "SMTP AUTH extension not supported by server.") smtplib.SMTPNotSupportedError: SMTP AUTH extension not supported by server. Why this is happening? My remote server has telnet access to address and port of this email server. Remote server has same settings as my local computer. Why it throws error while my local computer doesn't? -
Auth0 functionality for my Django project
I am trying to build a website where I have auth0 domain: https://sellercentral-europe.amazon.com/apps/authorize/consent?application_id=amzn1.sp.solution.5ea65d4afad-4d55-9751-fc0dc0aabsbakacaa8b8&version=beta Here the user will go for the authorization and after the authorization the uri will become like below https://d2yzyfnnpjylxu.cloudfront.net/index.html?amazon_callback_uri=https://amazon.com/apps/authorize/confirm/amzn1.sellerapps.app.2eca283f-9f5a-4d13-b16c-474EXAMPLE57&amazon_state=amazonstateexample&selling_partner_id=A3FHEXAMPLEYWS and from this url, I want to store the information of amazon_callback_uri, amazon_state and selling_partner_id. -
How do you get info from views and redirect it to another API on ajax (django framework)
I'm pretty new to ajax and javascript overall. Work is done on django framework. I ran into a problem. Here's the start of the code, basically calling ajax function, checking info, if ok, do another ajax call, if that is ok, being doing work. I can't show more due to confidentiality, sorry. return $.ajax( { url : '/documents/check_pdf_availability/{0}'.format(getID()), success : function ( data ) { if(data["answer"]) { return $.ajax({ url: '/documents/get_providers/{0}'.format(getID()), success: function (data) { if(data.providers.length == 1){ What I need to do next (no matter if there is one or more providers), is get the provider name, call a function which does some work with the data (based on the provider name if there is more than one, provider chosen through a popout), get the changed data and then send that data to an outside API, which will send me back a URL, I need to redirect to that URL. How do I approach that? Didn't find an answer on the web -
How should Python virtual environment be handled on Azure?
Background I want to set up an Azure Web Service with Django. On my local machine that app runs error-free in a virtual environment. (The virtual environment name, deploydjango, is indicated leftmost in my prompt - after activating using source deploydjango/bin/activate in repo root folder - before starting the Django server). The virtual environment is "documented" by pip freeze > requirements.txt. (As I am aware of this answer I git push'ed from my local machine to my GitHub repository with the virtual environment. activated. Question How come that Azure creates another virtual environment, antenv? Would it be right to edit the appropriate line of the Oryx manifest (Azure project root /oryx-manifest.toml) from virtualEnvName="antenv" to virtualEnvName="deploydjango" Or put in other words: Do I need to deploy my virtual environment? -
return elements from OnetoOne and ForeignKey Query using Django
I have the three tables below and i am trying to write a query(or multiple queries) that would return all the address and events fields from their respective tables. class Activity(models.Model): name = models.CharField(max_length=50) description = models.TextField(max_length=500) class Event(models.Model): date = models.DateField() start_time = models.TimeField() duration = models.PositiveSmallIntegerField() activity = models.ForeignKey(Activity, on_delete=models.CASCADE, related_name="activities") class Address(models.Model): event = models.OneToOneField(Event, on_delete=models.CASCADE, primary_key=True) address = models.CharField(max_length=100) This is what i tried but it does not seem to be appropriate, it crashes! adds = Address.objects.all() for ad in adds: for events in ad.event.all(): print("events", events) is there a better way to do it? how can i achieve it? Thanks -
React Axios call in componentDidMount()
I am trying to build a 'DataLoader' component that calls a Django Rest API via Axios and for testing purposes shows the results of the API call in an . The query terms are being generated in a parent component and passed via props. Initially, the API is called with the query terms manufacturer & model_name both being blank. This part works, after the initial render I can see a that shows all the expected results. When the parent component passes new query terms via props to the 'DataLoader' component, the render() function is being executed, as I can see the <ul><li>Data {this.props.selectedManufacturer}</li><li>Data {this.props.selectedModels}</li></ul> part being executed and re-rendered correctly. However, it seems that the componentDidMount() function with the Axios part is not being called again. How do I get React to call Axios again once new props have been passed from the parent component to the 'DataLoader' component? import React from 'react'; import axios from 'axios'; import { getDefaultNormalizer } from '@testing-library/react'; class DataLoader extends React.Component { state = { cars: [] } componentDidMount(props) { axios.get(`http://127.0.0.1:8000/firstdraft/api/data?manufacturer=${this.props.selectedManufacturer}&model_name=${this.props.selectedModels}`) .then(res => { const cars = res.data; this.setState({ cars }); console.log(this.state.cars) } ) } render(){ return( <> <h1>Top Selling Cars</h1> <ul>{this.state.cars.map(car => <li> … -
Django - Creating a checklist form
I've been working on a little side project for a while and I've gone into a deep hole. I'm hoping for some guidance from people who have been in the Django world longer than I. Currently, I'm working on a simple maintenance form, where we have a Model Maintenance_Items (which holds just a ID, Name and Description). I have a second model, which CheckList model, that use a ForeignKey from Maintenance_Items and has a BooleanField to mark an item as compliance that day. Note, I capture CreatedDate under my CommonInfo fields. class Maintenance_Item(CommonInfo): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, unique=True) name_description = models.CharField(max_length=255) class MaintenanceCheckList(CommonInfo): id = models.AutoField(primary_key=True) item = models.ForeignKey(Maintenance_Item, on_delete=models.CASCADE) is_compliant = models.BooleanField I'm looking for a way to generate a form, and I was thinking Formsets would be the answer, where a Form is generated for each Item in Maintenance Item with the Item Name prefilled. Where a user can quickly mark the item as compliance. But, i'm stuck where to begin and have been reading over all the formsets documentation. I'm hoping someone could provide some guidance. -
insert additional attributes during put-as-create requests (generic)
So I have a mixin like this. class PutAsCreateMixin: """ The following mixin class may be used in order to support PUT-as-create behavior for incoming requests. """ def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object_or_none() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) if instance is None: if not hasattr(self, 'lookup_fields'): lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field lookup_value = self.kwargs[lookup_url_kwarg] extra_kwargs = {self.lookup_field: lookup_value} else: # add kwargs for additional fields extra_kwargs = {field: self.kwargs[field] for field in self.lookup_fields if self.kwargs[field]} serializer.save(**extra_kwargs) return Response(serializer.data, status=status.HTTP_201_CREATED) self.perform_update(serializer) return Response(serializer.data) def partial_update(self, request, *args, **kwargs): kwargs['partial'] = True return self.update(request, *args, **kwargs) def get_object_or_none(self): try: return self.get_object() except Http404: if self.request.method == 'PUT': # For PUT-as-create operation, we need to ensure that we have # relevant permissions, as if this was a POST request. This # will either raise a PermissionDenied exception, or simply # return None. self.check_permissions(clone_request(self.request, 'POST')) else: # PATCH requests where the object does not exist should still # return a 404 response. raise I subclass this mixin to do put-as-create operations like this. class OverwritePutDestroyView(PutAsCreateMixin, MultipleFieldMixin, PutDeleteAPIView): queryset = Overwrite.objects.all() permission_classes = [IsAuthenticated, ManageRoles, EditOverwrites] serializer_class = OverwriteSerializer lookup_fields = ['channel_id', 'role_id'] path('channels/<int:channel_id>/permissions/<int:role_id>/', views.OverwritePutDestroyView.as_view(), name='overwrites-put-destroy'), However, I … -
DatePicker is not showing in the form
I am building a BlogApp and I am stuck on an Problem. I was building a DatePicker in the form in template. BUT nothing is displaying. What i am trying to do I am trying to build a DateTimePicker in template using Jquery. The Problem DateTimePicker is not displaying in the form in template. I have also put widgets in forms fields but nothing is worked. forms.py class PostForm(forms.ModelForm): date_added = forms.DateTimeField(initial=timezone.now) class Meta: fields = ('date_added') widgets = {'date_added':forms.TextInput(attrs={'class':'datepicker'})} base.html <script type="text/javascript" src="scripts/bootstrap.min.js"></script> <script type="text/javascript" src="scripts/moment-2.4.0.js"></script> <script type="text/javascript" src="scripts/bootstrap-datetimepicker.js"> new_blog_post.html <form method="post" enctype="multipart/form-data" id="formUpload"> {% csrf_token %} {{ form|crispy }} <script> $(function() { $( ".datepicker" ).datepicker({ changeMonth: true, changeYear: true, yearRange: "1900:2012", }); }); </script> <button type="submit">Save Changes</button> </form> I don't know what am i doing wrong. Any help would be appreciated. Thank You in Advance.