Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing kwargs into get_or_create method in Django
I have a model with a custom save function, where I want to perform certain functions based on a condition like this: class ClassName(models.Model): def save(self, *args, **kwargs): reindex = **kwargs.pop("reindex") super().save(*args, **kwargs) if reindex: People.objects.create() Now inside a task I want to call the following: kwargs = { "reindex": False} ClassName.objects.get_or_create(**kwargs) When it does a create, it obviously runs the save function, but it's giving me an error saying reindex is not a field. I have been researching it for a while now and can't figure out what to do. Maybe someone can point me in the right direction. I just want to pass in an argument into the get_or_create, so that I can conditionally perform a certain function in the save method. Thank You in advance! -
Django: How to validate a birthdate entry as over 18
Probably a silly question, but what would be the easiest way of validating a date field form entry as being over 18 years ago in Django? (For a birthdate entry, validating age) -
Django "Lock wait timeout exceeded; try restarting transaction" while saving/updating a model
I'm still a little new to Django, and I'm getting (1205, 'Lock wait timeout exceeded; try restarting transaction') when I try to update my model via the admin interface. Earlier today, it was working, and I've been rolling back changes to the last working version to try to narrow down what seems to be the issue. The problem seems to be it failing to update and timing out. Just editing and hitting save in via the admin interface is triggering this issue. I've disabled any signal handling (post/presave) I had setup, but I think just the UPDATE call after hitting save changes is triggering this issue. I've looked into it and can kill the process after following this link: Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction But it doesn't solve the problem. I can kill the process while it's going, but it's the only running query, and not even a big one at that. The model only has 7 fields, describing VPN servers I'm cataloguing. A show processlist gives me this: updating | UPDATE openvpn_client SET name = 'rsa_test1', local_ip = '2.2.2.2', vpn_ip = NULL, type = The end gets cut off … -
WebSocket connection in django chatting application
i have a chatting application in my Django website project using web faction server, so i followed the multi chat example channels-examples but when i try to connect and create the hard shake i got this error: [Error] WebSocket connection to 'ws://gadgetron.store/Pchat/' failed: Unexpected response code: 404 (x3) settings.py redis_host = os.environ.get('REDIS_HOST', 'localhost') CHANNEL_LAYERS = { "default": { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": {"hosts": [(redis_host, 6379)],}, "ROUTING": "chatbot.routing.channel_routing",},} PP_chat_index.js $(window).load(function() { $messages.mCustomScrollbar(); setTimeout(function() { welcomingMessage(); var ws_path = "/Pchat/"; var webSocketBridge = new channels.WebSocketBridge(); webSocketBridge.connect(ws_path); webSocketBridge.listen(function(data) { if (data.join){ msg = $('.message-input').val(); webSocketBridge.send({ "command": "send", "room": data.join, "message": msg});} else if (data.message){chatMessage(data);}});},100);}); chatbot/routing.py(in the same folder as the settings.pt) routing = [include(chat_routing, path=r"^/Pchat"),] channel_routing = [include("Pchat.routing.websocket_routing", path=r"^/Pchat"),include("Pchat.routing.custom_routing"),] Pchat/routing.py(in the chatting app) websocket_routing = [ route("websocket.connect", ws_connect),route("websocket.receive", ws_receive),route("websocket.disconnect", ws_disconnect),] -
Django-Filter: Dynamically Create Queryset on Search or Hide Queryset until Search
I am using django-filter to search a model. Here is the code: filters.py: class PersonFilter(django_filters.FilterSet): lastName = django_filters.CharFilter(lookup_expr='icontains') firstName = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Person fields = ['lastName', 'firstName'] views.py: def search(request): people = Person.objects.all() people = PersonFilter(request.GET, queryset=people) context = {'filter': people} return render(request, 'myapp/template.html', context) template.html: <form method="get"> {{ filter.form.as_p }} <button type="submit">Search</button> </form> <table> {% for field in filter.qs %} <tr> <td> {{ field.idno }} </td> <td> {{ field.lastName }} </td> <td> {{ field.firstName }} </td> <td> {{ field.status }} </td> </tr> {% endfor %} </table> {% endblock %} </body> </html> Right now, this results in a table that mirrors my model with search boxes for first name and last name. The search works perfectly. How do I prevent the table of data from showing up initially? Logically, this could be done superficially (hide) or, better yet, substantially (dynamically create queryset). Is this possible? -
How to paginate django-filter results from form with Django?
Programming noob here. I have been using the django-filter app to filter models. When I try to use Django's paginator, to paginate from the filtered query, it does not work. All results are put on to one page, although the page numbers are on the bottom. When I click on a different page number, the results are unfiltered at put on to one page. Does any body know a solution to this? views.py from .models import Video from django.shortcuts import render from .filters import VideoFilter from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def search(request): video_list = Video.objects.all() video_filter = VideoFilter(request.POST, queryset=video_list) paginator = Paginator(video_filter.qs, 1) page = request.GET.get('page') try: videos = paginator.page(page) except PageNotAnInteger: videos = paginator.page(1) except EmptyPage: videos = paginator.page(paginator.num_pages) return render(request, 'search/user_list.html', {'filter': video_filter,'videos':videos}) search/user_list.html {% extends 'base.html' %} {% block content %} <form method="post">{% csrf_token %} {{ filter.form.as_p }} <button type="submit">Search</button> </form> <ul> {% for video in filter.qs %} <li>{{ video.title }}</li> {% endfor %} </ul> {% if videos.has_other_pages %} <ul class="pagination"> {% if videos.has_previous %} <li><a href="?page={{ videos.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in videos.paginator.page_range %} {% if videos.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% … -
Run Python Debugger "Standalone" Against Specific Django Module?
Is it possible to run the Python debugger against a specific module in a Django application without running the Django webserver and then executing pdb from within a view or model? I have a MailManager class inside a models.py file that contains some methods for sending emails. I'd like to debug one of these methods without having to run the Django server and then GET/POST the view that would call that method. I tried doing 'pdb myapp/models.py" and it seems to execute the very first command in my model file (which happens to be 'import logging'), but if I do 'dir(MailManager)', pdb tells me it's not defined. Is it possible to debug methods in this model class "standalone" in the way I'm describing? -
git pull bringing extra level in django project
I have a django project in which the project is called projectname, and the inner base directory is also called projectname. This is the norm for django projects. When I run git pull to the server after making changes in my development instance, git inserts the whole top level into that inner projectname directory. Here is a picture before running git pull: projectname - -app1 -app2 -app3 -static -templates -projectname -settings.py -urls.py -wsgi.py -views.py After I run git pull to bring in changes (git pull https://github.com/user/remoterepo), I have this: projectname - -app1 -app2 -app3 -static -templates -projectname -settings.py -urls.py -wsgi.py -views.py projectname - -app1 -app2 -app3 -static -templates -projectname -settings.py -urls.py -wsgi.py -views.py You can see, it has pulled the whole project into the subdirectory. I am running pull in the top directory, not in the subdirectory. In the repository, it looks like the first example, as the project should look, and as it looks in the repository and on my development machine. Why does the git pull process do an extra iteration and bring the whole project into the subdirectory? I have not seen this particular problem in my searches for a solution, so I wonder what I am … -
Detect new entries in django model through ajax
Is there a way I can check for new entries through ajax and update the page appending them to a div? I'm thinking about a situation like this: Client x access the page Client y post a new entry. Client z access the page. For client x, it will display a message: New entry found and a button that can get that entry. For client z, everything it's normal, as for client x before client y submitted a new entry. I haven't figured out how can I do this, actually, I have no idea, so I apologize because I haven't tried anything yet to show you. Thanks in advance for answers! -
Using DJango Models across Apps
Good afternoon, I have seen similar questions but none of the answers really resonate with me. I am new to django development and am trying to get use to the models. My question is how do I utilize a model from one app in another appropriately? For instance, I have a project, Project 1 that consists of the a Person app that manages the users profile. This app has the model for a person, but then that person is used in Activities for the activities they have completed, and another progress in a game. All of these apps need the person to be the key. I am not understanding how to make these relate. Thanks for your help as I become django-ified. -
Django bypasses permissions decorator for user registration and asks for authentication
I'm struggling with registering users for my API service. I've checked the methods and everything is valid, but I still receive an error code when POST'ing user registration data Error Code: {"details": "Authentication credentials not provided"} Settings.py I've added Basic Authentication, IsAuthenticated and TokenAuthentication to the framework REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.BasicAuthentication', ) } The only thing that works currently is obtaining a token for an existing user: Urls.py url(r'^auth/', views.obtain_auth_token, name='get_auth_token'), Other endpoints in Url.py url(r'^login/', Login.as_view(), name='login'), url(r'^register/', Register.as_view(), name='signup'), I believe I'm not using the best practice for user registration or prepares I'm confusing the login with the signup. I'm not sure. Register User method in Views.py # Register User class Register(APIView): queryset = User.objects.all() serializer_class = UserSerializer # permission_classes = [permissions.IsAuthenticated] @permission_classes([permissions.IsAuthenticated, ]) @api_view(['POST', ]) def register_user(self, request, *args, **kwargs): serializer = UserSerializer(data=request.data) if serializer.is_valid(): self.perform_create(serializer) # serializer.save() headers = self.get_success_headers(serializer.data) token, created = Token.objects.get_or_create(user=serializer.instance) return Response({'token': token.key, 'id': serializer.instance.id}, status=status.HTTP_201_CREATED, headers=headers) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Login User method in Views.py queryset = User.objects.all() serializer_class = UserSerializer @api_view(['POST', ]) def login(request): username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return … -
Error from creating profile update in django
I am trying to create a profile update in django application and I got the following error in the browser local variable 'form' referenced before assignment any help would be appreciated. I am confused right now. Below is my views.py. Thanks View.py def update_profile(request): if request.method == 'POST': form = UpdateProfile(request.POST or None, instance=request.user) profile_form = ProfileEditForm(data = request.POST or None,instance=request.user,files=request.FILES) if form.is_valid() and profile_form.is_valid(): form.save() profile_form.save() return redirect('profiles')#HttpResponseRedirect(reverse('index')) else: form = UpdateProfile(instance=request.user) profile_form = ProfileEditForm(instance=request.user) context = { "form": form, "profile_form": profile_form, } template = 'edit.html' return render(request, template, context) Error Trace Traceback: File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/Olar/Desktop/arbithub/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/Users/Olar/Desktop/arbithub/src/profiles/views.py" in update_profile 49. if form.is_valid() and profile_form.is_valid(): Exception Type: UnboundLocalError at /profile/edit/ Exception Value: local variable 'form' referenced before assignment additional codes would be provided based on request. -
Django Closed Socket Error with Repeated AJAX Calls [WinError 10053] An established connection was aborted by the software in your host machine
I'm trying to implement a live search through the jquery plugin Select2 in my Django 1.11.4 project. Running Python 3.6. When I type in the textbox, the server doesn't seem to be able to handle the number of requests and it closes, followed by these series of errors. I've spent a couple hours following a couple threads on SO SO(more) , Google, etc but none have a working solution. I thought it was a python version issue, but I've upgraded from 2.7 to 3.6 and still have it. Any help would be great thanks! This the view that's being called by the ajax call: def directory_search(request): # Query text from search bar query = request.GET.get('q', None) if query: # Searches the DB for matching value customers = Customer.objects.filter( Q(name__icontains= query)| Q(contract_account__icontains= query)| Q(address__icontains= query)| Q(address__icontains= query)| Q(email__icontains= query) ).distinct() # Turns queryset into dict customers = customers.values("contract_account","name") # Turns dict into list customers_list = list(customers) return JsonResponse(customers_list, safe=False) else: return JsonResponse(data={'success': False,'errors': 'No mathing items found'}) This is the js/ajax call for the Select2 plugin: $(".customer-search-bar").select2({ ajax:{ dataType: 'json', type: 'GET', url:"{% url 'portal:directory_search' %}", data: function (params) { var queryParameters = { q: params.term } return queryParameters; }, processResults: … -
How to inject data from db in each templates django?
I have to inject contacts in footer in each my templates. I thought use my own context processor, but I don't know whether to access the database from context processors and join it with context from view. Will you help me? -
How do i display pdf inline using django models
Hello previous question not answered all i want is how to display my pdf file on a template using FileField from the django admin i want to be able to upload only from admin not from a form just from admin. -
Difference between localhost and production
I have this statement on localhost If self.request.user.is_authenticated: And when I am not logged in it does not enter, but in production if it enters Do you know why the difference? -
Django models: Dependent fields
Say I have the following model: class Book(models.Model): due_back = models.DateField(null=True, blank=True) AVAILABILITY = ( ('a', 'Available'), ('o', 'On loan'), ('n', 'Not available'), ('r', 'Reserved'), ) status = models.CharField(choices=AVAILABILITY, blank=True) My problem here is that the two fields due_back and status depend on each other. For example if the book is "on loan" it does not make sense to have a due_back date. The goal is that the book may only have a due_back date if the book is "on loan". But how to do this, are there "best practices" for this kind of problems? -
How i can get object serializer in has_permission (Django)
Sorry for my english. I beginner in django, and i dont understand why it dont work. I create custom permissions. In this permission i need get values of object serializer. For example, its my view: class ProposeFromDealer(generics.CreateAPIView): serializer_class = CatInHouseSerializer permission_classes = (custom_permissions.CheckExistCatInHouse, permissions.IsAuthenticated) my custom permission class CheckExistCatInHouse(permissions.BasePermission): message = 'Cat not exist in this house' def has_object_permission(self, request, view, object): current_house = object.house house = House.objects.get(id=current_house.id) cats_in_house = house.cats.values_list('id') current_cat_id = object.cat.id if current_cat_id in cats_in_house: return True else: return False It method return False if cat doesnt exist in this house and true if exist. But permission success. I can do method like this: def has_permission(self, request, view): but i dont know how i can get object in this method? Like this: class CheckExistCatInHouse(permissions.BasePermission): message = 'Cat not exist in this house' def has_opermission(self, request, view): object = get_serializer_object() #how i can get object ??? current_house = object.house house = House.objects.get(id=current_house.id) cats_in_house = house.cats.values_list('id') current_cat_id = object.cat.id if current_cat_id in cats_in_house: return True else: return False -
Automatic email confirmation by django admin
I want a user email to be automatically confirmed if the admin adds a user. Currently the admin adds a user, next select the newly created user and edit manually to confirm user email. I want this process to be automatic from the admin whenever admin creates a user. accounts/models.py-- 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 from phonenumber_field.modelfields import PhoneNumberField User._meta.get_field('email').blank = False User._meta.get_field('email')._unique = True class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name ='profile') email_confirmed = models.BooleanField(default=False) phone_number = PhoneNumberField( blank=True, null=True) organisation = models.CharField(max_length=30, blank=True) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() accounts/admin.py from django.contrib import admin from django.contrib.auth import admin as upstream from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.models import Group, User from django.utils.translation import ugettext, ugettext_lazy as _ from django.db.models.signals import post_save from django.dispatch import receiver from .models import Profile class ProfileInline(admin.StackedInline): model = Profile can_delete = False verbose_name_plural = 'Profile' fk_name = 'user' class CustomUserAdmin(UserAdmin): inlines = (ProfileInline, ) list_select_related = ( 'profile', ) list_display = ('email', 'username', 'first_name', 'last_name', 'is_staff') #exclude = ('username',) fieldsets = ( ('Personal information', {'fields': ('first_name', 'last_name', 'username', 'email', 'password')}), ('Permissions', {'fields': ('is_active', … -
Django - WeasyPrint renders HTML code as a text
I want to create an invoice using Django-WeasyPrint. The problem is when a column in the HTML table is orderable. And the color is not the same too. This is the header code: <thead> <tr> <th class="nazov_polozky">Názov Položky</th> <th class="pocet">Počet</th> <th class="jednotka">Jednotka</th> <th class="cena">Cena</th> <th class="zlava">Zľava</th> <th class="dph">DPH</th> <th class="celkom orderable"><a href="?sort=celkom&amp;id=26">Celkom</a></th> </tr> </thead> THE VIEW: class WDokladToPdf(PDFTemplateView): def get(self, *args, **kwargs): self.doklad = get_object_or_404(Doklad, pk=self.request.GET.get('id')) self.template_name = 'pdf/{}_pdf_template.html'.format(self.doklad.typ) return super(WDokladToPdf, self).get(*args, **kwargs) def get_context_data(self,**kwargs): context = super(WDokladToPdf, self).get_context_data(**kwargs) doklad = get_object_or_404(Doklad, pk=self.request.GET.get('id')) polozky_table = PolozkyTable(doklad.polozky.all()) RequestConfig(self.request).configure(polozky_table) context['doklad']=doklad context['polozky_table']=polozky_table return context class PDFTemplateResponse(TemplateResponse): def __init__(self, filename=None, *args, **kwargs): kwargs['content_type'] = "application/pdf" super(PDFTemplateResponse, self).__init__(*args, **kwargs) if filename: self['Content-Disposition'] = 'attachment; filename="%s"' % filename else: self['Content-Disposition'] = 'attachment' @property def rendered_content(self): """Returns the rendered pdf""" html = super(PDFTemplateResponse, self).rendered_content base_url = self._request.build_absolute_uri("/") pdf = weasyprint.HTML(string=html, base_url=base_url).write_pdf() return pdf class PDFTemplateResponseMixin(TemplateResponseMixin): response_class = PDFTemplateResponse filename = None def get_filename(self): """ Returns the filename of the rendered PDF. """ return self.filename def render_to_response(self, *args, **kwargs): """ Returns a response, giving the filename parameter to PDFTemplateResponse. """ kwargs['filename'] = self.get_filename() return super(PDFTemplateResponseMixin, self).render_to_response(*args, **kwargs) class PDFTemplateView(TemplateView, PDFTemplateResponseMixin): pass Do you know where is the problem? -
Django custom error message
I want to display error messages in my native language. Below pasted code from 4 different trials and none of them worked None of the methods I found were not working Django, Models & Forms: replace "This field is required" message forms.py class UserCreateForm(UserCreationForm): email = forms.EmailField(required=True, error_messages = {'required': "custom"}) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) class Meta: model = User fields = ("username", "email", "password1", "password2", "first_name", "last_name") error_messages = { 'unique_together': "custom", 'blank': "custom", 'null': "custom", } def __init__(self, *args, **kwargs): super(UserCreateForm, self).__init__(*args, **kwargs) self.fields['email'].error_messages = {'required': 'custom'} # if you want to do it to all of them for field in self.fields.values(): field.error_messages = {'required':'custom {fieldname} custom'.format( fieldname=field.label)} views.py def signup(request, string, step): if request.POST: user_form = UserCreateForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() Profile.objects.create(**{ 'city':request.POST['city'], 'phone': request.POST['phone'], 'isStudent': istudent, 'emailnotafications': request.POST.get('emailnotafications', False), 'user': user }) ... template <div class="form-group field-user-username required"> <label class="control-label" for="user-username">Email</label> {{ user_form.email |add_class:"form-control" }} </div> <div class="form-group field-user-username required"> <label class="control-label" for="user-username">Hasło</label> {{ user_form.password1 |add_class:"form-control" }} </div> -
How to put two different model's uuid and id in a same url?
I have two different model linked by a ForeignKey one contains a certain uuid and the other has a certain id. I'd like to be able to put these in the same URL. Here's the models.py : class Creation(models.Model): ... uuid = models.UUIDField(default=uuid.uuid4, unique=True) class User(models.Model): ... creation = models.ForeignKey(Creation, null=True) Here's what the URL pattern should look like : url(r'^edit/(?P<id>\d+)/(?P<uuid>[^/]+)/$', views.edit, name='edit'), Views.py def edit(request, id, uuid): user_uuid = User.objects.filter(id=id) user = get_object_or_404(User, id=id, uuid=user_uuid.creation.uuid) As you can see the view function doesn't make any sense since I don't see how what I'm trying to do should work but the User should be the id in the URL and the Creation should be the uuid since each user can have many Creations. How can I achieve this? -
Django's authentication form is always not valid
I was trying to implement a basic login system using Django with a custom user using the AbstractUser class. Here is my models.py: from django.db import models from django.contrib.auth.models import AbstractUser class Stock(models.Model): stock_name = models.CharField(max_length=10) stock_price = models.FloatField() def __str__(self): return self.stock_name class CustomUser(AbstractUser): stocks = models.ManyToManyField(Stock) def __str__(self): return self.username My forms.py: from .models import CustomUser,Stock from django.contrib.auth.forms import AuthenticationForm class loginform(AuthenticationForm): class Meta: model = CustomUser fields = ('username', 'password') My views.py: def successful_login(request, pk): user = get_object_or_404(CustomUser, pk=pk) return render(request, '../templates/stock_portfolio.html',{'user':user}) def loginview(request): err=0 if request.method=="POST": form = loginform(request.POST) pdb.set_trace() if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: pdb.set_trace() login(request, user) pk = user.id pdb.set_trace() return redirect('successful_login', pk=pk) else: err=1 return render(request,'../templates/login.html',{'response':err,'form':form}) else: form = loginform() return render(request, '../templates/login.html',{'form':form}) While logging using pdb here is what I am getting for the form. <loginform bound=False, valid=Unknown, fields=(username;password)> How do I proceed now? -
Django: Ajax function is not triggered when I submit the form
I try to make a basic chat app that will show the message sent without the page refreshing, but for some reason I can't make that javascript running. html <form id="chat-form" method="POST" action="/chat/{{ sender.id }}{{ receiver.id }}/post/"> {% csrf_token %} <div id="chat-bottom" class="input-group"> <input id="textbox_message" type="text" class="form-control" placeholder="Type your message" name="textbox_message"> <span class="input-group-btn"> <input id="send" class="btn btn-default pull-right" type="submit" value="Send" name="btn_send"/> </span> </div> ajax $('#chat-form').on('submit', function(event){ event.preventDefault(); $.ajax({ url : '/chat/{{ sender.id }}{{ receiver.id }}/post/', type : 'POST', data : { msg : $('#textbox_message').val() }, dataType : 'json', success : function(json){ $('#textbox_message').val('');//clear the chat message box $('#msg-list').append('<li class="text-right list-group-item">' + json.message + '</li>');// append the new message to the list var chatlist = document.getElementById('msg-list-div'); chatlist.scrollTop = chatlist.scrollHeight;//scroll down after the message is send } error: function(){ alert("Error while sending the message"); } }); }); views.py def post_message(request, sender, receiver): if request.method == 'POST': if ('textbox_message' in request.POST) and request.POST['textbox_message'].strip(): message = request.POST['textbox_message'] Inbox.send_message(request.user, User.objects.get(id = receiver), message) return JsonResponse({ 'message': message}) return HttpResponse("Deal with this later") urls.py urlpatterns = [ url(r'^(?P<sender>\d+)(?P<receiver>\d+)/$', views.index), url(r'^(?P<sender>\d+)(?P<receiver>\d+)/post/$', views.post_message), ] The question is: why the Ajax is not triggered (it doesn't enter neither the success nor the error calls) and how can I make it … -
How to display pdf file on a template from upload from admin only
I want to serve PDF document on my website using the django admin only. I am totally lost this is what i have as my model class PastQuestion(models.Model): years = models.ForeignKey(Year) file = models.FileField(upload_to='uploads/', max_length=100,) posted_by = models.CharField(max_length=50)