Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form: subsetting a ModelMultipleChoiceField
I am looking for a way to filter a multiple choice field in django forms such that one will see only a specific portion of the user database. I have three models: a research results model (named Forskningsresultater); a user model (the default User model); and a custom-made M2M model between the first two models (named PersonRes). This custom-made M2M model has been imported using Django Import/Export. Say that I have a model with 300 users and that one particular research result has 5 authors. In the form, I want to display checkboxes for only these 5 authors instead of all 300. The checkboxes are used to change the participant field in the PersonRes model (see the models.py box below). Therefore, I want to: Subset so only authors related to a specific research result through the M2M model are shown. Even though a user unchecks an author as a participant (so that we have four checked authors and one unchecked), it should be able to go back to this form and still see all authors (here: all five authors) and make additional changes to all these authors if needed. models.py class Forskningsresultater(models.Model): id = models.IntegerField(primary_key=True) ... authors = models.ManyToManyField(settings.AUTH_USER_MODEL, through='PersonRes', … -
Debug AdHoc Code from from shell_plus with VS Code
I have a Django project and sometimes I need to execute class methods and/or Django "commands" for ad hoc debugging via shell_plus. I can do this from the terminal AND add debugging "break points" by adding standard pdb code: import pdb; pdb.set_trace() But debugging this way is rather painful. I am new to VS Code and looking to use its debugging interface. I have set up a new debug configuration in launch.json like this: { "version": "0.2.0", "configurations": [ { "name": "Shell Plus", "type": "python", "request": "launch", "stopOnEntry": false, "pythonPath": "${config:python.pythonPath}", //"preLaunchTask": "configStaging", "program": "${workspaceRoot}/manage.py", "args": [ "shell_plus" ], "debugOptions": [ "WaitOnAbnormalExit", "WaitOnNormalExit", "RedirectOutput", "DjangoDebugging" ], "env" :{ "LOGGING_LEVEL" : "DEBUG", //Lots of other env variables } } ] } If I run this configuration I can see shell_plus standard output in debug console. I can also run ad hoc commands from the command prompt including importing some classes and trying to instantiate and execute them. The problems are: a) I cant see the output from the code executed. If I were to launch shell_plus from the command line, import and then execute code, any print statements for example would be sent to standard out and then be shown in … -
Django - cannot load image saved to database
Exactly as the title says i cannot load the image i saved in the database. Im am saving the uploaded images in "TV/media/logo_image/" Thi is my MEDIA_URL: STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT= os.path.join(BASE_DIR, 'Tv/media') My model: class EmpresaProfile(models.Model): empresa = models.CharField(max_length=20, blank=False, default="") logo = models.ImageField(upload_to='logo_image', blank=True) def __str__(self): return self.empresa This is my views.py: def index(request): empresa = EmpresaProfile.objects.all() return render_to_response('Tv/index.html',{'empresa': empresa}) template: <div style="height: 100px;"> {% for empresa.logo in empresa %} <img class="img-responsive" src="{{MEDIA_URL}}{{ empresa.logo }}" alt="" width="1000px" /> {% endfor %} </div> This is the vey first page i access so this is mu url: urlpatterns = [ url(r'^$', views.index, name='index'),] I am getting source "unknown" in the image tag thank you -
Setting up Django with Apache got DB error - DatabaseError: DPI-1047
I am setting up Django in Apache 2.4, Suse 11. Apache starts with no issue. If I don't put any DB connection info in Setting.py, the index page can be opened with no issue. When I put the DB info in, then tried to access the index page, I see below DB errors in Apache error output. However, if I just run 'python', then 'import cx_Oracle as Database', there is no error. I also put 'PassEnv LD_LIBRARY_PATH' and 'PassEnv PATH' in httpd.conf. Oracle Env variables are: export LD_LIBRARY_PATH=/usr/lib/oracle/11.2/client64/lib:$LD_LIBRARY_PATH export PATH=/usr/lib/oracle/11.2/client64:$PATH Django version 1.10 Python version 2.7.13 64 bit cx_Oracle 6.0 Let me know if any more detailed information from me could help. Thanks a lot! import cx_Oracle as Database DatabaseError: DPI-1047: Oracle Client library cannot be loaded: libclntsh.so: cannot open shared object file: No such file or directory. -
Django/Python - Store data from a request to 3rd party API and then serve profile data
In my Django application, called velosparkapp, I am taking profile information an API client and storing it on behalf of the user. I would like to store said profile information (id, firstname, lastname, profile_pic_url, etc...) in db upon successful login. For third party login I am using django-all-access. I don't provide the ability to login with django and the third party provider. The provider I'm using is strava. The application is working with my home page('index.html') and contact_page('contact.html') which are both serve no dynamic content yet. The following link works but user.id is not the correct primary key for the athlete's information: profile page link: <a href="{% url 'profile' user.id %}"><span class="glyphicon glyphicon-user"></span></a> I'm thinking on the profile page, the context variable I would have to access would be something like this(ex.: profile pic medium): {{% athlete.profile_medium %}} Finally, I know the way to call the provider API for additional data from the django-all-access docs is something like: from allaccess.views import OAuthCallback class NewActivityDataCallback(OAuthCallback): def get_login_redirect(self, provider, user, access, new=False): "Send a tweet for new Twitter users." if new and provider.name == 'strava': api = access.api_client params = {'page': 0} url = 'https://www.strava.com/api/v3/athlete/activities' response = api.request('get', url, params=params) # Check … -
How create a filter_horizontal on self-referential M2M django model?
I have a self-referential M2M model. I can display data in a select drop down. I like to use a filter_horizontal instead of the drop down select to improve user experience. I have tried many options but I have not been able to crack this. This is what I have: RELATIONSHIP_FOLLOWING = 1 RELATIONSHIP_BLOCKED = 2 RELATIONSHIP_STATUSES = ( (RELATIONSHIP_FOLLOWING, 'Following'), # Following: denotes the relationship from the user, i.e. following (RELATIONSHIP_BLOCKED, 'Blocked'), ) class Application(TimeStampModel): name = models.CharField(verbose_name='CI Name', max_length=100, unique=True) relationships = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to') def get_following(self): return ", ".join(str(x) for x in self.get_relationships(RELATIONSHIP_FOLLOWING)) def get_followers(self): return ",".join(str(x) for x in self.get_related_to(RELATIONSHIP_FOLLOWING)) def get_friends(self): return self.relationships.filter( to_apps__status=RELATIONSHIP_FOLLOWING, to_apps__from_application=self, from_apps__status=RELATIONSHIP_FOLLOWING, from_apps__to_application=self) def get_friends_display(self): return ", ".join(str(x) for x in self.get_friends()) ---- admin @admin.register(Application) class ApplicationAdmin(admin.ModelAdmin): form= ApplicationChangeForm filter_horizontal = ('relationships',) list_per_page = 30 verbose_name = 'Application' inlines = [ApplicationInLine, DbGroupInline, RelationshipInline, ] list_display_links = ['name', '_num_servers',] date_hierarchy = 'updated_on' list_display = [ 'name', 'get_following', 'get_following_count', 'get_followers', 'get_followers_count', 'get_friends_display', ] And it is displayed as shown here. But I want to change the layout to be displayed as Filter_horizonal. -
Cannot run Pycharm debugger for django view
I am trying to debug a view in my Django project but to no avail. Here's my code And here's what I get in my debugger console: /home/dmmeow/Work/tutor/leaf/bin/python3.5 /home/dmmeow/Downloads/pycharm-2017.1.4/helpers/pydev/pydevd.py -- multiproc --qt-support --client 127.0.0.1 --port 46561 --file /home/dmmeow/Work/tutor/genmaicha/mainscr/views.py warning: Debugger speedups using cython not found. Run '"/home/dmmeow/Work/tutor/leaf/bin/python3.5" "/home/dmmeow/Downloads/pycharm- 2017.1.4/helpers/pydev/setup_cython.py" build_ext --inplace' to build. pydev debugger: process 3853 is connecting Connected to pydev debugger (build 171.4694.38) Process finished with exit code 0 How can I access debugger in this case? -
How to draw boxes around table elements being displayed on the webpage using Django
I'm trying out Django for the first time as a web framework. My views.py function looks as follow: def display(request): find_duplicate() return render_to_response('index.html', {'obj': my_model.objects.order_by('id')}) def get_dict(): d={} for e in my_model.objects.all(): col2 = e.col2 col3 = e.col3 col2 = unicode(col2).encode('UTF8') col3 = unicode(col3).encode('UTF8') d.setdefault(col2, []) d[col2].append(col3) del d[''] return d def find_duplicate(): #print(d) d = get_dict() for k,v in d.items(): if len(v) > 1: name=[] id=[] #print(k) for i in v: #print(i) reg1 = i.split("(")[0] name.append(reg1) reg2 = re.search(r'[A-Z0-9]*', i.split("_")[1]) id.append(reg2.group()) #print(name) #print(id) And my index.html is as follows: <body> <div class="container"> <table align="center"> <tr> <th bgcolor="#f0a00c">Col1</th> <th bgcolor="#f0a00c">Col2</th> <th bgcolor="#f0a00c">Col3</th> <th bgcolor="#f0a00c">Col4</th> <th bgcolor="#f0a00c">Col5</th> </tr> {% for b in obj %} <tr> <td>{{ b.col1 }}</td> <td>{{ b.col2 }}</td> <td>{{ b.col3 }}</td> <td>{{ b.col4 }}</td> <td>{{ b.col5 }}</td> </tr> {% endfor %} </table> </div> <!-- /container --> <script> var col21 = [], col31 =[]; {% for b in obj %} col21.push("{{b.col2 }}"); col31.push("{{b.col3 }}"); {% endfor %} console.log(col21); console.log(col31); </script> </body> My urls.py: urlpatterns = patterns( '', url(r'^admin/', include(admin.site.urls)), url(r'^$', 'myapp.views.display'), ) So, right now the index.html displays the database from mysql ordered by col2 like this: Col2 | Col3 | Col4 1 | Name1(something_1234) | Some_date 1 | … -
Displaying and saving Django ArrayField
I have an a type of ArrayField in a model. The backend in a list of suggested elements for my_list automatically. However, the user then needs to update this list as needed. The model looks like this: class my_model(models.Model): my_list = ArrayField( models.CharField(max_length=10) ) The problem is that when my_list is rendered in the template is a single html input tag with a comma separated list. For example a,b,c,d. My question is two fold. How can I get the templating language to display the comma separated list so that each element has their own html input box. Moreover, the harder thing that I am struggling with is how to make it so that these elements will be saved back to the model back as an array. My current thinking is to hack the front-end with javascript. But is there a better way to do it with Django? -
Django - print NAME where ID is something
I am new to DJango and I am trying to just print a name out of an object, where its ID is 2. Tried with UserData.objects.filter(user=2) but i get a list of repeating UserData: UserData object and I am completely lost. -
Django models.ForeignKey issue with model with custom foreign key
I use Django 1.11, Python 3.6 and PostgreSQL 9.6. I define two models as described in the documentation. class CircDetect(models.Model): oid = models.AutoField(primary_key=True) ... class Meta: db_table = 'circdetect' class PatientMed(models.Model): ... circdetect = models.ForeignKey(CircDetect, on_delete=models.CASCADE, to_field='oid') ... But when I try to get an access to the list of PatientMed objects on the admin site I get an exception: ProgrammingError at /canreg/editor/patientmed/ column patient_med.circdetect_id does not exist LINE 1: ... "patient_info"."id") INNER JOIN "circdetect" ON ("patient_m... HINT: Perhaps you meant to reference the column "patient_med.circdetect". It looks like Django tries to get id filed of circdetect, which is actually has name oid. What can I do to fix this issue? -
django - Single User object can store multiple objects of model
I am making a django app where a User can have multiple urls stored in his account .The problem, I am facing is a Single User is able to store a single url ,on adding multiple it gives a Integrity error. So how can i add Multiple url to a single User object models.py class Userprofile(models.Model): user = models.OneToOneField(User) url = models.CharField(max_length = 100 ,) shortcode = models.CharField(max_length = 10 ,blank = True) timestamp = models.DateTimeField(auto_now_add = True) def save(self , *args , **kwargs): if self.shortcode is None or self.shortcode is '': self.shortcode = create_shortcode(self) super(Userprofile, self).save(*args , **kwargs) def __str__(self): return self.user.username forms.py class URLForm(forms.ModelForm): class Meta: model = Userprofile fields = ('url',) widgets={ 'url':forms.TextInput(attrs={'placeholder':'Long URL','class':'form-control'}), } def clean_url(self): url = self.cleaned_data['url'] url_validator = URLValidator() try: url_validator(url) except: raise forms.ValidationError('Enter a proper URL ') return url Views.py def user_url_info(request): if request.method == 'POST': form = URLForm(request.POST) if form.is_valid(): # try: # obj = Userprofile.objects.get(url = form.cleaned_data['url']) # print('already') # except: obj = form.save(commit = False) obj.user = request.user obj.save() return render(request , 'detaail.html',{'obj':obj}) else: form = URLForm() return render(request , 'urlform.html' ,{'form':form}) so I want that a request.user can sore multiple object of Userprofile -
in Django is it better to make a different model for authors to relate to post? or put it in the post model?
I am relatively new to django trying to be able to get a users personal post to show up on a user page. My problem is that the post don't add the author automatically. I also need it to do it for multiple users so i cant just filter by name. class Post(models.Model): creator = models.CharField(max_length=250) post_name = models.CharField(max_length=250) post_photo = models.FileField() author = models.ForeignKey(Author, blank=True, null=False, related_name ='user_post') category = models.ManyToManyField(Category) slug = models.SlugField(unique=True) def get_absolute_url(self): return reverse('post:detail', kwargs={'pk': self.pk}) def __str__(self): return self.creator + ' - ' + self.post_name class Author(models.Model): name = models.CharField(max_length=200) created_by = models.ForeignKey(User, on_delete=models.CASCADE) -
Django: Filtering a model's ManyToMany field with __in=[somelist] produces zero results when it should produce several
I haven't found a solution online to this--I can't be the first person attempting this. Here's my model structure: class TopModel(models.Model): type = models.CharField() class MiddleModel(models.Model): parent = models.ForeignKey(TopModel) class LowerModel(model.Model): middleParent = models.ForeignKey(MiddleModel) topParent = models.ForeignKey(TopModel, related_name="ref_to_top_parent") topmodel_refs = models.ManyToMany(TopModel, related_name="ref_to_other_tops") I need to filter by some weird querying--I know this--but bare with me. I use the MiddleModel to filter the Top Model twice--you'll see. So I'm making 2 query sets: currentMidMod = MiddleModel.objects.get(pk=1) firstQuerySet = currentMidMod.topmodel_set.all() secondMidMod = MiddleModel.objects.get(pk=2) secondQuerySet = secondMidMod.topmodel_set.all() Then I filter the 1st: firstQuerySet = firstQuerySet.filter(type__contains="somevalue") Then I filter the 2nd: secondQuerySet = secondQuerySet.filter(type__contains="test") #produces a count() of 10 #Grab a valueset of the pks compareList = list(secondQuerySet.values_list('pk', flat=True)) Then here is where the issue occurs: newQuerySet = firstQuerySet.filter(ref_to_top_parent__topmodel_refs__in=compareList) newQuerySet.count() #equals 0 when I know it should equal 5 So I'm trying to filter my first queryset by all of its LowerModel reverse foreignkeys by those LowerModels ManyToMany list of keys back to TopModels by comparing it with a list of pk values in the values list I create It never finds matching 'pks' even though I can manually look through phpAdmin and find the matches myself I'm dying. Please help! -
How to provide my own 'clean_is_staff' on UserChangeForm?
I'm working on a django project that I inherited, and I want to add validation when setting the 'is_staff' attribute of a user. I can't figure out how ... My goal is to ensure that a regular user (a student, in this case) cannot be given 'is_staff' privilege by mistake. This is extra protection beyond training the existing administrators not to do this Bad Thing. The project uses the standard auth.user, and has its own Profile class. That all works fine. Once a student registers, he or she has a User object and a Profile object. Staff users are/should be created only by an administrator, using the standard 'Add New User' action in the Admin UI. BTW, this is Django 1.8. My idea is to add a custom 'clean_is_staff()' method and raise ValidationError if the User being edited has a Profile object. So I did two things: wrote 'ValidatingUserChangeForm' as a subclass of UserChangeForm, to put my logic in, and wrote 'ValidatingUserAdmin', to have a code path to ValidatingUserChangeForm. It's not working; my ValidatingUserAdmin seems to work fine, but my ValidatingUserChangeForm is ignored. I'm sure it's my fault - guidance welcome. I'll provide the output in a comment to this … -
Docker compose don't wait postgres
Ok guys so here is my problem I made a Dockerfile based on python3 image, here is the code: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ This is my docker-compose.yml file, that starts a simple django app: version: '2' services: web: build: . env_file: composeexample/.env command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - "db" command: ["./wait-for-postgres.sh", "db", "--", "python", "news/"] db: image: postgresql volumes: - /var/lib/postgresql/data I'm trying to execute the ./wait-for-postgres.sh script from this page: https://docs.docker.com/compose/startup-order/ And it have the following code: #!/bin/bash # wait-for-postgres.sh set -e host="$1" shift cmd="$@" until psql -h "$host" -U "postgres" -c '\l'; do >&2 echo "Postgres is unavailable - sleeping" sleep 1 done >&2 echo "Postgres is up - executing command" exec $cmd However my postgres image on docker has it's own Dockerfile, this is the postgresql Dockerfile: # # example Dockerfile for https://docs.docker.com/examples/postgresql_service/ # FROM ubuntu # Add the PostgreSQL PGP key to verify their Debian packages. # It should be the same key as https://www.postgresql.org/media/keys/ACCC4CF8.asc RUN apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys B97B0AFCAA1A47F044F244A07FCC7D46ACCC4CF8 # Add PostgreSQL's repository. It contains the most recent stable … -
Is there a way to handle multiple celery workers with the same task with atomic blocks?
I have this task def some_task(self, param): do_some_stuff_that_might_break_with_models() normally I could do this: def some_task(self, param): try: with transaction.atomic(): do_some_stuff_that_might_break_with_models() except: self.retry(....) But by doing so, it seems like if I have a couple workers performing this task it'll lock the db because of the atomic block. But if I get rid of it my try except will get angry. How could I handle this? I've tried preprocessing my input with unique hashes and then dispatching each chunk to its own worker and getting rid of the atomic and try blocks but by doing so I lost the ability to retry/track what tasks failed. I can still see what failed from the admin panel through djcelery, but not within the task itself. -
How to use optional parameters in Django Swagger Documentation?
Let's assume that we have for example such URL - localhost:8000/object?name=STH. Anyone have an idea how can I display object with name equals STH using Django Swagger Documentation? -
Ajax in django.. Normal submission of form, not entering ajax
I have been trying this thing since three days but I didn't get what exactly my error is.. What I want is, I want the user to select options from drop-downs and click submit to view the results in a table, yeah, without page refresh. As of now, the ajax is not being called and the form is getting submitted normally. Here is my JS and apply.html (JS included in the same file) < script src = "//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js" type = "text/javascript" > $(document).ready(function() { $("#filter").click(function() { $.ajax({ url: '/home/filter', type: 'GET', data: { mon: $('$mon').val(), year: $('$year').val(), place: $('place').val(), }, x = JSON.stringify(data), contentType: "application/json;charset=utf-8", success: function(x) { alert('YOHOO!'); console.log(data); }, error: function(x) { console.log(err); } }); }); }); < /script> {% extends "base.html" %} {% block content %} <div class="row"> <!-- <div class="col-md-4"> --> <div class="form-group"> <form action="{% url 'apply:filter' %}" method="GET" id="filter"> {% csrf_token %} <table> <tr> <td style="padding-right:30px;"> <select class="form-control" id="mon" name="mon"> <option value="1">Jan</option> ... <option value="12">Dec</option> </select> </td> <td style="padding-right:30px;"> <select class="form-control" id="year" name="year"> <option value="2017" selected="">2017</option> ... </select> </td> <td style="padding-right:30px;"> <select class="form-control" id="place" name="place"> <option value="India" selected>India</option> ... </select> </td> <button name="action" value="Apply Filter" class="col-lg-2" style="display: inline-block; float:right"> Apply Filter </button> </table> </form> </div> … -
CSRF Tag Still Rejecting Twilio Requests
I'm writing a simple view which takes in a Twilio SMS request and returns a simple SMS, based on this tutorial. For some reason, requests still are met with 403 Forbidden: Forbidden (CSRF cookie not set.): /haul/response [20/Jul/2017 17:39:42] "POST /haul/response HTTP/1.1" 403 2857` My view is as follows: from django.http import HttpResponse from twilio.rest import Client from django.views.decorators.csrf import csrf_exempt @csrf_exempt def response(request): twiml = '<Response><Message>Test</Message></Response>' return HttpResponse(twiml, content_type='text/xml') Anyone have any idea why this might be happening? -
Django - receiving multiple varities of json objects in the same post method
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import QandA from .serializers import QandASerializer import json import random from itertools import count class QandAlist(APIView): _ids = count(0) def __init__(self): self.id = next(self._ids) def get(self, request): questions = QandA.objects.all() serializer = QandASerializer(questions, many=True) return Response(serializer.data) def post(self, request): serializer = QandASerializer(data=request.data) lists = [] if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: try: n = json.loads(request.body) return Response(n) except: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: questions = QandA.objects.order_by('?')[:n] serializer = QandASerializer(questions, many=True) return Response(serializer.data) here i am trying to accept 2 kinds of json. one at a time one which updates the database with a QandA object other which looks like { "number" : 3 } this number must be extracted and 3 random QandA objects must be returned everything except for the "number" thing works. the try block always fails and i get exception saying i have missed all fields of QandA object -
How to write raw SQL queries without hardcoding database names for the Django ORM models and fields?
I need to use some raw SQL queries in my Django application, but I need to do it in a way that will still work even if the database table and field names change. For example, in one version the query might look like: INSERT INTO app_foo_a27e2da2 SELECT DISTINCT app_bar_id_309f86af AS app_foo_id_655d53fe, app_bar_name_729cb7a0 AS app_foo_name_ad439fec FROM app_bar_c7c976e7 WHERE app_bar_id_309f86af IS NOT NULL; (Note this is a dramatization, the real database isn't this bad.) Ideally, I'd like to be able to write something in a similar vein to this: INSERT INTO {{App.foo}} SELECT DISTINCT {{bar.id}} AS {{foo.id}}, {{bar.name}} AS {{foo.name}} FROM {{App.bar}} WHERE {{bar.id}} IS NOT NULL; and then have the actual field names automatically filled in. I could possibly roll my own with str.format or something, but this seems like the sort of thing that should already have a solution. How can I write raw SQL queries that don't require hardcoding the database table and field names for the models in question? -
Django - save() prohibited to prevent data loss due to unsaved related object - Formsets and CreateView
I'm developing a small web app for timesheet control using Django 1.10.5 and I've came across an error that I cannot find the solution. I've search Stackoverflow and Google up and down and, even though I can find similar problems, none uses my approach (or I cannot find one similar). I'm trying to extend the default User Model from django auth by creating a TUser Model with a One to One relation. I've created a forms.py with two Forms - UserForm and AccountForm and a AccountInlineFormSet. For adding the data to the database I've used a class based view approach, by creating a class AccountAddView(CreateView). Now, when saving, I keep getting save() prohibited to prevent data loss due to unsaved related object even though I first save the main form and then save the inline form. Here you can find the code: forms.py https://github.com/hgpestana/chronos/blob/master/apps/account/forms.py views.py https://github.com/hgpestana/chronos/blob/master/apps/account/views.py Any ideas on what the problem is? I'm a newbie on Django so I think it must be some stupid mistake, but I cannot figure it out. Thanks =) -
Add data to Django form before it is saved?
In this simplified use case, I have a Django form that contains MyField_1 and MyField_2. The user fills out MyField_1. Before the form is saved as a model, I want the computer to add MyField_2 programmatically which is some data pulled in from another data source. The view I currently have looks like this: class MyCreate(CreateView): model = MyModel fields = ['MyField_1'] How can I add the data to MyField_2 before the model is saved? -
How to factor out Django model fields into their own model, keeping data?
I have a Django ORM Model like this: class Foo(models.Model): data = models.CharField(null=True, blank=True) bar_id = models.IntegerField(null=True, blank=True) bar_data = models.CharField(null=True, blank=True) I want to factor out bar_id and bar_data into a separate model class: class Foo(models.Model): data = models.CharField(null=True, blank=True) bar = models.ForeignKey('Bar', null=True, blank=True) class Bar(models.Model): id = models.IntegerField(primary_key=True) data = models.CharField(null=True, blank=True) I already know for sure that each bar_id has only a single value for bar_data associated with it, and bar_data is always None if bar_id is None, so it should be possible to migrate the old bar_data field into the new Bar objects, I just don't know how to do it. Hoe can I migrate to these new models while keeping data?