Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter query with range within Model
I'm trying to execute a query with the range test in my class (MapArea), but I don't seem to have a grasp on the visibility of objects in Models as I get NameError: name 'MapArea' is not defined. My class is as follows: class MapArea(models.Model): lat = models.DecimalField(max_digits=15,decimal_places=6) lon = models.DecimalField(max_digits=15,decimal_places=6) nearby_streets = MapArea.objects.filter(lat__range=[self.lat - 2, self.lat + 2], lon__range=[self.lon - 2, self.lon + 2]) # Meta class Meta: abstract = True Setting nearby_streets to MapArea.objects.filter(lat__range=[self.lat - 2, self.lat + 2], lon__range=[self.lon - 2, self.lon + 2]) is what causes the NameError: name 'MapArea' is not defined. It seems like MapArea should be defined according to other answers, but I don't seem to be accessing it correctly. How can I access MapArea.objects.filter() in order to use the range test feature? Thank you in advance. -
Save user's id in the database, when submitting the form in django
I have a form that user can add his feed URL and then see the articles of the feeds he has submitted before. How can I change my code in order to save the owner of the feed (the user that submitted it to the site)? models.py: from django.db import models from django.contrib.auth.models import User class Feed(models.Model): user = models.ManyToManyField(User) category = models.ManyToManyField(Category) title = models.CharField(max_length=200) url = models.URLField() is_active = models.BooleanField(default=False) def __unicode__(self): return self.title class Article(models.Model): feed = models.ForeignKey(Feed) title = models.CharField(max_length=200) url = models.URLField() description = models.TextField() publication_date = models.DateTimeField() def __unicode__(self): return self.title views.py: from .models import Article, Feed from django.http import HttpResponse from .forms import FeedForm def new_feed(request): if request.method == "POST": form = FeedForm(request.POST) if form.is_valid(): feed = form.save(commit=False) existingFeed = Feed.objects.filter(url=feed.url) if len(existingFeed)==0: feedData = feedparser.parse(feed.url) feed.title = feedData.feed.title feed.save() for entry in feedData.entries: article = Article() article.title = entry.title article.url = entry.link article.description = entry.description d = datetime.datetime(*(entry.published_parsed[0:6])) dateString = d.strftime('%Y-%m-%d %H:%M:%S') article.publication_date = dateString article.feed = feed article.save() return redirect(feeds_list) else: form = FeedForm() return render(request, 'news/new_feed.html', {'form': form}) forms.py: from django import forms from .models import Feed class FeedForm(forms.ModelForm): class Meta: model = Feed fields = ('url',) After adding a … -
regist() got an unexpected keyword argument 'template_name'
i got a error that TypeError at /accounts/regist/ regist() got an unexpected keyword argument 'template_name' . i can understand there is no variable in my file. but,in login,no template_name file can be worked. So,i cannot know how to fix it. I wrote in urls.py of accounts, from django.conf.urls import url from . import views from django.contrib.auth.views import login, logout urlpatterns = [ url(r'^login/$', login, {'template_name': 'registration/accounts/login.html'}, name='login'), url(r'^logout/$', logout, name='logout'), url(r'^regist/$', views.regist, {'template_name': 'registration/accounts/regist.html'}, name='regist' ), url(r'^regist_save/$', views.regist_save, name='regist_save'), ] in views.py from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import render, redirect from django.views.decorators.http import require_POST from .forms import RegisterForm def index(request): context = { 'user': request.user, } return render(request, 'accounts/index.html', context) @login_required def profile(request): context = { 'user': request.user, } return render(request, 'accounts/profile.html', context) def regist(request): form = RegisterForm(request.POST or None) context = { 'form': form, } return render(request, 'accounts/regist.html', context) @require_POST def regist_save(request): form = RegisterForm(request.POST) if form.is_valid(): form.save() return redirect('main:index') context = { 'form': form, } return render(request, 'accounts/regist.html', context) if i have to define template_name,which file should i write it and how? Are there differences to make system login page and regist page? -
django - Using one form to create two model instances
This seems like something that should be rather simple, and something that should be a common thing to need, but the more I try and find an answer, the more confused I get. I have an event model that is linked to multiple other models that need events, so I created a separate event model for it. Now, I want to create an event when I create a job model, but I am having trouble figuring out how to do it. In my job field, I have a OneToOneField relationship to an event, and the only thing I need to decide at the time I make the event is the duration. A simplified Job model might look like this: class Job(models.Model): customer = models.ForeignKey(Customer) address = models.CharField(max_length=100, verbose_name="Job Address", null=False, blank=False) city = models.CharField(max_length=100, verbose_name="City", null=True, blank=True) state = models.CharField(max_length=2, verbose_name="State", null=True, blank=True) zip = models.CharField(max_length=5, verbose_name="Zip Code", null=True, blank=True) # Simply need to set duration event = models.OneToOneField(Event, on_delete=models.CASCADE, null=False, blank=False) And a simplified Event model might look like this: class Event(models.Model): TIME_LIST = ( (1, "0:30"), (2, "1:00"), (3, "1:30"), (4, "2:00"), (5, "2:30"), (6, "3:00"), (7, "3:30"), (8, "4:00"), (9, "4:30"), (10, "5:00"), (11, "5:30"), (12, "6:00"), … -
Error no auto add language code before url when set debug=false in multi language django
I have problem with multi language in django. if I set debug=True, it is work fine but if set debug=False it no auto add language code before url exam: my url: localhost:8000 case True: it auto convert localhost:8000/en/ case debug=False; it no auto convert localhost:8000/en/ (keep localhost:8000 so have error) this is my code in url from __future__ import unicode_literals from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from django.views.i18n import set_language from mezzanine.core.views import direct_to_template from mezzanine.conf import settings from solid_i18n.urls import solid_i18n_patterns from index import views from cartridge.shop.views import order_history import spirit.urls admin.autodiscover() # Add the urlpatterns for any custom Django applications here. # You can also change the ``home`` view to add your own functionality # to the project's homepage. urlpatterns = solid_i18n_patterns( # Change the admin prefix here to use an alternate URL for the # admin interface, which would be marginally more secure. url("^admin/", include(admin.site.urls)), url(r'^accsocial/', include('allauth.urls')), url(r'^forums/', include("spirit.urls")), url(r'^emoji/', include('emoji.urls')), url("^shop/", include("cartridge.shop.urls")), url("^fabprofile/", include("fabprofile.urls")), url("^account/orders/$", order_history, name="shop_order_history"), url("^", include("index.urls")), url("^", include("mezzanine.urls")), ) and this is my error Traceback (most recent call last): File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/home/vuong/Documents/flo/2016/xyzs1/django/core/handlers/wsgi.py", line 189, in call response … -
link a cartridge SKU to a FormField on a product page
Hello my dear programmers, i am trown into the deep with this project. i need to build a e-commerce website but a little bit different, this person does not want a checkout cart but a contact form underneath every product with a field for: name product textfield we need to make it so the SKU of the product on that page gets inserted in the product field. maybe there is a way to do it with a url instead, that it automaticly pastes the products URL in a textField. i hope someone can give me some directions i need to look in or some documentation to read. Django 1.10 Mezzanine CMS Cartridge shop python 2.7 -
Render or redirect from one page to another (i.e from login page to index page) that is separated in two different apps in Django
This what i'm getting I tried to render or redirect from one page to another (i.e from login page to index page ) that is separated in two different apps (accounts and home) in Django but its redirecting to the same login page. I have to redirect to 'home/index.html' after login and have to authenticate the user details exists in the database. For registration also i'm getting the same issue, its storing the details but not redirecting to the index page after registration completes. Please some one help me fix this. Thanks in advance **`accounts - models.py'** from django.db import models class Registration(models.Model): email = models.EmailField(max_length=30) password = models.CharField(max_length=16) def __str__(self): return self.email **'accounts - forms.py'** from django import forms from .models import * class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = Registration fields = ['email', 'password'] class LoginForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = Registration fields = ['email', 'password'] **'accounts - views.py'** from django.contrib.auth import authenticate, login from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import UserForm, LoginForm def registration(request): form = UserForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) email = form.cleaned_data['email'] password = form.cleaned_data['password'] user.save() user = authenticate(email=email, password=password) if user is not … -
Django: send dictionary/list data to form
GOAL: Send a dictionary of data to a form, to be used in a dropdown boxself. Views.py form = FormsdbForm(initial={'user': default_state}) # (to set the default value of the 'user' field) Forms.py class FormsdbForm(forms.ModelForm): ROOMLIST = (('roomID_abcdefghi','Room ABC'), ('roomID_jklmnopqr','Room JKL')) roomid = forms.ChoiceField(required=False, choices=ROOMLIST) class Meta: model = Formsdb fields = ('user', 'uniqueid', 'roomid') The above setup displays a form where the field 'roomid' is a dropdown box showing to entries: Room ABC Room JKL After saving, the database is populated with the matching 'RoomID_xxxxxxxxx' Perfect so far! In my Views.py I have a dictionary (that I can easily convert into a list-of-lists) with the data that is now statically configured in Forms.py (ROOMLIST). QUESTION: How can I pass this dictionary (or list) to the form so it displays a dropdown box with choices? This would replace the current "ROOMLIST" variable and it could easily contain 400-600 entries. -
How to filter on field whose value is derived while creating mongoengine document in Django Model?
Hello I am using Mongoengine version '0.11.0' and Django version '1.10.4'. I have the following model from django.utils.text import slugify from datetime import datetime import mongoengine class MyModelMethodsMixin: def __init__(self, *args, **kwargs): self._signals_data = {} field_kwargs, non_field_kwargs = {}, {} for field_name, field_value in kwargs.items(): if field_name in self._fields_ordered: field_kwargs[field_name] = field_value else: non_field_kwargs[field_name] = field_value super().__init__(*args, **field_kwargs) for field_name in non_field_kwargs: if field_name in dir(self): setattr(self, field_name, non_field_kwargs[field_name]) class MyModel(MyModelMethodsMixin, mongoengine.Document): name = mongoengine.StringField(required=True) _name_slugify = mongoengine.StringField(required=True) @property def name_slugify(self): return self._name_slugify @name_slugify.setter def name_slugify(self, name): self._name_slugify = slugify(name) Now, If I want to filter by name_slugify, I get the error for no such field. Anyone please help, how can I accomplish this? -
How to add new table to database in the Django application
I'm working on Django project and I need certain users to be able to add a new table to existing database from the application admin panel. Since I don't know specificity of products users would like to add to application over time, I need a way for them to just click "add new category" which will become the name of new table in database and inside add category parameters (column names in database) and after clicking "save" it will add such table to database on running application, and other category of users will be able to add products to this category by providing the data for "category parameters". Since I have no idea how to do it in django, I kindly ask for your help. -
Uploading django app to digitalocean server: 502 bad gateway nginx/1.4.6 (Ubuntu)
I'm using the following tutorial to upload a django webapp to a digital ocean server. Everything seems fine while entering the following commands: pip install --upgrade django service gunicorn restart According to the tutorial I now should be able to see my webpage (without the bootstrap theme/fonts) after refreshing the host ip in my browser. Instead I get the following error: I've looked up the nginx error.log in /var/log/nginx/error.log and it says the following: 2017/01/20 08:18:23 [error] 9342#0: *38 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 92.111.75.86, server: _, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:9000/", host: "104.236.68.12" Question: How do I fix this 502 bad gateway so that my site works properly? I've tried to add ALLOWED_DOMAINS to settings.py already and I've also tried to create a droplet with ubuntu 16.04 as well. -
Django: Adding variable to template context
I have problem with a form if invalid data is submitted. My ErrorView view uses the app/feriehus_detail.html template, but I'm not including price_data in the template context. This seems to cause a KeyError when the template tries to use price_data as an argument in a filter. I can't figure out how to the template context? Any help will be much appreciated. I'm using Python 3.5 and Django 1.9. Traceback: Template error: In template C:\Conference\app\templates\app\feriehus_detail.html, error at line 221 Failed lookup for key [%s] in %r 211 : <td class="text-center">{{ object.price_rec_F }} kr</td> 213 : <td class="text-center">{{ object.price_rec_F|percentage_dif:object.price_cur_F }}</td> 214 : </tr> 215 : </tbody> 216 : </table> 217 : </div> 218 : <div class="col-xs-12" style="padding-bottom:25px;"> 219 : <div class="grid"> 220 : <div class="col-1-1"> 221 : {% column_chart price_data with height='500px' %} 222 : </div> 223 : </div> 224 : </div> template: <form role="form" action="{% url 'error' pk=feriehus.id %}" method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit">Send</button> </form> forms.py: class ErrorForm(forms.Form): content = forms.CharField( required=True, widget=forms.Textarea ) def __init__(self, *args, **kwargs): super(ErrorForm, self).__init__(*args, **kwargs) self.fields['content'].label = "Beskriv fejl" self.helper = FormHelper() urls.py: url(r'^feriehus/(?P<pk>[0-9]+)/$', views.FeriehusDetail.as_view(), name='feriehus_detail'), url(r'^feriehus/(?P<pk>[0-9]+)/error/$', views.ErrorView.as_view(), name='error'), views.py: class FeriehusDetail(DetailView, FormMixin): model = Feriehus form_class = ErrorForm def get_context_data(self, … -
Wagtail mock images show as broken in admin but visible on template
I have a demo Wagtail website. A site is generated via a Cookiecutter. To populate the CMS with initial content I have added a load_initial_data command that can be run once Wagtail is installed. This populates text content from a fixtures JSON file, and moves images from the fixtures folder to the Wagtail site's media_root folder. The code looks like: # load_initial_data.py import os, shutil from django.conf import settings from django.core.management.base import BaseCommand from django.core.management import call_command class Command(BaseCommand): def handle(self, **options): fixtures_dir = os.path.join(settings.PROJECT_DIR, 'fixtures') fixture_file = os.path.join(fixtures_dir, 'db.json') image_src_dir = os.path.join(fixtures_dir, 'images') image_dest_dir = os.path.join(settings.MEDIA_ROOT, 'original_images') call_command('loaddata', fixture_file, verbosity=0) if not os.path.isdir(image_dest_dir): os.makedirs(image_dest_dir) for filename in os.listdir(image_src_dir): shutil.copy(os.path.join(image_src_dir, filename), image_dest_dir) This works to the extent that the images are copied to the correct directory, and on the templates the images appear as expected when requested. The problem is within /admin/images/ where the requested version of the image is unavailable, and so the browser shows a broken image icon. The admin page is looking for a specific size of the image ({your-image-name}.max-165x165.{.jpg|.png|.gif}. Watching how images move from original_images to images makes it appear that they are only processed after the template they are on is first requested. One idea … -
How to send silent notification from server to ios devices?
This is my python script which sends the fcm notification to the devices it sends priority notifications not silent notification.... def sendGCMToTopiciOS(): url = 'https://fcm.googleapis.com/fcm/send' headers = { 'UserAgent': "GCM-Server", 'Content-Type': 'application/json', 'Authorization': 'key=' + 'XXXXXXXXXXXXXXXXXXXX', } data = {'title': 'Yugam', 'message': 'Hello Everyone', 'event': '13', 'workshop': '-1', 'link': 'https://www.google.com'} notification = { 'body': data.get('message'), 'title': data.get('title') } values = { 'to': '/topics/' + 'global', 'data': data, 'notification': notification, "aps":{ "content-available":1} } pipe = requests.post(url=url, json=values, headers=headers) return pipe.json() -
Error in connecting Django with existing MongoDB using MongoEngine
I'm using Ubuntu 14.04. | Django 1.6.11 | MongoDB | PyMongo & MongoEngine Django projectname: dashboard Django app: sentiment I have a mongodb database and i created a django project to visualize the db collection on a website. Now, my problem is, that i can't connect the database with django. I used MongoEngine to connect, but always there is an error. I don't know why? I enter the correct details... Here is the collection of my database Error Message from the django server settings.py [saved in dashboard project] import os from mongoengine import connect BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'opze1kz)+zgm$uggwo-+n%lr2n7m^j+2u)+klhnd7(&*@2e_g4' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sentiment', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', #'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'dashboard.urls' MONGODB_DATABASES = { 'default': { 'ENGINE': 'django_mongoengine', 'NAME': 'sentimentdb', 'USER': 'uenver', 'PASSWORD': 'asd123yxc', 'HOST': 'localhost', 'PORT': '27017', } } TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'dashboard.wsgi.application' connect('sentimentdb', host="localhost", port=27017) AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = … -
Django parsing until another block tag
i'm learning django from a book where it has this example in custom template tags: books_extras.py def do_upper(parser, token): nodelist = parser.parse(('endupper',)) parser.delete_first_token() return UpperNode(nodelist) class UpperNode(template.Node): def __init__(self, nodelist): self.nodelist = nodelist def render(self, context): output = self.nodelist.render(context) return output.upper() When i'm wraping text arround {% upper %} and {% endupper %} i'm getting this error: django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 116: 'upper'. Did you forget to register or load this tag? Thing is there was another example for comments like this that was working and i didn't had to register it: def do_comment(parser, token): """Template commenter""" nodelist = parser.parse(('endcomment',)) parser.delete_first_token() return CommentNode() class CommentNode(template.Node): def render(self, context): return '' So, why am i getting this error? -
Override behaviour of delete for inline in Django
Some context first: The distributor create products and insert certain characteristics as inlines. To avoid redundancy, I don't create a new instance for each inline to each client, only if they change something, otherwise, the original is shown. The clients could edit those lines or delete them, without change the original characteristics of the distributor. To achieve that I do the following: class ProductAdmin(BaseAdmin): title = 'Products' inlines = [CharacteristicsInline, CharacteristicsReadOnlyInline] def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) if change: for instance in instances: if instance.pk and not instance.modified_by_client: v_user = User_client.objects.get(user=request.user, datetime_canceled__isnull=True) new_characteristics = Characteristics.objects.create(product= instance.product, raw_material= instance.raw_material, description= instance.description, formula= instance.formula, modified_by_client= True, reference= instance.pk, factory= v_user.factory, user_register = v_user, user_modified = v_user ) new_characteristics.save() It basically verify if the user have edited an original line, if he has done so, then I create a new characteristics that have a reference to the original, then I hide the original, showing that one. If he delete the edited one, the original appears again. My problem is: Clients can edit and delete lines. But when they delete a original line, I don't want to it to get deleted, I want to just hide that line from that client … -
global name 'RegisterForm' is not defined
I got a error that NameError at /accounts/regist/ global name 'RegisterForm' is not defined . I did defined 'RegisterForm'. I wrote in forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import AuthenticationForm class RegisterForm(UserCreationForm): def __init__(self, *args, **kwargs): __init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' class LoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): __init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['password'].widget.attrs['classF'] = 'form-control' in views.py from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import render, redirect from django.views.decorators.http import require_POST def index(request): context = { 'user': request.user, } return render(request, 'accounts/index.html', context) @login_required def profile(request): context = { 'user': request.user, } return render(request, 'accounts/profile.html', context) def regist(request): form = RegisterForm(request.POST or None) context = { 'form': form, } return render(request, 'accounts/regist.html', context) @require_POST def regist_save(request): form = RegisterForm(request.POST) if form.is_valid(): form.save() return redirect('main:index') context = { 'form': form, } return render(request, 'accounts/regist.html', context) in urls.py from django.conf.urls import url from . import views from django.contrib.auth.views import login, logout urlpatterns = [ url(r'^login/$', login, {'template_name': 'registration/accounts/login.html'}, name='login'), url(r'^logout/$', logout, name='logout'), url(r'^regist/$', views.regist,name='regist'), url(r'^regist_save/$', views.regist_save, name='regist_save'), ] How can i fix it? Furthermore,I really cannot understand i did not write global anywhere.(I am … -
django RawQuerySet says ORA-00911: invalid character
select id, login_id, is_active, auth_type_id, user_type_id, user_org_id, parent_id, user_create_date, user_expiry_date, quota_resource, quota_runs_per_month, quota_cost_per_month, remediate_priviledge, created_by, create_date, updated_by , update_date from cpe_user a connect by prior a.id = a.parent_id start with a.id > (select id from cpe_user where id = 75); This is my oracle-sql query, which I am passing it to childrens = User.objects.raw(). This query runs and gives output on oracle-sql developer. and I am trying to access it as for child in childrens: print child but above lines of code throwing error as ORA-00911: invalid character. Please help me find my mistake here. -
Django: website made and postgres populated with existing data now not allowing to create fresh data
I had a website made in another framework and now redesigned the site using django. However the issue is that i have uploaded all old data into postgres using CSV and now when i try to upload data it gives this error: duplicate key value violates unique constraint "auth_user_pkey" DETAIL: Key (id)=(4) already exists. I have already 600 users registered in old data. Now I cannot register new user because its giving integrity error. What command should be executed so that django considers database existing data? -
django load umessages templatetags in another app
i'm using django-userena with umessages and i've been trying for a while to load the umessages app templatetags on the accounts app so i can use the tags in accounts/profile instead of the regular messages/ directory but i faild so far everytime i use the tags nothing happens first i tried on a shell to import the tags to see if i'll get any error but i didn't get any so i went and add accounts view from userena.contrib.umessages.templatetags import umessages_tags in profile.html {% load umessages_tags %} settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'userena', 'guardian', 'easy_thumbnails', 'accounts', 'crispy_forms', 'userena.contrib.umessages', ] i went and check the init.py file as well but the tags wont work on any directory other than messages/ -
Use select_related for comma separated field
I have two class model like this: class Problem(models.Model): owner = models.ForeignKey(User) services = models.CommaSeparatedIntegerField(max_length=200) class Services(models.Model): name = models.CharField(max_length=50) ... As you see in Problem model I keep id's of Services in comma separated field. For example to solve this problem we should do this Services: "1,2,3". I want to show detail of problem and related services to user. To do this I should join Problem to Services table but I don't know how. -
What is wrong with the form?
I am trying to create a online Phone Book for my locality. I am getting problem with the app's entry creation view. Here is my PhoneEntry model: # coding=utf-8 from django.urls import reverse_lazy from django.db import models from django.template.defaultfilters import slugify from phonenumber_field.modelfields import PhoneNumberField class PhoneEntry(models.Model): # Name of the organisation org_name = models.CharField(max_length=100, verbose_name="Organisation's Name") org_details = models.CharField(max_length=500, blank=True, verbose_name="Organisation's Details") slug = models.SlugField(default='slug', unique=True) # Verified or not verified = models.BooleanField(default=False, blank=True) # Dates when the entry was added and verified added_date = models.DateField(auto_now_add=True, editable=False) verified_date = models.DateField(auto_now_add=True) last_edited_date = models.DateField(blank=True, null=True, auto_now_add=True) # The phone numbers of the organisation primary_ph_number = PhoneNumberField(verbose_name="Primary Phone Number") secondary_ph_number = PhoneNumberField(verbose_name="Secondary Phone Number", blank=True) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): super(PhoneEntry, self).save(force_insert, force_update, using, update_fields) self.slug = slugify(self.org_name+"-"+str(int(self.id))) super(PhoneEntry, self).save(force_insert, force_update, using, update_fields) @staticmethod def get_absolute_url(): return reverse_lazy('phbook:index') def __str__(self): return self.org_name+"-"+str(self.primary_ph_number) class Meta: verbose_name_plural = "Phone Entries" And this the EntryCreateForm: class EntryAddForm(forms.ModelForm): """org_name = forms.CharField(max_length=100, label="Enter your organisation name: ") org_details = forms.CharField(max_length=100, widget=forms.Textarea, label="Enter your organisation details: ", required=False)""" primary_ph_number = PhoneNumberField(label="Enter your primary phone number: ") secondary_ph_number = PhoneNumberField(label="Enter your secondary phone number: ", required=False) class Meta: model = PhoneEntry exclude = ['slug', 'last_edited_date', 'added_date', 'verified_date', … -
Django forms and Material Design Lite
I'm building my frontend with Google's MDL framework and I'm having troubles rendering Django forms with MDL's styling using: {{ form.as_table }} {{ form.as_p}} {{ form.as_ul}} Tried this way also: <form> <div class="mdl-textfield mdl-js-textfield"> {% for field in form %} <label class="mdl-textfield__label" for="{{ field.name }}">{{ field.label_tag }}</label> {{ field }} {% endfor %} <button type="submit" class="btn btn-primary">Submit</button> </div> </form> My Django form class: class MyClassUpdateForm(forms.ModelForm): class Meta: model = MyClass fields = '__all__' widgets = { 'foo': TextInput(attrs={'class': "mdl-textfield__input"}), 'bar': TextInput(attrs={'class': "mdl-textfield__input"}), 'baz': TextInput(attrs={'class': "mdl-textfield__input"}), } I'm trying to use this block of code from MDL's components: <form action="#"> <div class="mdl-textfield mdl-js-textfield"> <input class="mdl-textfield__input" type="text" id="sample1"> <label class="mdl-textfield__label" for="sample1">Text...</label> </div> </form> -
Can't access models from the script initialized in init.py
Can U tell me how to access models before all the apps gets loaded This is my mqtt.py which was initialized in init.py and accessing models import paho.mqtt.client as mqtt from Transport.models import BusPosition # Broker CONNACK response def on_connect(client,userdata,flags,rc): print ("Connected with result code "+str(rc)) # Subcribing to topic and recoonect for client.subscribe("trackrkct") #Receive message def on_message(client,userdata,msg): print(msg.topic+" "+str(msg.payload)) BusPosition.create(1, "Mon, 23 May 2016 08:30:15 GMT", 11.0998, 77.9098) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("broker.hivemq.com",1883,60) This is my init.py where mqtt.py was initialized from kctsmarttransport import mqtt mqtt.client.loop_start() and this is my models.py from __future__ import unicode_literals from django.db import models class BusPosition(models.Model): bus = models.ForeignKey(Bus) time = models.DateTimeField lat = models.FloatField(max_length=20) lng = models.FloatField(max_length=20) @classmethod def create(cls,bus,time,lat,lng): busPosition = cls(bus=bus,time=time,lat=lat,lng=lng) busPosition.save() return busPosition and I got these errors as apps aren't loaded yet "C:\Program Files (x86)\JetBrains\PyCharm 2016.2.3\bin\runnerw.exe" C:\Users\Navin\DjangoProject\kct_transport_env\Scripts\python.exe C:/Users/Navin/DjangoProject/kctsmarttransport/manage.py runserver 5000 Traceback (most recent call last): File "C:/Users/Navin/DjangoProject/kctsmarttransport/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Navin\DjangoProject\kct_transport_env\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\Navin\DjangoProject\kct_transport_env\lib\site-packages\django\core\management\__init__.py", line 316, in execute settings.INSTALLED_APPS File "C:\Users\Navin\DjangoProject\kct_transport_env\lib\site-packages\django\conf\__init__.py", line 53, in __getattr__ self._setup(name) File "C:\Users\Navin\DjangoProject\kct_transport_env\lib\site-packages\django\conf\__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "C:\Users\Navin\DjangoProject\kct_transport_env\lib\site-packages\django\conf\__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "c:\python27\Lib\importlib\__init__.py", line …