Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Translating a django session object back into a model object
Let's say I have a model user and I do this: request.session.object['my_user'] = my_user Later, I would like to create a new object with the value stored in that session object, something like: my_new_user = request.sesion.get('my_user'). Is it possible? How can or should I do it? -
Django Template: How to refer to individual objects in for loop in Javascript?
I am building an online puzzle app using Django which contains a solution feature. Each solution has a up_vote and down_vote field, each of which are ManyToManyFields with the User model. I take the .count() of each field and subtract them to calculate the net votes. I am trying to create a feature so that when the user clicks the "up" button, the up_vote field of the solution is updated. I am thinking of using Ajax for this. In order to do this, I need to be able to reference the specific solution in Javascript. Here is my current template: {% for solution in solutions %} <div class="card bg-light"> <div class="card-header subtitle"> <div class="triple-left">{{ solution.datetime }} by <a href="{% url 'profile' username=solution.user.username %}">{{ solution.user.username }}</a></div> {% if user == solution.user or user.profile.teacher %} <div class="triple-right"> <a href="{% url 'edit_solution' puzzleID=solution.puzzle.id solutionID=solution.id %}">edit</a> &nbsp;&nbsp; <a class="delete" href="{% url 'delete_solution' puzzleID=solution.puzzle.id solutionID=solution.id %}">delete</a> </div> {% endif %} <div class="triple-center"> <a class="up-not-clicked" id="up_vote">&uArr;</a> &nbsp;&nbsp; {{ solution.points }} &nbsp;&nbsp; <a id="down_vote">&dArr;</a> </div> </div> <a href="{% url 'solution' puzzleID=solution.puzzle.id solutionID=solution.id %}"> <div class="card-body"> <h5 class="card-title">{{ solution.title }}</h5> <p class="card-text">{{ solution.content|linebreaks }}</p> </div> </a> </div> <br> {% endfor %} Note this line: <a class="up-not-clicked" id="up_vote">&uArr;</a> In … -
django 2.0.3 and Browser not showing static files
django 2.0.3 and Python 3.6.x FireFox, Chrome, Safari I'm not sure that this is a django issue as this is something I've never seen happen. I am hoping someone has seen this before or knows what I am doing wrong. My browser will not find my static files with runserver. What is strange is that the urls within the templates are correct and if I paste the urls into the browser, the files are found. If I run ./manage.py findstatic --verbosity 2 css/style.css The files are found. Yet the browser, Firefox, Chrome, Safari (all latest versions) both show a 404 in the WebConsoles of the pages where I access the static resources. <link rel="stylesheet" href="{% static 'trans/css/style.css?1510690221335' %}"> Does not work. If I change to the actual URL <link rel="stylesheet" href="http://localhost:8080/trans/css/style.css?1510690221335"> Things work fine. My relevant (As best I can tell) configuration is `STATIC_ROOT = str(ROOT_DIR('staticfiles')) STATIC_URL = '/static/' STATICFILES_DIRS = [ str(APPS_DIR.path('static')), ] /#staticfiles-finders STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ]` I also added static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) to my urls.py All permissions on my static folder and sub folders are correct. Has anyone seen this before and know of a resolution? Thank you. -
Django Rest Framework - how to nest documentation?
I have created a web app with the following features: Users, Outreach, Favourites. Now I want to document the API, but I want to do it in a browsable way so that when you go to the API root you see: Users Outreach Favourites and then when you click on one, for instance Users, it takes you to another browsable 'root' that shows a link to: Create Update Delete for the resource users. Is this possible? I want the API to be as easy to understand and browse as possbile. Thanks for any help -
Django with external reverse Proxy
I was always running my django apps with Gunicorn + supervisor + nginx (as reverse proxy from domainename to localhost:8000) all of them in the same machine. Today I have an IMPOSED set up (testing and production): Machine 1: Port 8000 Open Django app only accessible to restricted IPs through domainname1:8000 Machine 2: Just Apache serving only as just a reverse proxy from domainname2 (http 80 port) to domainname1:8000 this machine is accessible to public. Problem due to this architecture: when user signs up, the verification link sent by email is domainname1:8000/<verification sequence> instead of domainename2/<verification sequence> Can you explain if you know what's exactly going on and what's the source of this logic inconvenience and if there is a workaround to solve this. Thank you. -
Django __init__() missing 1 required positional argument: 'data'
Im using Django 2.0.1 Basically I'm trying to implement cropperjs and first I was havving trouble with an 403, that prevented me from uploading an image (this is because the script returns a Json response and I didn't have my view to handle it) and so I did, but then I ran into this problem. Please help I don't deserve this, I pay my taxes. On my forms.py class EmployeeForm(forms.ModelForm): class Meta: model = Employee fields = '__all__' exclude = ['user', 'date_joined','Credits_earned','skills'] department = forms.CharField( widget=forms.TextInput(attrs={ "class": "form-control", "placeholder": _("User...") } ) ) title = forms.CharField( widget=forms.TextInput(attrs={ "class": "form-control", "placeholder": _("Title...") } ) ) avatar = forms.ImageField( widget=forms.FileInput() ) on my views.py from django.http import JsonResponse class EmployeeUpdate(JsonResponse,UpdateView): template_name = 'test.html' model = Employee form_class = EmployeeForm success_url = '/' def get_queryset(self): return super(EmployeeUpdate, self).get_queryset().filter(user=self.kwargs['pk']) def render_to_response(self, context, **response_kwargs): return self.render_to_json_response(context, **response_kwargs) The script on the template: <script> window.addEventListener('DOMContentLoaded', function () { var avatar = document.getElementById('avatar'); // Current avatar var image = document.getElementById('image'); var input = document.getElementById('id_avatar'); // Image input var $progress = $('.progress'); var $progressBar = $('.progress-bar'); var $alert = $('.alert'); var $modal = $('#modal'); var cropper; $('[data-toggle="tooltip"]').tooltip(); input.addEventListener('change', function (e) { var files = e.target.files; var done = … -
django ckeditor running into unexpected errors
I am using django-ckeditor python package in my django app (django 1.11 + python 2.7). I have integrated it with s3 and it is hosted on Heroku. So far everything runs smooth. Earlier I had an issue that non admin user could not upload images to server thus can not use any images as a part of their content. I fixed it by overriding ckeditor's browse and upload view. When i tested it it was working just fine. I pushed it to production. Now none of my user can use ckeditors image upload or browse feature. when I try it, (as an admin or as regular user) it works. some users reported that app crashes, some said image wont show up despite uploading to server (also I can't see it in my s3 bucket.) other images are working well with s3 for all users. but ckeditors images are working only for me, no matter which machine or which role I try as. I also checked heroku apps, but they are not helpful at all. Does anyone have idea any guesses why this could be happening. -
Django, DRF - returning a list of user permissions in boolean values
I would like to achieve the following in Django/DRF: Implement an endpoint which, given the id of an user, returns a list of their permissions. (And by that I mean the models User and Permission from django.contrib.auth.models). Now, this is quite simple, I can get those using this code below: class UserPermissions(RetrieveUpdateDestroyAPIView): serializer_class = PermissionSerializer def get(self, request, pk): permissions = User.objects.get(pk=pk).get_all_permissions() print User.objects.get(pk=pk).user_permissions data = { 'permissions': permissions } serializer = PermissionSerializer(data) return Response(serializer.data, status=status.HTTP_200_OK) And this is the response I get: { "permissions": [ "auth.add_user", "auth.add_group", "auth.add_userproxy", "auth.change_group", "auth.change_user", "auth.delete_permission", "evidence.view_all_customers" ] } However, this is not exactly what I want. I would like to return a list of all the permissions in the system, with a true/false value for each individual permission for a given user. Naturally, I tried getting the complete list of permissions to compare them against the user's permissions, but this is where I stumbled upon a problem: The Permission model from django.contrib.auth.models, from which I can get a complete list of permissions in the system, has the following attributes: name, content_type and codename. I found that codename is the attribute I need, but there's a problem - it contains the name without the … -
Django - django jsonresponse redirects "accounts/login"
I'm using bootstrap navigation bar to login into my website. I'm trying to use AJAX for login. However instead of sending back to the ajax page on success or failure, it redirects to "accounts/login" page. Following are my code details urls.py path('accounts/login', user_views.user_login, name='user_login'), views.py def user_login(request): username = password = '' response_data = {} if request.POST and request.is_ajax: email = request.POST['login'] password = request.POST['password'] try: user = authenticate(email=email, password=password) if user is not None: if user.is_active: login(request, user) response_data = {'message' : "Success"} else: response_data = {'inactive':"Email ID not activated."} else: response_data = {'incorrect':"Email Address / Password incorrect"} return JsonResponse(response_data, safe=False) .js file $(document).ready(function () { var $myForm = $('#login-nav') $myForm.submit(function(e) { e.preventDefault(); var formId = $(this).attr('id'); $.ajax({ url: $myForm.attr("data-url"), // the file to call type: "POST", // GET or POST data: $(this).serialize(), // get the form data success: function(data) { var login_response = jQuery.parseJSON(data); if (login_response.user == "nouser"){ $("#login-error").text('Email ID not Registered.') $('#login-error').css('display', 'block'); } } }); return false; }); }); I get this page all the time 127.0.0.1:8000/accounts/login {"incorrect": "Email Address / Password incorrect"} Please, can anyone help me here? -
Django Model Object to Javascript Array
This question was asked a few times before, but I'm unable to get results. I have a Django model. I convert the model to a JSON string: from django.core.serializers.json import DjangoJSONEncoder from django.core import serializers from .models import MonthData #Returns multiple rows monthData = MonthData.objects.filter(project=id) #Convert models to JSON string monthDataStr = serializers.serialize("json", monthData,cls=DjangoJSONEncoder) In my template, I want to convert the JSON string to a Javascript array: var monthData = JSON.parse({{monthData|safe}}); However Javascript fails to do the conversion. The JSON resulting string looks as follows: [{"model": "raidApp.monthdata", "pk": 3, "fields": {"project": 1, "month": "2017-06-01T00:00:00Z", "budgetCost": 0.0, "forecastCost": 385.0, "actualCost": 0.0, "baselineProgress": 6.0, "plannedProgress": 6.0, "actualProgress": 4.0}}, {"model": "raidApp.monthdata", "pk": 4, "fields": {"project": 1, "month": "2017-07-01T00:00:00Z", "budgetCost": 261.0, "forecastCost": 620.0, "actualCost": 0.0, "baselineProgress": 11.0, "plannedProgress": 11.0, "actualProgress": 8.0}}, {"model": "raidApp.monthdata", "pk": 5, "fields": {"project": 1, "month": "2017-08-01T00:00:00Z", "budgetCost": 391.0, "forecastCost": 741.0, "actualCost": 385.0, "baselineProgress": 19.0, "plannedProgress": 19.0, "actualProgress": 12.0}}, {"model": "raidApp.monthdata", "pk": 6, "fields": {"project": 1, "month": "2017-09-01T00:00:00Z", "budgetCost": 522.0, "forecastCost": 868.0, "actualCost": 500.0, "baselineProgress": 28.0, "plannedProgress": 28.0, "actualProgress": 15.0}}, {"model": "raidApp.monthdata", "pk": 7, "fields": {"project": 1, "month": "2017-10-01T00:00:00Z", "budgetCost": 652.0, "forecastCost": 1001.0, "actualCost": 550.0, "baselineProgress": 35.0, "plannedProgress": 34.0, "actualProgress": 20.0}}, {"model": "raidApp.monthdata", "pk": 8, "fields": {"project": 1, "month": "2017-11-01T00:00:00Z", … -
Reliably get client IP for HTTPS request in django?
Is there a way to reliably get client's IP in Django if the request is via HTTPS? For instance, is the data available in request.META['HTTP_X_REAL_IP'] secure against spoofing and other attacks? In my case request.META['REMOTE_ADDR']=='10.0.0.132' which is an internal IP. So I could rely on request.META['HTTP_X_REAL_IP'] or request.META['HTTP_X_FORWARDED_FOR'] only. My site is on pythonanywhere.com, if that matters. So, is there a reliable client IP in request.META via HTTPS? -
Foreign key to different model field in django
I have two models and I want to get- some fields of model 1 to model 2.For that I am using field in model 2 = models.ForeignKey(model1, to_field = 'field i want from model 1') The error which I get in console is myapp.IFileTable.calendar_year: (fields.E304) Reverse accessor for 'IFileTable.calendar_year' clashes with reverse accessor for 'IFileTable.created_on'. HINT: Add or change a related_name argument to the definition for 'IFileTable.calendar_year' or 'IFileTable.created_on'. lfcalendar.IFileTable.title: (fields.E311) 'IFile.title' must set unique=True because it is referenced by a foreign key. My model 1 class IFile(models.Model): title = models.CharField(max_length=255, blank=True) year = models.CharField(max_length=4) uploaded_at = models.DateTimeField(auto_now_add=True) My model 2 class IFileTable(models.Model): title = models.ForeignKey(IntermediateFile, to_field = 'title') user = models.CharField(max_length = 10) created_on = models.ForeignKey(IntermediateFile, to_field = 'uploaded_at') calendar_year = models.ForeignKey(IntermediateFile, to_field = 'year') -
How to create a MultipleInputWidget for the Django ArrayField?
I am used to the Kinto Admin ArrayField selector and I wanted to use a similar interface in the Django Admin. I created a model using an ArrayField: class Article(models.Model): primary_tags = ArrayField( models.CharField(max_length=30) ) Do you know of any AdminWidget that I could use to achieve that? -
LDAP E-Mail Backend in Django
I am working on my webapp by using the Django-Framework. Currently I can login as an LDAP user with the username (using python-auth-ldap). Is there a backend for an LDAP e-mail authentication. I did create a backend for local users (ModelBackend) to login with their e-mail. It workes perfectly fine. But when I try it with LDAP users, this is the error. search_s('DC=sbvg,DC=ch', 2, '(sAMAccountName=%(user)s)') returned 0 objects: Authentication failed for user@domain.com: failed to map the username to a DN. If you have a working backend or any idea, do not hesitate to post it. Thanks in advance. -
Django templates - Image from media_root rendered in homepage, but not other pages
I have an image that renders on my homepage, but it doesn't on a different page using the same code. I figure the problem may be the difference my url path maybe? It's the only difference I can find. When I inspect each element, this is what I see: Working image: /event/image.png Broken Image: /event/media/image.png I'm rendering the image like this in my template: <img src="media/{{event.image}}" class="img-responsive" /> My model is just aa model.Image field and here are is my view for the Broken image page: def event(request, product_id): event = get_object_or_404(Event, id=product_id) image = event.image context = {'event':event, 'image':image} template = 'tourney.html' return render(request, template, context) In my terminal, it says image not found. So how can I change my settings so that it looks in the right directory no matter which path I'm in? Here are my media settings: if DEBUG: MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static', 'static-only') MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static', 'media') STATICFILES_DIRS = ( os.path.join(os.path.dirname(BASE_DIR), 'static', 'static'), ) -
Django ArrayField. How to save nested array of time through django admin?
I already asked this question several months ago. Question is stupid, but i cant find solution. What a valid format for saving nested array of time from simple form text field? I have ArrayField like this: schedule = ArrayField( ArrayField( ArrayField( models.TimeField(null=True), ), size=2, null=True, ), size=7, null=True, blank=True, ) When i am trying to save it from django admin like: ((09:00, 09:00), (09:00, 09:00), (09:00, 09:00), (09:00, 09:00), (09:00, 9:00), (9:00, 9:00), (9:00, 9:00)) I'm getting errors Item 0 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 1 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 2 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 3 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 4 in the array did not validate: Item 0 … -
Django Ceilometer get events for all projects
I have a problem for getting all events for all tenants/projects in Ceilometer. When I get the event list I always get only the list of events related to project that my user assigned. The user is admin in openstack. Explaining in more detail: Here is my sample code: def sync_resources(): logger.info("Executing sync_resources") sync_tenants() tenants = Tenant.objects.all() managers = Manager.objects.filter(is_active=True) for manager in managers: services = manager.services.all() regions = manager.region_set.all() for region in regions: ceilometer_driver = CeilometerDriver(region_name=region.name, **manager.ceilometer_params) if ceilometer_driver.is_authenticated: for tenant in tenants: queries = [ceilometer_driver.make_query("project_id", ceilometer_driver.EQUAL, tenant.tenant_id)] resource_list = ceilometer_driver.get_event_list(query=queries) The sample function uses a driver that I have written. And the driver first authenticates with username,password and project_id. After that it should get the list of events based on prjojects. The problem here is that even the user is admin I can only get the events that the admin is assigned as user. For example instead of getting the events when I try to get the resource list I get all. However when I try events I get only events of projects for the user. # returns all the resources for all tenants/projects resource_list = ceilometer_driver.get_resource_list() # returns only the events for user projects resource_list = ceilometer_driver.get_event_list() … -
Pycharm produces different results if debugging with breakpoints
I'm using pycharm to debug the django development server for analysing a form instantiation where I'm using forms class inheritance. If I run my application without stepping into any breakpoints (temporarily disabling all) then everything works as it should. If I do stop at some breakpoint then the instantiated form produces different results. In particular I have two multiple choices fields, and sometimes only one or both are not bound to the initial value. I can see from the debugger that the part of the code that set field['field_name'].initial = value is executed, nonetheless randomly I get field['field_name'].initial == None. My watches panel is empty so there is no risk that I did modify any values by accident. This is very weird for me! Why would a code execution change depending if I step or not into some breakpoints? What might cause this odd behaviour? -
Django : Validator doens't work when specifying the field to show on the template
i'm new to Django, and i'm working on validators, so i've created a simple form that contains One CharField. after that i wrote a validation method for that field, and everything worked perfectly. form method="POST" action="/veentes">{% csrf_token %} {{form.as_p}} <input type="submit" name="submit"> </form> But when i want to specify the form field that i want to show like: {{form.url}} the form shows but , the validation method doesn't work any more ! here is my form.py: class SubmitUrlForm(forms.Form): url=forms.CharField(label='Submit Form', validators=[validate_url]) validators.py def validate_url(value): url_validator=URLValidator() try: url_validator(value) except: raise ValidationError("Invalid URl !") view : class HomeViews(TemplateView): def get(self, request,*args,**kwargs): form=SubmitUrlForm() context={"title":"submit","form":form} return render(request,"appOne/testPage.html", context) def post(self,request,*args,**kwargs): form=SubmitUrlForm(request.POST) if form.is_valid(): print(form.cleaned_data) context={"form":form} return render(request,"appOne/testPage.html",context) any help please , Thank You. -
How send POST request from localhost (http) to django (https)?
Send to proxy /api with all params (header/cookie/post) as docs PrtScreen with request param (header/cookie/post) And get PrtScreen with response 403 Forbidden server.js 'use strict'; const fs = require('fs'), proxy = require('http-proxy-middleware'), browserSync = require('browser-sync').create(); function returnIndexPageFn(req, res, next) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(fs.readFileSync('./public/app.html')); res.end(); next(); } browserSync.init({ port: 88, server: { baseDir: 'public/', index: 'app.html', middleware: [ {route: '/home', handle: returnIndexPageFn}, proxy(['/api', '/media'], { target: 'https://security-site.com', logLevel: 'debug', changeOrigin: true, headers: { Referer: 'https://security-site.com', }, }) ] } }); I try another with angular 5, but have the same result((( proxy.conf.json { "/api": { "target": "http://stage.attacher.co/", "secure": false, "changeOrigin": true, "logLevel": "info" } } How to solve this problem? -
Is it possible to run the pyomo solver in Django the framework?
I am setting up a Website for Solving Optimisation Problems on a website. I already built a model and it works. No I need to implement it into the Django framework. Is there any way to pass the Pyomo command as a function, so that the solver runs in a button click? I also ask myself if the framework has enough power to solve such problems. I would gladly appreciate any suggestions as I am also new to web development. -
MultiValue Dict Key Error Django - Forms when trying to display DateField
I have a form with DateField - 'receivedon' attribute as below: forms.py: class PreDataForm(forms.ModelForm): journalname=forms.ChoiceField(required=True,choices=JOURNAL_CHOICES) articletype = forms.ChoiceField(required=True, choices=ARTICLE_TYPES) granttype = forms.ChoiceField(required=True, choices=GRANTS) receivedon=forms.DateField(widget=forms.SelectDateWidget) class Meta: model=PreData fields=['journalname','articlename','articlenumber','caname','camail','articletype', 'country','affliation','granttype','status','receivedon'] I will be asking users to fill that date in html, normal procedure: html: <div class="center col-md-6"> Received On: {{ form.receivedon }} </div> Now i want to upload the date through django views like this: views.py: if request.method=="POST": form=PreDataForm(request.POST or None) print request.POST['receivedon'] if form.is_valid(): instance=form.save(commit=False) instance.save() One thing is that form is always invalid for post request, when i check is_valid function, other thing when I try to display datefield data using request.POST['receivedon'] i am getting Multi Value Dict Key Error Can any one help me with this? Thanks. -
Heroku app crash after deploy (using python with django)
I can't made any change in heroku app like if i am change any single word like HTML. When changes done in git the next step is deploy an app in heroku. When deploy is done the app is crashed. i didn't find any error for this. Please tell me why my app is crashed again and again. Thanks in advance. -
Django-allauth--overriding a view and saving form information
I'm overriding allauth's SignupView in order to add another form into the same view. The other form has additional information that I intend to make mandatory at sign up. But because it's connected to a separate model, Profile, I cannot simply add fields into the original SignupView form. I've managed to render my form into the view, but the input from the additional form will not save. How can I get the secondary form to save? Here's the view: from allauth.account.views import SignupView from .forms import initialPreferenceForm class MySignupView(SignupView): initial_preference_form = initialPreferenceForm def get_context_data(self, *args, **kwargs): # Pass the extra form to this view's context context = super( MySignupView, self).get_context_data(*args, **kwargs) context['initial_preference_form'] = initialPreferenceForm return context def form_valid(self, form): self.user = form.save(self.request) My form: class initialPreferenceForm(forms.ModelForm): class Meta: model = Profile fields = ['favorite1', 'favorite2'] Template: <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {{ form|crispy }} {{ initial_preference_form }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button class="btn btn-primary" type="submit">{% trans "Sign Up" %} &raquo;</button> </form> I'm obtaining the save logic for SignupView from the allauth code: https://github.com/pennersr/django-allauth/blob/master/allauth/account/views.py#L227 -
Photo in my django database wont display
I am trying to display some images from my django database Here are the models class Problemspage(models.Model): problemname = models.CharField(max_length=1000) difficultyproblem = models.CharField(max_length=50) difficultysolution = models.CharField(max_length=50) code = PythonCodeField(blank=True, null=True) photo = models.ImageField(upload_to='static/images', default='static/images') and here are my views where I am using the Id of the problemname to call the name of the problem, e.g 'multiples of 3 and 5' def viewproblem(request, problemnameId): context = { 'title':'Problem ' + problemnameId, 'data': allproblems, 'name': Problemspage.objects.filter(id=problemnameId) } return TemplateResponse(request, 'app/viewproblem.html', context) In my div I am trying to call that image {% for nameofproblem in name %} <img src="{{ nameofproblem.photo.url }}"/> {% endfor %} However I am getting an error Failed to load resource: the server responded with a status of 404 (Not Found) Even though the name of my images and the database are exactly the same. I have checked by copying and pasting the names so that they're identical. Other questions related to this on stackoverflow have not been successful as <img src="{{ nameofproblem.photo.url }}"/> should have worked. It works fine if I call the image directly through static like this: <img src="{% static 'images/Multiples_of_3_and_5.png' %}"/> Note: the underscores don't matter, I have tried making everything with underscores (including …