Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Latest version of Elasticsearch supported by Haystack 2.6.1
I want to know the latest version of Elasticsearch which is supported by Django Haystack 2.6.1, as I feel upgrading Elasticsearch may solve some of the problems I am facing. -
User Registeration Using Django Rest Framework
I am trying to create a api for user Registration using the django rest framework. I have the following models.py file from __future__ import unicode_literals 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 class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE , primary_key = True) mobileNumber = models.IntegerField(default=0) avatar= models.ImageField(upload_to = 'User/' , default = '/static/User/defaultProfileImage.png') def create_user_profile(sender, **kwargs): if kwargs['created']: profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_user_profile, sender=User) This is my Serializers.py file from rest_framework import serializers from User.models import UserProfile from django.contrib.auth.models import User class UserSerializer(serializers.HyperlinkedModelSerializer): username = serializers.CharField() password1 = serializers.CharField( style={'input_type': 'password'}, write_only=True) password2 = serializers.CharField( style={'input_type': 'password'}, write_only=True) email = serializers.EmailField() class Meta: model = User fields = ( 'id', 'username', 'password1', 'password2', 'email', 'first_name', 'last_name', ) class UserProfileSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer() class Meta: model = UserProfile fields = ( 'user', 'mobileNumber', 'avatar') And following is my views.py file from User.models import UserProfile from .serializers import UserProfileSerializer from rest_framework.viewsets import ModelViewSet class UserProfileViewSet(ModelViewSet): queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer What is the best way to create a User Registeration using the api view that i have created. I tried many alternatives like overriding the create method in the UserProfile Serializer class and … -
The render do not render to the template
In the admin index page I bind a id to a button, and use jquery ajax to request a logout event: $("#logout").click(function(){ $.ajax({ url:'/logout/', type:'POST' }) }) And in the frontend/views.py: def logout(request): if request.method == 'POST': request.session['username'] = None request.session['is_login'] = False import app_admin.views as app_admin_views app_admin_views.conn = None # clean the connection print ('before logout') return render(request,'frontend/login.html') In the Terminal have printed the 'before logout', but the page do not render to the frontend/login.html, and I also tried use redirect, all failure. -
django use column value for filtering
I have a table of points with location data as stored in the following columns: coordinates: the geolocation data in longitude and latitude radius: the distance from coordinate that it is visible Now I take a random point and want to find the points that are visible to the random point using django geolocation such as: LocationInfo.objects.filter(coordinates__distance_lt=(random_point, D(km=1)) Currently I am retrieving the points within 1 km radius but I want to use the radius from the table. How can I use the radius from the table? -
How to select a random file from a folder that where uploaded with django-filer
I use django-cms for a project and in the frontend (template) I want to select a random image from a folder. The media is managed by django-filer. I know how to use the files when I assign them directly in my models, but I can't figure out if and how it is possible to select a random image. For a better understanding, I have a model where I can choose an image. If that is not set by the editor, I want to choose a random image as backup. -
Render template and I want to the url address change too
I from login page render to the admin index page, but the url address did not change, how to change it? Code is below: return render(request, 'app_admin/index.html') As a common sense , all we know use render the url address do not change, but I want it change. how can I do that? I do not want to use the redirect, because I will pass data in render. how can I do that? -
Django connected SQL queries with filters
Example: class Room(models.Model): assigned_floor = models.ForeignKey(Floor, null=True, on_delete=models.CASCADE) room_nr = models.CharField(db_index=True, max_length=4, unique=True, null=True) locked = models.BooleanField(db_index=True, default=False) last_cleaning = models.DateTimeField(db_index=True, auto_now_add=True, null=True) ... class Floor(models.Model): assigned_building = models.ForeignKey(Building, on_delete=models.CASCADE) wall_color = models.CharField(db_index=True, max_length=255, blank=True, null=True) ... class Building(models.Model): name = models.CharField(db_index=True, max_length=255, unique=True, null=True) number = models.PositiveIntegerField(db_index=True) color = models.CharField(db_index=True, max_length=255, null=True) ... I want to output all rooms in a table sorted by Building.number. Data which I want to print for each room: Building.number, Building.color, Building.name, Floor.wall_color, Room.last_cleaning Furthermore I want to allow optional filters: Room.locked, Room.last_cleaning, Floor.wall_color, Building.number, Building.color With one table it's no Problem for me, but I don't know how I archive this with three tables. kwargs = {'number': 123} kwargs['color'] = 'blue' all_buildings = Building.objects.filter(**kwargs).order_by('-number') Can you please help me? Do I need write raw SQL queries or can I archive this with the Django model query APIs? I'm using the latest Django version with PostgreSQL. -
Django: inserted text into a text field sometime doesn't go trough after post
I have this weird bug that i can't replicate all the time. I have a html and with Jquery i populate a text field (Summernote). If i just populate the text, do nothing with it and i submit the form, sometimes the form field is, some time it goes trough just fine. Its like 30/70 ratio. But if i edit something, or even click on the text field it goes trough all the time. Has anyone encountered such behavior. My form class Form(forms.ModelForm): class Meta: model = modelname fields = ['field'] widgets = { 'notes': SummernoteInplaceWidget(attrs={'height': '600px'},), } my html var string = (function() {/* {{ message }} */}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1]; $('#button').click(function () { $('#id_field').summernote('code', string ); }); -
Permission error when installing Django within virtual environment
I have Django 1.10 installed within a virtualenv on my machine. Now I am creating another virtualenv (for another project) and installing Django 1.11 on it using the following command: pip install Django but I get a permission denied error: Collecting Django Using cached Django-1.11.5-py2.py3-none-any.whl Requirement already satisfied: pytz in /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages (from Django) Installing collected packages: Django Exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip/wheel.py", line 377, in move_wheel_files clobber(source, dest, False, fixer=fixer, filter=filter) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip/wheel.py", line 323, in clobber shutil.copyfile(srcfile, destfile) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/shutil.py", line 115, in copyfile with open(dst, 'wb') as fdst: PermissionError: [Errno 13] Permission denied: '/Library/Frameworks/Python.framework/Versions/3.5/bin/__pycache__/django-admin.cpython-35.pyc' I have read multiple SO posts about this but their solutions dont seem to apply to me. Please note: 1) I have already activated the new virtualenv before running the command. 2) I did not create the new virtualenv using sudo. I just did the following to create it: virtualenv name-of-the-new-virtualenv What could I be missing? -
IndexError: list index out of range Why can't I acsess two-dimensional array?
I cannot acsess the two-dimensional array. I wrote book3 = xlrd.open_workbook('./data/excel1.xlsx') sheet3 = book3.sheet_by_index(0) for row_index in range(7, sheet3.nrows): row = sheet3.row_values(row_index) area_row = row[0] or area_row row[0] = area_row if len(fourrows) == 5: fourrows=[] fourrows.append(row) fourrows_transpose=list(map(list, zip(*fourrows))) val3 = sheet3.cell_value(rowx=0, colx=9) user3 = User.objects.filter(corporation_id=val3).first() if user3: area = Area.objects.filter(name="America").first() pref = Prefecture.objects.create(name="prefecture", area=user3.area) city = City.objects.create(name="city", prefecture=pref) price_u1000 = Price.upper1000.objects.get(city=city) price_500_1000 = Price.from500to1000.objects.get(city=city) price_u500 = Price.under500.objects.get(city=city) pref.name = "NY" pref.save() for i in range(2,len(fourrows_transpose)): city.name = fourrows_transpose[i][1] city.save() print(fourrows_transpose[i][1]) price_u1000.name = fourrows_transpose[i][2] price_u1000.save() print(fourrows_transpose[i][2]) price_500_1000.name = fourrows_transpose[i][3] price_500_1000.save() print(fourrows_transpose[i][3]) price_u500.name = fourrows_transpose[i][4] price_u500.save() print(fourrows_transpose[i][4]) In print(fourrows_transpose),it is shown [['America', 'America', 'America', 'America', 'America'], ['', '', 'u1000', '500~1000', 'd500'], ['NY', 'City A', '×', '×', '×'], ['NY', 'City B', '×', '×', '×'], ['NY', 'City C', '×', '×', '×'], ['NY', 'City D', '×', '×', '×'], ['NY', 'City E', '×', '×', '×']] Now error happens,IndexError: list index out of range.Traceback says city.name = fourrows_transpose[i][1] is wrong.but I think fourrows_transpose is two-dimensional arrays,so I really cannot understand why I cannot access fourrows_transpose[2][1].What is wrong?How should I fix this? -
Automated answer in django's makemigrations
I want to automate the python manage.py makemigrations as in if a user encounters Did you rename game.last to game.las (a CharField)? [y/N] then the input will always be y but if the user encounters You are trying to add a non-nullable field 'las' to game without a default then it will automatically and continuously enter 1. I tried yes | python manage.py makemigrations as researched however this will just throw an infinite loop of Please select a valid option if the default input is asked My desire is the automation between 1 and y value as mentioned on my first paragraph or just throw an error if I input a wrong option on the default input -
Django multiple choice field on update
I am using Django multiple choice field to show check boxes and I am using same form for create and update group permissions.While updating group permissions I want all permissions which belongs to that group only. forms.py list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] queryset = Permission.objects.all().exclude(content_type_id__in=list) OPTIONS = () for item in queryset: OPTIONS = OPTIONS +((item.name, item.name),) group_name = forms.CharField(widget=forms.TextInput(attrs={'id': 'group_name','class': 'form-control'}),label='Group Name') name = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=OPTIONS, label="Permission") views.py class AssignPermission(LoginRequiredMixin, View): login_url = '/accounts/login/' redirect_field_name = 'next' form_class = AssignPermissionForm initial = {'name': ''} template_name = 'permission/assign.html' def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) group = Group.objects.all() user_list = [] for item in group: try: permission = item.permissions.all() if len(permission): user_list.append({'group_name':item.name, 'group_id':item.id, "permission":permission}) except: permission = None return render(request, self.template_name, {'results': user_list, 'form': form}) -
edit another model after creating an instance
I am trouble to figure out what I am trying to do. My app is the following. A user create a project. Now to that project he can or link a previous team that he created or create a new team. A team can be part of many project but a project is link to only ONE team. My model is the follwing: class Team(models.Model): team_name = models.CharField(max_length=100, default = '') team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) def __str__(self): return self.team_name class TeamMember(models.Model): user = models.ForeignKey(MyUser) team = models.ForeignKey(Team) def __str__(self): return self.user.first_name class Project(models.Model): name = models.CharField(max_length=250) team_id = models.ForeignKey(Team, blank=True, null=True) project_hr_admin = models.ForeignKey(MyUser, blank=True, null=True) def get_absolute_url(self): return reverse('website:ProjectDetails', kwargs = {'pk' : self.pk}) def __str__(self): return self.name my views : class ProjectCreate(CreateView): model = Project fields = ['name'] template_name = 'project_form.html' def form_valid(self, form): form.instance.project_hr_admin = self.request.user return super(ProjectCreate, self).form_valid(form) class ProjectDetailView(generic.DetailView): model = Project template_name = 'project_details.html' class TeamCreate(CreateView): model = Team fields = ['team_name'] template_name = 'team_form.html' def form_valid(self, form): obj = form.save(commit=False) obj2 = Project.team_id obj2 = obj.team_id obj2.save() print("sucess") I would like that when a user create a team, when the team is created it add automatically to the Project models the team_id … -
Django heroku connection refused
Deployment of my site to heroku seems to be working, until I try to use my login feature then it throws an error: OperationalError at /login/ could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? This error seems to occur during template rendering of a form (captcha). my procfile: web: waitress-serve --port=$PORT capstonenotespool.wsgi:application settings.py: import dj_database_url DATABASES = { 'default': dj_database_url.config() } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'capstonenotespool', 'USER': 'postgres', 'PASSWORD': '****', 'HOST': 'localhost', 'PORT': '', } } I've tried changing $PORT in the procile to 5432, but this does not work. I've also tried manually setting the PORT in settings to 5432 but this also doesn't work. I also noted that Django error logs produces these variables: SERVER_NAME 'localhost' SERVER_PORT '23994' SERVER_PROTOCOL 'HTTP/1.1' SERVER_SOFTWARE 'waitress' -
Can not trigger onclick function using Django,Python and javascript
I have an issue. I could not trigger the onclick event on the link using Django and Python. I am explaining my code below. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> {% load static %} <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript"> var query=''; function pageTransition(){ var full_url = window.location.search; var url = full_url.replace("?", ''); query=url.file; console.log('query',query); var url="'"+query+"'"; $.getScript(url,function(){ $('a').velocity("scroll", { duration: 1000 }); }) } </script> </head> <body> <header> <h1>Nuclear Reactor</h1> {% if count > 0 %} <b>Hi, {{ user.username }}</b> <a href="{% url 'home' %}?file=//cdnjs.cloudflare.com/ajax/libs/velocity/1.5.0/velocity.min.js" onclick="pageTransition();">Home</a> <a href="{% url 'view_reactor' %}?file=//cdnjs.cloudflare.com/ajax/libs/velocity/1.5.0/velocity.min.js" onclick="pageTransition();">View Reactor status</a> <a href="{% url 'logout' %}">logout</a> {% else %} <a href="{% url 'login' %}">login</a> / <a href="{% url 'signup' %}">signup</a> {% endif %} <hr> </header> <main> {% block content %} {% endblock %} </main> </body> </html> home.html: {% extends 'base.html' %} {% block content %} <center><h1>Welcome</h1> <p>This App allow to control the life cycle of the Nuclear Reactor and Retrive the status report </p> <p><a href="{% url 'status' %}">Status report</a><a href="{% url 'control' %}">Control panel</a></p> </center> {% endblock %} Here I need to get that query string value and include it inside that javascript function but the javascript function is not called at all.Please help me … -
AttributeError: type object 'User' has no attribute 'EXECUTOR'
My project doesn't run. Where is my mistake? I make simple freelance platform with api. My project structure is freelance api init.py apps.py models.py serializers.py urls.py views.py billing init.py admin.py apps.py models.py tests.py views.py base statics templates users init.py settings.py urls.py wsgi.py task migrations init.py admin.py apps.py models.py tests.py views.py users migrations init.py admin.py apps.py models.py tests.py views.py it is my api.views import json from django.db import transaction from rest_framework import viewsets, status from rest_framework.decorators import detail_route from rest_framework.response import Response from billing.models import TaskExpense from task.models import Task from users.models import User from .serializers import UserSerializer, TaskSerializer class ExecutorViewSet(viewsets.ModelViewSet): queryset = User.objects.filter(user_type=User.EXECUTOR) serializer_class = UserSerializer class CustomerViewSet(viewsets.ModelViewSet): queryset = User.objects.filter(user_type=User.CUSTOMER) serializer_class = UserSerializer class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer def create(self, request, *args, **kwargs): request.data['created_by'] = request.user.pk serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) @detail_route(methods=['POST', 'GET']) def assign(self, request, pk): try: task = Task.objects.get(pk=pk, assignee=None) except Task.DoesNotExist: return Response(json.dumps({"message": "Already taken"}), status=status.HTTP_400_BAD_REQUEST) expense, created = TaskExpense.objects.get_or_create( task=task, executor_id=request.user.pk, money=task.money) if created: with transaction.atomic(): request.user.update_balance(u"Взял задачу", task.money, task=task) Task.objects.filter(pk=pk, assignee=None).update(assignee=request.user) return Response(json.dumps({'message': "Taken"}), status=status.HTTP_200_OK) That is users.models from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): CUSTOMER = 1 EXECUTER = 2 … -
Django: Loop through objects and their feilds on template
I want to do something like this on template: {% for account in integrations %} <tbody> <tr> <td>#</td> <td> <p>{{ account.label }}</p> </td> <td> <button type="button" class="btn btn-success btn-xs">{{ account.link }}</button> </td> </tr> </tbody> {% endfor %} My views.py file: all_integrations = Worker.objects.filter(user=user) if all_integrations != 0: return render(request, 'integrations/index.html', {'section': 'integrations', 'integrations': zip(all_integrations)}) My models.py file: class Worker(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) a_key = models.CharField(max_length=255) a_secret = models.CharField(max_length=255) label = models.CharField(max_length=255) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) def __str__(self): return self.id My web page return the result but it's empty. i.e. one row but the account.label is empty. Also if I don't zip, it shows 10 empty rows whereas there's only one object. -
Display Information of table in Div on click with Django and Bokeh
the problem is that the bokeh documentation does not provide an example of using the event.Tab in combination with created elements that will give me the individual circle information. I was searching intensely on google, throughout StackOverflow and GitHub without success finding something that would point me in the right direction. My current Code: from Django.shortcuts import render from bokeh.plotting import figure from bokeh.embed import components from bokeh.models import Div, ColumnDataSource, Range1d, HoverTool, CustomJS from bokeh.layouts import column, row from bokeh import events from .models import Company, News import pandas as pd import math def index(request): def display_event(div, attributes=[], style = 'float:left;clear:left;font_size=0.5pt'): return CustomJS(args=dict(div=div), code=""" var attrs = %s; var args = []; for (var i=0; i<attrs.length; i++ ) { args.push(attrs[i] + '=' + Number(cb_obj[attrs[i]]).toFixed(2)); } var line = "<span style=%r><b>" + cb_obj.event_name + "</b>(" + args.join(", ") + ")</span>\\n"; var text = div.text.concat(line); var lines = text.split("\\n") if ( lines.length > 35 ) { lines.shift(); } div.text = lines.join("\\n"); """ % (attributes, style)) hover = HoverTool(tooltips=[ ("Company Name ", "@company"), ("score ", "@x"), ]) page_logo = figure(plot_width = 800, plot_height = 600, title="",tools=[hover]) page_logo.toolbar.logo = None page_logo.toolbar_location = None page_logo.xgrid.grid_line_color = None page_logo.ygrid.grid_line_color = None page_logo.yaxis.visible = None page_logo.xaxis.axis_label … -
How to add 1 day to timeuntil in django
I have a table in which I am displaying timeuntil for the difference between the dates.My timeuntil is showing in this way: Applied leave from Sept. 19, 2017 to Sept. 21, 2017 for 2 days,..But I need 3 days.How to achieve it? My Query is: Applied leave from {{pl.start_date}} to {{pl.end_date}} for {{ pl.end_date|timeuntil:pl.start_date }} -
Django: Adding User in a Group
Here's the model, class Groupchat(models.Model): admin = models.ForeignKey(User, related_name="admin") members = models.ManyToManyField(User, related_name="members", blank=True) name = models.CharField(max_length=50) I've no idea how can 'admin' add any user to the Group that he/she created. How can I do that or at least what is the right way to do so? Please helpme! -
Django Content-Type for text/xsl
I have been trying to set the content type for an xsl file. This is what I have done so far def xsl_content_type(): filename = static('sitemap.xsl') response = HttpResponse(filename) response['Content-Type'] = "text/xsl" response['Content-Length'] = len(filename) return response This returns HTTP/1.0 200 OK Date: Wed, 13 Sep 2017 05:04:46 GMT Server: WSGIServer/0.2 CPython/3.6.1 Last-Modified: Tue, 13 Jun 2017 03:54:17 GMT Content-Length: 7134 Content-Type: application/octet-stream Cache-Control: max-age=0, public Access-Control-Allow-Origin: * Even thought I did setup the Content-Type as text/xsl, all I get is application/octet-stream. I have also tried doing response = HttpResponse(filename, content_type="text/xsl"), but the content type is the same. What am I missing here? -
I wanna put data to upper1000 of Price model
I wanna put data to upper1000 of Price model. So I think I have to read upper1000 of Price,so I wrote price = Price.objects.create(city=city) price_u1000 = price.upper1000.create(city=city) but AttributeError: 'NoneType' object has no attribute 'create' error happens. models.py is class Price(models.Model): upper1000 = models.CharField(max_length=20, verbose_name='1000', null=True) from500to1000 = models.CharField(max_length=20, verbose_name='500~1000', null=True) Why does this error happen?What is wrong?How can I fix this? -
howto to post my html form to django model and save it?
i'm stuck with django forms. i have html form which i want to send and save to django model. when i try to send message i get error : ValueError at /account/userinfo/akylson/ "" needs to have a value for field "id" before this many-to-many relationship can be used. Request Method: POST Request URL: http://localhost:8000/account/userinfo/akylson/ Django Version: 1.11.3 Exception Type: ValueError Exception Value: "" needs to have a value for field "id" before this many-to-many relationship can be used. You can see my code below. Here is my html form <form role="form" class="form-horizontal" method="post"> {% csrf_token %} <div class="form-group"> <input type="checkbox" id="id_receiver" name="receiver" value="{{ user.username }}" checked hidden> <label class="col-lg-2 control-label">Тема</label> <div class="col-lg-10"> <input type="text" placeholder="" id="id_subject" name="subject" value="{{ subject }}" class="form-control"> </div> </div> <div class="form-group"> <label class="col-lg-2 control-label">Сообщение</label> <div class="col-lg-10"> <textarea rows="10" cols="30" class="form-control" id="id_message" name="message"></textarea> </div> </div> <div class="form-group"> <div class="col-lg-offset-2 col-lg-10"> <span class="btn green fileinput-button"><i class="fa fa-plus fa fa-white"></i> <span>Приложение</span><input type="file" name="files[]" multiple=""></span> <button class="btn btn-send" value="submit" type="submit">Send</button> </div> </div> </form> Here is my view.py: @login_required() def userinfo(request, username): username = User.objects.get(username=username) args = {} args['user'] = username if request.method == 'POST': sender = request.user receiver = request.POST['receiver'] subject = request.POST['subject'] message = request.POST['message'] b = Mail.objects.create(sender=sender, receiver=receiver, … -
Permission error when accessing apache2 application
I had deployed my python Django application in apache2.4.7 server in Ubuntu14.04 My 000-default.conf under /etc/apache2/sites-available looks like this <VirtualHost *:2080> DocumentRoot "/home/ubuntu/Webgis" #Coankry# Alias /conakry/static /home/ubuntu/Webgis/Map_Viewer/static <Directory /home/ubuntu/Webgis/Map_Viewer/static> Require all granted </Directory> Alias /conakry/media /home/ubuntu/Webgis/Map_Viewer/media <Directory /home/ubuntu/Webgis/Map_Viewer/media> Require all granted </Directory> <Directory /home/ubuntu/Webgis/Map_Viewer/Map_Viewer> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess conakry python-path=/home/ubuntu/Webgis/Map_Viewer python-home=/home/ubuntu/Webgis/Map_Viewer/env WSGIProcessGroup conakry WSGIScriptAlias /conakry /home/ubuntu/Webgis/Map_Viewer/Map_Viewer/wsgi.py process-group=conakry I am getting 404 forbidden error You don't have permission to access /conakry/ on this server. when i try to access the application from browser. But when it is configured to default 80 port, its working fine. I think this a permission issue. -
Django Rest Framework custom validation on ForeignKey
I have a ModelSerializer that has a ForeignKey field. This is the code for the model: class Attendance(models.Model): employee = models.ForeignKey(Employee, related_name='attendance_times') datetime = models.DateTimeField() and this is the serializer: class AttendanceSerializer(serializers.ModelSerializer): def validate_employee(self, value): try: Employee.objects.get(pk=value) except Employee.DoesNotExist: Employee.objects.create(pk=value) return value class Meta: model = Attendance fields = ('employee', 'datetime') the problem is when I send a post request to create a new object, the function validate_employee is not called and the serializer returns a validation error saying: Invalid pk "1321" - object does not exist. Why is this happening? Am I doing something wrong? Is there another validator that is being called before my validator?