Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way to implement django model that need several layers of relation
I am building a quiz application using Django and can’t figure out the best way of building the models in regard to question category. A question will be related to one domain, for example it could be IT, Aviation or Science etc. This will be unique field. A topic will relate to a domain, for example meteorology could be part of the Aviation domain but could also be part of Science domain. For this reason this can’t be a unique field. A sub-topic will directly relate to a topic (and consequently a domain), for example climate or atmosphere would be part of Aviation->Meteorology Here are some example of combination of categories Aviation->Meteorology->Climate Aviation->Meteorology->Atmosphere Aviation->Mass and Balance The sub-topic is optional but all combination must be unique i.e. I can’t have two “Aviation->Meteorology->Climate” or two “Aviation->Mass and Balance” I am not sure how to implement this in the models but was thinking of doing one of the two solutions below 1) class Question(models.Model): question_text = models.TextField('What is the question?', max_length=4000) question_category = models.ForeignKey(Category) question_type = models.CharField('Question Type', max_length=50) question_comment = models.TextField(('Question Comments/Explanations', max_length=4000) question_created = models.DateTimeField(auto_now_add=True) class Category(models.Model): domain = models.CharField(max_length=255, unique=True) topic = models.CharField(max_length=255) sub_topic = models.CharField(max_length=255) 2) class Question(models.Model): … -
Using Django's ImageFile and/or plain Pillow... how can I get the image size in inches?
This means: Images formats like PNG or JPEG have size metadata somewhere that allow to tell how many pixels per inch the image has. Right now I can only tell the pixel size of an image (my_model_instance.my_image_field.width and height). What I'd like to know actually comes in two parts: Validate that the uploaded image file supports pixels-per-inches somehow in its metadata, header, ... Be able to obtain such values and calculate something like iwidth = width / pixels_per_inch. -
Django unable to install Channels (websockets) with pip
pip install channels, in python 3.6.2, django 1.11.6 Failed building wheel for twisted Then a lot of random status updates about copying/creating etc.. Then: Command ""c:\program files\python36\python.exe" -u -c "import setuptools,tokenize;__file__='C:\\Users\\Phil\\AppData\\Local\\Temp\\pip-build-vrw7n8yu\\twisted\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Phil\AppData\Local\Temp\pip-ybcrap_c-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\Phil\AppData\Local\Temp\pip-build-vrw7n8yu\twisted\ My best attempt at implementing websockets into a django server, not going well! -
Authentication using Django’s sessions db from Apache
I have a Django application which I now want to integrate it with Kibana. So when authenticated users click on a link, they will be directed to Kibana. But this option should not be available to anonymous users. My stack is Psql + Django + mod_wsgi + Apache. The solution I came up with was restricting access to Kibana via Apache, and authenticating users in Django before giving them access. This HowTo in Django website says how you can authenticate against Django from Apache, but that one uses Basic authentication. When I use this approach, even for users who already have an active session in my Django app, they will be asked to enter their username/password in a browser dialog! I was hoping the authentication to happen using the current Django active sessions. I believe for that I need to use AuthType form and mod_session, instead of AuthType Basic, but it seems mod_wsgi has no plan to support mod_session (as discussed here). I checked other WSGI alternatives as well (gunicorn and uWSGI), but couldn't find anything. So my question is how I can Authenticate against Django session db? Is using mod_session + AuthType form correct? and if yes, what's the … -
In a Django admin, add an inline of a generic relation
Here are my simplified models : from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation) from django.db import models from django.utils.translation import ugettext_lazy as _ class Thing(models.Model): ''' Our 'Thing' class with a link (generic relationship) to an abstract config ''' name = models.CharField( max_length=128, blank=True, verbose_name=_(u'Name of my thing')) # Link to our configs config_content_type = models.ForeignKey( ContentType, null=True, blank=True) config_object_id = models.PositiveIntegerField( null=True, blank=True) config_object = GenericForeignKey( 'config_content_type', 'config_object_id') class Config(models.Model): ''' Base class for custom Configs ''' class Meta: abstract = True name = models.CharField( max_length=128, blank=True, verbose_name=_(u'Config Name')) thing = GenericRelation( Thing, related_query_name='config') class FirstConfig(Config): pass class SecondConfig(Config): pass And Here's the admin: from django.contrib import admin from .models import FirstConfig, SecondConfig, Thing class FirstConfigInline(admin.StackedInline): model = FirstConfig class SecondConfigInline(admin.StackedInline): model = SecondConfig class ThingAdmin(admin.ModelAdmin): model = Thing def get_inline_instances(self, request, obj=None): ''' Returns our Thing Config inline ''' if obj is not None: m_name = obj.config_object._meta.model_name if m_name == "firstconfig": return [FirstConfigInline(self.model, self.admin_site), ] elif m_name == "secondconfig": return [SecondConfigInline(self.model, self.admin_site), ] return [] admin.site.register(Thing, ThingAdmin) So far, I've a Thing object with a FirstConfig object linked together. The code is simplified: in an unrelevant part I manage to create my abstract Config at a Thing creation and … -
django python manage.py createsuperuser: AttributeError: module 'os' has no attribute 'PathLike'
so I'm trying a django tutorial. for some reason my existing superuser got deleted. creating that went fine. but I can't make another one. this also happens when I try to use pip. didn't change anything in the libraries so not sure why this happens now but didn't before. on windows 7 btw(python 3.6.3 django 1.11). I've seen similar but not the exact same problems for windows. still I checked the file and there seems to be a PathLike class. I've also tried to repair my python installation but it didn't help. any ideas? god bless -
How To Implement A SAAS App In Django Without Using Subdomains
This article makes a good argument for avoiding subdomains in a SAAS app. All of the SAAS solutions I've found for Django so far all use subdomains. Is there a reliable way to implement a multi-tenant app in Django that doesn't use subdomains? -
difficulty with bootstrap container - django-bootstrap3
I have the following template schema: layout.html is my base template And I have another templates which inherit from layout.html I am using third party package application django-bootstrap3 My layout.html is: (The divs amount of navbar and django variables templates does not matter - are just for demonstration) {% load staticfiles %} {% load bootstrap3 %} {% bootstrap_css %} {% bootstrap_javascript %} <html lang="es"> {% block head %} <head> <title>{% block title_tag %}My APP{% endblock %}</title> <link rel="stylesheet" href="{% static 'css/main.css' %}"> </head> {% endblock %} <body> <div class="wrapper"> <!-- Nav menu --> <header> {% if request.user.is_authenticated %} {% if userprofile %} <div class="profile-options"> {% comment %} Begin settings drowdown {% endcomment %} <div class="name-options-cont"> <div class="name"> <p>{{ userprofile.user.email }} - {{ userprofile.user.enterprise_name }}</p> </div> <div class="options"> <div class="drop-down"> <ul> <li><a href="{% url 'some-url' %}" >Some option</a></li> <li><a href="{% url 'some-url2' %}" >Some option2</a></li> <li><a href="{% url 'accounts:logout' %}">Exit</a></li> </ul> </div> </div> </div> </div> {% endif %} {% else %} <div class="registration"> <a href="{% url 'accounts:signup' %}">Registrarse</a><a href="{% url 'login' %}">Iniciar sesión</a> </div> {% endif %} </header> <div class="container"> {% if messages %} {% for message in messages %} <div class='alert {% if "success" in message.tags %}alert-success{% elif "warning" in … -
Django : cannot retrieve numbers of objects
I am working on a project in django 1.11.0, and I have this model called Album, every user can add albums. Well I wanted to show numbers of authentificated user, but nothing !! Here's the view : @login_required() def user_account(request): user = request.user user_albums = Album.objects.filter(user=request.user) nb_albums = 0 for i in user_albums: nb_albums = nb_albums + 1 context = { 'nb_albums': nb_albums } return render(request, 'music/user_account.html', {'user': user}, context) and here is the bit code in the page html : <td>{{ request.user }}</td> <td>{{ request.user.first_name }}</td> <td>{{ request.user.last_name }}</td> <td>{{ request.user.email }}</td> <td>{{ nb_albums }}</td> -
return float(value) ValueError: could not convert string to float in Django models
I try to makemigrations / migrate on this Django models : from django.db import models from myapp.models import Site class GscElement(models.Model): ctr = models.FloatField('Taux de clic', default=0.0) impressions = models.IntegerField('Nombre d\'impressions', default=0) position = models.FloatField('Position moyenne', default=0.0) clicks = models.IntegerField('Nombre de clics', default=0) site = models.ForeignKey( Site, models.SET_NULL, blank=True, null=True ) class Page(GscElement): page_field = models.TextField('Url de la page', default='') startdate = models.DateField('Date du debut', null=True) enddate = models.DateField('Date de fin', null=True) class Meta: unique_together = (('startdate', 'enddate', 'page_field',)) class Query(GscElement): query_field = models.TextField('Requête', default='') startdate = models.DateField('Date du debut', null=True) enddate = models.DateField('Date de fin', null=True) class Meta: unique_together = (('startdate', 'enddate', 'query_field'),) and I get this error : [...] , line 1781, in get_prep_value return float(value) ValueError: could not convert string to float: Do you have any idea why ? FYI I tried to restore the databased I had before my models changes and tried to squash migrations too, but the same error always occured. Thank you ! -
Django import errors for app csvimport
I really don't know where to start with this error message so wondering if anyone's seen similar before? The weird thing is that my CSV import itself actually works fine, but I am a tad concerned by the error messages: Applying csvimport.0002_test_models...Traceback (most recent call last): File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: syntax error at or near "csvtests_country" LINE 1: ...CONSTRAINT "csvtests_item_country_id_5f8b06b9_fk_"csvtests_c... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 93, in __exit__ self.execute(sql) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/mikey/.virtualenvs/fanta/lib/python3.5/site-packages/django/db/utils.py", … -
Remote Debugging Visual Studio Code, Django, Daphne, Daphne Workers running in Docker Containers
Just started using visual studio code for python development and I like it so far. I am having issues doing remote debugging in a django app running on docker. Was hoping someone would point me in the right direction to setup V.S debugging in django through docker. I am running Django rest framework in docker container. I am using asgi server daphne because of websocket connections. I want to know if there is a way to use remote debugging in django running in docker with daphne workers. I have looked at some tutorial but they are for wsgi part. The problem I am having is that daphne uses workers to connect to daphne server and process the requests that way. Things I have tried: Able to use pdb to debug. Have to connect to the worker container and also specify stdin_open: true and tty: true. It works but is a tedious process. Tried the steps involved in the tutorial URL specified but it didn't work for Visual Studio Code. Also tried using remote debugging in pycharm but the background skeleton processes make my computer really slow. But I was able to make it work. Hoping I could do the same … -
django object data disappears when I refresh page
When I load the page for the first time, the object data is there (so three links in the example below), after starting runserver on my computer. If I reload the object data is not longer there (so zero links in the example below). template {% for url in urls %} <a href="{{ url }}"> link </a> {% endfor %} view class IntroView(View): template_name = '[app_name]/template.html' model_names = ['shoe', 'hat', 'bag'] urls = [reverse_lazy('%s:%s' % ('[app_name]', name)) for name in model_names] dict_to_template = {'urls': urls} def get(self, request, *args, **kwargs): return render(request, self.template_name, context=self.dict_to_template) It's probably something really simple, but it's got me. Thank you for your time. -
Using LDAP authentication - extending user model
I'm currently using 'django_python3_ldap.auth.LDAPBackend', which I have working correctly were a user authenticates with their network login / password then a user is created in the data base with username, password, email, first_name, and last_name, user_created_at all extracted from LDAP, which is what I want to stay the same. Now The network login is the username in the auth_user table. I have another table, which stores user information with a field titled employee_ntname, the table below is a pre-existing table in the database which can not be changed or updated for this use case. class AllEeActive(models.Model): employee_ntname = models.CharField(db_column='Employee_NTName',max_length=50) # Field name made lowercase. employee_last_name = models.CharField(db_column='Employee_Last_Name', max_length=50, blank=True, null=True) # Field name made lowercase. employee_first_name = models.CharField(db_column='Employee_First_Name', max_length=50, blank=True, null=True) # Field name made lowercase. b_level = models.CharField(db_column='B_Level', max_length=10, blank=True, null=True) # Field name made lowercase. group_name = models.CharField(db_column='Group_Name', max_length=100, blank=True, null=True) # Field name made lowercase. r_level = models.CharField(db_column='R_Level', max_length=10, blank=True, null=True) # Field name made lowercase. division_name = models.CharField(db_column='Division_Name', max_length=100, blank=True, null=True) # Field name made lowercase. d_level = models.CharField(db_column='D_Level', max_length=10, blank=True, null=True) # Field name made lowercase. market_name = models.CharField(db_column='Market_Name', max_length=100, blank=True, null=True) # Field name made lowercase. coid = models.CharField(db_column='COID', max_length=50, blank=True, null=True) # Field … -
Altering href after document load with jQuery
I have the following jQuery fs_body.append('<div class="fs_title_wrapper ' + set_state + '"><a href=""><h1 class="fs_title"></h1></a><h3 class="fs_descr"></h3></div>'); With this, what I would like to do is target the href attribute of the element and add in the link dynamically. On the templating side I have the following: <script> gallery_set = [ {% for feature in features %} {type: "image", image: "{{ MEDIA_URL }}{{ feature.image_scroll_1.url }}", title: "{{ feature.title }}", description: "{{ feature.lead_in }}", href:{{ % feature.get_absolute_url %}}, titleColor: "#ffffff", descriptionColor: "#ffffff"}, {% endfor %} ] </script> How do I now target that href in the appended body inside the fs_title_wrapper class div? -
update_or_create Django 1.10
Hi I have live data coming in from an API, Since we have the same SKU, in multiple markets, I need a composite PK, (SKU, Country), I know Django does not support this, so I am using the update_or_create function. My issue is that the data keeps duplicating as the quantity values change country merch quantity sku USA CC 2807 1005 B00VQVPRH8 USA CC 2806 1004 B00VQVPRH8 Here is the call to save the data: obj, created = FBAInventory.objects.update_or_create( Account=merchant["company"], ASIN=ASIN, TotalSupplyQuantity=TotalSupplyQuantity, InStockSupplyQuantity=InStockSupplyQuantity, FNSKU=FNSKU, EarliestAvailability=EarliestAvailability, defaults={'SellerSKU': SellerSKU, 'Country': merchant["country"]}, ) Am I using the function incorrectly, I want to update the SKU/Country row, I do not want a duplicate with different quantity values. I know I can use get, but I want to take advantage of this function so I don't have to write a conditional statement. Should defaults hold the update values and the kwarg hold the values to match? -
Django form not saving to database
I'm having trouble saving form fields to my database. I know that it isn't saving because if I look at the Player model in django, there is always 0 data. If anyone could take a look and correct me, I would be very thankful. models.py - from django.db import models class Player(models.Model): player_one_name = models.CharField(max_length=30, default='') player_two_name = models.CharField(max_length=30, default='') forms.py - from django import forms class PlayerInfo(forms.Form): player_one_name = forms.CharField(max_length=30, label='First player name') player_two_name = forms.CharField(max_length=30, label='Second player name') views.py from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, render_to_response import os from .forms import PlayerInfo from .models import Player def start(request): if request.method == 'Post': form = PlayerInfo(request.POST) if form.is_valid(): obj = Player() obj.player_one_name = form.cleaned_data['fp_name'] obj.player_two_name = form.cleaned_data['sp_name'] form.save() return HttpResponseRedirect('/game/') else: form = PlayerInfo() args = {'form': form} return render(request, 'start.html', args) start.html - Meant to submit each player's name {% block botRow %} <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock %} game.html - Meant to render each player's name {% extends 'base.html' %} {% block midRow %} <p>{{ fpn }}</p> <p>{{ spn }}</p> {% endblock %} -
Django conditional javascript file in template causes missing staticfile error in production only
I have a conditional in a template used by several views which will include a js file if passed in by the view: in the template: {% if js_file %} {% block inner_js %} <script defer type="text/javascript" src="{% static js_file %}"></script> {% endblock inner_js %} {% endif %} which is eg used by a view by: ....... context = {'title': 'Sign up', 'form': form, 'js_file': 'js/supplier.js'} return render(request, 'pages/signup.html', context) This produces no errors in development, but when pushed to production I get the error: ValueError at /users/example/ Missing staticfiles manifest entry for '' If I remove the template if block above then this error dissapears (and works fine for those views which use the template without a js file). I would rather not have to create a new version of the template for every view which uses a js file, is their a better way to fix this? (seems a bit of a weird error). -
Django post form lost filed
I post form then lost a file, but it happens sometimes. enter image description here this is the from: class UniversityForm(forms.Form): # Select Dropdown university = forms.ModelChoiceField( queryset=University.objects.filter( recommended=True ), empty_label='Other', required=False ) school_country = forms.ChoiceField(choices=CIIP_COUNTRIES, label='University Country', required=False) school_name = forms.ChoiceField(choices=DEFAULT_CHOICES, label='University', required=False ) school_name_other = forms.CharField(label='University Name', required=False) # name = forms.CharField(label='University Name', required=False) contact_name = forms.CharField(label='Contact Name', widget=forms.TextInput(attrs={'placeholder': 'University Representative'}), required=False) contact_title = forms.CharField(label='Contact Title', widget=forms.TextInput(attrs={'placeholder': 'University Representative'}), required=False) contact_email = forms.EmailField(label='Contact Email', widget=forms.TextInput(attrs={'placeholder': 'University Representative'}), required=False) # country = forms.CharField(label='Country', widget=forms.TextInput(attrs={'placeholder': 'University Country'}), required=False) current_degree = forms.CharField(label='Current Degree', required=False) degree_type = forms.ChoiceField(label='Degree Type', required=False, choices=DEGREE_TYPES) last_gpa = forms.DecimalField(label='Grade Point Average', required=False, widget=forms.TextInput(attrs={'placeholder': 'Grade Point Average'})) graduation_year = forms.IntegerField(label='Graduation Year', widget=forms.TextInput(attrs={'placeholder': 'eg: 2017'}), required=False, min_value=1950, max_value=2045) if request.method == 'POST': # Instantiate the university form params.update({ 'form':UniversityForm( request.POST ) }) # Update university dropdown with our ajax choices so it can pass validation sem = request.POST.get('school_name') params.get('form').fields['school_name'].choices = [(sem, sem)] # Verify that the form is valid if params.get('form').is_valid(): gpa = params.get('form').cleaned_data['last_gpa'] if gpa > 100: params.update({'error': 'The GPA you entered is too high.'}) return render(request, 'student/index.html', params) else: # if no university data is entered, and it needs to be entered always. if params.get('form').cleaned_data['school_country'] == '' … -
Django query: Getting data over two relationships
I already googled much and read this site https://docs.djangoproject.com/en/1.11/topics/db/queries/ several times but I still have problems to get the right data. I extended the standard Django-User-Model with a MAC-Adress because I will need it later. I also have a relationship between the models like this: One "Django-Standard-User" has ONE UserProfile ONE "UserProfile" has MANY CalData from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User) mac = models.CharField(max_length=17, default='00:00:00:00:00:00') def __str__(self): return self.user.username class CalData(models.Model): user = models.ForeignKey(UserProfile) date = models.DateField(default="1970-01-01") timestamp = models.TimeField(default="00:00:00") entry_id= models.CharField(max_length=100, default="NoID") Now from the view, after the User has logged in, i want to make a query like this: "give me a Query (nor Objects) of Caldata where user = "the username of the Standard-Django-User" and where Date = Today. The second Question is: Is it better to set the ForeignKey of Caldata to "UserProfile" like I did or is it better to set it to "User" (standard Django-Model). My Goal is to say: One User has one unique MAC-Adress and many CalData. -
How do you paginate a viewset using a paginator class?
According to the documentation: Pagination is only performed automatically if you're using the generic views or viewsets But this doesn't seem to be the case. Here's what I have for my viewset: views.py class EntityViewSet(viewsets.ModelViewSet): def list(self, request): queryset = Entity.objects.all() serializer = EntitySerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = Entity.objects.all() user = get_object_or_404(queryset, pk=pk) serializer = EntitySerializer(user) return Response(serializer.data) Here's my urls entity_list = views.EntityViewSet.as_view({'get':'list'}) entity_detail = views.EntityViewSet.as_view({'get':'retrieve'}) ... url(r'^entity/$', entity_list, name='entity-list'), url(r'^entity/(?P<pk>[0-9]+)/$', entity_detail, name='entity-detail'), ... This is my pagination class class PagePaginationWithTotalPages(pagination.PageNumberPagination): page_size = 30 page_size_query_param = 'page_size' max_page_size = 1000 def get_paginated_response(self, data): return Response({ 'next': self.get_next_link(), 'previous': self.get_previous_link(), 'count': self.page.paginator.count, 'total_pages': self.page.paginator.num_pages, 'results': data }) and I set it in settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_PAGINATION_CLASS': 'myapp.pagination.PagePaginationWithTotalPages', 'UNICODE_JSON': False, } Now while this works for ListAPIView it doesn't appear to work for my viewset. Is there a step that I'm missing? -
bulk_create - TypeError: cannot convert the series to <class 'float'>
When I run this code records = [] for dt in rrule(DAILY, dtstart=a, until=b): records.append( Object(price=predictions_df1.loc[dt.strftime("%Y-%m-%d")], symbol = 'TFSM', date=dt.strftime("%Y-%m-%d"))) Object.objects.bulk_create(records) I get an error - TypeError: cannot convert the series to <class 'float'>. Does anyone have an idea how can I solve it? I tried .apply(np.float64) , .convert_objects(convert_numeric=True) etc. but nothing works. My Object looks in this way: class Object(models.Model): symbol = models.CharField(max_length=200) date = models.DateField(default=datetime.now, blank=True) price = models.FloatField() -
Django trigger post_save on update()
So I am using django-simple-history module that tracks changes in Model instances. However, it uses post_save signal to do so. In my project, I also need it to trigger on update(). My question is: How to overwrite the update() method to trigger post_save signals? -
module 'oscar' has no attribute 'OSCAR_MAIN_TEMPLATE_DIR'
I try to deploy my django-oscar app on heroku but when I run the migration : heroku run sandbox/manage.py migrate the following error occured: (the database used is postgresql and i've installed all requirements but i don't know the source of the problem) 2017-10-24T16:02:49.121254+00:00 heroku[run.8440]: Starting process with command `sandbox/manage.py migrate` 2017-10-24T16:02:49.731452+00:00 heroku[run.8440]: State changed from starting to up 2017-10-24T16:02:52.721398+00:00 heroku[run.8440]: State changed from up to complete 2017-10-24T16:02:52.595920+00:00 app[run.8440]: Traceback (most recent call last): 2017-10-24T16:02:52.595939+00:00 app[run.8440]: File "sandbox/manage.py", line 10, in <module> 2017-10-24T16:02:52.596126+00:00 app[run.8440]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line 2017-10-24T16:02:52.596124+00:00 app[run.8440]: execute_from_command_line(sys.argv) 2017-10-24T16:02:52.596439+00:00 app[run.8440]: utility.execute() 2017-10-24T16:02:52.596734+00:00 app[run.8440]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ 2017-10-24T16:02:52.596730+00:00 app[run.8440]: settings.INSTALLED_APPS 2017-10-24T16:02:52.597070+00:00 app[run.8440]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__ 2017-10-24T16:02:52.596912+00:00 app[run.8440]: self._setup(name) 2017-10-24T16:02:52.597067+00:00 app[run.8440]: self._wrapped = Settings(settings_module) 2017-10-24T16:02:52.596915+00:00 app[run.8440]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup 2017-10-24T16:02:52.597249+00:00 app[run.8440]: mod = importlib.import_module(self.SETTINGS_MODULE) 2017-10-24T16:02:52.597438+00:00 app[run.8440]: return _bootstrap._gcd_import(name[level:], package, level) 2017-10-24T16:02:52.597622+00:00 app[run.8440]: File "<frozen importlib._bootstrap>", line 961, in _find_and_load 2017-10-24T16:02:52.597996+00:00 app[run.8440]: File "<frozen importlib._bootstrap_external>", line 678, in exec_module 2017-10-24T16:02:52.597748+00:00 app[run.8440]: File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked 2017-10-24T16:02:52.598147+00:00 app[run.8440]: File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed 2017-10-24T16:02:52.597443+00:00 app[run.8440]: File "<frozen importlib._bootstrap>", line 978, in _gcd_import 2017-10-24T16:02:52.597878+00:00 app[run.8440]: File "<frozen importlib._bootstrap>", line 655, in _load_unlocked 2017-10-24T16:02:52.597253+00:00 app[run.8440]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", … -
Django sites framework and authentication
I want to build a web application using Django. Basically a CRM for specific business type. Lets say it's for Gyms for this explanation. I will have multiple customers. The customers will each get their own 3rd level domain name. Like golds.gym.com and 24hrfitness.gym.com. Each customer will have their own customers that will use the site as well. I want to allow overlapping usernames across sites, but unique to each site. I would also like to use the built in admin pages, but I will need to be sure that the admin pages are site specific. My question is more or less, "Is this possible". But I think what I really want to know is "Is this possible using something built in or something someone else has out there for Django?" I have looked at the sites framework documentation and that seems to be what I need, however I have not found any documentation on how to make the admin and the users site specific.