Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Email setup for Django in AWS using SES
I am trying to setup email capability for my Django website on AWS using Elastic Beanstalk. I have activated Simple Email Service (SES) and verified two email address for testing. Furthermore, I have followed instruction to install and setup Dango-SES. However, when I try to sign up in my website pretending to be a new user I receive this error in my browser: SESAddressNotVerifiedError: 400 Email address is not verified. That is confusing because I am using verified email to sign up (email verified by SES). I am using django-allauth for authentication and registration. Can anyone give an advice on this? Thank you very much! Regards -
Relationships between models (Django)
I have 2 models venta and detalleventa which is fine since a sale can have many details class Venta(models.Model): cliente = models.ForeignKey(Cliente,on_delete=models.CASCADE,verbose_name='Cliente') fecha = models.DateField(auto_now_add=True) descripcion = models.CharField(max_length=300, blank=True, verbose_name='Detalle del pedido') total = models.DecimalField(decimal_places=2, max_digits=7, verbose_name='Total de la venta') def __str__(self): return '{}'.format(self.id) class DetalleVenta(models.Model): producto = models.ForeignKey(Producto,on_delete=models.CASCADE,verbose_name='Producto') cantidad = models.IntegerField(verbose_name='Cantidad') venta = models.ForeignKey(Venta,on_delete=models.CASCADE, verbose_name='Venta') def __str__(self): return '{} - {}'.format(self.venta,self.producto) How do I access detail from venta if the foreign key has detalle? because if there are several detalles you should not edit one by one if you do not edit the venta that contains all the detalles So far I can edit but through its detalle: class VentaUpdate(UpdateView): model = DetalleVenta second_model = Venta template_name = 'venta/venta_form.html' form_class = DetalleForm second_form_class = VentaForm success_url = reverse_lazy('venta:ventas_listar') def get_context_data(self, **kwargs): context = super(VentaUpdate, self).get_context_data(**kwargs) pk = self.kwargs.get('pk', 0) detalle = self.model.objects.get(id=pk) venta = self.second_model.objects.get(id=detalle.venta_id) if 'form' not in context: context['form'] = self.form_class() if 'form2' not in context: context['form2'] = self.second_form_class(instance=venta) context['id'] = pk return context def post(self, request, *args, **kwargs): self.object = self.get_object id_detalle = kwargs['pk'] detalle = self.model.objects.get(id=id_detalle) venta = self.second_model.objects.get(id=detalle.venta_id) form = self.form_class(request.POST, instance=detalle) form2 = self.second_form_class(request.POST, instance=venta) if form.is_valid() and form2.is_valid(): form.save() form2.save() return HttpResponseRedirect(self.get_success_url()) … -
How do I call requests.get() from my own Django views to my Django Rest Framework?
Instead of trying to use the serializer class in my views, I'm trying to just do requests.get(<url for DRF>) and pull the json data, but I cannot seem to do that at all. It worked on my localhost:8000 when testing, but does not work on my production server on ec2. This is what I've tried: My django application is currently running on https:// So I've added SECURE_SSL_REDIRECT = False SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https') into my settings.py. I have tried requests.get(url=<url>, verify=False) I've tried logging the specific requests.get,but I found to see that my code does not even hit that line of code. I've used PyCharm to do remote debugging on http://, and that worked completely fine. The url that I use requests.get(url='https://<host>/api/users/', verify=False) note that there is a https:// when calling this url. I've tried using requests.get(url='http://<host>/api/users/), but I get a 404 response. But, if I use the same http:// on my PyCharm debug server, it works. Please don't suggest to just use the Serializers or Models. -
Django- Unable to access values from DetailView model object
I am trying to create a chat application that has two models: one holding the chat room names and another holding the messages. from django.db import models class ChatRoom(models.Model): name = models.CharField(max_length=256) professor = models.CharField(max_length=256) def __str__(self): return self.name class MessagesInChat(models.Model): room_name = models.ForeignKey(ChatRoom, on_delete=models.CASCADE, related_name="message_room") user_name = models.CharField(max_length=256) message = models.TextField(blank=True, null=True) def __str__(self): return str(self.user_name) However, whenever I try to access these fields from the template, I get the following error: No messages in chat found matching the query I did fill the models with dummy values before trying this. The following are my views.py file and template I'm using: views.py from django.views.generic import DetailView, ListView from chat import models class Chats(ListView): template_name = "chat_list.html" context_object_name = "chat_list" model = models.ChatRoom def get_queryset(self): return models.ChatRoom.objects.order_by("name") class ChatPage(DetailView): model = models.MessagesInChat template_name = "chat.html" context_object_name = "chat_page" Template <!-- 'm' stands for message --> {%for m in chat_page.message_room.all%} <div class="p-3 mb-2 bg-light text-dark" style="margin-top:20px;">{{m.message}}</div> <div class="p-3 mb-2 bg-success text-white" style="margin-top:20px;">{{m.message}}</div> {%endfor%} Also the urls.py file: from django.contrib import admin from django.conf.urls import url from chat.views import ChatPage, Chats urlpatterns = [ url('admin/', admin.site.urls), url(r'^$', Chats.as_view(), name="chat_page"), url(r'^(?P<pk>[-\w]+)/$', ChatPage.as_view(), name="chats") ] This problem has been bugging me for a while. … -
If condition is not working in Inner Loop in django templates
I don't know what is the problem and I've been stuck here for hours. There maybe duplicate questions but none of them could get me out of this. I am using an if condition in the inner loop to check if the attribute of inner is equal to the outer loop but if condition is never true even the data is same. I've printed the data individually, both attributes print the data mean data is correct. But when I use if condition it goes to else Data Here's the data I'm working with: activityy.activity_name = [Table Tennis,Swimming Pool, Football ] slot.activity = [Table Tennis,Table Tennis,Table Tennis,Table Tennis,Swimming Pool, Football] activities.html {% for activityy in all_activities%} <div style="margin-left: 450px; padding: 15px; border-radius: 5px; background-color: #dfdfdf;height: 150px; width: 800px; margin-top: 20px; text-align: center"> {% for slot in all_slots %} {% if slot.activity == activityy.activity_name %} <div style="background-color: #3a589a; padding: 15px; width: 120px; height: 120px; float: left; border-radius: 5px;"> <span style="color: #f1f1f1; font-size: 20px;"> {{ activityy.activity_name}}</span><br> </div> {% else %} <div style="background-color: #589a; padding: 15px; width: 120px; height: 120px; float: left; border-radius: 5px;"> <span style="color: #f1f1f1; font-size: 20px;"> {{ slot.activity}}</span><br> </div> {% endif %} {% endfor %} </div> {% endfor %} Views.py def … -
serializer custom queryset field
Is there a way to create a custom field in a serializer that calls a queryset ? Here is what I am trying to do: I have a serializer for Employee and I want to have "last_attendance" field included. class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ("id", "username", "first_name", "last_name") I would like to add one more field "last_attendance". Which is a queryset like this: "last_attendance" = Attendance.objects.filter(employee_id = idofthatemployee).last() -
DRF "field is required" error on POST request?
curl --user testuser:passwordz -d '{"name":"testplatform"}' -X POST http://localhost:8080/api/v1/platforms error {"name":["This field is required."]}% views.py class platform_list(APIView): def get(self, request, format=None): query = request.GET.get('name') if query: platforms = Platform.objects.filter(name=query) else: platforms = Platform.objects.all() serializer = PlatformSerializer(platforms, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = PlatformSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I know the auth works because if I type in wrong user or pass the error changes to "invalid credentials" . Why am I getting the field required error though? -
Pycharm permanently blinking "Updating indices..." in statusbar and html file
windows10 pycharm version:2017.31build number:py-173.3942.36 python3.6.3 anaconda3 django 2.0.1 pycharm blinking Hello I pasted a video link. These flashes only occur when HTML files are present. In python only case, it did not happen when anaconda only project. It happens when django's project. Deleting HTML files stops them. -
Image size warnings and what cropping field means in django-image-cropping
I'm trying to use django-image-cropping app on my website. I've set it up with size warnings on. Build in warnings are not good enough for me - as I understand if I try use size smaller than defined frame color in cutting tool is changing but nothing more. I'd like to check sizes in view but cleaned_data contains only cropping value which is string with 4 numbers in it. Does anybody know what those 4 numbers describe? Or maybe there is another way to prevent cropping not allowed sizes? -
taggit_templatetags2 exclude count
I'm using django-taggit to manage my tag. I want to include a list of used tags with the indication of how many times each of them has been used. To do so I'm using taggit_templatetags2. my template.html: {% load taggit_templatetags2_tags %} {% get_taglist as tags for 'blog.post' %} {% for tag in tags %} {% if tag.slug != 'draft' and tag.slug != 'retired' %} <h4 style="text-align:center"><a href="{% url 'blog:post_list_by_tag' tag.slug %}"> {{ tag }} ({{ tag.num_times }}) </a></h4> {% endif %} {% endfor %} But I want to exclude from the count all the tags of the draft posts and of the retired posts. I do not want just to exclude the tags 'draft' and 'retired' (I'm already doing that) but even the other tags that such posts can have. How can I do that? Probably I have to mess with the taggit_templatetags2 code... Here some code: @register.tag class GetTagList(TaggitBaseTag): name = 'get_taglist' def get_value(self, context, varname, forvar, limit=settings.LIMIT, order_by=settings.TAG_LIST_ORDER_BY): # TODO: remove default value for limit, report a bug in the application # django-classy-tags, the default value does not work queryset = get_queryset( forvar, settings.TAGGED_ITEM_MODEL, settings.TAG_MODEL) queryset = queryset.order_by(order_by) context[varname] = queryset if limit: queryset = queryset[:limit] return '' … -
How to change DRF to use a Response from a schema?
Is it possible to change the Django Rest Framework to use a Response from a schema? For example, a GET using the standard DRF will output: { "count": 0, "next": null, "previous": null, "results": [] } Where I would like it to output { "meta_stuff": { "License": "MIT" }, "data": [] } Where results=data and an extra ). Would I need to customise DRF or can a swagger.JSON schema be used to achieve this? -
Django asynchronous tasks locally
I have a web application that runs locally only (does not run on a remote server). The web application is basically just a ui to adjust settings and see some information about the main application. Web UI was used as opposed to a native application due to portability and ease of development. Now, in order to start and stop the main application, I want to achieve this through a button in the web application. However, I couldn't find a suitable way to start a asynchronous and managed task locally. I saw there is a library called celery, however that seems to be suitable to a distributed environment, which mine is not. My main need to be able to start/stop the task, as well as the check if the task is running (so I can display that in the ui). Is there any way to achieve this? -
Django view doesn't accept POST from html
I am making a login view, but I get an error indicating that POST method is not allowed. This is the view class: class LogIn(View); def get(self, request): if request.method == 'POST': username = request.POST.get('email') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('control_center')) else: return HttpResponse('Account not active!') else: return HttpResponse('Invalid user/name!') else: return render(request, 'UserManagerApp/login.html', {}) And this is the html form: <form action="{% url 'UserManagerApp:login' %}" method="post"> {% csrf_token %} <div class="card-body"> <label for="email">Email address</label> <input type="email" class="form-control" name="email" placeholder="example@attractora.com"> <label for="password" style="padding-top: 10px">Password</label> <input type="password" class="form-control" name="password"> </div> <div class="card-footer text-center"> <button type="submit" class="btn btn-primary" value="Login">Accept</button> <button type="cancel" class="btn btn-danger">Cancel</button> </div> </form> And this is the error I get: [01/Feb/2018 21:00:45] "GET /user_manager/login/ HTTP/1.1" 200 1686 Method Not Allowed (POST): /user_manager/login/ [01/Feb/2018 21:11:25] "POST /user_manager/login/ HTTP/1.1" 405 0 I am following some online directions but, evidently, I went astride at some point. -
How to write test for django FileBrowser - python
I used FileBrowser in my django project in one of models. class Person(models.Model): name = models.CharField(max_length=50) avatar = FileBrowseField( max_length=200, directory='pics/', extensions=['.jpg', '.jpeg', '.png', '.gif'], ) How can I write test for it? -
Design/Tool Suggestions Moving towards Remote Processing with Python
As the title suggests, I've made a desktop application and I'm looking to move towards re-implementing it with remote processing capability (as an example, utilizing something like Amazon Web Services). What I've got now is a master/slave setup with several machines on a local network. I use NFS, Redis, RabbitMQ, and Celery for distributed processing. However, at this point in time, some of my processing takes place during run time of my application, on the user's machine. I'd like to move towards a system where the user's machine isn't required to do any processing. In other words, I'd like to completely segment the system into back-end/front-end sections. Another reason I'm making this transition is to keep all back-end source code, containing all personally developed algorithms and methods, away from the users eyes. In a word: Security. From my reading, I've learned that the only real way to secure python source code is to implement my software as a service. First question: Is the type of system I'm suggesting SaaS (Software as a Service)? I'm wary to call it that since I'm not looking to build a webpage. The user will still install the UI portion of my system on a … -
Users can authenticate with DRF, but no permissions on POST
If i run: curl --user test:incorrectpass -d '{"name":"testplatform"}' -X POST http://localhost:8080/api/v1/platforms I get an error that says invalid credentials (as I should). If I pass in the correct credentials, this error goes away but I get a "you do not have permission" The user that I'm authenticating was created from the django admin panel and granted all permissions from the admin panel. Not sure if there is something else I need to do on the DRF side to enable permissions... class AuthOnPostOnly(permissions.BasePermission): def has_permission(self, request, view): # only accept POST request with correct token if request.method == 'POST': username = request.META.get('USERNAME') password = request.META.get('PASSWORD') if not username and password: return None try: authenticate(username=username, password=password) except User.DoesNotExist: raise exceptions.AuthenticationFailed('invalid credentials') else: return True This is a very barebones permission and more of a POC, ultimately I just want to check if user/pass are a match and if so move on, if not, raise an error. -
Reverse for 'restaurants_list' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Need help unable to rectify this error : NoReverseMatch at /myrestaurants/ Reverse for 'restaurants_list' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Request Method: GET Request URL: http://127.0.0.1:8000/myrestaurants/ Django Version: 1.8.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'restaurants_list' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Exception Location: /usr/lib/python2.7/dist-packages/django/core/urlresolvers.py in _reverse_with_prefix, line 495 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/vaibhav/Desktop/projects/myrecommendations', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/vaibhav/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/gtk-2.0'] Server time: Fri, 2 Feb 2018 02:02:23 +0000 My index.html looks like this : {% block content %} <nav class="nav nav-bar"> <div class="pull-right" style="padding: 20px;"> {% if user.is_anonymous %} <a href="{% url 'account_login' %}">Sign In</a> <a href="{% url 'account_signup' %}">Sign Up</a> {% else %} <a href="{% url 'account_logout' %}">Sign Out</a> {% endif %} </div> </nav> <div class="container"> <h1 class="app-font">Welcome to Food-orders</h1> <form method="GET" class="form-inline" action="{% url 'restaurants_list' %}"> <input type="text" id="locator" class="form-control"> {% buttons %} <button type="submit" class="btn btn-success"/> {% bootstrap_icon "glyphicon glyphicon-search" %} SEARCH FOR RESTAURANTS </button> {% endbuttons %} </form> </div> {% endblock %} My myrestaurants/urls.py looks like this : from django.utils import timezone from django.conf.urls import url from django.views.generic import ListView, DetailView, UpdateView import myrestaurants … -
Using Model class name names in DRF serializer
I have been given an example JSON output which I must reproduce uisng Django Rest Framework. Ths is the output: "results": [ { "Brand": [ { "BrandName": "20/20", "Store": [ { "ID": "4", "Languages": [ "eng" ], etc However, I don't see how DRF/Django can models this. For example, Brand and Store appear to me to be a 'model class name' (i.e. Brand) and NOT a feild name, right? Can this be done or have a missed something with models? For example, this is what I tried to do below and gives a whole different JSON output. class Brand(models.Model): BrandName = models.CharField( max_length=50, unique=True, ) class Store(models.Model): Languages = fields.ArrayField( models.CharField(max_length=50, blank=True) ) Brand = models.ForeignKey("Brand", models.CASCADE, null=False, blank=False, related_name="stores") class BrandSerializer(serializers.ModelSerializer): stores = Storeserializer() class Meta: """ Serializer configuration. """ model = Brand fields = ("BrandName", "stores") Which gives me "results": [ { "BrandName": "Test", "stores": {} } ] } -
Django filter() Query giving extra result in data
I have 2 objects contacts, companies_contact, I am using distinct() to get distinct value from contact the code looks like this: contacts = Contact.objects.filter(campaign=campaign) companies_contact = contacts.distinct('website') So, when I iterate the companies_contact I'm getting the following output... >>>for i in companies_contacts: i.created_at, i.website (datetime.datetime(2018, 1, 9, 10, 57, 40, 447445, tzinfo=<UTC>), 'www.creamstone.com') (datetime.datetime(2018, 1, 19, 6, 27, 32, 758898, tzinfo=<UTC>), 'www.facebook.com') (datetime.datetime(2018, 1, 18, 6, 20, 41, 145358, tzinfo=<UTC>), 'www.heteja.com') (datetime.datetime(2018, 1, 9, 12, 11, 17, 390755, tzinfo=<UTC>), 'www.kfc .com') (datetime.datetime(2018, 1, 31, 6, 44, 40, 916231, tzinfo=<UTC>), 'www.mvg.com') (datetime.datetime(2018, 1, 11, 12, 20, 55, 409986, tzinfo=<UTC>), 'www.subway.com') (datetime.datetime(2018, 1, 9, 9, 14, 58, 607180, tzinfo=<UTC>), 'www.websit.com') (datetime.datetime(2018, 1, 9, 6, 29, 53, 270203, tzinfo=<UTC>), 'www.website.com') (datetime.datetime(2018, 1, 9, 9, 22, 22, 869395, tzinfo=<UTC>), 'www.websitest.com') So, according to my understating companies_contact consists of this much data only but when I'm applying filter() on companies_contact with the different date which is not in above output then also it gives me the result. companies_contacts.filter(created_at__startswith='2018-02-01') The above query giving me the result but this created_at value is not there when I have iterate companies_contact I don't know why it is giving result and why it is working but I don't want result … -
Angular Django CSRF integration
I have a separate angular app and Django application running on different localhost ports with CORS enabled. My angular app sends its post requests to Django service endpoints to receive JSON response. I have attached the screenshot of angular project structure below. I need to know where I should integrate Django's CSRF token in my angular app assuming that I have one of my post request in Django.service.ts and what is the best practice that I need to follow? -
Connect Django to a table owned by a specific user in Oracle Database
I would like to have my Django connect to an already existing oracle database. This database contains multiple users and tables by each of them. How do I access the tables by a user and where do I need to provide this piece of code. -
ModuleNotFoundError: No module named 'login'
I have created application "login" django-admin.py startapp login In settings.py, I added the app INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'login', ] my views.py file content #views.py from login.forms import * from django.contrib.auth.decorators import login_required from django.contrib.auth import logout from django.views.decorators.csrf import csrf_protect from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from django.template import RequestContext @csrf_protect def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = User.objects.create_user( username=form.cleaned_data['username'], password=form.cleaned_data['password1'], email=form.cleaned_data['email'] ) return HttpResponseRedirect('/register/success/') else: form = RegistrationForm() variables = RequestContext(request, { 'form': form }) return render_to_response( 'registration/register.html', variables, ) def register_success(request): return render_to_response( 'registration/success.html', ) def logout_page(request): logout(request) return HttpResponseRedirect('/') @login_required def home(request): return render_to_response( 'home.html', { 'user': request.user } ) urls.py from django.conf.urls import patterns, include, url from login.views import * urlpatterns = patterns('', url(r'^logout/$', logout_page), url(r'^register/$', register), url(r'^register/success/$', register_success), url(r'^home/$', home), ) When i start the app, (project) H:\Django\myapp>python manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x05CDD9C0> Traceback (most recent call last): File "C:\Users\kalu\Envs\project\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Users\kalu\Envs\project\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "C:\Users\kalu\Envs\project\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "C:\Users\kalu\Envs\project\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Users\kalu\Envs\project\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper … -
django- how would I create a sort for a query to put one specific element first, then remaining by some field?
Specifically, I am looking to get a query of users. My User model has a first_name and last_name field. What I need to do is order the request.user at the top of the results, and the remaining users in alphabetical order by last_name, first_name. The last part is easy: q = User.objects.all().order_by('last_name', 'first_name') However I am not sure how to ensure that the request.user is the first result in the query. This is all being done for a django rest framework view, and thus (I believe) I need to have it done through a query which is passed on to the serializer. -
Which Layer does API access sit in?
I ma trying to wrap my head round the Django Framework and mapping it out on an architecture diagram. I am struggling to understand where the API calls are place (Model or View) and would like some guidance on this. -
Django go live with Nginx
I followed this tutorial to test going live with a django website. I don't have a DigitalOcean droplet but a local machine I have that eventually could be used as a server. Therefore, in the steps where I had to put the domain name I used the local machine IP address (it's the same IP address I use to login with ssh). All steps were ok and I have a response from whitin the local machine, i.e., if I open a browser in the local machine and with the IP address, the Django app runs ok. However, the same does not happen if I open it from an external computer. I'm not sure if it was suppose to work like that. Is it? If not what extra steps do I need to do to go public?