Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Icon in table is not accessible after rendering with jsRender
I am new to web development and struggling with a very simple issue. Please help me with a fix for this issue as I have not been able to move forward with my work. Requirement: I make an AJAX call to a django URL that gets me the data. I render the table using jsrender template. I have been able to get the table rendered just the way it is needed. Issue : The last column is a font awesome icon that when user clicks on should call a jQuery function that opens up a modal dialog and allows the edits. On click of the icon, nothing happens as I think the icon is not accessible for any events. Have I missed out some kind of update post jsrender that is making this icon not accessible for click. I had the same issue with jsrender and chosen-select. Found a hit in SO that post rendering, I need to udpdate the list with $("#name_of_list").trigger("chosen:updated"); Do I need to do something similar for the table / datatable. Please note that since django uses the tags {{ }} for rendering, I had to set jsRender to use [% %] below is my code... … -
Should I implement an intermediate Profile table now, or wait until if/when I need it?
Traditionally the schema is very simple: User <- Post I have written the code for a Profile model to be an intermediate: User <- ProfileUser -> Profile <- Post When registering for the website, a User is created. A User can create Profile's, and multiple User's can be attached to a Profile via ProfileUser. Reasons for implementation Potentially useful for bigger clients with multiple employees needing access to Post(s) For casual/free-tier users, Profile linking can be made transparent, they don't have to know the feature exists I might need this flexibility "one day in the future" for reasons I haven't yet thought of Reasons against implementation Complicates development, logistical overhead There may even be some performance overhead; I haven't profiled it but I expect the cost of two extra joins to be substantial. Liability of users complaining that another ProfileUser did something wrong and blame the website for primitive permissions control (I will not implement granular permissions or versioning/history). If this feature didn't exist, then their only option would be to share accounts, and the liability would be on them. One thing that would help me make a decision: Is it difficult to add in this intermediate table later? In … -
ElasticSearch multiple mapping trouble
Hi im using ElasticSearch with Django and my problem is that i cant understand a few things: 1) First, i have mapping in my push_data_to_index.py (management/commands) file, below is a part of it: def create_index(self): indices_client = IndicesClient(client=settings.ES_CLIENT) self.es_index = 'my_restaurants' self.es_type = 'restaurants' if indices_client.exists(self.es_index): indices_client.delete(index=self.es_index) indices_client.create(index=self.es_index) indices_client.put_mapping( index=self.es_index, doc_type=self.es_type, body={ 'properties': { 'title': { 'type': 'completion' } } } ) PS: 'title' is a field from models 'Restaurant' 2) Second, i have mapping in my search.py file, which contains all search logic, this is a part of it: def get_relevant_restaurants(search_query): relevant_restaurants_ids = [] relevant_restaurants_mapping = client.suggest( index='my_restaurants', body={ 'title': { 'text': search_query, 'completion': { 'field': 'title', 'fuzzy': { 'fuzziness': 2 }, 'analyzer': 'standard' } } } ) relevant_restaurants_options = relevant_restaurants_mapping['title'][0]['options'] for i in range(len(relevant_restaurants_options)): relevant_restaurants_ids.append(relevant_restaurants_options[i]['_id']) relevant_restaurants = Restaurant.objects.filter(id__in=relevant_restaurants_ids) return relevant_restaurants 3) Problem is, i think im doing something wrong, i have 2 mappings instead of 1 (should there be just 1 mapping actually?) and i dont know where to add extra parametets like stemming or tokenizer or custom analyzer etc. I tried adding extra parameters in my search.py file but i always get: TransportError(400, u'illegal_argument_exception') error. Can you help me solve my problem please? Thanks for your time -
How to use .sql database with a django project?
I have an education website and a blog to it, the website is in php language, but the blog was written in django. i need to make the blog use the users information from the php .sql database, so the user should not need to register in the blog. I am using sqllite in the blog. here is the .sql file. -- -- Table structure for table `users` -- CREATE TABLE `users` ( `ID` int(11) NOT NULL, `username` varchar(25) NOT NULL, `fullname` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `birth` date NOT NULL, `gender` varchar(22) NOT NULL, `role` varchar(22) NOT NULL DEFAULT 'Student', `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `users` -- INSERT INTO `users` (`ID`, `username`, `fullname`, `email`, `password`, `birth`, `gender`, `role`, `created_at`) VALUES (1, 'ahmedsobh', 'Ahmed Sobh', 'asobh98@hoba.com', '123123', '1995-03-25', 'Male', 'Doc', '2017-06-19 14:41:45'), (2, 'koko', 'Kareem Sobh', 'koko@ay', '1212', '1212-12-12', 'Male', 'Student', '2017-06-19 14:41:45'); -- -- Indexes for dumped tables -- -- -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`ID`), ADD UNIQUE KEY `username` (`username`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT … -
Enforce at least one value in many-to-one relationship's 'one' part
Suppose I have the following model: from django.db import models class Car(models.Model): manufacturer = models.ForeignKey( 'Manufacturer', on_delete=models.CASCADE, ) # ... class Manufacturer(models.Model): # ... pass I want to ensure that, whenever I create/save a Manufacturer, there is at least one Car belongs to that Manufacturer. A very similar question about many-to-many relationships asked HERE and the answer was no, at least through django-models. Only through a form, one can enforce such constraint. I'd like to learn whether it is valid for many-to-one as well. The example above is from Django documentation. -
data change puts object last in query django
all. I encountered a weird quirk with my Django setup. Each time I make a change in a data entry at Django's admin page, the data entry becomes dead last in a Query (e.g. Object.objects.all()). The behavior isn't a server-threatening bug, but I'd still like to know how I could resolve the problem. The one solution I can think of is creating a DateField and arranging the query by date, but I was wondering if a superior method is available. -
Autofill with the current login user in the admin Django
Hi i already try somethings from stackoverflow. Anything works, so i just want to autofill the doctor field with the current login user in the admin. My model.py class Medicard_rd(models.Model): Titulo = models.CharField(max_length=40, default='') hospital = models.CharField(max_length=30, default='') area = models.CharField(max_length=30) paciente = models.ForeignKey('auth.User', related_name= 'paciente', default = '') doctor = models.ForeignKey('auth.User', related_name= 'doctor', default='') fecha_creacion = models.DateTimeField(default=timezone.now) Telefono = models.CharField(max_length=10, default='') Imagen = models.FileField(upload_to='%Y/%m/%d', blank = True, default='') doctor = models.ForeignKey('auth.User',......) I want to autofill this field with the current login user in admin. -
cannot override the height of form input in django
<form role="form" action="" method="post" style="padding: 10%"> {% csrf_token %} <div class="form-group"> <label>LOG IN</label> {{ login_form.username|add_class:"form-control input_field"|attr:"placeholder:Username"}}<br> {{ login_form.password|add_class:"form-control input_field"|attr:"placeholder:Password" }}<br> <input type="submit" value="Log In" class="form-control btn btn-primary"> </div> </form> .input_field{ heigth: 80px; } it dose not change the height of the form filed. -
How to add fields together automatically
I'm going to build up an assets management system. Every property has an unique property-code combine with department-code and type-code. from django.db import models class Department(models.Model): # department_code like rm01 department_code = models.CharField(max_length=4, unique=True) name = models.CharField(max_length=100) class Type(models.Model): # type_code like fe03 type_code = models.CharField(max_length=4, unique=True) name = models.CharField(max_length=100) class Property(models.Model): # property_code like rm01fe037767 property_code = models.CharField(max_length=12, unique=True) name = models.CharField(max_length=100) department = models.ForeignKey(Department) type = models.ForeignKey(Type) How to do that? OR is there another way to achieve the aim? -
Is it possible to change the input text size with crispy filter
I have started using crispy-forms in my Django project. For authentication, I am currently using django.contrib.auth.views.login as an view and a custom template for rendering. In order to use the crispy-forms, I just made the following changes in template. {% extends 'base.html' %} {% load crispy_forms_tags %} {% block body %} <div class="container"> <h1>Welcome</h1> <p>You can login here</p> <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit">Login</button> </form> </div> {% endblock %} Now, my question is that with the above template, login input text widget spans across the entire width of screen. Can I change the widget size with crispy filter? What has to be changed if I had to use django.contrib.auth.views.login functionality with custom layout from crispy-form -
Adding and uploading imagefield to the inbuilt django user model in rest framework
I need the code for adding user image to the inbuilt User model in django rest framework. I do need the code for serializers, views and settings for directory of image I tried almost everything but completely unable to add it. my code for user registration is given but there is no models.py as I am using inbuilt User model Views.py class SignUp(APIView): def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(content, status=status.HTTP_201_CREATED) Serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): password = serializers.CharField(write_only=True) password_confirmation = serializers.CharField(read_only=True) username = serializers.CharField(allow_null=False) email = serializers.EmailField(allow_null=False) first_name = serializers.CharField(allow_null=False) last_name = serializers.CharField(allow_null=False) class Meta: model = User fields = ('id', 'username', 'password', 'password_confirmation', 'email', 'first_name', 'last_name') def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance def update(self, instance, validated_data): for attr, value in validated_data.items(): if attr == 'password': instance.set_password(value) else: setattr(instance, attr, value) instance.save() return instance -
Movil application: Data Usage
So I'm developing a mobile app with ionic and django (REST). I will offer free internet data, but I need to know how much internet data the application consumes. any idea about how i can do this? -
including opencv c++ program in django app?
I have a django app and would like to include implement an opencv application I wrote in c++. I was unsure the feasibility of this and the best way to go about it before I begin coding. Would it be best to rewrite the opencv application in python or could I use a library such as Boost Python to call my c++ code? My opencv application just takes a user image from their pc and does some processing (doesn't use the webcam). -
Django model - how to display class' property with foreign key in rest api
serializers.py: class PostSerializer(ModelSerializer): class Meta: model=Post fields=[ 'author', 'title', 'content', 'likes', ] models.py: class User(models.Model): name=models.CharField(max_length=255) surname=models.CharField(max_length=255) email=models.EmailField(max_length=255) username=models.CharField(max_length=255) password=models.CharField(max_length=2048) logged_in=models.BooleanField(default=False) def __str__(self): self.full_name=self.name+' '+self.surname return self.full_name class Post(models.Model): author=models.ForeignKey(User,on_delete=models.CASCADE) title=models.CharField(max_length=255) content=models.TextField() likes=models.IntegerField(default=0) My question is, How would I display author.name from Post model class in Rest API via serializer, since serilizer fields take literal parameter name from the given class? -
Django try upload file
When i try upload file got a problem. Traceback (most recent call last): ............... 290, in pre_save if file and not file._committed: AttributeError: 'MultiValueDict' object has no attribute '_committed' class UserFiles(models.Model): user = models.ForeignKey(User) file_name = models.CharField(max_length=255, null=True) file = models.FileField(blank=True, upload_to='media/files/users_file/', null=True) def __unicode__(self): return u'%s' % self.user How i can fix that? -
Gandi Python instance : How to run several web sites with git and wsgi
I want to run several Django web sites on a Gandi Python instance (Simple Hosting). From what I've understood on their wiki (here and here) I have only one virtual host and one git repository available for all domains. When asked, Gandi's support told me that to deploy my sites with git, I can use branches for each site and use the command $ ssh {login}@git.{datacenter_location}.gpaas.net 'deploy default.git [ {a_branch} ]'. I don't really think that's the proper way of using branches... Is there a better way ? If not, I have to create a repo on top of my local sites and a branch for each one ? Then what to put in wsgi.py at the root of my vhost to root to the right site depending on the domain ? Maybe something like this ? : import sys import socket import os.path from django.core.wsgi import get_wsgi_application current host = socket.gethostname() if current_host == "www.site_1.com": sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__),'site_1/site_1'))) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "site_1.settings") elif current_host == "www.site_2.com": sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__),'site_2/site_2'))) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "site_2.settings") application = get_wsgi_application() I'm new to python sites deployment, thanks by advance for your help ! -
Create permissions based on model field names in django
I am trying to create permissions, so that every user is able to see the articles of specific authors. Example permissions are Can view author1, Can view author2 etc. and Can view all. In the article class I tried creating the permissions as follow: class Article(models.Model) #some not important stuff class Meta: permissions = ( ('view_%s' % Author.name, 'Can view %s' % Author.name), ('view_all', 'Can view all'), ) This did not work and from what I know the permissions are stored in the database, so is it even possible to create the permissions this way? -
Visualizing MySQL data using D3js and JSON format in Django
This is my first post here so please ignore any naive errors please. I have successfully retrieved my data from database in JSON format. The database has several fields of which I require only timestamp and value. Now, I tried using .values("timestamp", "readings") but on serialization it popped an error as - no attribute _meta. Had to resort to .only("timestamp", "readings") but it returned all the attributes. Can you please tell me how to go about filtering the attributes and also visualizing it using D3js or any other library. Some relevant details - Model - **class Readings(models.Model): meter_id = models.CharField(max_length=100) timestamp = models.DateTimeField(default=datetime.now) readings = models.DecimalField(max_digits=20, decimal_places= 10, default=Decimal('0.0000'))** The result returned is of the form - [{"model": "log.readings", "pk": 4093, "fields": {"meter_id": "c30d4d9a-48b7-56fa-b714-c36247ee7aa8", "timestamp": "2017-04-01T00:00:00Z", "readings": "0E-10"}} From this I only need the timestamp and readings field Views.py - def current(request): user = Details.objects.filter(user_id=request.user.id) data = Readings.objects.filter(meter_id=user[0].meter_id).only('timestamp', 'readings') temp = serializers.serialize('json', data) return render_to_response("current.html", {'for_graph': temp}) -
How do I conditionally change the django admin form based on value in the model instance?
So I basically want to remove a field from the django admin under the condition that another field is not set. for example, in this case: class Category(models.Model): name = models.CharField(max_length=30) def __str__(self): # __unicode__ on Python 2 return self.name class Topic(models.Model): name = models.CharField(max_length=30) category = models.ManyToManyField(Category) class Document(models.Model): title = models.CharField(max_length=140) short_description = models.CharField(max_length=140) category = models.ManyToManyField(Category) topic = models.ManyToManyField(Topic, blank=True) def __str__(self): # __unicode__ on Python 2 return self.title class DocumentsAdmin(admin.ModelAdmin): pass admin.site.register(Document, DocumentsAdmin) I would like to only show the topic form field in the admin if the category has already been chosen and saved. I am doing this because the list of topics that should be available will be a queryset of topics that are associated with the categories that have been chosen. In order to grab the possible topic choices the category must be chosen first. -
mongoengine - Query on ListField of EmbeddedDocumentField
I use mongoengine with Django and python. This is my code: class Chambre(EmbeddedDocument): max_personne = IntField(default=0) prix = IntField(default=0) class Hotel(Document): code = IntField(default=0) nom = StringField(max_length=200) chambre = ListField(EmbeddedDocumentField(Chambre)) resume = StringField(max_length=200) 1 - I want a query to filter all Hotel that have at least a Chambre with prix >= a (a floeat number) 2 - also have that Chambre Any idea? -
Have django pull the value of {{ variable|add:"_date" }} from context instead of just printing it
I currently have a context variable called Myvar_date Now in my code I am doing this {{ variable|add:"_date" }} The output of above is Myvar_date since variable in above is equal to Myvar. Now the problem that I have with above is that it is simply printing it. It is not pulling the value of that variable Myvar_date from the context. How do I tell django that the statement {{ variable|add:"_date" }} actually returns a context variable name that needs to be pulled out from the context. -
Error 8: Nodename nor servname provided, or not known in Python
Working on an open source project, I keep getting the following error and I'm not sure what's going on. I have hosts set to "*" (which I know is not ideal) and have been pulling my hair trying to figure out this issue. [27/Jun/2017 13:29:16] INFO [django.server:124] "GET /reset/ HTTP/1.1" 200 6281 [27/Jun/2017 13:29:26] ERROR [django.request:135] Internal Server Error: /reset/ Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/joevasquez/Desktop/Development/Web/nadine/views.py", line 61, in password_reset form.save(**opts) File "/usr/local/lib/python2.7/site-packages/django/contrib/auth/forms.py", line 289, in save email, html_email_template_name=html_email_template_name, File "/usr/local/lib/python2.7/site-packages/django/contrib/auth/forms.py", line 243, in send_mail email_message.send() File "/usr/local/lib/python2.7/site-packages/django/core/mail/message.py", line 348, in send return self.get_connection(fail_silently).send_messages([self]) File "/usr/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 104, in send_messages new_conn_created = self.open() File "/usr/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 64, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 256, in __init__ (code, msg) = self.connect(host, port) File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 316, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 291, in _get_socket return socket.create_connection((host, port), timeout) File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line … -
Django authentication using email and password
I am trying to build an authentication system for my website in django but I need to use email instead of username for login, the problem is that the database has emails and passwords stored which are base64 encrypted, I am able to login the new users created from shell but not the pre-existing ones. Any advice what should i do? backends.py from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model from django.contrib.auth.hashers import check_password class EmailAuthenticationBackend(object): def authenticate(self, username=None, password=None): UserModel = get_user_model() try: user = UserModel.objects.get(email=username) if user.check_password(password): return user return None except UserModel.DoesNotExist: return None def get_user(self, person_id): UserModel= get_user_model() try: return UserModel.objects.get(pk=person_id) except UserModel.DoesNotExist: return None models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import BaseUserManager class MyUserManager(BaseUserManager): """ A custom user manager to deal with emails as unique identifiers for auth instead of usernames. The default that's used is "UserManager" """ def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('The Email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user … -
How to make a model Field take 2 values from two different drop down lists in Django
I am designing the models for a tutor page and I was wondering how to make a model field take two values from two different drop down lists and make them into one and the save that to the database. My objective is to make an availability model field which takes the day that a tutor is available to work from one dropdown list, and the available time that he is able to work on that day from the second dropdown list, and also the ability to add more than one day that the tutor is available. Something that would return this in shell. >>>tutor1.available_time (('Monday','after 4pm'),('Tuesday','In the Morning'),('Friday','after 2pm'),) >>>tutor2.available_time (('AnyDay','after 12pm')) -
Django Processing Form Data in class based view
I am trying to save some form data to a django model, right now when I submit the form the page just hangs and nothing happens, nothing get's saved to the ItemList model either. I am really confused and don't understand what I am doing wrong. Any help is greatly appreciated. forms.py class ItemListCreateForm(forms.ModelForm): items = forms.ModelChoiceField( queryset=item.objects.all(), widget=autocomplete.ModelSelect2Multiple() ) class Meta: model= ItemList # fields = ('__all__') fields = ['name', 'description', 'notes', 'items', 'public'] views.py class ItemListCreateView(FormView, autocomplete.Select2QuerySetView): template_name = 'itemlist.html' Model = ItemList success_url = 'itemlists' form_class = ItemListCreateForm def get_queryset(self): qs = Item.objects.values_list('symbol') if self.q: qs = qs.filter(name__istartswith=self.q) return qs def form_valid(self, form): form.instance.user = self.request.user return super(ItemListCreateView, self).form_valid(form) itemlist.html {% extends "base.html" %} {% load static %} {% load crispy_forms_tags %} {% block scripts %} {% endblock %} {% block styles %} {% endblock %} {#{% block title %}Login | {{ block.super }}{% endblock %}#} {% block content %} {{ form.media }} {% block headline %}<h2 align="center">Create Item List</h2>{% endblock %}<br><br> <div> <form action="" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> </div> {% endblock %}