Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx 403 Forbidden on serving large images
I have setup a django application, in which user can upload his image and it is served by nginx and gunicorn. I have a problem with uploading large image files which does not get appropriate permissions to be served by nginx location /medias/images/ { root /var/www/html; } However the smaller images get their permissions fine and are served properly The point is that both uploading small and semi-large (3mb) image files are done by a same process. any ideas? Thanks -
Deploying a Django Cookiecutter project with Docker to Digital Ocean
My problem is that I'm not properly deploying my project, and I'm not exactly sure where I'm going wrong. In following Cookiecutter documentation to deploy my project with docker, I am getting the project to launch in my terminal. Here are the commands I'm running - docker-machine create -d digitalocean --digitalocean-access-token=..... prod eval $(docker-machine env prod) docker-compose -f production.yml build docker-compose -f production.yml up At this point, the project is running, I can hit it from the URL - everything is great. The problem is that if I CTRL+C out of the terminal, it kills the services. This makes me think I'm not deploying the image to my Digital Ocean droplet, and that I'm running the image locally. Is that correct? Happen to have any advice on how to fix this? -
Check on integration test if user has log in
I am trying to create a test for checking in the user has successfully log in or not. But I am having troubles to check once the user fulfills the log in form if it appears as authenticated or not. I try to wait 10 s to leave time to Django to do the request , but I don't manage My actual test is class MySeleniumTests(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super(MySeleniumTests, cls).setUpClass() cls.driver = WebDriver() def setUp(self): pass @classmethod def tearDownClass(cls): cls.driver.quit() super(MySeleniumTests, cls).tearDownClass() def test_login(self): driver = self.driver user = auth.get_user(self.client) self.assertFalse(user.is_authenticated) user = User.objects.create_user(username="testuser", password="testuser") driver.get("http://127.0.0.1:8000/cuentas/login/") driver.find_element_by_id("id_login").click() driver.find_element_by_id("id_login").clear() driver.find_element_by_id("id_login").send_keys("testuser") driver.find_element_by_id("id_password").clear() driver.find_element_by_id("id_password").send_keys("testuser") driver.find_element_by_id("login-btn").click() self.driver.implicitly_wait(10) is_a = auth.get_user(self.client).is_authenticated #<-Problem here self.assertTrue(is_a) self.driver.implicitly_wait(10) driver.get("http://127.0.0.1:8000/") -
Restrict admin menu items by django user permission
I'm working extending wagtail and i'm using a the next hook: python @hooks.register('register_settings_menu_item') def register_django_admin_menu_item(): return MenuItem(_('Site Admin'), '/django-admin', classnames='icon icon-wagtail-inverse', order=20000) And i get a link for the django admin page, but i want to restrict that item only to user that have staff permission. How can i do it? -
Django Restframework _ custom authentication
I wrote some code for custom authentication with this structure: serializers.py class LoginSerializer(serializers.Serializer): first_token = serializers.CharField() phonenumber = serializers.CharField() token = serializers.CharField(max_length=255, read_only=True) views .py class LoginView(APIView): serializer_class = LoginSerializer permission_classes = (AllowAny,) def post(self, request, format=None): phonenumber = request.data.get('phonenumber', None) first_token = request.data.get('first_token', None) try: x = User.objects.get(phonenumber=phonenumber) except x.DoesNotExist: return Response('user does not exists') if first_token == x.first_token.token: user = authenticate(phonenumber=phonenumber) login_user = login(request, user) user_info = { 'phonenumber': user.phonenumber, 'username': user.username, 'token': user.token, 'is_admin':user.is_admin, } return Response(user_info, status=status.HTTP_200_OK) urls.py urlpatterns = [ re_path(r'^login/$', views.LoginView.as_view(), name='login'), ] so, authentication and login is successful and user logs in. but when i try to go another page testframework doesnt store the authentication. I made a custom authentication already . auth.py class PhoneAuthentication(authentication.BaseAuthentication): authentication_header_prefix = 'Token' def authenticate(self, request): request.user = None auth_header = authentication.get_authorization_header(request).split() auth_header_prefix = self.authentication_header_prefix.lower() if not auth_header: return None if len(auth_header) == 1: return None elif len(auth_header) > 2: return None prefix = auth_header[0].decode('utf-8') token = auth_header[1].decode('utf-8') if prefix.lower() != auth_header_prefix: return None return self._authenticate_credentials(request, token) def _authenticate_credentials(self, request, token): try: payload = jwt.decode(token, settings.SECRET_KEY) except: raise exceptions.AuthenticationFailed("invalid authentication . could not decode token") try: user = User.objects.get(pk=payload['id']) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return(user, token) -
Using loaddata to add a ManyToOneRel into a django models class
I have an .xml file with country and continent data, which looks like this <object model="countrydata.continent" pk="7"> <field name="name" type="CharField">South America</field> <field name="code" type="CharField">sa</field> </object> <object model="countrydata.country" pk="1"> <field name="name" type="CharField">Andorra</field> <field name="capital" type="CharField">Andorra la Vella</field> <field name="code" type="CharField">ad</field> <field name="population" type="PositiveIntegerField">84000</field> <field name="area" type="PositiveIntegerField">468</field> <field name="continent" rel="ManyToOneRel" to="countrydata.continent">6</field> </object> The first object is to a continent, the second one is to a country. I'm trying to build models for them so that I can use manage.py loaddata command to parse through the .xml, but I'm having trouble with the ManyToOneRel -part. My models.py is from django.db import models class Continent(models.Model): name = models.CharField(max_length=60, default='') code = models.CharField(max_length=3, default='') class Country(models.Model): name = models.CharField(max_length=60, default='') code = models.CharField(max_length=3, default='') capital = models.CharField(max_length=60, default='') population = models.PositiveIntegerField(default=0) area = models.PositiveIntegerField(default=0) , but I'm not sure what I need to add to Country in order to be able to read the <field name="continent" rel="ManyToOneRel" to="countrydata.continent">6</field> line. I tried fiddling around with foreignkey and manytoonerel, but got neither of them working. Latest attempt example: continent = models.ForeignKey(Continent) and I get the error "Country has no field named 'continent'", so it leads me to believe that I'm establishing the model field in a wrong … -
Django: Superuser cannot login to admin and user page after making an email login field instead of username
I was looking for the the answer and I still can't find the solution, which works for me. I am new to Django. I write a web app, which will be basically a blog in which authors are going to have their sites and under each article there will be a comment section. I want that after creation a superuser will be automatically one of them. The username field is not necessary, because the authors will be recognized by their first and last names. That is why I need them to log in using just an email. The Django version that I use is 2.0 and I try to use CBV (Class-Based Views) as much as possible. After making the username irrelevant and using just email and password in the login page, I am unable to lo login in both cases: - as the user registered on the website in the website login page - as the admin registered through the console command createsuperuser on an admin login page Here is the practical example. After deleting the whole database and registering a regular user on the webpage and a superuser in the terminal, they are saved correctly in the database. … -
aws elastic beanstalk websocket error: failed: Error during WebSocket handshake: Unexpected response code: 500
I am implementing websocket in beanstalk with python-django. As i understand above error is related to proxy setting. I have to set proxy in nginx file. I know i can add nginx via .ebextensions directory. But i dont know which exact configuration i needs to add in config file to pass proxy. My websocket is running on 8080 and websocket url is ws://xx.xx.xx.xx/xxxxxxxxxx/xxx/ws I tried to check nginx directory at /etc/nginx directory. But in my beanstalk server it does not exist. -
ajax is not getting the value from form in django
I am trying to get the value from a form in django but its giving me this Uncaught SyntaxError: missing ) after argument list here is my html form <form id="chat-form" method="post"> {% csrf_token %} <div id="chat-bottom" class="input-group"> <input type="text" id="chat-msg" name="chatmsg" class="form-control"/> <span class="input-group-btn"> <div> <input class="btn btn-primary" id="send" type="submit" value="Send"/> </div> </span> </div> </form> my ajax code <script> $(document).on('submit','#chat-form',functiom(e){ e.preventDefault(); $.ajax({ type: 'POST', url: 'http://127.0.0.1:8000/qasim/', data: { msg:$('#chat-msg').val(), csrfmiddlewaretoken:$('input[msg=csrfmiddlewaretoken]').val()#} }, success: function(){ alert("done");} }); }); here is my views.py class index(TemplateView): template_name = 'qasim/chat.html' def get(self,request): return render(request,self.template_name) def post(self,request): if request.method == 'POST': msg2 = request.POST.get('msg', None) return HttpResponse('') I just want the value and than i want to use that value in my views.py please help me with this thanks in advance -
Django 2.0 Tutorial Pt 1 Error 404 - URL Conf Probelm?
I have been working through the Django 2.0 tutorial on their website. In part 1 it has me set up a separate polls app, and write some code into it. When I run the server after initially changing the code, I keep getting an error 404. I have followed the tutorial exactly and have even copy and pasted their code to no avail. I have a feeling that there is something they might have glossed over because they assume people might know it and I do not. I'm running Django 2.0 w/ Python 3.6 in an virtual environment. The error I keep getting is: Debug: Using the URLconf defined in mysite3.urls, Django tried these URL patterns, in this order: polls/ admin/ The empty path didn't match any of these. Command line: Not Found: /[19/May/2018 12:42:35] "GET / HTTP/1.1" 404 2028 Code: Veiws.py: from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") urls.py (polls): from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] urls.py (mysite) from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] -
What are the correct file permissions for a Django project in virtual environment located in home folder?
In the context of a production environment, what are the correct file permissions for a Django project in virtual environment located in home folder? Apparently it is not good practice to install a venv in /var/www I am using Django 2.0 on Ubuntu 16, and have it installed in ~/myvevnv/ i.e. in my home directory. Thanks -
Django REST Framework - pass extra parameter to actions
I'm using Django 2.0 and Django REST Framework I have created an action method to delete particular object from database contacts/views.py class ContactViewSet(viewsets.ModelViewSet): serializer_class = ContactSerializer permission_classes = (IsAuthenticated, AdminAuthenticationPermission,) def get_queryset(self): return Contact.objects.filter(user=self.request.user) @action(methods=['get'], detail=False, url_path='delete_phone/<phone_pk>/') def delete_phone(self, request, pk=None): contact = self.get_object() print(contact) print(pk) print(self.kwargs['phone_pk']) return Response({'status': 'success'}) apps/urls.py router.register(r'contacts', ContactViewSet, 'contacts') api_urlpatterns = [ path('', include(router.urls)), ] But when I access DELETE: http://url/api/contacts/delete_phone/1 It gives page not found error. In the error page, there is listing in tried url patterns api/ ^contacts/delete_phone/<phone_pk>/$ [name='contacts-delete-phone'] api/ ^contacts/delete_phone/<phone_pk>\.(?P<format>[a-z0-9]+)/?$ [name='contacts-delete-phone'] -
Saving Instance with Foreign Key in Django
class B(models.model): # some fields class A(models.Model): b = models.ForeignKey(B) Now while in django serializer, I already have B created first. b = B.objects.get(id=1) Creating the instance for A like this: data['b'] = b But the serailizer.is_valid() gives error that it expected a dictionary but got that object. Now if I do this - data['b'] = b.__dict__ I get an error that B with this id is already present. -
Django: Cannot import name 'model'
So I am a student and I am trying to build a small shop using Django, so when I run it on my laptop it works as expected but when I upload it to the server I got this error cannot import name 'CustomerOrderModel' this is model.py class CustomerOrderModel(models.Model): # attribute def __str__(self): return self.customer_name this is forms.py from .models import CustomerOrderModel #the error in this line class Customer(forms.ModelForm): class Meta: model = CustomerOrderModel fields = [# some fields] -
Django Angular Folder structure to load angular templates
I've got the hang of constructing rest API's to pass all data, but I'm having trouble knowing how to set up the folder structure to be able to load an angular template by visiting an url. Lets say that in my settings.py I have a registered path api, that contains the JSON data i want to pass to the client, and have some angtemplate.html. I also have a Django app called apitest which gets data from the server and provides the data to the api that angular needs to get data from. How do I route the request so that when a user goes to a url on my server like 127.0.0.1:8000/apifetch, the user is presentet with angtemplate.html that has loaded the data from /apifetch? I realize this is a triple question involving first angular app-structure, second Django template syntax and folder structure, and thirdly url-patterns. I tried to follow the thinkster angular django tutorial, but was unable to connect the angular app to the website. My own theory is that inside the apitest Django application I create a few templates and in the static folder of that app I keep my angular apps, which I load as static into … -
Remove double quotes around string list
I have a list with dates in it. event_labels = [] for item in all_list: event_labels.append(str(item.event_created_at)) "['2018-05-18', '2018-05-17', '2018-05-16', '2018-05-15', '2018-05-14', '2018-05-13', '2018-05-12', '2018-05-11']" I am using this data to output for labels in chartjs. Problem is the sourrounding double quotes around the event_labels list. I have another list with just integers and it does not have the sourrounding quotes around the beginning and the end of the list. [26.0, 50.0, 27.0, 87.0, 46.0, 24.0, 18.0, 34.0] How do I output a string list without the double quotes at the beginning and end? -
how to change django default ForeignKey type from integer to string?
class NewStock(models.Model): stock_info = models.ForeignKey(Stock) stock_xcode = models.CharField(max_length=10, unique=True) class Stock(models.Model): stock_name = models.CharField(max_length=200) stock_id = models.CharField(max_length=10, unique=True, primary_key=True) In database,there will be a stock_info_id column and its type is integer. When stock_id starts with 0, such as 000001, It will be stock_info_id=1 and will fail to get stock_info because 1 is not found in column stock_id of Stock table. How can I specify an exact type for a ForeignKey. For this problem, things will be good if stock_info_id is CharField other than Integer. -
Angular app don't display on android browser
I've just built a project with Django/Angular. The output of the project in the computer's browser is displayed correctly. But when I want to see the project in the Android browser, the program is not loaded. At first I thought that the problem was in the code. But after experimenting with a new Angular project, I saw that the problem is from Angular. what's the solution? -
Django auto Mail
I've been trying to learn django for the past couple of days, and I've made a basic bug tracking software as of now (using the admin part of django) Ive created a table called bugs: from django.db import models # Create your models here. class Bugs(models.Model): STATUS_CHOICE = ( ('Work In Progress', 'Work In Progress'), ('Incomplete', 'Incomplete'), ('Completed', 'Completed') ) Project_Name = models.CharField(max_length=100) Basic_Description = models.CharField(max_length=100) Detailed_Description = models.TextField(default='The Description, here.') Status = models.CharField(max_length=18, choices=STATUS_CHOICE) Assigned_to = models.CharField(max_length=100) Reported_by = models.CharField(max_length=50, blank=True, null=True) Reporters_Mail_ID = models.CharField(max_length=50, blank=True, null=True) Reported_Date = models.DateTimeField(null=True, blank=True) Created = models.DateTimeField(auto_now_add=True, null=True, blank=True) Updated = models.DateTimeField(auto_now=True, null=True, blank=True) Deadline_Date = models.DateTimeField(null=True, blank=True) image = models.FileField(null=True, blank=True) def __str__(self): return self.Project_Name + ' [' + self.Status + '] ' + self.Basic_Description + ' [' + self.Assigned_to + ']' class Meta: verbose_name_plural = "Bugs" How do i make it such that when a project name is selected, the Assigned_to is also automatically selected? And How do i make sure that once it is assigned to the person/ Status is edited/ Or any sort of edit is made by the SuperUser, a mail is sent to the person it is assigned to, and when an edit is made by … -
Django 1.11 TypeError at / context must be a dict rather than unicode
I use Django 1.11 to create a website. When I run local host http://127.0.0.1:8000/ then the error "TypeError at / Context must be dict rather than unicode. "I do not know how to fix it. Offending line : \venv\lib\site-packages\django\template\context.py in make_context, line 287 Entire View code of context.py import warnings from contextlib import contextmanager from copy import copy from django.utils.deprecation import RemovedInDjango20Warning Hard-coded processor for easier use of CSRF protection. _builtin_context_processors = ('django.template.context_processors.csrf',) class ContextPopException(Exception): "pop() has been called more times than push()" pass class ContextDict(dict): def init(self, context, *args, **kwargs): super(ContextDict, self).init(*args, **kwargs) context.dicts.append(self) self.context = context def __enter__(self): return self def __exit__(self, *args, **kwargs): self.context.pop() class BaseContext(object): def init(self, dict_=None): self._reset_dicts(dict_) def _reset_dicts(self, value=None): builtins = {'True': True, 'False': False, 'None': None} self.dicts = [builtins] if value is not None: self.dicts.append(value) def __copy__(self): duplicate = copy(super(BaseContext, self)) duplicate.dicts = self.dicts[:] return duplicate def __repr__(self): return repr(self.dicts) def __iter__(self): for d in reversed(self.dicts): yield d def push(self, *args, **kwargs): dicts = [] for d in args: if isinstance(d, BaseContext): dicts += d.dicts[1:] else: dicts.append(d) return ContextDict(self, *dicts, **kwargs) def pop(self): if len(self.dicts) == 1: raise ContextPopException return self.dicts.pop() def __setitem__(self, key, value): "Set a variable in the current context" … -
Recommended way to find the source of a query when using Django?
I'm having difficulties with locating the source of the queries which I see in my database logs. I'm using Django, so the actual queries are generated automatically which makes a simple "grep" ineffective. I'm thinking of patching the database cursors to append the current stacktrace to the query, something like: for conn in connections.all(): with conn.cursor() as c: ctype = type(c.cursor) orig_execute = ctype.execute def _patchedExecute(self, query, params=None): query = query + ' -- ' + traceback.format_stack() return orig_execute(self, query, params) ctype.execute = _patchedExecute orig_execute_many = ctype.executemany def _patchedExecuteMany(self, query, params=None): query = query + ' -- ' + traceback.format_stack() return orig_execute_many(self, query, params) ctype.executemany = _patchedExecuteMany What I'm wondering: is there a ready made solution for this? (seems like a somewhat common problem to have) if not, are there better solutions than the one presented above? (I'm not all that familiar with the Django internals) -
add parameter to get_queryset request in Django REST Framework
I'm using Django 2.0 and Django REST Framework. I have two models in contacts app contacts/models.py class Contact(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100, blank=True, null=True, default='') class ContactPhoneNumber(models.Model): contact = models.ForeignKey(Contact, on_delete=models.CASCADE) phone = models.CharField(max_length=100) primary = models.BooleanField(default=False) def __str__(self): return self.phone contacts/serializers.py class ContactPhoneNumberSerializer(serializers.ModelSerializer): class Meta: model = ContactPhoneNumber fields = ('id', 'phone', 'primary', 'created', 'modified') and contacts/views.py class ContactPhoneNumberViewSet(viewsets.ModelViewSet): serializer_class = ContactPhoneNumberSerializer def get_queryset(self): return ContactPhoneNumber.objects.filter( contact__user=self.request.user ) urls.py router.register(r'contact-phone-number', ContactPhoneNumberViewSet, 'contact_phone_numbers') What I want is following endpoints GET: /contact-phone-number/{contact_id}/ list phones numbers of particular contact POST:/contact-phone-number/{contact_id}/ *add phone numbers to particular contact Edit: /contact-phone-number/{contact_phone_number_id}/ *update particular phone number DELETE: /contact-phone-number/{contact_phone_number_id}/ *delete particular phone number Edit and Delete can be achieved as default action of ModelViewSet but how to make get_queryset to accept contact_id as required parameter? -
How i can do these query on django
I've been trying everything, but I can not do this query in django SELECT to_char(fecha_hora, 'YYYY-MM-DD') as Fecha, SUM(count) + SUM(pax_subidos) + SUM(pax_bajados) as Total FROM public."Despachos_despacho" GROUP BY Fecha ORDER BY Fecha; -
Django 2.0.5 404 error-page not found
I am new in using Django and I am having some problems. When I run my server 'runserver' it shows 404 page not found. My project directory name is 'mysite' and my app name is 'webapp'. The problem I think is in 'urls' file. I have also put my app name in INSTALLED_APPS under the settings section. This is the code in mysite/urls.py file: """mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('webapp', include("webapp.urls")), ] And this is the code in webapp/urls.py file: from django.urls import path from . import views urlpatterns = [ path('', views.index, name = "index"), ] I am using the latest Django version 2.0.5, I have tried to look up for this error … -
Table with data obtained from a foreignkey in reverse, using "django-tables 2"
I'm trying to make a table with "django-tables 2" with data obtained from a foreignkey in reverse, these are my models: class CursoAttendance(models.Model): curso = models.OneToOneField('organizacion.Curso', on_delete=models.CASCADE, verbose_name="curso") class StudentAttendance(models.Model): student = models.OneToOneField('perfiles.Student', blank=True, null=True, on_delete=models.SET_NULL, related_name="asistencia_por_curso", help_text="estudiante") curso_attendance = models.ForeignKey('CursoAttendance', on_delete=models.CASCADE, verbose_name="curso especifico", related_name="attendance_student") class DailyAttendance(models.Model): ATTENDANCE_CHOICES = ( (None,''), (True,'Presente'), (False, 'Ausente') ) date = models.DateField(default=datetime.datetime.now) status = models.NullBooleanField(choices=ATTENDANCE_CHOICES, max_length=5, default=None) student_attendance = models.ForeignKey('asistencia.StudentAttendance', blank=False, null=True, on_delete=models.SET_NULL,, related_name='attendance_daily') These are my tables: class StudentAttendanceTable(tables.Table): numero = tables.Column('N°', empty_values=()) nombres = tables.Column('nombres', accessor='student.first_name') apellidos = tables.Column('apellidos', accessor='student.last_name') date = tables.Column('fecha', accessor='date')#LinkColumn status = tables.Column('status', accessor='attendance_daily.status') class Meta: model = StudentAttendance fields = ('numero', 'nombres', 'apellidos', 'date', 'status') def __init__(self, *args, **kwargs): super(StudentAttendanceTable, self).__init__(*args, **kwargs) self.counter = itertools.count() def render_numero(self): return '%d' % next(self.counter) def render_id(self, value): return '<%s>' % value class CursoAttendanceTable(tables.Table) #with StudentAttendanceTable? numero = tables.Column('N°', empty_values=()) nombres = tables.Column('nombres', accessor='student.first_name') apellidos = tables.Column('apellidos', accessor='student.last_name') curso = tables.Column('curso', accessor='curso_attendance.curso') status = tables.Column('status', accessor='attendance_daily.status') class Meta: model = CursoAttendance #extra_columns=[('dynamic_column', tables.Column('fecha', accessor='attendance_daily.status'))] fields = ('numero', 'curso', 'nombres', 'apellidos', 'attendance_daily.status' 'status') def __init__(self, *args, **kwargs): super(CursoAttendanceTable, self).__init__(*args, **kwargs) self.counter = itertools.count() def render_numero(self): return '%d' % next(self.counter) def render_id(self, value): return '<%s>' % value graphically this is what I want …