Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django arguments to run migration in different ways
In my app, I currently have a data migration which uses the Steam API, and takes a few hours to build the database: class Migration(migrations.Migration): def forward(apps, schema_editor): """ Generates Game and Tag entities from the SteamSpy and SteamStore APIs. Takes a long time. Testing should use --keepdb flag. """ print() Game = apps.get_model("game_finder", "Game") Tag = apps.get_model("game_finder", "Tag") multiplayer_tags = {'Multiplayer', 'Local Multiplayer', 'Co-Op', 'Co-op', 'Online Co-Op', 'Local Co-Op', 'Massively Multiplayer'} all_tags = {} print("Generating Games and Tags.") content = get_json_response("https://steamspy.com/api.php?request=all") if content: items_len = len(content.keys()) counter = 0 for appid, game_data in content.items(): counter += 1 game_tags = [] game_multiplayer_tags = [] if game_data['tags']: game_tags = game_data['tags'].keys() game_multiplayer_tags = game_tags & multiplayer_tags missing_tags = game_tags - all_tags.keys() # Creates tags as needed. for item in missing_tags: print("Creating Tag: {}".format(item)) if item in multiplayer_tags: tag = Tag(name=item, is_multiplayer=True) else: tag = Tag(name=item) tag.save() all_tags[item] = tag # Creates Games. game_name = game_data["name"] print("Creating Game: {} ({}/{})".format(game_name, counter, items_len)) if len(game_multiplayer_tags) > 0: price = get_price(appid) game = Game(appid=int(appid),title=game_name,price=price, is_multiplayer=True) game.save() else: game = Game(appid=int(appid), title=game_name) game.save() for key in game_tags: game.tags.add(all_tags[key]) game.save() def backward(apps, schema_editor): """ Deletes all Game and Tag entries. """ Game = apps.get_model("game_finder", "Game") Tag = … -
Django custom User model throwing SystemCheckError - The field 'username' clashes with the name 'username'
I'm writing a custom User model in Django, inheriting it from AbstractUser as is mentioned in the official Django tutorials. But this throws an error. django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: redditauth.RedditUser.username: (models.E006) The field 'username' clashes with the field 'username' from model 'redditauth.reddituser'. Here is the code I wrote for the custom user model. class RedditUser(AbstractUser): username = models.CharField(unique=True, primary_key=True, validators=[validate_reddit_username], max_length=20) token = models.CharField(max_length=256) USERNAME_FIELD = username REQUIRED_FIELDS = ['token'] def reddit(self): with open('secret.json', 'r') as f: secret = json.load(f) return praw.Reddit(client_id=secret['client_id'], client_secret=secret['client_secret'], refresh_token=self.token, user_agent='Plan-Reddit by /u/SkullTech101') I have tried renaming it to something other than username, thinking that maybe there was already field named username in AbstractUser, but that didn't solve the problem. -
Elasticsearch port 9300 django
I'm facing a strange issue, using Django Haystack and ElasticSearch so I can't rebuild_index. ElasticSearch is properly running on the machine : $ curl -X GET 'http://localhost:9200' { "status" : 200, "name" : "Ziggy Pig", "cluster_name" : "elasticsearch", "version" : { "number" : "1.7.2", "build_hash" : "e43676b1385b8125d647f593f7202acbd816e8ec", "build_timestamp" : "2015-09-14T09:49:53Z", "build_snapshot" : false, "lucene_version" : "4.10.4" }, "tagline" : "You Know, for Search" } But this is the log of ElasticSearch : [2017-11-29 18:25:22,723][INFO ][node] [Ziggy Pig] initialized [2017-11-29 18:25:22,724][INFO ][node] [Ziggy Pig] starting ... [2017-11-29 18:25:22,913][INFO ][transport] [Ziggy Pig] bound_address {inet[/127.0.0.1:9300]}, publish_address {inet[/10.142.0.2:9300]} [2017-11-29 18:25:22,937][INFO ][discovery] [Ziggy Pig] . elasticsearch/HWEvbIkAR3mFwcGeHIa7Cg [2017-11-29 18:25:26,710][INFO ][cluster.service] [Ziggy Pig] new_master [Ziggy Pig][HWEvbIkAR3mFwcGeHIa7Cg][stagelighted] [inet[/10.142.0.2:9300]], reason: zen-disco-join(elected_as_master) [2017-11-29 18:25:26,734][INFO ][http] [Ziggy Pig] bound_address {inet[/127.0.0.1:9200]}, publish_address {inet[/10.142.0.2:9200]} [2017-11-29 18:25:26,734][INFO ][node] [Ziggy Pig] started [2017-11-29 18:25:26,762][INFO ][gateway] [Ziggy Pig] recovered [1] indices into cluster_state [2017-11-29 18:26:22,946][WARN ][cluster.service] [Ziggy Pig] failed to reconnect to node [Ziggy Pig][HWEvbIkAR3mFwcGeHIa7Cg] [stagelighted][inet[/10.142.0.2:9300]] org.elasticsearch.transport.ConnectTransportException: [Ziggy Pig][inet[/10.142.0.2:9300]] connect_timeout[30s] at org.elasticsearch.transport.netty.NettyTransport.connectToChannels(NettyTransport.java:825) at org.elasticsearch.transport.netty.NettyTransport.connectToNode(NettyTransport.java:758) at org.elasticsearch.transport.netty.NettyTransport.connectToNode(NettyTransport.java:731) at org.elasticsearch.transport.TransportService.connectToNode(TransportService.java:216) at org.elasticsearch.cluster.service.InternalClusterService$ReconnectToNodes.run(InternalClusterService.java:584) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) Caused by: java.net.ConnectException: Connection refused: /10.142.0.2:9300 at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method) at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717) at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.connect(NioClientBoss.java:152) at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.processSelectedKeys(NioClientBoss.java:105) at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.process(NioClientBoss.java:79) at org.elasticsearch.common.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:337) at org.elasticsearch.common.netty.channel.socket.nio.NioClientBoss.run(NioClientBoss.java:42) at org.elasticsearch.common.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108) at org.elasticsearch.common.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42) I installed JAVA and Elastisearch … -
'ascii' codec can't encode characters in position 0-3: ordinal not in range(128) in djago-admin
First of all I want to mention that I saw nearly all the similar question and non of them was helpful. so I decided to make this new question on SO. I use python 2.7 and django 1.11.7 and nginx as server. models.py: from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Post(models.Model): postTitle = models.CharField('Title', max_length=60) postText = models.TextField('Text') postDate = models.DateTimeField('Date',default=None) def __str__(self): return self.postTitle I use Postgresql as database and this is how I created the database : postgres=# CREATE DATABASE djangodbjavad WITH ENCODING 'UTF8' LC_COLLATE='en_US.UTF-8' TEMPLATE=template0; I tried to write some Persian text in postTitle field at django admin and it fails to handle it. but interesting enough that it can handle Persian text correctly in postText field. Full log available at here : http://dpaste.com/2Z034BV -
Foreign key in serializer is not json serializable
I'm trying to create a serializer that points to two different objects from Account and Currency, but when its called i keep getting following error: TypeError: Object of type 'Account' is not JSON serializable. what am i doing wrong? class InvoiceSerializer(serializers.ModelSerializer): class Meta: """Meta class to map serializer's fields with the model fields.""" model = Invoice fields = ('user', 'currency', 'task', 'deposit_amount', 'receive_amount') read_only_fields = ('created_at', 'updated_at') def create(self, validated_data): user = Account.objects.only('id').get(id=validated_data['user']) currency = Currency.objects.only('id').get(id=validated_data['currency']) return Invoice.objects.create( user=user, currency=currency, task=validated_data['task'], deposit_amount=validated_data['deposit_amount'], receive_amount=validated_data['receive_amount'] ) -
type of map - location field django
This is my model, class Site(models.Model): name = models.CharField(max_length=100) code = models.CharField(max_length=8) is_active = models.BooleanField(default=True) location = gis_models.PointField(geography=True, blank=True, null=True) gis = gis_models.GeoManager() objects = models.Manager() def __str__(self): return self.name + ', ' + self.city.name This is how I view its location in map, This map is no good for me. If I zoom in, it remains the same and does not show any address. I want a proper map like google shows with proper labeling. How can I achieve that? -
AttributeError: 'NoneType' object has no attribute 'visible_fields'
I'm trying to add a class to <input> on my form. Following the instructions of the first answer to this question, I added some code into my form's __init__ method. However I got the error displayed in the title. forms.py class SignupForm(UserCreationForm): email = forms.EmailField(max_length=200, help_text='Required') first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) def __init__(self, *args, **kwargs): form = super(SignupForm, self).__init__(*args, **kwargs) for visible in form.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' class Meta: model = User fields = ('username', 'email', 'password1', 'password2', 'first_name', 'last_name',) -
Migrating from SQLite3 to Postgres issues with non-null constraints
I'm trying to move from SQLite to Postgres in my Django application, but now I'm getting errors like this when I try to make a POST request: django.db.utils.IntegrityError: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, 2017-11-29 18:48:23.976207+00, 0, 2017-11-29 18:48:23.976247+00, a2bc5886-baf1-4e91-ad08-03a030bb7be7, Hello, 7, 7, 44). The model is very simple in this case: from uuid import uuid4 from django.db import models from scouting.core import TimestampModerated from profiles.models import Profile from photos.models import Photo class Comment(TimestampModerated): uuid = models.UUIDField(db_index=True, default=uuid4, editable=False) user = models.ForeignKey('auth.User', related_name='user_comments', on_delete=models.CASCADE) profile = models.ForeignKey(Profile, related_name='profile_comments', on_delete=models.CASCADE, null=True) photo = models.ForeignKey(Photo, related_name='comments', on_delete=models.CASCADE, null=True) text = models.CharField(max_length=255) class Meta: verbose_name_plural = "comments" def __str__(self): return self.text One thought I have is that it seemed with SQLite I didn't have to explicitly declare the id field. Maybe that is not the case with postgres? -
django ModelForm - this field is required error always shows
I have this in my views but why does it always show the error that the field is required form = ProgressReportForm(request.POST or None): return render(request, template, {'form': form}) Here is my form class ProgressReportForm(ModelForm): class Meta: model = ProgressReport fields = ['title', 'report_progress'] widgets = { 'report_progress': forms.Textarea(attrs={'class': 'form-control'}) } -
Crispy-Forms Include Tag Causing Many Duplicate Templates
I have a Django site that uses the below template to render a crispy-forms model formset. Using django-debug-toolbar, I gathered that the include tags are rendering the bootstrap4 templates many, many times. I think this is what is killing my performance (i.e. 3-4 minutes to load an inline formset with 100 forms in it) How should I replace the include tags to avoid the duplicate rendering? Should I use extend somehow? I can replace the include tags with the actual html from the bootstrap4 crispy-forms templates, but those templates have nested templates as well. That creates an exercising of building a master crispy-forms template that includes everything...which seems like the wrong way to go about this. In addition, I tried replace the bootstrap4/field.html include tag with the actual html, and field.html was still duplicated, and the data lost it's table structure because of the loss of with tag='td'. {% load crispy_forms_tags %} {% load crispy_forms_utils %} {% load crispy_forms_field %} {% specialspaceless %} {% if formset_tag %} <form {{ flat_attrs|safe }} method="{{ form_method }}" {% if formset.is_multipart %} enctype="multipart/form-data"{% endif %}> {% endif %} {% if formset_method|lower == 'post' and not disable_csrf %} {% csrf_token %} {% endif %} <div> … -
Django does not add an extra attribute to the custom ModelForm widget
models.py class MyModel(models.Model): pub_date = models.DateTimeField(default=timezone.now) title = models.CharField(max_length=255, blank=False, null=False) text = models.TextField(blank=True, null=True) forms.py class MyModelForm(ModelForm): tos = BooleanField() class Meta: model = models.MyModel fields = ['title', 'text', 'tos'] widgets = { 'title': TextInput(attrs={'class': 'form-control', 'placeholder': 'Title'}), 'text': Textarea(attrs={'class': 'form-control', 'placeholder': 'Text'}), 'tos': CheckboxInput(attrs={'data-validation-error-msg': 'You have to agree to our terms and conditions'}), } Results: >>> print(forms.MyModelForm()) <tr><th><label for="id_title">Title:</label></th><td><input type="text" name="title" class="form-control" placeholder="Title" maxlength="255" required id="id_title" /></td></tr> <tr><th><label for="id_text">Text:</label></th><td><textarea name="text" cols="40" rows="10" class="form-control" placeholder="Text" id="id_text"></textarea></td></tr> <tr><th><label for="id_tos">Tos:</label></th><td><input type="checkbox" name="tos" required id="id_tos" /></td></tr> You can see that the in the TOS field data-validation-error-msg attribute is missing. Any ideas? -
ChartJs Radar customisation in django
I am trying to make charts work in my Django Application using chart.JS But I am having some difficulties to make it look great ! here it how it looks: I would have two questions: 1) How can I add a bottom margin in the chart label 'Team Test" 2) How can I center verticaly the right chart 3) How can I increase the space of the chart and the labels ? Here is my code : //graph 2// var info_process = new Chart(ctx2,{ type: 'radar', data: { labels: labels_info, datasets: [{data: info_data, label: team_name, backgroundColor: "rgba(102, 187, 158, 0.2)", borderColor: "rgba(102, 187, 158, 0.9)", pointBackgroundColor: "black", pointBorderColor: "#fff", pointHoverBackgroundColor: "yellow", pointHoverBorderColor: "rgba(179,181,198,1)", }] }, options: { scale: {display: true, ticks: { beginAtZero: true, } }, responsive:true, maintainAspectRatio: true, } }); //end graph 2// //graph 3// var info_process = new Chart(ctx3,{ type: 'radar', data: { labels: label_action, datasets: [{data: action_data, label: team_name, backgroundColor: "rgba(102, 187, 158, 0.2)", borderColor: "rgba(102, 187, 158, 0.9)", pointBackgroundColor: "black", pointBorderColor: "#fff", pointHoverBackgroundColor: "yellow", pointHoverBorderColor: "rgba(179,181,198,1)", }] }, options: { scale: {display: true, ticks: { beginAtZero: true, } }, responsive:true, maintainAspectRatio: true, } }); //end graph 3// -
How to edit Django form into a bootstrap modal?
My situation: urls.py url(r'^edit/(?P<pk>[0-9]+)/$', views.edit, name='edit'), views.py def edit(request): if request.method == 'POST': form = EditForm(request.POST) if form.is_valid(): form.save() else: pass return redirect('home') template.html {% extends 'base.html' %} {% load staticfiles %} <div class="container"> {% for x in context %} [...] <button class="btn btn-warning" role="button" data-toggle="modal" data-target="#modalEdit">Edit</button> [...] {% endfor % </div> {% include 'modal.html' %} modal.html <div class="modal fade" id="modalEdit" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <h3 class="text-center">Edit form</h3> <form method="POST" action="{% url 'edit' object.pk %}">{% csrf_token %} {% render_field edit_form.title class="form-control" %} <button type="submit" class="btn btn-bold btn-primary">Save</button> </form> </div> </div> </div> </div> In this case, and if I want to show context element info too, I can't see it into bootstrap modal. How can I pass x.pk into modal to edit it or see information like x.title? -
Django keeps adding ' character to first cell of my data so it can't store it in the model
I'm going nuts. Whatever I do, Django adds a ' character to the start of the first field of my data. I have a df that looks like so: Year JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV \ 0 1910 6.1 7.2 8.9 9.6 14.5 17.1 17.3 16.9 15.6 12.5 6.9 1 1911 5.8 6.5 7.5 9.7 16.2 17.8 21.7 21.4 17.3 12.4 8.2 2 1912 6.0 7.5 9.1 12.5 14.4 16.0 18.4 15.0 13.7 11.6 8.4 3 1913 6.7 7.2 8.5 10.4 13.8 16.5 17.6 18.5 16.5 13.5 10.6 4 1914 5.6 8.7 8.4 13.2 13.8 17.6 18.5 19.1 17.0 12.9 9.1 5 1915 5.9 6.4 7.7 10.8 15.1 18.0 16.9 17.7 17.0 11.9 6.0 6 1916 9.2 5.7 5.5 11.1 14.1 14.5 18.3 19.2 16.0 12.9 8.8 7 1917 2.7 3.8 6.1 8.4 16.3 17.5 19.3 17.1 16.2 10.7 9.9 8 1918 6.4 8.4 8.7 10.1 16.2 16.6 18.4 18.3 14.3 11.5 8.5 ... I have a function that puts it into a model: def add_to_db(weatherstats_df): print(weatherstats_df) for row in weatherstats_df.itertuples(): # print(row) year = int(str(row.Year).strip('\'')) print(year) measurement = row.Measurement location = row.Location ikey = 0 for key, month_or_season in WeatherStatistics.MONTH_OR_SEASON: ikey += 1 … -
self excluding excecution of functions in django
i have a django model that has values stored in a json field. but some of the values have to be unique, for that i have a function check_unique(). but this check fails if two users try to save the same value at the same time since when check_unique() runs neither of the values is stored in the database and then they are individually correct. There is a way to avoid this behavior? i tried avoiding this using trheadeing.Lock but apache runs in different processes and it does'nt work in that case. Besides, i would like that the check would be at application level (in python) and not at database level. the code looks like this: semaphore.claim() try: uniques = check_unique(self.answers) if not uniques: self.go_save() semaphore.release() return Response("All OK") except Exception as e: semaphore.release() return e -
Linking outer html page to the reverse_lazy() of signup page
I have written code to develop a social media clone site using django. In that, after signup, i have to move to homepage instead of login page. The homepage html code is present in another folder outside of this current folder. I am unable to access the url of the html page from this. The code is: from django.contrib.auth import login, logout from django.core.urlresolvers import reverse_lazy from django.views.generic import CreateView from . import forms class SignUp(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy("login") template_name = "accounts/signup.html" Instead of "login", the url should be "base". The path of "login.html" is: "project/accounts/templates/accounts/login.html". And the path of "base.html" is: "project/templates/project/base.html". Please suggest me a method to modify this. -
install python package on heroku without pypi support
I am trying install a Django app on Heroku. My app needs pyke3. The recommended way for installing pyke3 is to download pyke3-1.1.1.zip https://sourceforge.net/projects/pyke/files/pyke/1.1.1/ and then install (into a virtualenv if desired) using the instructions on http://pyke.sourceforge.net/about_pyke/installing_pyke.html. How do I install pyke3 on heroku? Is there a way to add this to the requirements.txt, and how will heroku know where to get the pyke3 zip file? -
Making a dynamically generated list mutually exclusive
I have an unordered list that appears as part of an autocomplete dropdown and that is being dynamically generated, by a plugin, that only appears in the DOM after a user interaction. On the page in question, this list can be rendered multiple times. I want to make the list mutually exclusive so that when one item is selected, it can no longer be selected in a new list. The main problem I am having is that I am struggling to get access to the element that I actually need to perform the event on. The code that is generated for the list is like so: <span class="select2-container select2-container--default select2-container--open" style="position: absolute; top: 310px; left: 523.172px;"> <span class="select2-dropdown select2-dropdown--below" dir="ltr" style="width: 144px;"> <span class="select2-search select2-search--dropdown"> <input class="select2-search__field" type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="textbox"> </span> <span class="select2-results"> <ul class="select2-results__options" role="tree" id="select2-id_eventconfigstepkeycharacteristicfield_set-0-key_characteristic-results" aria-expanded="true" aria-hidden="false"> <li class="select2-results__option" role="treeitem" aria-selected="true">Depot</li> <li class="select2-results__option select2-results__option--highlighted" role="treeitem" aria-selected="false">Month</li> <li class="select2-results__option" role="treeitem" aria-selected="false">bdfdf</li> </ul> </span> </span> </span> I basically want to make so that when a li has select2-results__option--highlighted in its class it will be removed from the list when it is rendered again. So far I can get access to this by adding a jQuery event … -
Slow Django Model Formset Rendering
I have a Django Model Formset that is rendered with a crispy-forms in a custom table inline formset template. The formset is a list of alerts with entities, logic, and comments. Entity and logic are populated in each form, and the user writes a comment prior to submitting the form. The formset currently has 140 forms (i.e. 140 records in the Alert model), and it will need to handle more than that number. It takes 2 minutes for alerts.html to render. I can use Django-based pagination to limit the queryset and reduce rendering time, but this precludes me from using something like jQuery datatables to paginate and quickly add JS functionality. I used django-debug-toolbar to review. The queries are definitely funky and duplicated per form (i.e. the query grabbing entity information is duplicated for each form and also includes duplicate where statements). However, it only takes 3-4 seconds for the queries to run, so the problem must be elsewhere. I used Chrom dev tools to record the performance, but I didn't see anything helpful. Why is the render taking so long? Is there anything in my code below that could be optimized? I know caching is an option, but I … -
save unknown number of images in django
a post may have no image or may have 10 images in the request so i dont know how to save them and here is my models models.py class Post(models.Model): owner = models.ForeignKey(User) birthday = models.DateTimeField() class PostImages(models.Model): owner = ForeignKey(Post) image = ImageField() im going to save all of the images that are uploaded in POST.FILES so i tried: for file in POST.FILES: PostImages.objects.create(owner=post, image=file) but file gives me a string and when i save it it have no filename extension i mean i cant use the file anymore because it has no type.i would like to use formsets but i don't know how to use it in this case or maybe i can't, i have no idea. -
How to create a user and its corresponding profile object in django shell
I have a Profile model which has OneToOneField to User model(django.contrib.auth.models).I have a custom Signup form in which apart from default user fields, I use 2 other custom fields(type and organisation).I use post_save signal to automatically create or update the profile for the user instance that is being saved. All this works completely fine in admin and through a view.But when I try to create a user through django shell using User.objects.create_user(username='..',password='..'), I get an Integrity Error which is because of the 2 custom fields being non-nullable.How can I create the user in django shell. forms.py class UserRegistrationForm(forms.ModelForm): password = forms.CharField(label='Password',widget=forms.PasswordInput) password2 = forms.CharField(label='Repeat Password', widget=forms.PasswordInput) class Meta: model = User fields = ('username','first_name','last_name','email') def clean_password2(self): cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError('Passwords don\'t match.') return cd['password2'] class SignUpForm(UserRegistrationForm): organisation = forms.ModelChoiceField(label='Your Organisation',queryset=Organisation.objects.all()) type = forms.ChoiceField(label='You are a ', choices=TYPE_CHOICES) class Meta: model = User fields = ('username','first_name','last_name','email','institute','category','password','password2') def save(self, commit=True): user = super(SignUpForm, self).save(commit=False) # add attribute to user model for access in signal user._type = self.cleaned_data['type'] user._organisation = self.cleaned_data['organisation'] if commit: user.save() return user -
Auto Populate Field if PK/FK exists in another model
I'm really struggling with this issue. As a newbie if my logic or thought process is incorrect please help direct me. I'm attempting to auto populate a field in my custom user model with a 1 or a 0 if the formattedusername exists in another model/pre-existing database table with the following signal, but i can't seem to get it to work correctly: @isthisflag def is_this(self, is_this): if cfo.ntname is user.formattedusername: return 1 else: return 0 I have a custom User model like the following: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=7, unique=True) formattedusername = models.CharField(max_length=11, unique=True, primary_key = True) is_this = models.BooleanField(default=False) USERNAME_FIELD = 'username' I then have another model we'll call cfo that has a list of formattedusernames with the ntname field as a FK to formattedusernames. class cfo(models.Model): ntname = models.OneToOneField(settings.AUTH_USER_MODEL,db_column='CFO_NTName',primary_key=True, serialize=False, max_length=11) class Meta: managed = False db_table = 'cfo' If ntname exists as the User who logs with their LDAP authentication I want to place a 1 in the User.is_this field. -
Django - concatenate form fields before validation
There is a Person model in models.py: class Person(models.Model): ... tel = PhoneNumberField(blank=True, default='') ... Where phone is of type PhoneNumberField Now, in my forms I have something like this: class PersonForm(forms.ModelForm): # Some code... class Meta: model = Person fields = [..., 'phone',...] phoneprefix = ChoiceField(choices=phone_prefixes) Where phone_prefixes is list that maps, well, phone prefixes so user can choose from dropdown list phone code for his desired country, for example +44 for UK. What I want to achieve is to make Django concatenate value of phoneprefix to phone in form, and then run any validation to check if phone number is possible/valid. django-phonenumber-field library has some nice functions for validation, but I want them to be run on +44 1632 960741, not just 1632 960741. How can I do that? -
How to install xhtml2pdf in Cloud9 using python 2.7?
I have tried to install xhtml2pdf for render pdf from html.I have followed the instructions bellow. Installation For python2.7: pip install xhtml2pdf To obtain the latest experimental version that has Python 3 support, please use a prerelease: pip install --pre xhtml2pdf but in this process , C9 shows me this error. How can I solve this problem? Thanks -
Django save blank value
I have a number of unknown values in a df, where the cells are filled with the chars '---' I would like to tell Django that, if it finds something that is not a number of any kind (int / decimal / floating point) to leave the value of that field blank. I also want the default to be blank, but it does not seem to allow this either. My model looks like this: value = models.FloatField( # default=blank, null=True, validators=[MinValueValidator(0)], ) My view calls a function like this: if (value == "---"): value = None MyModel( value=value, ).save() My form looks like this: from django import forms from .models import WeatherStatistics class WeatherStatisticsForm(forms.ModelForm): class Meta: model = WeatherStatistics fields = [ "value", ] How can I post a blank value to the db?