Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin - Create a edit button for each row
I have to create a django admin button that makes each row of my table editable(after i click the button). And then save the edited row without redirecting to any page. To be 100% clear: when clicking 'edit' all fields in that row will be editable. 1 edit button per row. django admin image: https://gyazo.com/def02a6ed68ddc2e777c0daaf26a0c5d my admin.py from django.contrib import admin from .models import Remedio from django.contrib.admin import AdminSite class MyAdminSite(AdminSite): site_header = 'Farmacia' class RemedioAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['descricao']}), (None, {'fields': ['data_de_fabricacao']}), (None, {'fields': ['data_de_validade']}), (None, {'fields': ['manipulado']}), (None, {'fields': ['maioridade']}), (None, {'fields': ['preco']}), (None, {'fields': ['faca_editar']}), ] list_display = ('descricao', 'data_de_fabricacao', 'data_de_validade', 'preco', 'maioridade', 'manipulado', 'faca_editar') list_filter = ['preco'] search_fields = ['descricao', 'preco'] list_editable = ['preco'] list_display_links = ['data_de_fabricacao'] # readonly_fields = ['preco'] def make_price_zero(self, request, queryset): queryset.update(preco=0.00) make_price_zero.short_description = "Marque os remedios que queira zerar o preco" actions = ['make_price_zero'] admin.site.register(Remedio, RemedioAdmin) admin_site = MyAdminSite(name='farmacia_vitu') my models.py from __future__ import unicode_literals from django.db import models class Remedio(models.Model): descricao = models.CharField(max_length=200) data_de_fabricacao = models.DateTimeField() data_de_validade = models.DateTimeField() imagem = models.ImageField() maioridade = models.BooleanField() manipulado = models.BooleanField() preco = models.DecimalField(decimal_places=2, max_digits=8) faca_editar = models.URLField() def __str__(self): return self.descricao -
How to set up Django MySQL Database on pythonanywhere?
It's the first time I'm deploying a site using MySQL instead of SQLite3, so I'm quite new at this, after reading some documentation I found out that I have to change some files like this : settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_site_db', 'USER': 'username', 'PASSWORD': 'password', 'HOST': '?', #currently using pythonanywhere (not on localhost) 'PORT': '?', } } manage.py try: import pymysql pymysql.install_as_MySQLdb() except: pass (PyMySQL==0.7.10, Django 1.9, Python 3.5) When I run the Bash Console using python manage.py migrate I get this error message : django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)") I thought it has something to do with the HOST and the PORT from the Database configurations, I don't know what I should add in these, does it have to do with MySQL, PythonAnywhere or even my own domain ? How can I resolve this problem and set up MySQL correctly with Django 3.5 ? -
Django make_aware usage
Django docs says: The pytz.NonExistentTimeError exception is raised if you try to make value aware during a DST transition such that the time never occurred (when entering into DST). Setting is_dst to True or False will avoid the exception by moving the hour backwards or forwards by 1 respectively. For example, is_dst=True would change a non-existent time of 2:30 to 1:30 and is_dst=False would change the time to 3:30. So I expect the time to be shifted one forward or backward depending on the value of is_dst. But from my tests, the timezone is being shifted, not the time. Am I misunderstanding the Django docs or this is a bug ? I tested the following : tz = pytz.timezone('America/Sao_Paulo') dt = datetime.datetime(2017, 10, 15 ,0 ,0) print(make_aware(dt, tz)) --> NonExistentTimeError print(make_aware(dt, tz, True)) --> 2017-10-15 00:00:00-02:00 print(make_aware(dt, tz, False)) --> 2017-10-15 00:00:00-03:00 -
upload file using django form
Can anyone help me find my mistake.I am new to django.I want to upload a image using form. #forms.py class ProfileFormSt(forms.Form): image_url = forms.FileField(required=False) #views.py class UpdateProfileStView(FormView): template_name = "home/member_st_form.html" def get(self, request, id): user = User.objects.get(id=self.kwargs['id']) profile = StudentProfile.objects.get(user=user) form = ProfileFormSt(initial={ 'image_url': profile.propic, }) return render(request, self.template_name, {'form': form}) def post(self, request, id): user = User.objects.get(id=self.kwargs['id']) form = ProfileFormSt(request.POST, request.FILES) profile = StudentProfile.objects.get(user=user) if request.POST.get('image_url'): profile.propic = request.POST.get('image_url') profile.save() return redirect('home:member-profile-st', id) #member_st_form.html <form action="" method="post" enctype="multipart/form-data">{% csrf_token %} {{ form.as_p }} <button type="submit">update</button> </form> #models.py class StudentProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) propic = models.FileField(default="profile-icon.png") request.POST.get('image_url') always returns empty...cant find what I did wrong... -
'tuple' object has no attribute 'get' when requesting class based view Django
Hi this should be an easy one i'm sure. Just losing my patience with class based views. Not really sure how they simplify things. Function based views seem to a lot more readable and make more sense. Anyway am trying to convert one of my functional views to a class one and getting this error when I request the view 'tuple' object has no attribute 'get' Here is the urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^upload_photo/$', views.upload_photo, name='upload_photo'), url(r'^upload_photo_class/$', views.UploadPhotoView.as_view()), ] Here is the class based view class UploadPhotoView(View): form = PhotoModelForm formset = formset_factory(PhotoExtendedModelForm, max_num=1, validate_min=True) template_name = 'upload_photo.html' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get(self, request): form = self.form formset = self.formset return (request, self.template_name, {'form': form, 'formset': formset}) def post(self, request, *args, **kwargs): form = self.form(request.POST, request.FILES) formset = self.formset(request.POST) if all([form.is_valid(), formset.is_valid()]): photo = form.save() photo_instance = photo user_id = request.user for inline_form in formset: data = inline_form.save(commit=False) data.Photo = photo_instance data.user = user_id data.save() return render(request, 'upload_photo_done.html') else: return (request, self.template_name, {'form': form, 'formset': formset}) Here is the original function based view @login_required def upload_photo(request): form = PhotoModelForm formset = formset_factory(PhotoExtendedModelForm, max_num=1, validate_min=True) if request.method == … -
Using graphene-django, is it possible to add additional fields to specific edges?
Let's say we have three primary tables; Ingredient, Recipe, and GroceryStore whereby recipes can have many ingredients and ingredients can belong to many recipes (many-to-many relationship). Likewise, grocery stores can sell many ingredients and ingredients can be found at many grocery stores. In the many-to-many relationship between a Recipe and an Ingredient, we would like to store some additional information such as the quantity of ingredients required for a recipe, however, the GroceryStore to Ingredient relationship needs no such information and, in fact, might store something entirely different such as the price of an ingredient. We could model this as such: class Ingredient(Model): name = CharField(max_length=50) class Recipe(Model): name = CharField(max_length=50) ingredients = ManyToManyField('Ingredient', related_name='recipes', through='RecipeIngredient') class RecipeIngredient(Model): recipe = ForeignKey('Recipe') ingredient = ForeignKey('Ingredient') quantity = PositiveIntegerField() class GroceryStore(Model): name = CharField(max_length=50) ingredients = ManyToManyField('Ingredient', related_name='grocery_stores', through='GroceryStoreIngredient') class GroceryStoreIngredient(Model): grocery_store = ForeignKey('GroceryStore') ingredient = ForeignKey('Ingredient') price = DecimalField(decimal_places=3, max_digits=5) Easy enough. Now we can define some simple nodes for these models: class IngredientNode(DjangoObjectType): grocery_stores = DjangoConnectionField(lambda: GroceryStoreNode) recipes = DjangoConnectionField(lambda: RecipeNode) class Meta: interfaces = [relay.Node] model = Ingredient only_fields = ['name'] class RecipeNode(DjangoObjectType): ingredients = DjangoConnectionField(lambda: IngredientNode) class Meta: interfaces = [relay.Node] model = Recipe only_fields = ['name'] class … -
Serializing a list of objects with django-rest-framework
In DRF, I can serialize a native Python object like this: class Comment(object): def __init__(self, email, content, created=None): self.email = email self.content = content self.created = created or datetime.now() class CommentSerializer(serializers.Serializer): email = serializers.EmailField() content = serializers.CharField(max_length=200) created = serializers.DateTimeField() class CommentSerializer(serializers.Serializer): f1 = serializers.CharField() f2 = ... comment = Comment(email='leila@example.com', content='foo bar') serializer = CommentSerializer(comment) serializer.data # --> {'email': 'leila@example.com', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'} Is it possible to do the same for a list of objects using ListSerializer? -
Django Restful: Nested Serializers
I'm adding a 'tests' field to my 'Sample' model, where 'tests' will be a list of 'TestRequest' objects. Currently, I'm getting this error: Got AttributeError when attempting to get a value for field `tests` on serializer `SampleSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Sample` instance. Original exception text was: 'Sample' object has no attribute 'tests'. 'tests' is not a field on my model. I'm just trying to add it to the serialized data. Currently, I can get a nested serializer to work for 'klass' but that is because it's defined in the model. Models: class Sample(models.Model): name = models.CharField(max_length=50, null=False, blank=False) comments = models.TextField(null=True, blank=True) klass = models.ForeignKey('samples.Batch', null=True, blank=True, related_name='samples', verbose_name='Batch') product = models.ForeignKey('customers.Product', blank=False) NOTRECEIVED = 'nr' RECEIVED = 'rc' DISCARDED = 'dc' DEPLETED = 'dp' SAMPLE_STATUS = ( (NOTRECEIVED, 'not received'), (RECEIVED, 'received'), (DISCARDED, 'discarded'), (DEPLETED, 'depleted'), ) status = models.CharField( max_length=2, choices=SAMPLE_STATUS, default=NOTRECEIVED) is_recycling = models.BooleanField(default=False) is_submitted = models.BooleanField(default=False) received_date = models.DateTimeField( _('date received'), null=True, blank=True) class TestRequest(models.Model): client = models.ForeignKey('customers.Client') company = models.ForeignKey('customers.Company') sample = models.ForeignKey('samples.Sample') procedure_version = models.ForeignKey('registery.ProcedureVersion') replicates = models.PositiveIntegerField(editable=True, null=True, blank=True) created_date = models.DateTimeField('Date created', auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) comments = models.TextField('Comments', … -
How to use Python type hints with Django QuerySet?
How to use Python type hints with Django QuerySet, can I specify what model type in QuerySet? Like in list (for example, List[SomeModel]), but with QuerySet? -
Django blog posts not being returned
I am very new to Django and have been following through the blog tutorial from the book: "Django by Example." The code below should return all blog posts with a status of "published" but it refuses to work. What appears to be the correct page loads up using the list.html code but there are no posts showing. I have double checked and I am creating posts with the admin site with the status set to "published." I am not sure if the problem is with the template, model, views or URLs so I am including it all here: I am very new to Django and have been following through the blog tutorial from the book: "Django by Example." The code below should return all blog posts with a status of "published" but it refuses to work. What appears to be the correct page loads up using the list.html code but there are no posts showing. I have double checked and I am creating posts with the admin site with the status set to "published." I am not sure if the problem is with the template, model, views or URLs so I am including it all here: from django.db import models … -
Passing a variable on the template to a view
I am trying to pass a few variable to my view in django. This is to flick through months in a calendar. The information needed is whether the user wanted the next or previous month, and the current month. Here is what I have got so far... <a href="{% url 'tande:holiday' %}?value=previous" class='previous' id='previous' name='previous'><<-Previous</a>&nbsp;&nbsp;<a href="{% url 'tande:holiday' %}?value=next" name = 'next' class='next' id='next'>Next->></a> I've got the next and previous bits to work - no problem! But I can't get the year and month information. The view: def holiday(request, value=None): if request.method == "GET": if value != None: #THIS IS WHAT I NEED TO GET current_year = request.GET.get('year') current_month = request.GET.get('month') value = request.GET.get('value') if value == "next": #calculate next month year = next_month.year month = next_month.month if value == "previous": #calculate previous month year = last_month.year month = last_month.month else: date_today = datetime.now() year = date_today.year month = date_today.month #...... # render html calendar with a form for input requesting holiday context = { # dont know if i need this...?? "year": year, "month": month, } return render(request, "tande/calendar.html", context) I'm not having any luck with this at the moment. Can I pass multiple variables in my url? i.e. … -
facing issues with django forms
i am facing some issue in django forms. Problem is even though i put this code "attrs={'class': 'form-control'}" but when ever go to site and inspect-element, html doesn't include this class it shows this... <input id="id_name" maxlength="100" name="name" type="text" required=""> as you can see it didn't render 'class':'form-control' I might be doing something wrong please tell me how to solve this problem??? forms.py, view.py and .html file code is given below forms.py from django import forms from .models import ContactUs class ContactUsForm(forms.ModelForm): name = forms.CharField(required=True, widget=forms.TextInput(attrs={'class': 'form-control'})), email = forms.EmailField(required=True), subject = forms.CharField(required=True), message = forms.CharField( required=True, widget=forms.Textarea(attrs={'class': 'form-control'}) ), class Meta: model = ContactUs fields = ['name', 'email', 'subject', 'message'] contact.html <div class="container main-container"> <div class="row"> <div class="col-xs-offset-1 col-xs-10 col-md-offset-1 col-md-5"> <h5>Contact Us</h5> <form method="POST" action="/contact/">{% csrf_token %} {% for fields in form %} <div class="form-group"> <label for="{{ fields.id_for_label }}">{{ fields.label }}</label> {{ fields }} </div> {% endfor %} <input class="btn btn-primary" type="submit" value="Submit"> </form> </div> </div> views.py from .forms import ContactUsForm from django.shortcuts import render, redirect from django.contrib import messages from django.http import HttpResponseRedirect def Contact(request): if request.method == 'POST': form = ContactUsForm(request.POST) if form.is_valid(): model_instance = form.save() messages.add_message(request, messages.SUCCESS, 'YOUR FORM HAS BEEN SUBMITTED') return redirect('/contact/') else: … -
Django: How to implement custom authentification with master password
I need to implement a cusotm authorization in django which works like that: A user logs in with his forname, surname and a global password which is stored in a specific table. I am wondering what steos are neccessary to achieve this. Things that came to my mind: custom user model custom authentification backend ??? The admin login should work as well. Any thoughts on this? -
Advice on troubleshooting Wagtail/SQL Azure compatibility required
My organisation is developing a new publishing platform based on Wagtail as a CMS backend. We have extensive in-house expertise in MS SQL databases, but next to none with Postgres or MySQL so would prefer to utilise MS SQL (specifically SQL Azure) - which Wagtail's docs seem to suggest is possible. I have an instance of Wagtail running and have installed a Django backend (https://pypi.python.org/pypi/django-pyodbc-azure) that claims to support SQL Azure. I have configured my database connection settings in settings.py. I can successfully run migrations and create a superuser, so I am reasonably confident that the database connectivity is good. I can then browse to the Wagtail login page at http://localhost:8000/admin but immediately upon logging in with the credentials provided to the createsuperuser script, I get the following error: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'LIMIT'. (102) (SQLExecDirectW)") It would seem that Wagtail itself is using this LIMIT keyword which is unsupported in MS SQL - what's my best approach for troubleshooting and attempting to resolve this behaviour? Or am I on a hiding to nothing? -
Django Static files not found
I am working on a website which uses Django framework. I have put my project related static files in the folder called our_static and collectstatic files in static. Below are my settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") STATICFILES_DIRS = [ os.path.join(BASE_DIR, "our_static"), ] base.html file: {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{% static 'style.css' %}" /> </head> Here our_static files are not at all getting read. My style.css is in our_static folder. -
Adding to a django serializer
I was using the django-serializer: object_list = ZoneEntity.objects.filter(cesiumentity__sensor__in=sensor) jdata =serialize('geojson', object_list, geometry_field = 'mpoly', fields = ('zone_number')) And it works well, but I have realized I want to pass back to my website some of what is in the object_list and some other data I create/correlate on the fly. basically add some more fields to that object_list (some that include another list) Is there a way to do this ? Without the serializer I guess just maybe passing a geojson object back somehow? -
AWS Machine Learning - Django Template
I have this response (I'm just showing some of response) from AWS Machine Learning: {u'Prediction': {u'predictedLabel': u'Luxemburgo', u'predictedScores': {u'Irlanda': 0.0003484287590254098, u'B\xe9lgica': 0.013423046097159386, u'Espa\xf1a': 0.002083213534206152, u'Grecia': 0.0014155727112665772, u'San Marino': 0.00233459216542542, u'Letonia': 0.0008684576023370028, u'Azerbaiy\xe1n': 0.0651199221611023, u'Finlandia': 0.0015709727304056287, u'Andorra': 0.00023321053595282137, u'Italia': 0.0007921983487904072, u'Vaticano': 0.011585880070924759, u'M\xf3naco': 0.01911487616598606, u'Dinamarca': 0.004232937004417181, u'Pa\xedses Bajos': 0.0007871986017562449, u'Islandia': 0.006683974526822567, u'Francia': 0.004822706338018179, u'Montenegro': 0.018228678032755852, u'Bielorrusia': 0.0024703771341592073, u'Alemania': ... I want to show users the predictedScores in a django template so I'm doing {% for p in response.Prediction.predictedScores %} {{p}} {% endfor %} This gives me a nice list of countries BUT I also want to show the probabilities and I cannot work out how to access them. I am sure it is simple but I cannot see it. -
Jquery Load is Duplicating Behaviour in django template
I am trying to populate a page using jquery.load() method. The loading is working fine but a form inside the newly loaded part is duplicating its behaviour on submit event. Relevant jquery part : $('#settings').on('click',function(event){ var tax_submit_url = "{% url 'clinic_tax_submit' %}"; $('.right_col:visible').load(tax_submit_url); return false; }); HTML Part(inside dashboard.html) <div id="sidebar-menu" class="main_menu_side hidden-print main_menu"> <div class="menu_section"> <ul class="nav side-menu"> <li><a href="{% url 'clinic:clinic_dashboard' %}"><i class="fa fa-home"></i> Home </a></li> <li><a><i class="fa fa-edit"></i> Appointments <span class="fa fa-chevron-down"></span></a> <ul class="nav child_menu"> <li id="doctors"><a>Doctors<span class="fa fa-chevron-down"></span></a> <ul class="nav child_menu"> {% for membership in memberships %} <li class="sub_menu membership_button" id="membership_{{membership.id}}" data="{% url 'clinic_doctor_scheduler' membership.doctor.slug %}"> <a> <span><h6 style="margin:0">{{ membership.doctor }}</h6></span> <span style ="color:#1abb9c;"><small>{{ membership.doctor.doctorSpecial }}</small></span> </a> </li> {% endfor %} </ul> </li> </ul> </li> <li><a><i class="fa fa-desktop"></i> Billing & Invoicing <span class="fa fa-chevron-down"></span></a> <ul class="nav child_menu"> <li id="invoicing_summary"><a> Invoicing Summary </a></li> <li id="settings"><a> Settings </a></li> </ul> </li> </ul> </div> </div> <!-- /sidebar menu --> <div class="right_col" role="main"> </div> Form inside template <div class="col-xs-4" style="float:right;"> <h3>Add Another Tax</h3> <br> <form class="taxes_form" method="POST" action=""> {{ taxes_form.as_p }} <button class="primaryAction btn-success" type="submit" style="width:100%;">Submit</button><br/> </form> <div class="alert alert-success" role="alert" style="display:none !important;"> <button type="button" class="close" aria-label="Close"><span aria-hidden="true">&times;</span></button> <strong>Success!</strong> You have added a tax successfully! </div> </div> View to render taxes.html … -
Displaying variable from tags file in Django Template
According to my other question about : Handle dynamic staticfiles path with Django I don't finding the way to solve my problem. I would like to insert in my HTML template a variable corresponding to a Django query. I already used tags in order to allow some parts depending on users' groups. My tags.py file looks like : from django import template from django.contrib.auth.models import Group from Configurations.models import Theme register = template.Library() @register.filter(name='has_group') def has_group(user, group_name): group = Group.objects.get(name=group_name) return group in user.groups.all() @register.assignment_tag def GetTheme(Theme): mytheme = Theme.objects.values_list('favorite_theme').last() return mytheme And my HTML template looks like : <!DOCTYPE html> <html> <head> {% load staticfiles %} {% load static %} {% load user_tags %} <title> DatasystemsEC - Accueil </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="{% get_static_prefix %}{{ mytheme }}/css/Base_Accueil.css"/> The goal is to pick up the variable mytheme in my tags.py file and insert it in my html template. In return, I'm getting all the time : #Look double // in my url http://localhost:8000/static//css/Base_Accueil.html #I should get http://localhost:8000/static/{{ mytheme }}/css/Base_Accueil.html But, after a long moment to search a solution and with the generosity … -
How to Handle Load Management in Django?
I am new to django development. I am making a web application. How can we do load management in django applications. -
Is Django the best way to run a simple python program on a website?
My end goal is a webpage that just has the following code running underneath it. Where the user is presented with a prompt asking for their name and then the outcome. `name = (input("What is your name?")) print ("hey there",name,"how are you?")` I've looked at using Django and have started to learn this. But I just want to check that Django will provide me with the easiest solution for what I want to do?. I should mention that I have to use python (as I have more complicated ideas down the road). I open to all ideas. -
How to access db on server from local computer
I want to insert data into remote db from local computer. It is a repeated task so wanted to get a way to do this most effeciently. My db settings.py """ ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Newsletter', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'django_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "Templates")], '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 = 'django_project.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'django', # Or path to database file if using sqlite3. # The following settings are not used with sqlite3: 'USER': 'django', 'PASSWORD': '7d7bjsksos', 'HOST': '127.0.0.1', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 'PORT': '', # Set to empty string for default. } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Africa/Nairobi' USE_I18N = True USE_L10N = True USE_TZ = False # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') # Build paths inside the project like this: os.path.join(BASE_DIR, … -
Print with win32print in python application, Django from server iis windows server 2012
i have a application on django and development in python, exist a module which serves to printing a tickets in a printer with the library win32print. this aplications is Hosted in a iis windows server 2012 R2. the code is: printer=win32print.GetDefaultPrinter() phandle=win32print.OpenPrinter(printer) dc=win32ui.CreateDC() the problem is that the client Is the one that makes the request to print the ticket with his personal printer connecting connect via web -
What's the best way to add more fields to the Django User model
I'm a little new to Django. I have created a custom User model because I wanted to use the email for authentication and followed the example in the docs which works well and have the following code: class CustomUserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): """ Creates and saves a User with the given email and password. """ now = timezone.now() if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): return self._create_user(email, password, True, True, **extra_fields) class User (AbstractBaseUser, PermissionsMixin): ''' Custom User Model ''' email = models.EmailField(verbose_name = "email address", max_length = 255, unique = True) date_joined = models.DateTimeField('date joined', default=timezone.now) first_name = models.CharField(_('first name'), max_length=30, blank=False) last_name = models.CharField(_('last name'), max_length=30, blank=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() def get_absolute_url(self): return "/users/%s/" % urlquote(self.email) def get_full_name(self): """ Returns the first_name plus the last_name, with a space in between. """ full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): "Returns the … -
How to customize a specific TextField inside the Django admin not all?
I have two TextField in my model. But i want to change the rows and cols attribute of only of the TextField. I know from this page that the look of TextField can be changed using the following code in the admin.py. class RulesAdmin(admin.ModelAdmin): formfield_overrides = { models.TextField: {'widget': Textarea( attrs={'rows': 1, 'cols': 40})}, } ... admin.site.register(Rules, RulesAdmin) As I said, using the above code changed the look of both the TextField, I want only to change one of those here is how my model looks like: class Lesson(models.Model): title = models.CharField(max_length=200) content = models.TextField() pub_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) meta = models.TextField(blank=True) def __str__(self): return self.title I want only to change the look of meta field. How should I go about this ?