Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I do my logic in `http://127.0.0.1:8000/rest-auth/login/` of `django-rest-auth`?
How can I do my logic in http://127.0.0.1:8000/rest-auth/login/ of django-rest-auth When I login it is like below and the url is provide by django-rest-auth. How can I write my own logic when I login? -
django ajax MultiValueDictKeyError
I am receiving this error: MultiValueDictKeyError at /orders/ajax/add_order_line "'cart'" Here is my script var cart = { 0: { id: "1", quantity: 50 } } $.ajax({ url: myURL, type: "post", data: {cart: cart}, success: function() {}, error: function(){} }); Meanwhile in my django views, the error was found in this line: def something(request): cart = request.POST['cart'] -
Django Chatterbot is not running properly
I am working on django project. I want to integrate Chatter Bot in my website but it is not properly responding. I have cloned the repository from GitHub but it is not working as expected. urls.py from django.conf.urls import include, url from django.contrib import admin from chatterbot.ext.django_chatterbot import urls as chatterbot_urls from example_app.views import ChatterBotAppView urlpatterns = [ url(r'^$', ChatterBotAppView.as_view(), name='main'), url(r'^admin/', include(admin.site.urls), name='admin'), url(r'^api/chatterbot/', include(chatterbot_urls, namespace='chatterbot')), ] settings.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'chatterbot.ext.django_chatterbot', 'example_app', ) # ChatterBot settings CHATTERBOT = { 'name': 'Django ChatterBot Example', 'trainer': 'chatterbot.trainers.ChatterBotCorpusTrainer', 'training_data': [ 'chatterbot.corpus.english.greetings' ], 'django_app_name': 'django_chatterbot' } Here is the result: Image I got stuck on that part of my application -
Django: Distinct and Order_by Together
I'm trying to build a messaging app. Here's my model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) This is what I tried in view, data = User.objects.filter(Q(sender__receiver=request.user) | Q(receiver__sender=request.user)).order_by('-receiver') Here User is the built in user model of django In the template, {% for abc in data %} {{ abc}} <br/> {% endfor %} Here i wants to filter the distinct users and re-order them based upon the fact that to whom request.user sent new message recently (as we see on social media platforms). I tried almost everything with data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user))....(order, values, distinct) But either it's not re-ordering or it's not working with distinct() when used together. How can I do that with User model? -
Django CreateView didn't return an HttpResponse object
Can't figure out why CreateView doesn't return HttpResponse. For now, I use this view just for posting (no GET). I thought that set self.success_url should be enough (as you can see in def post). class TripCreationView(CreateView): form_class = TripCreationForm template_name = 'frontend/homepage.html' def post(self, request, *args, **kwargs): self.success_url = request.POST.get('success_url') or reverse('frontend:homepage') super(TripCreationView, self).post(self, request, *args, **kwargs) # # def form_valid(self, form): # trip = form.save(self.request) # return HttpResponseRedirect(self.success_url) def get_form_kwargs(self): kwargs = super(TripCreationView, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs Do you know what to do? -
Django's user_logged_in signal not working when running a test case
I have this signal: @receiver(user_logged_in) def on_user_login(sender, request, **kwargs): if request.user.is_superuser: It all works when running the app. But when testing, this piece of code fails: self.client.force_login(...) The test fails with: AttributeError: HttpRequest object has no attribute user If I remove the signal, that test case runs just fine. I have Django 1.10 -
How to get last record of current active user?
I need to take a last record which user uploaded to DB. I know how to find last one, it is easy(Documents.objects.last()). But I am not sure it's right, cause in same time another user can upload a file, so I will get his record. Here is my code: models.py from django.db import models class Document(models.Model): username = models.CharField(max_length=100, blank=True, null=True) document = models.FileField(upload_to='documents/%Y/%m/%d/%H:%M:%S') uploaded_at = models.DateTimeField(auto_now_add=True) tabu.py from .models import Document class TabuName: def tabufunction(self): res = Document.objects.last() return res I can't use request.user.username in that file. I've read that it is not good practice in django. Do you know a solution of this problem? -
Django qs1.difference(qs2, qs3) not supported by backend
I need to check a table from a remote db and update another table in my db. The models have same fields but checking with difference method will return an error: qs1 get the data from one postgresql db qs2 get the data from one mysql db qs1 = (Local.objects .values_list('ref') ) qs2 = (Remote.objects .filter() .values_list('ref')) >>> qs1.difference(qs1, qs2) DatabaseError: intersection not supported on this database backend. -
Getting Django-Filter and Ajax to work together
I have got django-filter (link) set up and working as intended on my e-commerce website. There are a few filters, for example filter by colour (<input type="checkbox">) and sort by price (<select>), which the user chooses and then hits "Submit" to submit the form. djngo-filter then adds the query to the URL and returns the filtered products. What I would like to do is make it so that as soon as the user checks the box or selects an option from the dropdown, the products are automatically filtered, without having to hit the "submit" button, which I would like to get rid of. I'm fairly certain that AJAX is what is needed to achieve this - however looking through the web most tutorials deal with POST forms. Plus, the actually queryset/filtering logic is handled by django-filter and not myself in the views. So how exactly would I get this to work? Model: class ProductFilter(django_filters.FilterSet): price = django_filters.RangeFilter(name="price") product_colours = django_filters.ModelMultipleChoiceFilter(name="product_colours", label="Product Colour", widget=forms.CheckboxSelectMultiple, queryset=ProductColour.objects.all(), conjoined=False) product_family = django_filters.ModelMultipleChoiceFilter(name="product_family", widget=forms.CheckboxSelectMultiple, queryset=ProductFamily.objects.all(), conjoined=False) o = django_filters.OrderingFilter( choices=( ('-price', 'Price - Highest to Lowest'), ('price', 'Price - Lowest to Highest'), ('-first_published_at', 'Latest'), ('hearts', 'Most Popular'), ), fields=( ('price', 'price'), ('first_published_at', 'first_published_at'), ('hearts', 'hearts'), … -
Convert Blob to File then append to Form and save in Django model
User create audio tag, that saved in blob: <audio controls="" src="blob:http://localhost:60027/d2b9603d-4743-4f29-9c93-d1397d878e88"></audio> I need add this file to form: <form id="fo" enctype="multipart/form-data"> My js: function sub(){ var form = document.querySelector('form'); var blob = blobToFile(new Blob([$("#ul audio").attr( "src" )], {type: 'file'})); var filename = 'test.ogg' var data = new FormData(form); data.append('file', blob, filename); $.ajax({ url : "/sub", type: 'POST', data: data, contentType: false, processData: false, success: function(data) { alert("boa!"); }, error: function() { alert("not so boa!"); } }); } and my django def sub(request): m = mess() m.type = request.POST["media"] m.txt = request.POST["txt"] m.pdata = request.POST["pdata"] m.save() if request.POST["media"]!="text": fi = filelist() fi.mess_id = m.id fi.file = request.FILES["file"] fi.save() return JsonResponse({"result":"OK"}) In Django def, I see all Post data and one File( len()=64) This logic created file in right folder, but I cannot open him. I thing that problems with convert blob to file. What I need to change? Thanks -
How do I connect Django server (created on aws ec2) to my android application
I have a django server on AWS EC2. I want to connect that to my android application for authentication(sign in and sign up), data update and fetch(database implementation). Any idea how to do so? -
What is .<format> arguement for?
Django==1.11 django-extensions==1.9.7 /api/userprofiles/<pk>/ poinkbackend.apps.userprofiles.api.viewsets.UserProfileViewset api:userprofile-detail /api/userprofiles/<pk>\.<format>/ poinkbackend.apps.userprofiles.api.viewsets.UserProfileViewset api:userprofile-detail /a Docs says show_urls - Displays the url routes that are defined in your project. Very crude at this point. I had searched with format keyword. But the results do no related to my need. Is it stand for ?format=json arguement? I had tried replacing json by html, xml. I got error in return. Reference: http://django-extensions.readthedocs.io/en/latest/command_extensions.html?highlight=show_urls -
Django: sqlite3.OperationalError: no such table in python shell
I'm following a django blog tutorial. When I used python manage.py shell and tried following commands in shell from mainsite.models import Category, Tag c = Category(name='category test') c.save() this error occured: sqlite3.OperationalError: no such table: mainsite_category This is my model.py in mainsite folder, which I think is correct: from django.db import models from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name I have tried manage.py makemigrations, manage.py migrate and can successfully use manage.py runserver to see the website. So what is wrong here? -
Django Rest API, how to create post api for 2 model entries, and has foreign key associated to the model
I am trying to use DRF Django Rest Framework to create a post API to create entry for 2 models and associate foreign key relationship. How do I accomplish that ? I have 2 models - Employee model that OneToOne association with User, and has a ForeignKey Company - Company model I want to have a post to create employee model entry and also company model entry and associate the employee to the company. The employee also I want to enter in the User data (username, first_name, last_name, etc). The following are the code excerpts: https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee') company = models.ForeignKey(Company) class Company(models.Model): name = models.CharField(max_length=50) tel = models.CharField(max_length=15, blank=True) https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/views.py class EmployeeWithCompanyCreateView(generics.ListCreateAPIView): """This class defines the create behavior of our rest api.""" queryset = Employee.objects.all() serializer_class = EmployeeWithCompanyCreateSerializer def perform_create(self, serializer): """Save the post data when creating a new bucketlist.""" serializer.save() https://gitlab.com/firdausmah/railercom/blob/master/railercom/urls.py urlpatterns = [ url(r'^employee/$', EmployeeWithCompanyCreateView.as_view(), name="create"), https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/serializers.py class EmployeeWithCompanyCreateSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ("id","identity_number", "tel") -
Django QuerySet chaining, subset and caching
I know that QuerySets are lazy and they are evaluated only on certain conditions to avoid hitting the databases all the times. What I don't know is if given a generic query set (retrieving all the items) and then using it to construct a more refined queryset (adding a filter for example) would lead to multiple sql queries or not? Example: all_items = MyModel.objects.all() subset1 = all_items.filter(**some_conditions) subset2 = subset1.filter(**other_condition) 1) Would this create 3 different sql queries? Or it all depends if the 3 variable are evaluated (for example iterating over them)? 2) Is this efficient or would it be better to fetch all the items, then convert them into a list and filter them in python? -
How to connect two Foreign Key Fields
I have a model called Part that looks like this: class Part(model.Model) = some attributes... uses = models.ForeignKey('self', null = True, blank = True, on_delete = models.SET_NULL, limit_choices_to={'used_in' : None}, related_name = 'part_uses') used_in = models.ForeignKey('self', null = True, blank = True, on_delete = models.SET_NULL, related_name = 'device_used_in') Now, I want to update uses in one object, when another is set to used_in, e.g.: if a.uses(b) I want to automatically set b.used_in(a). I did this by setting it manually in the form_valid method of my UpdateView --> for example, if a.uses is changed, look for b and change its used_in. However, this has several disadvantages. First of all, I don't really like having to do this manually and was wondering whether this could not be done some other way, but I didn't find anything on Google. The second problem is that one Part can use several other Parts, but with my method, only the last Part that was used is shown. My question is: Is it somehow possible to connect the two foreign keys inside the model, or shift to only one foreign key, or do this in some other way that makes sense. -
Adding and accessing headers to HTTP POST request in python
I'm django 1.11.7 with rest framework. I've been trying to access POST request headers but when I print it I get 'None'. I'm sending a request using the application postman. I've added a key-value pair in the Headers section and the request code looks like this: POST /create_user HTTP/1.1 Host: localhost:8000 Content-Type: application/json key1: value1 Cache-Control: no-cache Postman-Token: # Postman token { "username": "abcdefgh@123" } In my django app, my views.py file looks like this: from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status import json # Create your views here. class CreateUser(APIView): def post(self, request, format='json'): try: request_data = json.loads(request.body.decode(encoding='UTF-8')) print 'Header data:', request.POST.get('key1') The 'request' variable is of type Request (Django Rest Framework object). There is no exception raised. So how do I access the POST 'key1' header? -
How to reload the list method in Rest Framework?
I have a CloudServerListAPIView: class CloudServerListAPIView(ListAPIView): """ list all the cloud server """ serializer_class = CloudServerListSerializer def list(self, request, *args, **kwargs): openstackclouduserid = self.request.user.openstackcloud_id if openstackclouduserid == None or openstackclouduserid == "": return Response(data="please enter the password", status=HTTP_511_NETWORK_AUTHENTICATION_REQUIRED, exception=Exception()) return Response(data="I want there to return the CloudServerListSerializer data", status=HTTP_404_NOT_FOUND, exception=Exception()) And the serializer is like bellow: class CloudServerListSerializer(ModelSerializer): openstackserver = serializers.SerializerMethodField() class Meta: model = CloudServer fields = "__all__" def get_openstackserver(self, instance): # instance is CloudServer instance openstackserver = getOpenstackServerById(instance.openstackserverid) return OpenstackServerSerializer(openstackserver).data But I don't know how to return the CloudServerListSerializer data in the views.py. -
Distinct Users in Messaging App
I'm trying to build a messaging app in django. Here's my model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) This is what I tried in the view, data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)) In the template, {% for abc in data %} {{ abc.receiver }} <br/> {% endfor %} Here I wants to filter the distinct receivers and re-order them based upon the fact that to whom request.user sent new message recently (as we see on social media platforms). How can I do that? I'm hanged with this code from a long time, I will be very thankful with your little help :) -
How to manually send a reset-password email?
I need to manually send a password reset email. I followed the steps described here, but all I get in return to calling PasswordResetView.as_view()(pwreset_request) is a 403 because of an invalid CSRF token. Despite that (and consequently getting that email) there are no errors on the page and everything is working fine. from django.http import HttpResponseForbidden, HttpResponse, HttpRequest from django.middleware.csrf import get_token def new_user(request): user_form = UserForm(request.POST, instance=user) if request.method == 'POST': if user_form.is_valid(): user = user_form.save() # Manually send password reset email pwreset_request = HttpRequest() pwreset_request.method = 'POST' pwreset_request.META['HTTP_HOST'] = request.META['HTTP_HOST'] pwreset_request.POST = {'email': user.email, 'csrfmiddlewaretoken': get_token(HttpRequest())} PasswordResetView.as_view()(pwreset_request) # returns 403 invalid csrf token ... Any ideas how to fix that? -
django: how to change or set default value for forgien field of django model from view function
I want to set default value for college and program fields of django model from view .. how can I solve this problem ?? class Student(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=50) college = models.ForeignKey(College, on_delete=models.CASCADE, default='1') program = models.ForeignKey(Program, on_delete=models.CASCADE, default='1') def __str__(self): return self.name -
Docker - "127.0.0.1" is not a valid port - Django
Hi I have a django app that I am currently moving to docker and ducker hub to start testing. I currntly have the docker file and the project is building. There is an issue that is coming up when trying to run the python manage.py runserver command. It is saying that there is the following issue: omars-mbp:helloworld omarjandali$ docker run omaryap/helloworld CommandError: "127.0.0.1" is not a valid port number or address:port pair. Here is my docker file for the django project I am currently running. If anyone can help me with this... FROM python:3 WORKDIR hello COPY requirements.txt ./ EXPOSE 8000 RUN pip install -r requirements.txt COPY . . CMD ["python", "manage.py", "runserver", "127.0.0.1"] -
Enable to display data which are related in django and python
This is my model THis is my View This is my template As shown in pictures there is AddProduct model is related with its SubCategory Model. So i am unable to display products related with its subcategory I dont see anything Kind querying them in db, Can anyone tell me where i have messed the things -
JQuery:Not able to fetch value of "td" when onclick on button happens second time
Following is the code of my table. In the action column i have a buttons named accept and reject. On click on reject I want to get the values of 2 and 3 "td" present in that "tr". <table class="w3-table" id="tbl_task" width="100%"> <tr> {% for ele in d|slice:":1" %} {% for key in ele.keys %} <th>{{ key }}</th> {% endfor %} {% endfor %} <th>Action</th> </tr> {% for ele in d %} <tr class="class_1"> {% for k, v in ele.iteritems %} {% if k in "Assigned_Users" %} <td> {% if v|length > 2 %} <div style="width: 80%;max-height: 37px;overflow:auto;margin-left: 32px;"> {% for ch in v %} {{ ch|linebreaksbr }} {% endfor %} </div> {% else %} {% for ch in v %} {{ ch }} {% endfor %} {% endif %} </td> {% else %} <td> {{ v }} </td> {% endif %} {% endfor %} <td class="noexcel"> <div id="td_button_div"> <button id="status_accepted" class="btn btn-default btn-sm" name="accept"> <span class="glyphicon glyphicon-ok"></span> Approve </button> <button id="status_rejected" class="btn btn-default btn-sm" name="reject" data-toggle="modal" data-target="#myModal"> <span class="glyphicon glyphicon-remove"></span> Reject </button> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title" … -
Sending a POST query in JSON using JQuery and Django
I'm very confused about the urls when it comes to sending/receiving data. The snippet I'm trying in my views is very simple: class EditGetInfo(View): def post(self, request, *args, **kwargs): response_data = {} response_data['test'] = 'Test message' return HttpResponse(json.dumps(response_data), content_type="application/json") In my urls I have: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^edit/getInfo$', EditGetInfo.as_view()), url(r'^edit/', Edit.as_view()), url(r'^$', Home.as_view()), ] My goal is to send the request to website.com/edit/getInfo. And I try to do it as (this is loaded when I open website.com/edit): $.post("edit/getInfo",function(data) { alert(data); });