GeoDjango - How to present points on a map?

Simple 'Example' - have millions of points within specific geography. Have everything loaded and able to see in GeoAdmin the whole 9 yards. So. How do I show all points on a map - and base it on zoom level? Are there any simple examples out there?

Django templates split text on fullstop

Using django templates I would like to split a block of text on the first fullstop. I would then like to give the first sentence a class of highlight and then the rest of the text a class of normal. how would i do this? e.g. (I know this doesn't work) text = Aliquam pretium vestibulum nibh, vel molestie velit varius nec Curabitur non neque sed elit tincidunt. Dignissim eget vel du molestie magna auctor faucibus. Curabitur id nisl nec ipsum molestie egestas in at dolor. Morbi et risus ac quam s

Advice on django form change emailing

Goal: On submission of a form to add/update/delete objects an email is sent out with the current contents of the DB object and the new contents of the DB object in html. Example Object Title was oldTitle and has been changed to newTitle Object Date was oldDate and has been changed to newDate My assumption this can be done two different ways. Directly through send_mail or via signals. My gut leans towards using signals to make sure I can grab previous content and the new content but I a

Selecting related foreignkeys in Django

Say I have two models, Article and Category: class Article(models.Model): category = models.ForeignKey(Category, related_name='articles') class Category(models.Model): ... When I run Category.objects.select_related(), the ORM does not select the articles. I realize it's because of the way the foreignkey is shuffled around, but I'm not sure how to go about doing that. Any ideas?

help with setup of multiple django sites under a single subdomain

Under the same subdomain, I need to set up several independent sites each running django, these sites are totally separate. Each site should be in its own subdirectory, and these subdirectories have to be password-protected. for example: I am using apache2 and have a virtual server entry for the subdomain. django is run using FastCGI. basically, I do not know how to set this up. What do I put in to my <VirtualHost> entry for the subd

Django - emulating searching/filtering of admin interface

I have a simple Django view that displays a list of objects. I want users to be able to search/filter/sort, etc. the list of objects. The way the admin interface does it by default (with all of those enabled) is exactly what I'm looking for. Is there any easy way to do this in Django? Or is there some third-party plugin to do it for me? Or am I stuck writing all of the code by hand? I feel like this is a problem that many others must have faced before, so what's the easiest (and least redu

Django Choosing a random item from a tagged library

Gradding a random image causes the title, url (etc) attributes on the tag.rand_img to vanish, meaning I can't display anything more than the object name. def locations_gallery(request): queryset = Photo.objects.all() tags = Tag.objects.usage_for_queryset(queryset, counts=True) tags.sort(key=operator.attrgetter('count'), reverse=True) for tag in tags: image_tag = Tag.objects.get(name=tag) tag.rand_img = TaggedItem.objects.get_union_by_model(Photo, image_tag).order_by('?

How to make the login form available on whole site on Django

I'm using Django registration to manage the registration and login / logout together with Django's auth system. It's working fine, I have a base template where I have put a 'login' link that takes the user to another page to login. I'd like to replace this link with the actual login form (username / password) so the form appears directly in every page. Any suggestions?

How use the filter of django Admin in my apps on my Projects

I tried to find a way to use the filter that gives the Django Admin in my applications, as you know by just adding "list_filter" in, to enter the Admin, our results can be filtered, I would like know if there are ways to use the same application but in my own projects Thanks!!

Django User Registration Issue

Django newbie, running on Ubuntu 12.04, Django 1.3.1 and apt-get install python-django-registration. Trying build a demo site to use the user registration module. I followed the steps from But when I try to access accounts/ or admin/, getting the following error: "name 'registration' is not defined" I am able to access the admin interface, after commenting out the registration part in Any tips to overcome this issue?

Django query for linking related data in template

I have two tables of data in a Django app, one containing shipping vessel details and the other containing offers related to individual vessels. My models are as follows: class Vessel(models.Model): name = models.CharField(max_length=64) image = models.CharField(max_length=64) vesseltype = models.ForeignKey(VesselType) capacity = models.IntegerField() length = models.FloatField() beam = models.FloatField() speed = models.IntegerField() activities = models.CharFie

Django How can I raise exception in model while rendering the template?

I have some custom functions in model class which process some data, and then add custom attribute to the model. Thing is, I do not know how could I raise an exception if there are any while the template is generated (the error seems to be only silent, so it will process the template further but gives NO ERROR ) In the view test.objects.all() render_to_string('template.html', {'test': test}) In the template {{ entry.state }} In the model: @property def state(self): somedict = {'a': 11

Django model design basics

I have two models status_message,comment each has a id,text(and some extra fields) each status can have many comments I need one more model called likes. status_message and comment can have many likes.what should be the correct model for the likes? 1)a "type" field for finding whether likes is for a status_message or a comment, and common field "postid" for id of status_message,comment or 2)separate status_message_id,comment_id and each with null option true My requirement includes - find o

Django template request.user exists in model class Universe(models.Model): name = models.CharField(max_length=50, unique=True) Members_list = models.ManyToManyField('Profile', through='Members', blank=True) ... class Profile(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) ... class Members(models.Model): uni = models.ForeignKey(Universe) profile = models.ForeignKey(Profile) ... class UniverseDetailView(DetailView): model = Universe

Django Data not being shown when template is included in another template

I have a html file that contains the following line: core.html {% include 'events/events.html' %} And I have this other template: events.html {% for event in events %} {{ event.event_name }} <br/> {% endfor %} When I open the URL that loads the events.html it perfectly shows the data: Evento 1 Pentaho Workshop But when I open the main URL that loads core.html it shows me nothing. If I write "blabla" out of the for block it is shown!!! Events -> from django.shortcut

Django Angularjs 405 method not allowed. tutorial

I am running through the tutorial found at: I have gotten about 1/3-1/2 way through it. I am now testing it to see if it will register a user. It will not, every time I submit the form it gives me POST 405 (METHOD NOT ALLOWED), I have ran back through the same tutorial half a dozen times to see where my mistake is but I can't seem to find it. I'm not %100 positive where the problem is so I will post

django dynamic add form fields

Based on this i want to write a dynamic template, where i can dynamicly add forms with choosen width. Models: class TodoList(models.Model): SEC = 'section' DIV = 'div' SECCHOICES = ( (SEC, "Section"), (DIV, "Div"), ) tag = models.CharField(max_length=20, choices=SECCHOICES, default=SEC) def __unicode__(self): return class TodoItem(models.Model): COL16 = '16' COL25 = '25' COL33 = '33' COL50 = '50' COL66 = '66'

Django - Is correct this custom FileField?

I just wrote a custom ImageField (I don't really know if this way is correct). The code is above: from django.db import router from django.contrib.auth.models import User from django.db.models.fields.files import ImageField, FileField def content_file_name(instance, filename): return "/".join([router.db_for_read(User), # DATABASE ALIAS instance._meta.app_label, # APP NAME instance._meta.module_name, # MODEL NAME filename]) #

How to import django model into a script?

I'm writing a script to import data into an existing Django model: import csv from django.db import models from movies.models import Movie from sys import argv script, filename = argv with open(filename) as csvfile: reader = csv.reader(csvfile) for row in reader: print (row) # _, created = Movie.title.get_or_create( # title=row[0], # ) But I'm running into this error when trying to import my model: Traceback (most recent call last): File

django redirect with login

I have trouble in the login process def zero_default_auth(request): print 'default auth............' username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) message = '' if user is not None: if user.is_active: login(request, user, ) print "login success" message="success!!!" else: message = 'disable' else: message = 'er

Django: how to group apps in directories?

I am using modified sources from few third party apps in my project. I would like to put these third party apps in a separate directory, so that they are not on the same directory level as my own apps. Is this possible in django? I tried simply putting the apps in a directory thirdparty and changed my INSTALLED_APPS like so: INSTALLED_APPS = ( 'my_app', ... 'thirdparty.django_messages', This of course failse with: ImportError: No module named thirdparty After which I naturally

Django ModelChoiceField queryset does not return actual values from db

My models are: class ActionType(models.Model): id_action_type = models.FloatField(primary_key=True) action_name = models.CharField(max_length=15, blank=True, null=True) class Meta: managed = False db_table = 'action_type' class TicketsForm(models.Model): ticket_id = models.FloatField(primary_key=True) ticket_type = models.CharField(max_length=30, blank=True, null=True) action_type = models.CharField(max_length=15,blank=True, null=True) In my forms

Django query sum values from related table

I have two tables: Ticket Table id paid_with_tax 1 5 2 6 3 7 TicketAdjustment Table id ticket_id value_with_tax 1 1 2 2 1 1 3 1 2 4 1 3 5 2 5 The query I use: use = 0 Ticket.objects.all().annotate( paid_amount=Sum( F('paid_with_tax') + Coalesce(F('ticketadjustment__value_with_tax'), 0) * use ) ) the query would return the following: [ {id: 1, paid_amount: 7}, {id: 1, paid_amount: 6}, {i

Setting session variables vs setting variable in browser cookie (Django app)

I need to clear a concept. I'm tracking unauthenticated users in my Django social networking web-app via setting a temp_id that's set in the request.session dictionary as soon as a new user hits the web-app's landing page. The code is is simply: temp_id = request.session.get('temp_id',None) if not temp_id: request.session['temp_id'] = get_temp_id() So far so good. Apart from saving a temp_id in request.session, another technique I could have used is setting a browser cookie explicitly

Django All fields give this field is required error

When I submit this form & all fields are correctly populated, the _valid() returns false & all the fields give : this field is required error, even the CharField!!! can anybody see what's wrong? this is my form: class TemplateConfiguredForm(forms.Form): """This form represents the TemplateConfigured Form""" template = forms.ChoiceField(widget=forms.Select(attrs={'id':'TemplateChoice'})) logo = forms.ImageField( widget = forms.FileInput(attrs={'id': 'inputLogo'}))

Django rest framework - cant serialize query set

I try to serialize query set def do(self): reservations = Reservation.objects.all() serializer = ReservationSerializer(data=reservations, many=True) if serializer.is_valid(): encoded_data = json.dumps( r ='', headers={'Content-Type': 'application/json'}, data=encoded_data) print(r.text) else: print(serializer.errors) And I always get error of {u'non_field_

Django decimal rounding

I have this function and I want to allow only 2 decimal places for the value. This is not a model field but it's being calculated from them. What is the right way to do it? @property def value(self): value = self.average_flow_rate * (self.d_n / 1000) / if 2320 < value < 4000: return 4000 else: return value

Adding an image into a django template from the static folder - Django

I have a Django template and I want to add a static image to the file from my static folder that I have within the application. I am trying to but nothing is appearing on the template. Does anyone know where my error is coming from? Here is my code: {% extends "base.html" %} {% block content %} <div class="row"> <div class="col"> <img src="static/images/Artboard1.png" alt=""> <h2>{{ currentUser.username }}</h2> </div> <a href="{% url 'l

Check if a form exists or is rendered in Template. Django

I have a situation where I display a Form sometimes and sometimes I don't display it. Actually, there are multiple forms using the same Submit button. What do I do to take care of the situation when a particular form is not shown in the template. The template code {% extends BASE_TEMPLATE %} {% load crispy_forms_tags %} {% block title %}<h2>New Thread</h2>{% endblock %} {% block content %} <div class="col-md-6"> <form method="post" accept-charset="utf-8">

Django login url

How to enable redirect user after login at personal page included, like http://mysite/client/12. I added app client. from django.conf.urls import url from . import views app_name = 'client' urlpatterns = [ url(r'^(?P<user_id>\d+)/$', views.user_profile, name='user_profile'), ] from django.shortcuts import render from django.contrib.auth.decorators import login_required @login_required def user_profile(request,user_id): user_id =

Django display list[0] list[1] in template form default value

I have a tag list passed to template context = {"tags": ["python", 'django']} I want to retrieve them respectively as the input default value <input type="text" class="form-control" name="q" placeholder="Search ..." value="[{{ tags[0] }}] [{{ tags[1] }}]"> I intend it to be displayed as [python] [django] in the search bar but I get an error.

DjangoREST annotate count of related entries with filtering

So I'm doing a little project in Django REST, and I'm still getting used to the ORM. I'm dealing with the following Django model: class Session(models.Model): date = models.DateTimeField(default=now, blank=False) owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='efforts', on_delete=models.CASCADE) I'm particularly interested in the number of session each owner has, given a specific month. As follows: Session.objects.filter(date__gte=start, date__lt=end).values('owner'

Django Display Count of Foreign key in Other table

i want to display number of Users in that company for all companies. I am using User in-built Model. UserProfile Model class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_company = models.ForeignKey(Company, on_delete=models.CASCADE) Company Model class Company(models.Model): company_name = models.CharField(max_length=20, unique=True) company_description = models.CharField(max_length=100) View to display Companies class Compan

Django Rest Framework ViewSets is returning selected records rather than all records in list view

I have a django application. I have one part of my app that is not working as I was expecting. As of now I am using the django rest framework view sets. What I want is two basically have 2 different list views in the same viewset. 1 that returns all of the accounts in the accountviewset and another list view that returns all of the accounts associated with a user based on the user foreignkey in the account model. The code below returns all the acccounts associated with a specific person, but I

Django Reset email send me url

When I try to use the password password/reset send me a mail with this this url Any ideas?? SITE_ID = 1 #Registro simple sin correo EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' #Login no mail ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_CONFIRM_EMAIL_ON_GET = True ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS

Django Download link from ForeignKey model

I would like to create an attachment on every post of my blog. Then I've do this: class FileUpload(models.Model): name = models.Charfield(max_length=70) file = models.FileField() def __str__(self): return def get_absolute_url(self): return reverse("single_file", kwargs={"pk":}) class BlogPost(models.Model): title = models.Charfield(max_length=70) . . . attachment = models.ForeignKey( FileUpload, on_delete

Django REST saves Image but returns wrong path

I am trying to save Community image and it saves it to /api/media/imagename.jpg, but when I retrieve a community it gives me /media/imagename.jpg without /api and then it can't find a image. So I have this Community model with FileField: class Community(models.Model): """DB Model for Community""" name = models.CharField(max_length=150, unique=True) description = models.TextField(default="") created_by = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.D

Trying to pass Bokeh Wordcloud2 to Django Templete

I am working on passing data visualization using Bokeh library to Django project. I am able to pass standard Bokeh visualization but when I am trying to used an external wordcloud2 library my project crashes. I receive message "A server error occurred. Please contact the administrator." Any ideas would be much appreciated?! Imports used: from bokeh.plotting import figure, output_file, show from bokeh.embed import components # Bokeh WordCloud from impo

Is converting timestamp to datetime in django will convert datetime by default to datetime in UTC

I am creating an app which will use peoples from different timezones. I have a model class Fixture(models.Model): fixture_id =models.IntegerField(primary_key=True) event_date = models.DateTimeField(null=True) I want while creating objects from this model that event_date field save datetime object in UTC to convert it in user's timezone while show him this data in front-end. In django documentation i read that When su

How to change a form's data after already populating it in Django

This might be a duplicate but I tried lots of solutions and none worked for me. class signup_view(View): def get(self, request): signup_form = SignUpForm() return render(request, 'signup.html', {"forms": signup_form}) def post(self, request): signup_form = SignUpForm(data=request.POST) if signup_form.is_valid(): email = signup_form.cleaned_data.get('user_email') password = signup_form.cleaned_data.get('user_pass') print("Original password is: "

Django @method_decorator change from Python 2 to 3?

I am currently working on the migration from Python 2 to 3 of my code. I use Django and it looks like i am missing something. I am using the decorator @method_decorator(func) from Django. my function is define like that : @decorator func(action_meth, *args, **kwargs): result = action_meth(*args, **kwargs) # do # something # with # result My problem is that the value of args from Python 2 and Python 3 is not the same and then args cannot be use as arguments for my acti

Django i18n: how to translate None when rendering a model field in template?

I have this code: # class MyModel(models.Model): end_date = models.DateField(verbose_name=_('end_date_field'), null=True, blank=True) notes = models.TextField(verbose_name=_('notes_field')), null=True, blank=True) # template <span>{{ object.end_date }}</span> <span>{{ object.notes }}</span> # USE_I18N = True USE_L10N = True LANGUAGE_CODE = 'pl' If end_date or notes is NULL in the database, it displays as "None" in the template. How do I

Django tables - data in rows

I have a simple loop that looks at the domains and populates the sub domains column. The first column has one domain and one subdomain. So it works fine. The second domain (A6) has two subdomains (A.6.1 and A.6.2). However, the A.6.2 gets pushed to the far right. It should be under A.6.1 and A6 rows should be merged so the domain is only repeated once. So the table should be Domain Subdomain A5 A.5.1 A6 A.6.1 A.6.2 A.6.3

Django-tables2 add html attribute to column

I have an Imagefield in a model, in my table that field is displayed as a link but when you click on it, it directs to a the url and instead I want to do download it. I foud that in html you can add the "download" attribute like this: <a href="/media/pictures/CFE.JPG" download></a> so in my django-tables2: class PagosDetailTable(tables.Table): imagen = tables.Column( attrs={"td": {"href": "download"}}) class Meta: model = Pagos tem

KeyError in my view context when trying to dynamically call a view in Django

I try to dynamically call a view in Django with this url configuration : url(r'^niveau/(?P<niveau_id>\d+)/(?P<channel>\w+)/$', views.switcher , name='vue_niveau') Then in my, i have : def switcher(request, niveau_id, channel): if channel == 'VueNiveau': return VueNiveau.as_view()(request) It works, as i get the good view call, but then when i try to get the niveau_id in my VueNiveau context : class VueNiveau(generic.TemplateView): template_name = 'cours/vue_niveau.html'

Django/Celery - Object matching query does not exist only when using delay

I am working with Django and Celery to asynchronously send_mass_mail. When I call the view function that calls the task, I get the following error: [2020-09-08 17:47:49,148: ERROR/ForkPoolWorker-8] Task main_app.tasks.send_notice[244944f6-604c-47a0-901a-4c510563d76e] raised unexpected: DoesNotExist('Notice matching query does not exist.') This only happens when I am using delay. If I call send_notice_task(notice_id) instead of send_notice_task.delay(notice_id) it can find the notice, but with de

When migrating Django to deployment i get this error why?

On my local machine there is no issue. Everything runs perfectly. Even python check --deploy brings up no issues on my local. The error i get stops me from doing anything with the project seemingly no matter the manage command. But when I run makemigrations on my external server for deployment it gives me this error: Traceback (most recent call last): File "/opt/pyapps/venv/lib/python3.8/site-packages/django/db/backends/", line 86, in _execute return self.curso

Why do I get an IntegrityError when calling Django's create_user helper function?

The current Django doc on Creating users says that the following helper function can be used to create a user: >>> from django.contrib.auth.models import User >>> user = User.objects.create_user('john', '', 'johnpassword') But when I run this code in the Python shell I get this error: django.db.utils.IntegrityError: null value in column "last_login" violates no-null constraint DETAIL: Failing row contains (7, <hashed password>, null, f, joh

Best way to speed up Django post requests?

I'm running a local Django server on a virtual machine that is remote interpreted onto a Raspberry Pi. The purpose of the remote connection is to have the Raspberry Pi upload a bunch of data from various sensors to the local server every minute. I'm running into an issue now where the Post request speed is far too slow for the amount of data that will be coming in (Post speed is about one, sometimes two posts a second). I'm assuming this is due to the remote connection and the fact that it is ru

Connecting Django models to tables with primary key name other than ID

I have a project where primary column name is 'N' in place of standard 'id'. I have no access to the original database to change it, so I hoped that the following code will do the trick: class ExSLoc(models.Model): id = models.IntegerField(primary_key=True, db_column='n') class Meta: db_table = original_db_table managed = False It actually does, but I run into a strange bug from Django model forms, telling that: 'ExSLoc' object has no attribute 'id' Here's the full traceback. | Tra

  1    2   3   4   5   6  ... 下一页 最后一页 共 409 页