Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how should i pass the primary.In my line code it showing error
In my django template for user profile, I have a link for Edit profile template. But Its giving no reverse found error. .This is my html template from where i m passing my pk from model UserProfile which is user. I am not able to pass the primary key for using it in reversing function (this is the error I guess). Also How can I call the primary key in the variable to pass it in the template ? Button this my views.py lass NewUserProfileView(FormView): template_name = "visit/user_profile.html" form_class = UserProfileForm def form_valid(self, form): form.save(self.request.user) return super(NewUserProfileView, self).form_valid(form) def get_success_url(self, *args, **kwargs): return reverse("main:home") class EditUserProfileView(UpdateView):#Note that we are using UpdateView and not FormView model = UserProfile form_class = UserProfileForm template_name = "visit/user_profile.html" def get_object(self, *args, **kwargs): user = get_object_or_404(User, pk=self.kwargs['pk']) # We can also get user object using self.request.user but that doesnt work # for other models. return user.userprofile def get_success_url(self, *args, **kwargs): return reverse("main:home") this is my urls url(r'^profiles/new/(?P<pk>\d+)/$', NewUserProfileView.as_view(), name="new-user-profile"), url(r'^users/(?P<pk>\d+)/edit/', EditUserProfileView.as_view(), name="edit-user-profile"), this is the errorReverse for 'new-user-profile' with keyword arguments '{'pk': <SimpleLazyObject: <User: sid>>}' not found. 1 pattern(s) tried: enter code here['profiles/new/(?P<pk>\\d+)/$'] -
DJANGO MODEL WITH TWO FOREIGN KEYS
newbie here. I have the following models in django and i want to get in a queryset the customers of a specific salesman. That means that I want the customers that have at least one Policy with a specific salesman. class Salesman(models.Model): name = models.Charfield() class Customer(models.Model): name = models.Charfield() class Policy(models.Model): policy_number = models.Charfield() salesman = models.Foreignkey(Salesman) customer = models.Charfield(Customer) can anyone help? many thanks -
Admin panel in django is not working
I have this miniblog, I run " manage.py runserver " in cmd, and run " http://127.0.0.1:8000/ " in browser its open my Home/index page, but the problem is when "http://127.0.0.1:8000/admin" it won't redirect, is the problem with URL.py ? Thank you for your time, AC Atlantis is a web directory of latest Computer Science Technologies that changed the world in a better way -
django-mptt get full tree from table
I'm using the app django-mptt to store a small tree structure. In django view, how can I query the entire table in a single query, to get a queryset/list with each instance having a children attribute? So I would like to do: groups = SongGroup.objects.all().values() for group in groups: group['children'] # list of children But as I see in the docs, get_children() will trigger another query? Which I want to avoid, since I've already used all() to query the entire table. I couldn't find a way in the docs to get an actual tree like structure from the table. My model: class SongGroup(MPTTModel): song = models.ForeignKey(Song, on_delete=models.CASCADE) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) -
Django Migrations Issue. makemigrations ignoring some fields in model file
THIS IS MY MODEL FILE from django.db import models class Donor(models.Model): Donor_name = models.CharField(max_length=150), Donor_status = models.IntegerField(), Donor_city = models.CharField(max_length=50), Donor_group = models.CharField(max_length=10), Donor_phone = models.CharField(max_length=12), Donor_mail = models.EmailField(max_length=50) THIS IS MY MIGRATION Generated by Django 2.0.2 on 2018-03-30 09:19 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Donor', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ) Why are other fields ignored ? using Django version 2 with MySQL. -
Django - Disabled select option returning ro same page after submit
I am wondering how I can get the disabled option value from the select after hitting submit and sending to POST. I have tried this but completely ignores it. The S and B values are choices but want the value of none. How can I get it? def results(request): if request.POST.get('size') == 'none': return render(request, 'polls/search_form.html') else: # Other action and HTML <select name="size" class="preferences"> <option value="none" selected disabled>Please select a size</option> <option value="S">Small</option> <option value="B">Big</option> </select> -
ImproperlyConfigured at /posts/1/delete/
ImproperlyConfigured at /posts/1/delete/ DeleteView is missing a QuerySet. Define DeleteView.model, DeleteView.queryset, or override DeleteView.get_queryset(). Request Method: GET Request URL: http://127.0.0.1:8000/posts/1/delete/ Django Version: 2.0 Exception Type: ImproperlyConfigured Exception Value: DeleteView is missing a QuerySet. Define DeleteView.model, DeleteView.queryset, or override DeleteView.get_queryset(). -
Get date selection widget in generic form view django
I have a model task for which I've written the following generic form to give facility to add a new task: class AddTask(generic.CreateView): model = task fields = ['project','task_name','expected_date'] success_url = reverse_lazy('home') template_name = 'st_web/addtask.html' This is working pretty fine. The only problem is that date field is an text type field. I read solutions for similiar questions, one of which proposed writing a date widget in my view like: from django import forms ........................ class DateInput(forms.DateInput): input_type = 'date' ......................... ......................... class AddTask(generic.CreateView): model = task fields = ['project','task_name','expected_date'] widgets = { 'expected_date': DateInput() } success_url = reverse_lazy('home') template_name = 'st_web/addtask.html' However this doesn't work for me. Can please anyone suggest a simple answer(some of them were suggesting adding some i8j.js or something like that but it'd really be helpful if there is a shorter solution available) to this problem? Thanks. -
Access model properties in Django Admin templates?
I have Django 2.0.3 on Python 3.5.3. I search for simple way to small improve my standard Django Admin dashboard (main page of Django Admin). Here is my template for Admin main page ./templates/admin/index.html: {% extends "admin/base_site.html" %} {% load i18n static %} {% block extrastyle %}{{ block.super }} <link rel="stylesheet" type="text/css" href="{% static "admin/css/dashboard.css" %}"/>{% endblock %} {% block coltype %}colMS{% endblock %} {% block bodyclass %}{{ block.super }} dashboard{% endblock %} {% block breadcrumbs %}{% endblock %} {% block content %} <div id="content-main"> {% if app_list %} {% for app in app_list %} <div class="app-{{ app.app_label }} module"> <table> <caption> <a href="{{ app.app_url }}" class="section" title="{% blocktrans with name=app.name %}Models in the {{ name }} application{% endblocktrans %}">{{ app.name }}</a> </caption> {% for model in app.models %} <tr class="model-{{ model.object_name|lower }}"> {% if model.admin_url %} <th scope="row"><a href="{{ model.admin_url }}">{{ model.name }}</a></th> {% else %} <th scope="row">{{ model.name }}</th> {% endif %} {% if model.add_url and request.user.is_superuser %} <td><a href="{{ model.add_url }}" class="addlink">{% trans 'Add' %}</a></td> {% else %} <td>&nbsp;</td> {% endif %} {% if model.admin_url and request.user.is_superuser %} <td><a href="{{ model.admin_url }}" class="changelink">{% trans 'Change' %}</a></td> {% else %} <td>&nbsp;</td> {% endif %} </tr> {% endfor %} … -
Django & Ajax : need to execute ajax request on added forms of my formsets
I still learn Django , and I'm new to Ajax . I actually have a template that contains a formset and a button that can add a new form : <form action="/veentes" method="POST" enctype="multipart/form-data" id="personForm" data-tiers-url="{% url 'ajax_load_tiers' %}">{% csrf_token %} <table id="id_forms_table"> {% for form in formset %} <tr style="border:1px solid black;" id="{{ form.prefix }}-row" class="dynamic-form" > <td{% if forloop.first %} class="" {% endif %}><div class="col-xs-1"><b><p name="np1">1</p></b></div></td> <td> {% render_field form.typeTiers class="form-control" id="id_type" placeholder="Montant HT" %}{{form.typeTiers.errors}} </td> <td> {% render_field form.tiers class="form-control" id="id_tiers" placeholder="TVA" name="tiers" %}{{form.tiers1.errors}} </td></tr> {% endfor %} </form> <td><input type="submit" name="ajoutligne" value="Ajouter une ligne" class="btn btn-primary" id="add-row" style="background-color: #8C1944; border-color: #8C1944; float:right;margin: 5px;" onclick=""></td></tr> when clicking on "ajoutligne" button, a new form is added, i did that using js from the answer of this question Dynamically adding a form to a Django formset with Ajax . After that i made the two ModelChoiceFields depend on each other using with Ajax query like that : $("#id_type").change(function () { var url = $("#personForm").attr("data-tiers-url"); // get the url of the `load_cities` view var typeID = $(this).val(); // get the selected country ID from the HTML input // alert(countryId) $.ajax({ // initialize an AJAX request url: url, // set the … -
Speeding up a Django database function for geographic interpolation of missing values
I have a large address database of commercial properties (about 5 million rows), of which 200,000 have missing floor areas. The properties are classified by industry, and I know the rent for each. My approach for interpolating the missing floor areas was to filter for similarly-classified properties within a specified radius of the property with unknown floor area, and then calculate the floor area from the median of the cost/m2 of the nearby properties. Originally, I approached this using pandas, but that has become problematic as the dataset has grown larger (even using group_by). It often exceeds available memory, and stops. When it works, it takes about 3 hours to complete. I am testing to see whether I can do the same task in the database. The function I've written for radial fill is as follows: def _radial_fill(self): # Initial query selecting all latest locations, and excluding null rental valuations q = Location.objects.order_by("locode","-update_cycle") \ .distinct("locode") # Chained Q objects to use in filter f = Q(rental_valuation__isnull=False) & \ Q(use_category__grouped_by__isnull=False) & \ Q(pc__isnull=False) # All property categories at subgroup level for c in LocationCategory.objects.filter(use_category="SGP").all(): # Start looking for appropriate interpolation locations fc = f & Q(use_category__grouped_by=c) for l in q.filter(fc & … -
How do I adjust my own redis settings to play well with Heroku-redis?
I have a couple settings configurations that incorporate some kind of Redis backend and they're all different. This one is required by django-channels: # REDIS BACKEND redis_host = os.environ.get('REDIS_HOST', 'localhost') # Channel layer definitions # http://channels.readthedocs.org/en/latest/deploying.html#setting-up-a-channel-backend CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [(redis_host, 6379)], }, }, } and makes use of this channels_redis library. I also have this: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': f'{env("REDIS_URL", default="redis://127.0.0.1:6379")}/{0}', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', # Mimicing memcache behavior. # http://niwinz.github.io/django-redis/latest/#_memcached_exceptions_behavior 'IGNORE_EXCEPTIONS': True, } } } cache storage which comes default thanks to Cookiecutter-django and uses the django-redis backend. I'm now trying to upload the app to Heroku, but Heroku requires that we use their Heroku-Redis addon. Upon deploying my app, I'm getting what I believe are redis issues--the same errors that occur during local development which are solved by running redis-server in a terminal, are popping up once the app is deployed on Heroku. Unfortunately, the only proof of this I can provide is this output: 2018-03-30T07:50:42.366099+00:00 heroku[router]: at=info method=GET path="/chat/loadhistory/" host=paira.herokuapp.com request_id=b52c5600-56c5-4711-b743-85df254bf9bb fwd="121.129.196.176" dyno=web.1 connect=0ms service=609ms status=101 bytes=145 protocol=https 2018-03-30T07:50:45.402850+00:00 heroku[router]: at=info method=GET path="/chat/stream/" host=paira.herokuapp.com request_id=a10fe599-0960-4836-af91-694b8041fc92 fwd="121.129.196.176" dyno=web.1 connect=0ms service=1016ms status=101 bytes=145 protocol=https 2018-03-30T07:50:45.696224+00:00 app[web.1]: 10.79.192.24:30767 - … -
autoreloader exits with 1
Django 1.11 Settings for development manage.py runserver goes back to the prompt short time after start. Looking at django/utils/autoreload.py with my print-statements: def restart_with_reloader(): while True: args = [sys.executable] + ['-W%s' % o for o in sys.warnoptions] + sys.argv new_environ = os.environ.copy() print('auto 291 new_env', new_environ) new_environ["RUN_MAIN"] = 'true' print('auto 292', args) exit_code = subprocess.call(args, env=new_environ) print('auto 294',exit_code) if exit_code != 3: return exit_code I found the exit code is 1. In which cases there is exit code 1? -
Heroku: “Process exited with status 127” after deploying python Django App
after deploying the app on Heroku , When i run my app it shows an error like this: Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. and when i check the logs it shows : 2018-03-30T07:25:13.273255+00:00 heroku[web.1]: Process exited with status 127 2018-03-30T07:25:14.757951+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=protected-journey-42490.herokuapp.com request_id=fdaf6efd-b490-4848-8f55-f583f1fc6b50 fwd="125.16.236.158" dyno= connect= service= status=503 bytes= protocol=https 2018-03-30T07:25:15.888944+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=protected-journey-42490.herokuapp.com request_id=7cdefbb6-e1a0-42bf-bb4d-0deed69f9c61 fwd="125.16.236.158" dyno= connect= service= status=503 bytes= protocol=https here's the reference link of my repository : pages_project -
Replacing auth_user with a different table
I have a 'user' table which contains usernames and passwords etc.. I want to use it instead of django auth_user. Is it possible? If YES how can I do it. -
Not able to download and install Django using Pip on windows 7
I am trying to install django using pip but I am not able to do it. Is there any other way to install Django. I tried like below. pip install Django But I got the below error. Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.requests.packages.urllib3.conne ction.VerifiedHTTPSConnection object at 0x00000000041C8198>, 'Connection to pypi.python.org timed out. (connect timeout=15)')': /simple/djando/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.requests.packages.urllib3.conne ction.VerifiedHTTPSConnection object at 0x00000000041C8160>, 'Connection to pypi.python.org timed out. (connect timeout=15)')': /simple/djando/ -
Django: Redirect to the previous page and keep the scroll position
I have seen this question where you can redirect to the previous page using: return HttpResponseRedirect(request.META.get('HTTP_REFERER')) but is there a way to also keep the scroll position that it was at? The above reloads the page afresh. -
'ImageFieldFile' object has no attribute 'user'
I've got the following code that allows the user to create a blog post. models.py class Article(models.Model): title = models.CharField(max_length=100) body = models.TextField() thumb = models.ImageField(upload_to=upload_location, null=True, blank=True, validators=[file_size]) author = models.ForeignKey(User, on_delete=models.CASCADE, default=None) def __str__(self): return self.title forms.py class CreateArticle(forms.ModelForm): class Meta: model = models.Article fields = ['title', 'body', 'thumb'] views.py @login_required(login_url="/accounts/login/") def article_create(request): if request.method == 'POST': form = forms.CreateArticle(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() messages.success(request, "Successfully Created", extra_tags='successtag') return redirect('articles:article_list') else: messages.error(request, "Not Successfully Created", extra_tags='errortag') context = { "form": form } return render(request, 'articles/article_create.html', context) else: form = forms.CreateArticle() return render(request, 'articles/article_create.html', { 'form': form }) This code works perfectly. The user can create an article with an image and view it in their blog. The issue starts here. I added some code to rotate the image on the blog post based on blog image's exif data. As a result, my view.py now looks like this: views.py def fix_orientation(filename): img = Image.open(filename) if hasattr(img, '_getexif'): exifdata = img._getexif() try: orientation = exifdata.get(274) except: orientation = 1 else: orientation = 1 if orientation is 1: pass elif orientation is 2: img = img.transpose(Image.FLIP_LEFT_RIGHT) elif orientation is 3: img … -
How can I print(to a printer) a string in django using a button click?
For printing the string from the database, all I know is to generate a pdf and then render it on a button click. I want to make all that happen(generating a pdf and rendering) on a single click of button. Is there a faster & efficient way to achieve that? -
How to get the data from mysql views in django
I have a mysql view called Books. mysql views don't have a primary key, so when I use Books.objects.all(), I get an error as 1054, " unknown column books.id in field list. " Is there any other way to get the data from mysql view. Thanks in advance. -
How Do I get Entries from my old database into new Django project?
SO I have Two django projects Old and New. I Have setup everything in new same to old one. How do I get Entries in database from old to new ? I tried copy pasting the migrations folder and dbsqlite file. Is there another way ? -
Browserify, es6, and reactjs
I have been trying to follow this guide for integrating react.js with Django. I have been incredibly unsuccessful because I cannot figure out how to use browserify with the something like the below script. If I run browserify like in the guide, it complains about the import statements. If I run browserify with -t [ babelify --presets es2015 ], browserify complains about the naked html from react. I have also tried following this guide(using gulp) and this guide (also gulp). The gulp solutions won't work because it can't seem to accept the raw html inside of index.js and I have been unable to figure out how to get around that. How can I get browserify to run on a file like that one below? // index.js import React from 'react'; import ReactDOM from 'react-dom' function NoBlogsAvailable() { return ( <p> No blogs available. </p> ); } function Blog(props) { return ( <div> <p> Something with a blog. </p> </div> ); } function BlogView(props) { const hasBlogs = props.blogs === undefined ? false : true; if (hasBlogs) { return <Blog />; } return <NoBlogsAvailable />; } ReactDOM.render( React.createElement(BlogView, window.props), window.react_mount, // a reference to the #react div that we render to … -
How to make asynchronous ajax requests if the server side work takes plenty of time to finish?
I need advice or sample code to achieve a task related asynchronous ajax request that server side work takes plenty of time to finish its job. Here is the sample scenario; I've a simple CSV file upload form. User submits file Server starts processing CSV file. Server makes queries to external web apis for each line of CSV file. (additional network request/response delays) Server parses each response (regex calculations, additional delays) and stores data into database. Server produces another output CSV file. If the CSV file contains < 100 rows, it works even without using ajax. However I need to make it asynchronous to be able to feed a lot of rows. The critical part is I don't want to have timeouts as long as server side code is working. I want to be able to update client side regularly about the progress of work (log-like update, for example "x record is saved into database") Can you provide me a working dummy sample code (for example, calculating fibonacci numbers) both client side and server side. (if possible django) Thanks. -
Django Rest Framework Post method not allowed for a Route
I'm writing a rest API using Django rest framework, I have setup viewsets, serializers and routes in their corresponding files.But when I send a post request to a route it returns POST method not allowed. Here's what i have done: viewsets.py class DocRestViewSet(viewsets.ModelViewSet): serializer_class = serializers.DocRestSerializer def create(self, request, *args, **kwargs): return super().create(request, *args, **kwargs) routes.py router = routers.DefaultRouter() router.register(r'deployments', viewsets.DeploymentViewSet, base_name='rest_deployments') router.register(r'rest_deployments', viewsets.DocRestViewSet, base_name='docrest_deployments') serializers.py class DocRestSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.DocRestModel fields = ('name', 'user', 'serviceName', 'dockerImageURL', 'routing') urls.py urlpatterns = [ url(r'^create/new$', views.DeploymentView.as_view(), name='new-rest-dep'), url(r'^rest/$', views.DeploymentView.as_view(), name='doc-rest-dep'), ] views.py class DocRestView(LoginRequiredMixin, CreateView): def post(self, request, *args, **kwargs): return 'Post req received for docrest' When I submit a POST request to http://127.0.0.1:8000/api/users/rest_deployments/ it returns: {"detail":"Method \"POST\" not allowed."} what can be a problem? -
Django API to return response without saving in Database
I want build django API which accepts simple paragraph perform some operation on it and return the result of that operation in return from the API without saving it in database.