Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
makemigrations doesn't see changes after adding unique_together constraint
Using django version 1.11.2 final. I have the model below, for small invoices. I made several migrations along the way, and eventually added the unique_together = ('facture', 'article') constraint into the 'Line' model. However, when running ./manage.py makemigrations, no changes are detected. Also tried with unique_together = (('facture', 'article'),) syntax, but get the same result. from django.db import models from django.db.models import F, Sum from personnes.models import Person # Create your models here. class Facture(models.Model): date = models.DateField(auto_now=True) client = models.ForeignKey(Person, related_name="factures", on_delete= models.CASCADE) articles = models.ManyToManyField("Article", through="Line", related_name="factures") @property def total(self): return self.lines.aggregate(total=Sum(F('count')*F('article__price'))) def __str__(self): return "%s %s %s" % (self.id, self.date, self.client.first_name) class Article(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return "%s %s" % (self.name, self.price) class Line(models.Model): facture = models.ForeignKey(Facture, related_name="lines", on_delete=models.CASCADE) article = models.ForeignKey(Article, related_name="lines", on_delete=models.CASCADE) count = models.IntegerField(default=1) @property def amount(self): return self.count * self.article.price def __str__(self): return "facture %s - %s x %s %s" % (self.facture.id, self.count, self.article.name, self.article.price) class META: unique_together = ('facture', 'article') -
Apply filter to result of Django custom template tag (like i18n trans)
We have a Django project with a legacy translation module that stores translations in the database, and does not use Django i18n (gettext). We have written custom template tags {% db_trans ... %} that work like Django's default {% trans ... %}, but there is one trick we cannot duplicate. In this example, "tree" (English) translates to "boom" (Dutch). In my Django template, if I use default i18n and write {% trans "tree" %} I will see the result boom. When I want to use this as a title, I use the capfirst filter like this {% trans "tree"|capfirst %}, and the result will be Boom. Note the capital B. This seems to be a special trick. Our db_trans custom tag (based on simple_tag) capitalizes the input before translation. Since there is no translation in the database for Tree, {% db_trans "tree"|capfirst %} renders its default (untranslated) value, Tree. I now about {% filter capfirst %}...{% endfilter %} and will probably use it if we cannot find an easy solution. I have checked the Django source code and I saw that {% trans ... %} is not based on simple_tag and does quite a lot of text argument parsing. My … -
Install pip3 package using ansible instead of pip2
I am trying to setup a Django project in vagrant using ansible. I have used the following code for installing the pip packages: - name: Setup Virtualenv pip: virtualenv={{ virtualenv_path }} virtualenv_python=python3 requirements={{ virtualenv_path }}/requirements.txt I need to use python3 for the django project and even though I have explicitly mentioned to use python3, it is installing the pip packages via pip2. Please, help me install the packages via pip3. -
django auto generated form-fields
Hello everyone and thank you in advance for any help. What I want to do is some of the fields in my form to be automatically added according to the previous value. Let me show you my example: my model class Measurement(models.Model): group = models.CharField(max_length=250) subgroup = models.CharField(max_length=250) number=models.PositiveIntegerField(default=1) voltage= models.PositiveIntegerField() comment = models.TextField(default='no comment') created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.group forms.py class MeasurementForm(forms.ModelForm): class Meta: model = Measurement fields = ['group','subgroup','number','voltage','comment'] my views.py def measurement(request): if request.method == "POST": form = MeasurementForm(request.POST, request.FILES) if form.is_valid(): measurement = form.save(commit=False) measurement.save() return redirect('data:measurement') else: form = MeasurementForm() context = {'form': form,} template = 'data/measurement.html' return render(request, template, context) html.file <div class="panel panel-primary"> <div class="panel-heading"> <h4>Add a measurement</h4> </div> <div class="panel-body"> <form method='POST' enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <button type = 'submit' class="btn btn-success">Save</button> </form> </div> </div> What I would like to have though is the fields group, subgroup and number to be automatically generated according to what I entered before. For example, first measurement I enter: Group:House Subgroup:Light Number:1 Voltage: 10 Comment: No comment Once I click save I want the fields Group, Subgroup and Number to have the following information already: Group:House Subgroup:Light Number:2 Voltage: 12 Comment: … -
ImportError at /: cannot import urls [on hold]
i surely saw previous questions like this, but none of them helped for me. I'm working on a project: but today the urls package won't import. These are my files: urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('burnersite.urls')), ] appname/urls.py from django.conf.urls import url from . import views urlpatterns=[ url(r'^$', views.index, name='index'), url(r'^image/(?P<id>[0-9]+)$', views.image_detail, name='image-detail'), url(r'^country/(?P<country>[^/?]+)$', views.country, name='country'), url(r'^country/(?P<country>[^/?]+)/city/(?P<city>[^/?]+)$', views.city, name='city'), url(r'^category/(?P<category>[^/?]+)$', views.category, name='category'), url(r'^artist/(?P<artist>[^/?]+)$', views.artist, name='artist'), url(r'^tag/(?P<tag>[^/?]+)$', views.tag, name='tag'), url(r'^search$', views.search, name='search'), ] The error says it came from the first file, the second url-line. I'm curious to know more about this error. Cheers EDIT I'm using virtualenv too. Traceback from shell $ import burnersite.settings Traceback (most recent call last): File "", line 1, in ImportError: No module named settings Traceback from browser: ImportError at / No module named urls.base /usr/lib/python2.7/importlib/init.py in import_module __import__(name) ... ▶ Local vars /home/toby/burnersite/burners/urls.py in url(r'^/$', include('burnersite.urls')), ... ▶ Local vars /usr/lib/python2.7/dist-packages/django/conf/urls/init.py in include urlconf_module = import_module(urlconf_module) ... ▶ Local vars /usr/lib/python2.7/importlib/init.py in import_module __import__(name) ... ▶ Local vars /home/toby/burnersite/burnersite/urls.py in from . import views ... ▶ Local vars /home/toby/burnersite/burnersite/views.py in from django.urls.base import reverse -
Create a dynamic form from a list of attributes (Fields) in Django
I have a model Category which has above 4000 Categories stored in the database. One field is called attributes which is a JSONField and its content is a list of objects that details what Fields should the Product model have. For example a Computer has [Processor Speed, RAM Size] While a Camera would have [Lens Size, Sensor Size]. The list of the attributes are more comprehensive than that. to give you an example. it looks something like this [ { "name": "Processor Speed", "isMandatory": "1", "InputType": "Text" }, { "name": "RAM Size", "isMandatory": "0", "InputType": "Integer" }] the whole 4000+ Categories with each having its own set of attributes needs Forms. And i figured that i can create a form by passing the attributes as a list to the init function and then assign each to its name while required can be extracted as well. even the input type. Now. is there any better way or a simpler way to accomplish this without having to modify the init ? -
Unicode errror from Haystack indexing
I've got a Django system with haystack & elasticsearch powered search. More specifically I'm using django-cms and aldryn search to integrate search with the CMS. aldryn-search==0.3.0 Django==1.10.7 django-cms==3.4.3 django-haystack==2.6.0 elasticsearch==2.4.1 requests==2.13.0 requests-aws4auth==0.9 The whole process for indexing haystack is controlled by third party apps, but I've never experienced this before so hopefully can find a fix. When running update_index for haystack there's some unicode issues; File "/Users/mwalker/Sites/myproj/lib/python2.7/site-packages/elasticsearch/client/__init__.py", line 785, in bulk doc_type, '_bulk'), params=params, body=self._bulk_body(body)) File "/Users/mwalker/Sites/myproj/lib/python2.7/site-packages/elasticsearch/transport.py", line 327, in perform_request status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout) File "/Users/mwalker/Sites/myproj/lib/python2.7/site-packages/elasticsearch/connection/http_requests.py", line 68, in perform_request response = self.session.request(method, url, data=body, timeout=timeout or self.timeout) File "/Users/mwalker/Sites/myproj/lib/python2.7/site-packages/requests/sessions.py", line 488, in request resp = self.send(prep, **send_kwargs) File "/Users/mwalker/Sites/myproj/lib/python2.7/site-packages/requests/sessions.py", line 609, in send r = adapter.send(request, **kwargs) File "/Users/mwalker/Sites/myproj/lib/python2.7/site-packages/requests/adapters.py", line 423, in send timeout=timeout File "/Users/mwalker/Sites/myproj/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 601, in urlopen chunked=chunked) File "/Users/mwalker/Sites/myproj/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 356, in _make_request conn.request(method, url, **httplib_request_kw) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1053, in request self._send_request(method, url, body, headers) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1093, in _send_request self.endheaders(body) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1049, in endheaders self._send_output(message_body) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 891, in _send_output msg += message_body UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1815: ordinal not in range(128) Haystack settings; awsauth = AWS4Auth(TBH_AWS_ACCESS_KEY, … -
how to increase speed creating test database in djnago testing
enter image description here **It is taking too time to create test database ** -
Choosing between Springboot and Django
I'm a current graduate school student about enroll in Thesis Writing subject after a month. A requirement in our thesis is to develop a system. My plan is to develop a web site or a web app. I've picked up Java during my undergrad studies and had been teaching myself Spring Boot and some Spring features (Basic things, I think) a few months now. I've been able to read so many article regarding the Spring in particular and how It's not a popular choice for small projects. I've recently picked up Python, about five month ago, because of a class in school, and been doing research about Django, but I haven't tried it yet. I need to make a decision on what to focus more on. I'm graduating soon and will pursue a career in Software development and also I need to use a web framework where in I can finish thesis, learn and will also be an asset moving forward. Thanks for the answers. -
How can I use django mezzanine?
I am planning to build using Django a website where users can ask to be interviewed and I post it in the website, I looked over the internet, and I saw that Mezzanine might be a good framework because my website will be like a blog. However I may add new features that are not related to a blog. So my question is should I create a new django project and add mezzanine as an app or create directly a mezzanine project ? Or is there another solution ? Thank you -
django: regular expression does not match url
The app name is notes In urls.py: url(r'^(?P<note_type>[a-zA_Z ]+)/(?P<sub_category>[a-zA_Z ]+)/$', views.NotesSubView, name = "notes-sub-view") The url is http://127.0.0.1:8000/notes/python/General%20Python The error message is Using the URLconf defined in notes_system.urls, Django tried these URL patterns, in this order: ^admin/ ^notes/ ^$ [name='index'] ^notes/ ^(?P<pk>[0-9]+)/$ [name='detail'] ^notes/ add/$ [name='notes-add'] ^notes/ ^(?P<notes_id>[0-9]+)/delete_notes/$ [name='notes-delete'] ^notes/ ^(?P<pk>[0-9]+)/modify_notes/$ [name='notes-modify'] ^notes/ ^(?P<note_type>[a-zA_Z ]+)/$ [name='notes-view'] ^notes/ ^(?P<note_type>[a-zA_Z ]+)/(?P<sub_category>[a-zA_Z ]+)/$ [name='notes-sub-view'] ^static\/(?P<path>.*)$ ^media\/(?P<path>.*)$ The current path, notes/python/General Python, didn't match any of these. I also tried http://127.0.0.1:8000/notes/python/general%20python/, this one works well. -
Verify submitted Django form in view
I have a view, which expects a POST request. The post request should contain data submitted through a Django form. The Django form looks something like this: class SubmitForm(forms.Form): title = forms.CharField(max_length=100) comment = forms.CharField(max_length=255) I know I have access to the submitted data with request.POST["title"] and request.POST["comment"]. So I can theoretically check if they're set and valid manually. But is there a way to use .is_valid() (Link to Django documentation), to validate the submitted form? One possibility would be to create a form in the view, fill it with the submitted data and then check it for validity. data = {'title': request.POST["title"], 'comment': request.POST["comment"]} f = SubmitForm(data) f.is_valid() # True/False Is there a direct way to use is_valid() on a submitted Django form? -
Django Create and Save Many instances of model when another object are created
I am designing a game of chess and I would like to initialize the fields with chess figures (State model) after the start of a new ChessParty (save method). I read about ovveriding save model method, but i don't know how to use in my case. And I am reading about signals like post_save, but is the same problem. Something like this? def save(self, *args, **kwargs): (Here i want create many instances of another Model) super(ChessParty, self).save(*args, **kwargs) And here my code: class ChessParty(models.Model): chessparty_id = models.AutoField("ID partii", primary_key=True) arbiter = models.ForeignKey(Arbiter, related_name='sedzia', verbose_name="Sędzia") white = models.ForeignKey(Player, related_name='Białe', verbose_name="Białe figury") black = models.ForeignKey(Player, related_name='Czarne', verbose_name="Czarne figury") tournament = models.ForeignKey(Tournament, verbose_name="Nazwa turnieju") def __str__(self): return "{white} vs {black}, ({tournament})"\ .format(black=self.black, white=self.white, tournament=self.tournament) class OneMove(models.Model): party = models.ForeignKey(ChessParty, default='0', verbose_name="Partia") chessman = ( ('a1_w_rook', 'biała wieża a1'), ('h1_w_rook', 'biała wieża h1'), ('b1_w_knight', 'biały skoczek b1'), ('g1_w_knight', 'biały skoczek g1'), ('c1_w_bishop', 'biały goniec c1'), ('f1_w_bishop', 'biały goniec f1'), ('d1_w_queen', 'biały hetman d1'), ('e1_w_king', 'biały król e1'), ('a2_w_pawn', 'biały pion a2'), ('b2_w_pawn', 'biały pion b2'), ('c2_w_pawn', 'biały pion c2'), ('d2_w_pawn', 'biały pion d2'), ('e2_w_pawn', 'biały pion e2'), ('f2_w_pawn', 'biały pion f2'), ('g2_w_pawn', 'biały pion g2'), ('h2_w_pawn', 'biały pion h2'), ('a8_b_rook', 'czarna wieża a1'), ('h8_b_rook', … -
Django Haystack - MissingDependency
I have checked these posts without success: Can't get Elasticsearch working with Django Error: The 'elasticsearch' backend requires the installation of 'requests'. How do I fix it? haystack.exceptions.MissingDependency: The 'elasticsearch' backend requires the installation of 'elasticsearch' my requirements.txt appdirs==1.4.3 bcrypt==3.1.3 certifi==2017.4.17 cffi==1.10.0 chardet==3.0.4 construct==2.5.3 dj-database-url==0.4.2 Django==1.10.7 django-cors-headers==2.0.2 django-debug-toolbar==1.8 django-field-history==0.6.0 django-haystack==2.6.1 django-pandas==0.4.1 djangorestframework==3.6.2 drf-haystack==1.6.1 elasticsearch==2.4.1 future==0.16.0 gunicorn==19.7.1 idna==2.5 numpy==1.12.1 olefile==0.44 packaging==16.8 pandas==0.20.1 pefile==2016.3.28 Pillow==4.1.1 psycopg2==2.7.1 pycparser==2.17 pyparsing==2.2.0 python-dateutil==2.6.0 python-ptrace==0.9.2 pytz==2017.2 requests==2.17.3 simplejson==3.10.0 six==1.10.0 sqlparse==0.2.3 urllib3==1.21.1 whitenoise==3.3.0 my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #===external apps=== 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'field_history', 'elasticsearch', 'haystack', 'debug_toolbar', ] HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch2_backend.Elasticsearch2SearchEngine', 'URL': 'http://192.168.99.100:3276/', 'INDEX_NAME': 'crm', }, } When trying to run python manage.py rebuild_index I get the following error: File "C:\Users\kazi_\Documents\GitHub\esar_drf\venv\lib\site-packages\haystack\backends\elasticsearch2_backend.py", line 9, in <module> from haystack.backends.elasticsearch_backend import ElasticsearchSearchBackend, ElasticsearchSearchQuery File "C:\Users\kazi_\Documents\GitHub\esar_drf\venv\lib\site-packages\haystack\backends\elasticsearch_backend.py", line 33, in <module> raise MissingDependency("The 'elasticsearch' backend requires the installation of 'elasticsearch'. Please refer to the documentation.") haystack.exceptions.MissingDependency: The 'elasticsearch' backend requires the installation of 'elasticsearch'. Please refer to the documentation. -
python - django-tenant-schemas static files on nginx
How to serve static files on nginx in DEBUG = False mode while using django-tenant-schemas? I'm getting 404 on css/js files from static files. -
Using html input tag for iterating over Django fields
I want to iterate over fields list in Django so as to create a generalized template for major of my forms. The problem I face is that my form is not considered as valid when I'm using the input fields. I want to stick to input fields as I'm using materialize css . Below is my form_template.html <div class="row "> {% for field in form %} <div class="form-group"> {% ifequal field.name "password" %} <div class="row"> <div class="input-field col s3 xl12"> <input id="{{ field.name }}" type="password" class="{{ field.name }}"> <label for="{{ field.name }}">{{ field.label }}</label> </div> </div> {% endifequal %} {% ifnotequal field.name "password" %} {% ifequal field.name "email" %} <div class="row"> <div class="input-field col s3 xl12"> <input id="{{ field.name }}" type="{{ field.name }}" class="validate">{{ form.field }} <label for="{{ field.name }}" data-error="Not a valid email" data-success="Valid Email">{{ field.label }}</label> </div> </div> {% endifequal %} <br> {% ifnotequal field.name "email" %} {% ifequal field.name "album_logo" %} <div class="file-field input-field col s3 xl12"> <div class="btn"> <span>File</span> <input type="file" multiple> </div> <div class="file-path-wrapper"> <input class="file-path validate" type="text" placeholder="Upload an album cover"> </div> {% endifequal %} {% ifnotequal field.name "album_logo" %} {% ifequal field.name "date_joined" %} <div class="row"> <div class="input-field col s3 xl12"> <input id="{{ … -
Access data from running python script and django app
I hava a python script wich receives and sends data from a Bluetooth device. The script runs on several threads in an infinite loop. However I want to access this Bluetooth data from a django application which runs on an apache server. What is the best way to send and receive data between this two components? I don't want to write all data in a database because the Bluetooth data will be refreshed every second. Is it possible to access the variables in the main script from the django app? -
How to decrypt django hashed sha256 password?
How to decrypt django hashed sha256 password? I have a encrypted password-'pbkdf2_sha256$12000$laEnG5drNrAt$mFMVBvQh8YF+vriNXbe/Nb8eYEySWwPT5+oSaMPvUiA='. Its equivalent to 'admin'. Now I need to decrypt the password. Means I wanted 'admin' as output. Is this possible? -
Django changes filename while saving ImageField
I have a django model with a field: ImageField When i am saving data in it, its saving successfully. But it changes its name. Code i am using to save from django.core.files.base import ContentFile def save_file(request): mymodel = MyModel.objects.get(id=1) file_content = ContentFile(request.FILES['video'].read()) mymodel.video.save(request.FILES['video'].name, file_content) Now whatever name is in request.FILES['video'].name (a random 36 character uid) django just changes its last some character while saving. I am using django 1.9 and python 2.7 -
How to serialize data not coming from the request and properly validate it (ModelSerializer in Django Rest Framework)?
Using Django Rest Framework 3, Function Based Views, and the ModelSerializer (more specifically the HyperlinkedModelSerializer). When a user submits a form from the client, I have a view that takes the request data, uses it to call to an external API, then uses the data from the external API to populate data for a model serializer. I believe I have this part working properly, and from what I read, you are supposed to use context and validate() In my model serializer, I have so far just this one overidden function: from django.core.validators import URLValidator def validate(self, data): if 'foo_url' in self.context: data['foo_url'] = self.context['foo_url'] URLValidator(data['foo_url']) if 'bar_url' in self.context: data['bar_url'] = self.context['bar_url'] URLValidator(data['bar_url']) return super(SomeSerializer, self).validate(data) Just in case, the relevant view code is like so: context = {'request': request} ... context['foo_url'] = foo_url context['bar_url'] = bar_url s = SomeSerializer(data=request.data, context=context) if s.is_valid(): s.save(user=request.user) return Response(s.data, status=status.HTTP_201_CREATED) Now assuming I have the right idea going (my model does populate its foo_url and bar_url fields from the corresponding context data), where I get confused is how the validation is not working. If I give it bad data, the model serializer does not reject it. I assumed that in validate(), by adding … -
Open new window with options, then set choice in original window with Django
I have a Django application, where I offer, let's say a recipe finder. The website offers the users to select a number of ingredients and according to the choices, a matching recipe is displayed. A list of recipes is displayed on the site and a button, which should open a new window, allowing the users to define the desired ingredients. After choosing the ingredients on the new window, the choice is confirmed with the click of a button. To have an example the new window displays the following. The user can click on the images (e.g. Pineapple and Chicken Breast) and then confirm. The original window receives the chosen string (e.g. Pineapple and Chicken Breast) and for sake of simplicity, simply shows the chosen string in a text box. Question Now, the question is how I can open a new window from a Django site, which, upon confirmation, allows the original window to represent the choices made by the user. The question is not about how I could code the image/text choice window itself. The example above is just an illustration of my web app and may not reflect the optimal UX/UI choice for it. But it is as close … -
Unable to django start server after commited some migration files to smartgit
(kemgo-api-v2) ronnie@vax-PC-88:/var/www/html/kemgo-api-v2$ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function wrapper at 0x7f22b50abcf8> Traceback (most recent call last): File "/home/mohit/.virtualenvs/kemgo-api-v2/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 222, in wrapper fn(*args, **kwargs) File "/home/mohit/.virtualenvs/kemgo-api-v2/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 107, in inner_run self.check_migrations() File "/home/mohit/.virtualenvs/kemgo-api-v2/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 159, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/mohit/.virtualenvs/kemgo-api-v2/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 17, in __init__ self.loader = MigrationLoader(self.connection) File "/home/mohit/.virtualenvs/kemgo-api-v2/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 48, in __init__ self.build_graph() File "/home/mohit/.virtualenvs/kemgo-api-v2/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 241, in build_graph self.graph.add_dependency(migration, key, parent) File "/home/mohit/.virtualenvs/kemgo-api-v2/local/lib/python2.7/site-packages/django/db/migrations/graph.py", line 42, in add_dependency raise KeyError("Migration %s dependencies references nonexistent parent node %r" % (migration, parent)) KeyError: u"Migration storefront.0002_storeview dependencies references nonexistent parent node (u'km', u'0010_auto_20170327_0841')" -
Django downloading a csv file with variable in name
I am trying to write some code to allow a user to download a .csv file with the results bases on their search when they press a download button. I would like to include the date in the default name of the csv file but can't get it to work. The relevant code in views.py is: now = datetime.datetime.now() date = str(now.year)+'-'+str(now.month)+'-'+str(now.day) response = HttpResponse(content_type='csv') response['Content-Disposition'] = 'attachment; filename="results"+str(date)+".csv"' This returns a default filename 'results_+str(date)+_.csv'. -
Django missing fields after initial makemigration
When I run python manage.py makemigrations myapp and check the 0001_initial.py file in my migrations folder, I expected to see every field in my models, however what I see is below: from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Data', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('original_file', models.TextField(max_length=255)), ], options={ 'managed': False, 'db_table': 'acoustic_data', }, ), migrations.CreateModel( name='Sites', fields=[ ('site_name', models.TextField(primary_key=True, serialize=False)), ], options={ 'managed': False, 'db_table': 'site', }, ), ] you can see that the Data model only has 'original_file' field while I was expecting also 'data_id', 'site_id', 'date_recorded', 'time_recorded' and 'average'. For the Site model 'site_id' is also missing. I am wondering why only the last field shows up? Below is my models.py: from django.db import models # Create your models here. class Sites(models.Model): #subfamily_id = models.IntegerField(primary_key=True, db_column='subfamily_id') site_id = models.TextField(primary_key=True) site_name = models.TextField(primary_key=True) class Meta: managed = False # this means Django should never alter this table db_table = 'site' class Data(models.Model): #subfamily_id = models.IntegerField(primary_key=True, db_column='subfamily_id') data_id = models.IntegerField(primary_key=True) site_id = models.ForeignKey(Sites, db_column='site_id', to_field='site_id') date_recorded = models.DateField('%Y-%m-%d') time_recorded = models.TimeField('%H:%M:%S') average = models.FloatField(null=True, blank=True, default=None) original_file = models.TextField(max_length=255) class Meta: managed = False # this means Django … -
Difference between TestCase and TransactionTestCase classes in django test
Can you please anyone explain the difference between TestCase class and TransactionTestCase class. I have read the document but its only saying that TestCase run test in DB transaction and uses rollback to 'undo' the test in the DB and If you need to manually manage transactions within your test, you would need to use django.test.TransactionTestCase. Will you please help me to understand the actual difference with an example? I just want to know in what condition the TestCase fails? also whether the rollback are taken place automatically or we have to write statement for rollback? Please help me