Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Create Custom Page in admin site with list filter - Django?
I am new to Django, let say I have a page which displays car brands in the admin panel. Now I would like to add a new custom page in admin site which displays all cars based on the brand name like image . how can I achieve this? -
HTML input is blank even though value is set on Django Crispy form
I have a Django crispy form for editing a user: class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) confirm_password = forms.CharField(widget=forms.PasswordInput) def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.layout = Layout( Fieldset( '', 'username', 'first_name', 'last_name', 'email', 'password', 'confirm_password' ), ButtonHolder( Submit('submit', 'Submit', css_class='button white') ) ) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password'] The email field appears blank when I run the form even though the inspector in the browser shows a value: <input name="email" value="timthum@xxxxx.com" id="id_email" maxlength="254" class="emailinput" type="email"> I am using Bootstrap 2.3.2 with Django Crispy forms. -
Django Two Models in One View
I have a simple Member Model and a Blog Model. My Blog model is called MyPosts. However, whatever I have tried, I couldn't make them to be published on the same page. I want to show some personal informations and below them there will be last 10 posts of the Member. My MyPosts.user is a FK to Member user = models.ForeignKey(Member, on_delete=models.CASCADE, blank=False, null=True) My view is something like this: class MemberDetailView(generic.DetailView): model= Member template_name = 'members/member-detail.html' def get_queryset(self): return Member.objects.all() Allright, this shows the detail page with the personal information. But no result together with Blog Posts in the same view = on the same page. -
Django - store excel file in a variable during an entire session
I have developped multiples python functions that helps me process some data from an Excel file (using pandas library by the way). Those functions are able to read and process the file. Now, I want to develop a web interface that can display the processed data to the users of the website. To be more precise, when a user come on my web page : He'll upload an excel file (via an html form and using AJAX) Once the file is loaded on the server (via my reader function), he'll be able to choose some criteria to display the data he wants (using the other functions I developped to process the data). The thing is, I want to reuse my code and how can I manage to store the excel file in a variable during the entire session of the user ? I'm open to any other solution if you have any. P.S : I use pandas.read_excel(MY_EXCEL_FILE) to read the excel file. Thanks in advance -
How can I reorder the column sequence of my DataTable in my Django App?
I am doing a ajax request to pass some data from Views.py to the HTML file and render it using DataTables() javascript library. The problem I am facing is that the displayed datatable is not following the column order that I would like to. I don´t know if the solution is to reorder the json data that the datatable receives or to use some functionallity of DataTables(). What should be the best solution to reorder the table´s column? And how can I apply it to the code bellow? Views.py ... def test_table(request): data_pers = { 'Product':request.GET.get('Product'), 'Length':request.GET.get('Length'), 'Cod':request.GET.get('cod'), 'partnumbetr':'42367325' } return JsonResponse({'data_prod':data_prod}) ... HTML ... $.get('{% url "test_table" %}', {Product:Product,Length:Length,Cod:Cod}, function (data_prod) { var data_json_prod=data_prod['data_prod']; var data_array_prod = []; var arr_prod = $.map(data_json_prod, function(el) { return el }); data_array_prod.push(arr_prod); $('#id_prod').DataTable({ destroy: true, data:data_array_prod, }); ... -
digitalocean 502 bad Gateway error nginx/1.10.3(ubuntu)
This is the first time I am using digital ocean or the first attempt to deploy my django project. I have created a droplet using 1 click install django app. I have used putty and winscp to try put my files into the droplet. After uploading files and updating settings.py and urls.py I tried to open it on the browser with the droplet ip address. I get this 502 Bad Gateway error. I couldn't find a solution for this. Please help me from here. Thank you. 502 Bad Gateway nginx/1.10.3(Ubuntu) -
Django REST Framework with Social Auth over API
I'm developing a mobile app using Ionic 3 and the backend for it using Django. I want to be able to create an account normally, or via facebook login. I'm currently trying to figure out how to register a user on my own backend, if he has a facebook account and logs in with that. I took this post a guideline: https://www.toptal.com/django/integrate-oauth-2-into-django-drf-back-end I use the same serializer and view from the post above: class SocialSerializer(serializers.Serializer): access_token = serializers.CharField(allow_blank=False, trim_whitespace=True,) @api_view(['POST']) @permission_classes([AllowAny]) @psa() def exchange_token(request, backend): serializer = SocialSerializer(data=request.data) if serializer.is_valid(raise_exception=True): try: nfe = settings.NON_FIELD_ERRORS_KEY except AttributeError: nfe = 'non_field_errors' try: user = request.backend.do_auth(serializer.validated_data['access_token']) except HTTPError as e: return Response( {'errors': { 'token': 'Invalid token', 'detail': str(e), }}, status=status.HTTP_400_BAD_REQUEST, ) if user: if user.is_active: token, _ = Token.objects.get_or_create(user=user) return Response({'token': token.key}) else: return Response( {'errors': {nfe: 'This user account is inactive.'}}, status=status.HTTP_400_BAD_REQUEST, ) else: return Response( {'errors': {nfe: 'Authentication Failed'}}, status=status.HTTP_400_BAD_REQUEST, ) Here is the url: url(r'^api/social/(?P<backend>[^/]+)/$', exchange_token, name='facebook-login'), Now if I make a post request it requires an access token. This is the first thing I don't get. From how I understand it, this implies, that I need to somehow have the mobile app login with facebook (over an in … -
Django UpdateView has empty forms
I'm using UpdateView to edit data using forms. After cliking the Edit button a modal is being popped up with a few forms that can be edited and then after I edit and click confirm I redirect to /edit/{PK}. The problem is that the forms are blank! are totally new.. I want to have the previous data inside the forms already instead of blank. view.py- from django.shortcuts import render_to_response from django.shortcuts import get_object_or_404 from django.shortcuts import render, redirect from django.template import RequestContext from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView from DevOpsWeb.forms import HomeForm from DevOpsWeb.models import serverlist from django.core.urlresolvers import reverse_lazy from simple_search import search_filter from django.db.models import Q class HomeView(TemplateView): template_name = 'serverlist.html' def get(self, request): form = HomeForm() query = request.GET.get("q") posts = serverlist.objects.all() if query: posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query)) else: posts = serverlist.objects.all() args = {'form' : form, 'posts' : posts} return render(request, self.template_name, args) def post(self,request): form = HomeForm(request.POST) posts = serverlist.objects.all() if form.is_valid(): # Checks if validation of the forms passed post = form.save(commit=False) #if not form.cleaned_data['ServerName']: #post.servername = " " post.save() #text = form.cleaned_data['ServerName'] form = HomeForm() return redirect('serverlist') args = {'form': form, … -
Django FileField - not stored on disk?
I have django file upload application. I have a model looking like this: class BaseFile(Model): input_name = CharField( max_length = 132 ) content = FileField( upload_to = "%Y/%m/%d" ) upload_time = DateTimeField( auto_now_add=True ) owner_group = CharField( max_length = 32 , default = None ) In the settings.py file I have set: MEDIA_ROOT = "/tmp/storage" When I use this with the development server things seem to work, I can upload files and if I go to the /tmp/storage directory I can the %Y/%m/%d directories created and populated with my files. When I try this using Apache and mod_wsgi things also seem to work: The HTTP POST returns status 200. A subsequent GET will return the files in question. But - when I go the /tmp/storage directory there are no directories/files to be found and if I stop and start Apache the GET will fail with IError: No such file: /tmp/storage/2017/11/27/FILEX_Z1OZMf8 So - it seems to me that Django keeps the files in memory when using mod_wsgi? I am using 100% default Django settings when it comes to storage backend. I see no errors in the Apache log. -
TypeError at /admin/blog/entry/add/ - Python 2.7
I'm a beginner and I'm having this error while trying to do this tutorial: Link Tutorial Blog Django. Please help me solve this problem. I suspect that it may be related to the use of the Markdown package. The Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/blog/entry/add/ Django Version: 1.11.7 Python Version: 2.7.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'django_markdown'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 19 context must be a dict rather than Context. 9 : {% for field in line %} 10 : <div{% if not line.fields|length_is:'1' %} class="field-box{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> 11 : {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} 12 : {% if field.is_checkbox %} 13 : {{ field.field }}{{ field.label_tag }} 14 : {% else %} 15 : {{ field.label_tag }} 16 : {% if field.is_readonly %} 17 : <div class="readonly">{{ field.contents }}</div> 18 : {% else %} 19 : {{ field.field }} 20 : {% endif %} 21 : {% … -
Can't save and redirect form with django
I'm trying to do a form to obtain patient data via Django. I've followed this tutorial https://tutorial.djangogirls.org/en/extend_your_application/ and everything is fine until I press the "save" button of the form. It doesn't save the new patient in the database and neither does it redirect it to the main page. Could someone help me? I send the "view", "form" and "patient_detail", the error should be somewhere here... If you need any more of the code please tell me! I've followed the tutorial thoroughly though... enter image description here enter image description here enter image description here -
Getting HTTP 400 when trying to upload image from Javascript to Django
I am trying to upload an image from HTML/JS front end to Django. Getting the following error - The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS. It's a 400 (Bad Request) that I am getting back to the front end. HTML <form method="post" id="imgForm" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <h3> <span class="label label-default">Upload Image</span> </h3> <div class="input-group"> <span class="input-group-btn"> <span class="btn btn-default btn-file"> Browse… <input type="file" id="imgInp" accept="image/*" image="image" name="imgInp" /> </span> </span> <input type="text" class="form-control" readonly> </div> <img id='img-upload'/> <br><br> <button class="btn btn-primary" type="submit" style="" id="tf_predict">Predict</button> </div> </form> JS $("#tf_predict").click(function (e){ e.preventDefault(); image_file = $('#imgInp')[0].files[0];//prop('files'); //csrfmiddlewaretoken = document.getElementsByName('csrfmiddlewaretoken')[0].value var myFormData = new FormData(); myFormData.append('image_file', image_file); //myFormData.append('csrfmiddlewaretoken', csrfmiddlewaretoken); $.ajax({ type: "POST", url: 'http://localhost:8000/ap/predict', // or just url: "/my-url/path/" processData: false, data: myFormData, success: function(data) { console.log(data) resp = JSON.parse(data); perc_prob = resp.water * 100; value = perc_prob.toString()+'%' $('#progress_bar').text(value); $('#progress_bar').attr("style","width:"+value); }, error: function(xhr, textStatus, errorThrown) { alert("Please report this error: "+errorThrown+xhr.status+xhr.responseText); } }); }); Views.py def predict(request): if request.method=='POST': image_data = request.FILES['image_file'] results = {' {"water": 0.8, "nowater":0.2 } '} print(results) return HttpResponse(results) My form only has the one image input that I am trying to send. Any help would be appreciated! -
How to run the django web server even after closing the shell on Amazon Linux
I'm running a Django application on my Amazon Linux instance using the below command: python manage.py runserver ec2-instance-ip.us-east-2.compute.amazonaws.com:8000 I want the application to be running even after I quit the shell. How do I run this web server even after quitting the shell on Amazon Linux? I tried using the & as shown below, but it didn't work. python manage.py runserver ec2-instance-ip.us-east-2.compute.amazonaws.com:8000 & -
Show Hide conditional statement for select
I'm trying to figure out how to implement a simple show/hide conditional statement on a select HTML tag. If I have a select tag like the following: <select class="form-control" id="accesslevel_id"> <option> Facility </option> <option> Division </option> </select></div> In the example of a user selecting facility or division with the view defined as: facilitycfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 1).values_list('cfo_ntname', flat = True) divisioncfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 2).values_list('cfo_ntname', flat = True) args = {'facilitycfo': facilitycfo,'divisioncfo': divisioncfo} return render(request,'accounts/requestaccess.html', args) How would I display either facilitycfo or divisioncfo queryset depending on the select. I'm not using a form.py file for this example only the template with the view inside a form tag. You'd this something like this would be very trivial without having to use Jquery. I'm in the process of learning so if my logic is incorrect please help clarify. -
Django: cannot login via API
So I have two web-sites: A (the main service) and B (an internal tool). My goal is to auto-login to B via A. So in A I have an endpoint for authorization in B, which simply renders the basic A's login template. If a user successfully logins, then a hidden request is sent to a special B's endpoint (more details on this later), and finally the user gets redirected back to B. At this step I assume, that the user should have already been authenticated in B, but actually it's not the case :( The hidden request to B after authenticating in A simply uses the provided credentials to create/update the corresponding user in B, and also includes the following code snippet: user = auth.authenticate(...) auth.login(request, user) As I said before, this code doesn't work, i.e. after redirecting to B I still have to manually login. The interesting part here is that each time I repeat the workflow mentioned above, a new Session object is created in B, but I guess the session_key of that object is never used. I tried to set the sessionid cookie in the redirect response, but again without success. -
Django FieldError on poly__within
I cannot further find the cause why Django presents an error at the line where I call poly__within to query GeoDjango in PostGIS. My model doesn't have a poly yet the error below says its a FieldError. I do not know where or why its looking for a field for poly Traceback (most recent call last): File "/home/gridlockdev/Desktop/heroku/grace/env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/gridlockdev/Desktop/heroku/grace/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/gridlockdev/Desktop/heroku/grace/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/gridlockdev/Desktop/heroku/grace/network/views.py", line 71, in view_routes routes = Route.objects.filter(poly__within= geom[0]) File "/home/gridlockdev/Desktop/heroku/grace/env/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/gridlockdev/Desktop/heroku/grace/env/lib/python3.5/site-packages/django/db/models/query.py", line 784, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/home/gridlockdev/Desktop/heroku/grace/env/lib/python3.5/site-packages/django/db/models/query.py", line 802, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/home/gridlockdev/Desktop/heroku/grace/env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1250, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/home/gridlockdev/Desktop/heroku/grace/env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1276, in _add_q allow_joins=allow_joins, split_subq=split_subq, File "/home/gridlockdev/Desktop/heroku/grace/env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1154, in build_filter lookups, parts, reffed_expression = self.solve_lookup_type(arg) File "/home/gridlockdev/Desktop/heroku/grace/env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1034, in solve_lookup_type _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) File "/home/gridlockdev/Desktop/heroku/grace/env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1352, in names_to_path "Choices are: %s" % (name, ", ".join(available))) django.core.exceptions.FieldError: Cannot resolve keyword 'poly' into field. Choices are: agency, agency_id, created_at, distance, duration, ogc_fid, route_color, route_desc, route_id, route_long, route_name, … -
ValueError: invalid literal for int() with base 10: '' I got this error when empty value was sent
I got ValueError: invalid literal for int() with base 10: '' error. I wrote def convert_json(request): json_body = json.loads(request.body) return json_body.get('ans', 0) When I send json like { "ans": "" } the error happens.I really cannot understand why this error happens because I think 0 is returned.In this json,"" means None , so 0 should be returned,I think.But my code did not work wells how should i fix this?What should I write it to make ideal system? -
Looping in django template creating earror in table data
I am using a table in django template. I passed two arrays of objects in context to the template. When i am looping through the two arrays of objects, it is creating problem when the if condition is failing. When if condition is not fulfilled it places the value of later td in the previous ones. Then i tried to apply an else to provide blank td if the condition is not fulfilled. But because of else condition it creates skips the first four blocks in all conditions. I just want to give blank spaces in first for td(table data) if the if condition is not statisfied. <table id="searchFilterNewAdmin" class="table table-striped table-bordered table-hover" > <thead> <tr role="row"> <th class="sorting_asc" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" aria-sort="ascending" aria-label="Rendering engine: activate to sort column descending">Admin Name</th> <th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" aria-label="Browser: activate to sort column ascending">Tablet No</th> <th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" aria-label="Platform(s): activate to sort column ascending">Region</th> <th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" aria-label="Engine version: activate to sort column ascending">Car Make</th> <th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" aria-label="CSS grade: activate to sort column ascending">Total Time(s)</th> <th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" aria-label="CSS grade: activate to sort column ascending">Last Opened</th> <th … -
Django queryset filter model where related objects have ALL a field value
I have two models: class Photo(models.Model): # fields class PhotoTags(models.Model): photo = models.ForeignKey(Photo, related_name="tags") tag_name = models.Charfield() is_disabled = models.BooleanField(default=False) What I'm trying to achieve is to get photos where tags are all with is_disabled = True. EDIT I tried with Photos.objects.filter(tags__is_disabled=True) but it returns photos with at least one tag that is disabled Thank you -
Save items and display the saved items dynamically in Django with Postgresql database
I am new to Django. I am trying to input person names in a HTML page, save it to the Postgresql and show the saved names in the HTML. I need help to create the model.py This is my index.html :- <!DOCTYPE html> <html> <body> <form> First name:<br> <input type="text" name="firstname"> <br> Last name:<br> <input type="text" name="lastname"> <br><br> <input type="submit" value="Submit"> </form> <div class="saved_names"> <!-- Here I am want to display the saved names dynamically --> <li>Micky Mouse</li> <li>Name 2 </li> <li>Name 3 </li> ..... </body> </html> This is view.py :- # homeapp/views.py from django.shortcuts import render from django.views.generic import TemplateView # Create your views here. class HomePageView(TemplateView): def get(self, request, **kwargs): return render(request, 'index.html', context=None) I have successfully connected the Postgres, this is settings.py :- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'testdb', # DB Name 'USER': 'testuser', # User 'PASSWORD': 'mypass', # Password 'HOST': 'localhost', 'PORT': '5432', } } testdb is my Postgresql database. It has a table called user. user table has three columns id, First_Name, Last_Name . I can create the database, table, columns and also insert the data in the Postgresql columns CREATE DATABASE testdb; CREATE TABLE user ( id serial PRIMARY KEY, First_Name … -
Django Website - TemplateDoesNotExist at /edit/117/
I'm using UpdateView to edit data using forms. After cliking the Edit button a modal is being popped up with a few forms that can be edited and then after I edit and click confirm I get an error: TemplateDoesNotExist at /edit/117/ (or other pk...) DevOpsWeb/serverlist_form.html Request Method: POST Request URL: http://devopsweb:8000/edit/117/ Django Version: 1.11.6 Exception Type: TemplateDoesNotExist Exception Value: DevOpsWeb/serverlist_form.html Why do I get this error? Why when I get the modal the information of the PK is blank...? Does anyone know any of these questions? I'm really stuck :( Thank you! view.py- from django.shortcuts import render_to_response from django.shortcuts import get_object_or_404 from django.shortcuts import render, redirect from django.template import RequestContext from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView from DevOpsWeb.forms import HomeForm from DevOpsWeb.models import serverlist from django.core.urlresolvers import reverse_lazy from simple_search import search_filter from django.db.models import Q class HomeView(TemplateView): template_name = 'serverlist.html' def get(self, request): form = HomeForm() query = request.GET.get("q") posts = serverlist.objects.all() if query: posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query)) else: posts = serverlist.objects.all() args = {'form' : form, 'posts' : posts} return render(request, self.template_name, args) def post(self,request): form = HomeForm(request.POST) posts = serverlist.objects.all() if form.is_valid(): # Checks … -
Celery beat shedule task in runtime doesn't execute with crontab options
I try to schedule task dynamically during the runtime but it doesnt work. task_name = 'my_task_{}'.format(timezone.now()) now = timezone.localtime() + relativedelta(minutes=1) crontab_shedule, _ = CrontabSchedule.objects.get_or_create( minute = str(now.minute) ) PeriodicTask(name=task_name, task=my_p_func, crontab=crontab_shedule).save() This code will save expected records to the database including new timestamp into periodic_tasks last_update column. Running beat worker recognize this changes and correctly rewrite scheduled tasks (new one is including). But nothing more happens. When I schedule task via interval, it works fine. I think the problem is with timezone or something similar. But it seems ok. django_celery_beat.utils.now() This returns correct time for my timezone and crontab record into database is ok too. Using CELERYBEAT_SCHEDULE variable in settings file with crontab works fine too. Interval scheduling in runtime works fine. Starting celery beat celery -A my_project beat -l debug --scheduler django_celery_beat.schedulers:DatabaseScheduler Using django-celery-beat==1.1.0, celery==4.1.0 and broker is redis. I forgot for something? Thank you for your advice. -
Django Imagefield and Legacy Database
I'm working with a legacy database that has images stored in a table. I want to use these images in <img> tags. Do I need to write a script to read all the rows in the table, create a corresponding Django model, then save the model so that the image file is saved to the file system? Or is there a way to do this without iterating through all the old data? Thanks! -
Django Image Not found using template tags
I'm in trouble for many days now and all solutions given didn't helped me yet. The image profile I want to show doesn't appear if I use the template variable {{ userprofile.photo.url}} (the result is the Alt text) but it does work when I put the path to the image like this : /dashboard/media/photo/profils/user.png. I've tried to debug, it seems the url is good but the result given is this : **[27/Nov/2017 13:55:07] "GET /dashboard/ HTTP/1.1" 200 44757 Not Found: /media/photos/profils/user.png [27/Nov/2017 13:55:07] "GET /media/photos/profils/user.png HTTP/1.1" 404 2295** Here the files of the project : Structure of the project : project_dir/ dash-app/ __init__.py settings.py urls.py wsgi.py dashboard/ __init__.py admin.py app.py forms.py models.py urls.py views.py ... templates/ dashboard/ index.html ... static/ dashboard/ images/ logo9.png ... media/ dashboard/ photos/ profils/ user.png ... On the urls.py : from django.conf.urls import url from dashboard import models from dashboard import views from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'^$', views.index, name='index'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) On the settings.py : STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, "dashboard", "static") #dashboard/media/ MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "dashboard", "media") On the … -
Tastypie - How to only authorize update a model through foreign keys?
A have a Location model that is foreign key in many models. don't want users to be able to create, edit or delete a Location directly (using the /api/v1/location/ endpoint), but i want them to be able to do is while creating an object that has Location as its foreign key. e.g.: /api/v1/event/ { "name": "xxx", "location": { <new location> } } Is it possible?