Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get the email sent for VerifiedEmailField from verified_email_field.1.2.3
I want to get users that signup to verify their email addresses and from reading a previous thread on doing this, someone posted about django-verified-email-field which I have installed and followed the guidance for but am getting no email sent through. I have added verified_email_field to my settings.py in the INSTALLED_APPS. I added: url(r'^verified-email-field/', include('verified_email_field.urls')), to my urls.py I then used the field inside one of my forms: email = VerifiedEmailField(label='email', required=True) this gives no errors and renders the signup form correctly from my signup.html page, however the validation email is never sent to me. I tried the final step of adding the code: {% addtoblock "js" %} {{ form.media.js }} {% endaddtoblock %} to my html template but I get the error that the "js" block doesn't exist. I'm not sure (based on a couple of quick Google searches and dredging through the source code for the verified_email_field) whether this is part of django or part of the package. I'm also not certain if I'm doing the right thing by trying to solve this or whether I should be adding my own clean method to the form instead and then calling a function from there to send the validation … -
Enter A Valid Date issue with form - django
I notices this question came up a few times in stackoverflow but none of the answers I read worked in helping me with my situation... I have a form that is using the DatetimeField. I am submitting a proper time but it is saying that for some reason there is an error that is not validating the form before collecting the information and storing it. I want to grab the date and time that the user is submitting.. here is my code: form.py: class CreateEventForm(forms.ModelForm): alert_choices = (('1', '1 hour before'), ('2', '2 hour before'), ('3', '3 hour before'), ) start_date = forms.DateTimeField( label='Start', widget=forms.widgets.DateTimeInput(format="%d/%m/%Y %H:%M:%S", attrs={'type':'datetime-local'}), ) end_date = forms.DateTimeField( label='End', widget=forms.widgets.DateTimeInput(format="%d/%m/%Y %H:%M:%S", attrs={'type':'datetime-local'}) ) alert = forms.TypedChoiceField( choices = alert_choices, label = "Alert" ) class Meta: model = Event fields = ['name', 'start_date', 'end_date', 'location', 'notes'] Models.py class Event(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) calendar = models.ForeignKey(Calendar, on_delete=models.CASCADE) name = models.CharField(max_length=30, default='Event') start_date = models.DateTimeField(default=datetime.now) end_date = models.DateTimeField(default=datetime.now) email = models.CharField(max_length=40, default='example@example.com') location = models.CharField(max_length=40, default='location') notes = models.CharField(max_length=200, default='note') repeat = models.IntegerField() # 0 = no repeat # 1 = daily # 2 = weekly # monthly created = models.DateTimeField(auto_now_add=True) screenshot my settings file: LANGUAGE_CODE = 'en-us' TIME_ZONE … -
Jinja lookup key in for loop
I pass 2 groups of data from my view.py to my html file. But only one group of data is shown in the webpage. html: <h3>Database: A</h3> <table> <tr> <th>A</th> <th>Counts A-1</th> <th>Counts A-2</th> <th>Value</th> </tr> {% load lookup %} {% for i in Amatch %} <tr> <th> {{ Amatch|lookup:forloop.counter0 }} </th> <td> {{ Amatchtotal|lookup:forloop.counter0 }} </td> <td> {{ AmatchCount|lookup:forloop.counter0 }} </td> <td> {{ Avalue|lookup:forloop.counter0 }} </td> </tr> {% endfor %} </table> <h3>Database: B</h3> <table> <tr> <th>B</th> <th>Counts B-1</th> <th>Counts B-2</th> <th>Value</th> </tr> {% load lookup %} {% for i in matchAnno %} <tr> <th> {{ Bmatch|lookup:forloop.counter0 }} </th> <td> {{ Bmatchtotal|lookup:forloop.counter0 }} </td> <td> {{ BmatchCount|lookup:forloop.counter0 }} </td> <td> {{ Bvalue|lookup:forloop.counter0 }} </td> </tr> {% endfor %} </table> view.py return render(request, 'analysis/result.html', {'Amatch':Amatch, 'Amatchtotal':Amatchtotal, 'AmatchCount':AmatchCount, 'A_re':A_re, 'Avalue':Avalue, 'Bmatch':Bmatch, 'Bmatchtotal':Bmatchtotal, 'BmatchCount':BmatchCount, 'B_re':B_re, 'Bvalue':Bvalue,}) Two groups of data are supposed to be shown on the page as I expected. However, only the data from group B is shown on the page. I tried to switch the order of group A and group B, but still only group B is shown. I'm pretty sure data are passed successfully by checking them in terminal. Are there anything wrong with my code? -
Writing a for loop with an IntegerField rather than an int
I'm trying to create a for loop for creating a dynamic number of objects in Otree, which extends Django (I know, crazy idea, but bear with me). Unfortunately the latest version of otree will throw compile time errors if you attempt to use integers in your code. So for example, the following code: num_decs = 8 for d in range(1, num_decs + 1): locals()['dec_r'+str(r)+'_'+str(d)]= models.CharField(choices=[Constants.choice1_name, Constants.choice2_name],widget=widgets.RadioSelectHorizontal(),blank=False,initial='blank') Will throw the following error (as opposed to a warning, which occurred with previous versions of Otree): (otree.E111) NonModelFieldAttr: Player has attribute "d", which is not a model field, and will therefore not be saved to the database. I imagine that the best way to resolve this would be to declare d in the for loop as an IntegerField object and then cast it as an int using the int() method as follows: num_decs = models.IntegerField(initial=8) d = models.IntegerField(default=0) for d in range(1, num_decs.__int__() + 1): But I receive an error that IntegerField lacks a int() method. What should I do to cast an IntegerField as an int for a for loop? Thanks! -
passing template name into DJango view for rendering
I am working with a DJango View. It is being implemented as a function-based view. What I would like to do is to pass in a template into the function for rendering into an HTML document. In the example below, instead of hardcoding 'storeowner/mstrstorehead_form.html', I would like to pass in a template name for use. How can this be done? I saw the information here: How should template names be set dynamically using class based views? but it deals more with Class-Based-Views TIA views.py @login_required def edit_store_data(request): success = False message = 'No changes to report' message_color = 'green' username = request.user.username local_email = request.user.email local_pass = request.user.password [... snip ... ] return render(request, 'storeowner/mstrstorehead_form.html', {'form': master_store_head_form, 'success': `success, 'message': message, 'message_color': message_color})` -
Is it possible to create partitions on db tables with django==1.11 and postgresql?
Is it possible to create partitions on db tables with django==1.11 and postgresql? Thanks a lot! -
multiple input entry search in html
` Just a quick question. I was wondering whether any one could be of help. Any idea on how to search multiple text input either as strings with comma separation or nextline (inline search) example: search (SPEED1, SPEED2, SPEED3). and get results for all the SPEEDs` -
No module named rest_framework
i've seen a lot of people having trouble with this here, and i always see them saying other to use pip3 or just pip to install it. But in my case i've uninstalled it and installed id multiple times both using pip or pip3 and none of them seem to work. I've added 'rest_framework' to my settings as well and still doesn't seem to work. Help me out please -
How to Handle Error during Django CreateView
Using Django, I have a model and a class based view based on the provided CreateView class. Everything works fine - I can have a template that renders the form, validation occurs, the data is properly saved and the success_url redirected to on completion. The problem occurs in that I have a unique_together constraint on two of the fields. If this error is hit, it appears that form_valid() doesn't catch it, and an error page is produced instead. My goal is to be able to catch this ahead of time and return the user to the form - with the data filled in from their last attempt - and display a message to them. Feels like this should be simple, and I added code to form_valid() in the view to identify the problem, but I have no clue what to do next. A redirect doesn't work because I can't add the context in (or can I?) and I really don't want to put everything in the URL. Any ideas where to look? -
How to serialize a Django MPTT family and keep it hierarchical?
I was trying to find solution for this (Google cache) And I could only came up with a solution like this: import json from mptt.utils import tree_item_iterator from rest_framework import generics from rest_framework.response import Response from .models import Category def tree_family_items_to_json(instances): data = '' channel = '"{}"'.format(instances[0].channel.slug) for category, structure in tree_item_iterator(instances): if structure['new_level']: data += '{' else: data += '],' data += '"channel": {}'.format(channel) data += '},{' data += '"slug": "{}",'.format(category.slug) data += '"name": "{}",'.format(category.name) data += '"subcategories": [' for level in structure['closed_levels']: data += '],' data += '"channel": {}'.format(channel) data += '}' return json.loads(data) class CategoryFamily(generics.RetrieveAPIView): lookup_field = 'slug' queryset = Category.objects.all() def retrieve(self, request, *args, **kwargs): instances = self.get_object().get_family() json_data = tree_family_items_to_json(instances) return Response(json_data) The point is that I used tree_item_iterator from mptt and now I'm looking for something more fancy. It suited the need for a while. But now sure for how long. Any ideas? -
object.get_or_create works, but stops working when I use models.FileField(upload_to)
I designed a webpage for users to upload and extract data from a test file. But I'm trying to prevent them from uploading and extracting data if this file has previously been uploaded (a mistake that has happened several times in the past) I created a model for the file class TestFile(models.Model): file = models.FileField() test_object = models.ForeignKey(TestObject) I created a view for the users to upload def upload_data_file(request, pk): try: mytempfile = request.FILES['myfile'] created = process_data_file(mytempfile, pk) if created: return HttpResponseRedirect(reverse('myApp:object-detail', kwargs={"pk": pk})) else: return HttpResponse("This data has previously been uploaded" "You are not allowed to upload and match this data to a different test object")) except KeyError: return HttpResponseRedirect(reverse('myApp:object-detail', kwargs={"pk": pk})) And here is my function where I process the data (removed all the processing code because my trouble is in the get_or_create) def process_data_file(myfile, my_id): a, created = TestFile.objects.get_or_create(file=myfile) if created: analyze and extract a bunch of information from the data file a.save() return created This has been working just fine except that I didn't think ahead. All of my files are going into my /media/ directory. At first this was ok but now there are at least 100 files in there and it doesn't seem like … -
voice enabled auction system in django
I wanna do my project That consists of designing and implementing a voice enabled - auction system (AS) which offers its services to end-users who can offer items for auction and bid for items.The AS allows for the end-users to register. At registration time, end-users might select the option of being notified by voice when selected events happen (e.g. end-users registering /leaving, new items put on sale, items sold).my question is how could I enable voice notification on django? thank you for your help. -
django allauth registration link issue
django v1.11.17 django-allauth: 0.34.0 Person creates new account by filling his e-mail address and password, then receives an e-mail. In this e-mail the link is clicked. PROBLEM: A user with EDGE browser v40, clicking the link from outlook sees this error message appearing in the EDGE browser itself: /head>HTTP/1.1 301 Moved Permanently Server: openresty/1.9.15.1 Date: Mon, 11 Dec 2017 22:05:32 GMT Content-Type: text/html; charset=utf-8 Content-Length: 0 Connection: keep-alive x-xss-protection: 1; mode=block x-content-type-options: nosniff Content-Language: nl strict-transport-security: max-age=600; includeSubDomains Vary: Accept-Language Location: /swingit/ X-Frame-Options: SAMEORIGIN X-Clacks-Overhead: GNU Terry Pratchett Note the missing '<' in the head tag? Could this be a link to the problem? When he presses BACK button, he ends up on the site and can login. When I try the same with a mac (Mac Mail & Safari) or windows PC (gmail & EDGE 40) there is no issue... Seeing the SAMEORIGIN remark, I tried both django settings below, but both fail: X_FRAME_OPTIONS = 'ALLOW' X_FRAME_OPTIONS = 'SAMEORIGIN'` Security Settings: SECURE_SSL_REDIRECT = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = False X_FRAME_OPTIONS = 'SAMEORIGIN' SECURE_HSTS_SECONDS = 600 SECURE_HSTS_INCLUDE_SUBDOMAINS = True Thank you for your help! DJ -
Django objects.get not working
I'm having an trouble pulling data from my database. I'm trying to get it to display New York Yankees (or any American League team) in html from my database, using the get function. If one of you folks can point out why it may not be working, that would be greatly appreciated. Thank you. standings/models↓ from __future__ import unicode_literals from django.db import models class AlStandings(models.Model): team = models.CharField(db_column='TEAM', max_length=30, blank=True, null=True) w = models.IntegerField(db_column='W', blank=True, null=True) l = models.IntegerField(db_column='L', blank=True, null=True) pct = models.DecimalField(db_column='PCT', max_digits=4, decimal_places=3, blank=True, null=True gb = models.DecimalField(db_column='GB', max_digits=65535, decimal_places=65535, blank=True, null=True) rs = models.IntegerField(db_column='RS', blank=True, null=True) ra = models.IntegerField(db_column='RA', blank=True, null=True) diff = models.IntegerField(db_column='DIFF', blank=True, null=True) home = models.CharField(db_column='HOME', max_length=7, blank=True, null=True) road = models.CharField(db_column='ROAD', max_length=7, blank=True, null=True) east = models.CharField(db_column='EAST', max_length=7, blank=True, null=True) cent = models.CharField(db_column='CENT', max_length=7, blank=True, null=True) west = models.CharField(db_column='WEST', max_length=7, blank=True, null=True) l10 = models.CharField(db_column='L10', max_length=6, blank=True, null=True) strk = models.CharField(db_column='STRK', max_length=3, blank=True, null=True) standings/urls↓ from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), ] standings/views↓ from django.shortcuts import render from django.template.response import TemplateResponse from standings.models import AlStandings def index(request): data = AlStandings.objects.get('New York Yankees’) return TemplateResponse(request, 'standings/index.html', {"data": data}) standings/index.html↓ {% extends 'layout/layout.html' %} {% block content … -
displaying both date and time inputs from DateTImeField - Django
I have a django template and a form where I want the user to input a date and time into the right fields and save the date and time into the database. I also want to initialize a specific time when ever the form is created. I currently have the date time field in my model and form but I am not sure how to get it to display both the time and date. it is only showing the default date so far. Here is the code that I have right now. models: class Event(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) calendar = models.ForeignKey(Calender, on_delete=models.CASCADE) name = models.CharField(max_length=30, default='Event') start_date = models.DateTimeField(default='1950-01-01') end_date = models.DateTimeField(default='1950-01-01') email = models.CharField(max_length=40, default='example@example.com') location = models.CharField(max_length=40, default='location') notes = models.CharField(max_length=200, default='note') repeat = models.IntegerField() # 0 = no repeat # 1 = daily # 2 = weekly # monthly created = models.DateTimeField(auto_now_add=True) forms: class CreateEventForm(forms.ModelForm): start_date = forms.DateTimeField( label='Start', widget=forms.widgets.DateInput(attrs={'type':'date'}), ) end_date = forms.DateTimeField( label='End', widget=forms.widgets.DateInput(attrs={'type':'date'}) ) class Meta: model = Event fields = ['name', 'start_date', 'end_date', 'location', 'notes'] views: form = CreateCalenderForm() parameters = { 'form':form, } return render(request, 'calender/create_calender.html', parameters) here is what it looks like: -
Deploying django app with channels on Daphne - SSL
I am trying to deploy a simple django app to receive websocket messages (wss). I am using the following command: daphne -e ssl:443:privateKey=key.pem:certKey=cert.cer bms_project.asgi:channel_layer with the following included in the settings.py file: SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECRET_KEY = os.environ["SECRET_KEY_BMS"] and the following asgi.py file: import os from channels.asgi import get_channel_layer os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bms_project.settings") # secret key os.environ["SECRET_KEY_BMS"] = "some random self-signing key off the internet" channel_layer = get_channel_layer() the following error is given: File "c:\program files\python36\lib\site-packages\django\conf\__init__.py", line 129, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I feel like I am handling the key incorrectly, no idea what the correct method is. -
How to fill a field with pre-defined options in the admin page
I'm new to Django and to learn it I'm trying to create a news-like site, where the news-posts are written in the admin page. To achieve this I created a model called Post, and, among other things, I want it to store the post genre. Therefore I made a variable called genre which equals models.CharField() method. The problem with this approach is that in the admin page I have to write the post genre every time, when instead I'd like to choose the genre from a set of pre-defined genres. How can I achieve this functionality in the admin page? -
Authenticate client in Heroku/Django
I have a Django app running on Heroku and would like to authenticate clients with SSL certificates. Idea is to store CA on a server, which generates and signs client certificates. Certificate's "Subject" field contains, say, username: ➜ cli git:(master) ✗ openssl x509 -in client.crt -text -noout | grep Subject Subject: CN=lev When I send requests to server, I specify client certificate: def test_cn(): url = "/".join([HOST, "test_cn"]) print(requests.post(url, cert=("client.crt", "client.key")).text) Server verifies that client's certificate is indeed valid and fetches username from "Subject" field. The question is, what is needed to be done on Heroku/Gunicorn/Django side to make it work? -
accessing dict in django template
I have a django project writing to a PSQL database and I am figuring out how to check which queries are being done. Is there a way to check which queries actually make it to the database? I noticed some queries are cached and use no actual call to the database. (https://docs.djangoproject.com/en/1.11/topics/db/queries/#caching-and-querysets) Reason why I ask: I have a model JobId, which holds all jobs processed on my platform. Processing jobs uses credits. At the end of each job, I save the JobId.credit_detla (= amount credits used) and JobId.credits (= amount credits on account left). I want to show the JobId.credits in the navigation menu but don't want to pull queries on every visited page for this single value. So 2 questions: how could I figure out the quantity of queries? is there a better typical-one-liner-code practice to get this query result in my navigion menu? -
Passing JavaScript variable into Django url?
I have a dropdown menu that allows the user to select between three different use cases, and I want to pass that information to the next page. <option id='b2c-menu' value="Delivery">Delivery</option> <option id='taxi-menu' value="Air Taxi">Taxi</option> <option id='hub-menu' value="Hub-to-Hub">Metro</option> On select, I'm capturing this option as a variable in my JavaScript, and I'd like my second page to be aware of what the currently selected option is. To pass that, I'd like to do something like this: <a href="page2/{{ selected_option }}"</a> Is there a way to make my links dynamic based on my JS content? -
Python - Django - server - Searches for installed module in wrong version of Python using WinSCP
when I try to load my server using Django, I get a 'no module named bs4' error. It seems that it searching to for it in Python 2.7 library instead of Python3.6. python 3.6 is in my PATH. I tried looking, but I'm pretty new to this and don't quite understand all the jargon. Can someone 'explain like I'm 5' on how to make it so that it searches Python 3.6 instead of python 2.7? This is the error: ImportError at / No module named bs4 Request Method: GET Request URL: http://104.236.89.238/ Django Version: 1.8.7 Exception Type: ImportError Exception Value: No module named bs4 Exception Location: /usr/lib/python2.7/dist-packages/gevent/builtins.py in __import__, line 93 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/django/django_project', '/home/django/django_project', '/usr/bin', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] Server time: Mon, 11 Dec 2017 20:58:02 +0000 I'm using WinSCP to transfer the files. Everything works perfectly on a local host before I transfer the files and try and run it on a server. Here are some settings on WinSCP. First here is my manage.py #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_project.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) my settings.py in WinSCP is: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) … -
How can I avoid "database is locked" sqlite3 errors in django?
Django version 1.11, sqlite3 version 3.11. I'm using WAL mode and a long timeout: from django.apps import AppConfig from django.db.backends.signals import connection_created class SQLite3Config(AppConfig): name = 'sqlite3_config' def ready(self): connection_created.connect(configure_sqlite) # noinspection PyUnusedLocal def configure_sqlite(sender, connection, **_): if connection.vendor == 'sqlite': cursor = connection.cursor() cursor.execute('PRAGMA journal_mode=WAL;') cursor.execute('PRAGMA busy_timeout=5000;') I want to retain sqlite3 and not move to mysql or postgres because the application is small and is installed by users on multiple servers. I believe WAL should allow "concurrent" writes by serializing them. The "Database is locked" problem was observed when small bursts (half a dozen or so) were received together. I can reproduce the problem in the shell with threads. The django model method simply sets a flag and saves the model: def activate(self): self.activate = True self.save() When I use threads I find it fails if I launch a few threads that attempt it at the same time. There is no wait so the timeout is not involved. The error occurs before the 5 second busy timeout has elapsed (in less than two seconds): In [2]: [NGThread(notifier_group.id).start() for notifier_group in NotifierGroup.objects.all()[:2]] Out[2]: [None, None] In [3]: [NGThread(notifier_group.id).start() for notifier_group in NotifierGroup.objects.all()[:3]] Out[3]: [None, None, None] In [4]: [NGThread(notifier_group.id).start() … -
django cannot read css file in static folder
I am trying to make a base.html template and inserting a css file in the header. in the page it includes all the styling by it does not do any styling when the link the other page is pressed. I have two files extending base.html one color_choose.html the other statistics.html which have the exact same lines for linking files. color_choose.html works and it is the first page that opens when navigated and the other is statistics.html here is the base.html: <!DOCTYPE html> <html lang="eng"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> <title>ColorStore</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> {% block styles %} {%endblock%} </head> <body> <div id="ColorFavor"> <div style="float: right;"> <h2 id="title" class="page-name">Color Picker</h2> </div> </div> {% block navigation %} {% endblock %} {% block display %} {% endblock %} {% block modal %} {% endblock %} {% block scripts %} {% endblock %} </body> </html> here is the urls.py in the app file: from django.urls import path from . import views urlpatterns = [ path('', views.ColorPageView.as_view(), name='color'), path('statistics/',views.StatsPageView.as_view(), name='statistics'), this is the file css is applied and is also the same text in the other file: {% extends 'base.html' %} … -
complex nested data representation
I'm trying to get all Currency objects with the Ticker objects nested in each currency object. So far i've only been able to get the tickers with the currency object inside, but this is really not convenient? i'm not sure what changes i need to make to achieve below output so for instance what i want is something like this: [ { "id": 1, "name": "Dollar", "symbol": "USD" "ticker": [ { "id": 1, "rank": 1, "price_dkk": 123.25 } ] } ] models class Currency(models.Model): symbol = models.CharField(max_length=4, default='BTC', unique=True) name = models.CharField(max_length=20, default='Bitcoin', unique=True) img = models.ImageField(upload_to = 'static/img/currencies', blank=True) is_active = models.BooleanField(default=False) class Meta: verbose_name_plural = _('currencies') def __str__(self): return self.name class Ticker(models.Model): currency = models.ForeignKey('Currency', on_delete=models.CASCADE) rank = models.IntegerField() price_dkk = models.DecimalField(max_digits=20, decimal_places=6) market_cap_dkk = models.BigIntegerField() percent_change_1h = models.DecimalField(max_digits=4, decimal_places=2) percent_change_24h = models.DecimalField(max_digits=4, decimal_places=2) percent_change_7d = models.DecimalField(max_digits=4, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = _('Ticker') def __str__(self): return self.id serializer class CurrencyTickerSerializer(serializers.HyperlinkedModelSerializer): currency = serializers.PrimaryKeyRelatedField(many=False, queryset=Currency.objects.all()) class Meta: model = Ticker fields = ('currency', 'rank', 'price_dkk', 'market_cap_dkk', 'percent_change_1h', 'percent_change_24h', 'percent_change_7d',) -
Django OneToOneField relation with to_field and db_column been ignored on makemigrations files
Even after reading the docs on db_column and Django' recomendations I was not able to accomplish the desired results with this feature. This is part of my code class DefaultBaseModel(models.Model): slug = models.SlugField(primary_key=True, unique=True, null=False, blank=False) class Bill(DefaultBaseModel): class Payment(DefaultBaseModel): bill = models.OneToOneField(Bill, related_name='payments', on_delete=models.CASCADE, to_field='slug', db_column='bill_slug') What I expect to do is the following on Django's shell: from apps.bills.models import Bill b = Bill.objects.first() b.branch_slug However I get the error: Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'Bill' object has no attribute 'branch_slug' Well, b.branch_id gives me the slug value but it is still creating the column with the suffix _id. I tried to delete makemigrations (migrate) files (those initial.py and others) and create it again Moved from Sqlite to Postgres Looked into Django's makemigrations files and db_column='bill_slug' was there. Any ideas?