Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django target WSGI script cannot be loaded as Python module
I am trying to deploy mod_wsgi with apache to run a django application but I am getting an error 500 internal server error The apache logs shows: [Fri May 05 22:38:22.709307 2017] [:error] [pid 2750] [remote 18.189.13.77:36] mod_wsgi (pid=2750): Target WSGI script '/var/www/html/venv/testproject/testproject/wsgi.py' cannot be loaded as Python module. [Fri May 05 22:38:22.709350 2017] [:error] [pid 2750] [remote 18.189.13.77:36] mod_wsgi (pid=2750): Exception occurred processing WSGI script '/var/www/html/venv/testproject/testproject/wsgi.py'. [Fri May 05 22:38:22.709379 2017] [:error] [pid 2750] [remote 18.189.13.77:36] Traceback (most recent call last): [Fri May 05 22:38:22.709406 2017] [:error] [pid 2750] [remote 18.189.13.77:36] File "/var/www/html/venv/testproject/testproject/wsgi.py", line 12, in <module> [Fri May 05 22:38:22.709441 2017] [:error] [pid 2750] [remote 18.189.13.77:36] from django.core.wsgi import get_wsgi_application [Fri May 05 22:38:22.709465 2017] [:error] [pid 2750] [remote 18.189.13.77:36] ImportError: No module named django.core.wsgi Server: CentOS 7 Django: 2.0 Python: 3 Apache: 2.4.6 Installed: mod_wsgi Followed URL(https://www.server-world.info/en/note?os=CentOS_7&p=httpd&f=20) but only failed until last step. My virtual django /var/www/html/venv/testproject/testproject/wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.settings") application = get_wsgi_application() My Apache /etc/httpd/conf.d/django.conf: `WSGIDaemonProcess testapp python-path=/var/www/html/venv/testproject:/var/www/html/venv/lib/python3.6/site-packages WSGIProcessGroup testapp WSGIScriptAlias /django /var/www/html/venv/testproject/testproject/wsgi.py Require all granted ` Do I need to set any configurations on httpd/conf? or setting any os.path? -
How do I run Django tests on a copy of my production database?
I've written a series of tests for my Django app, and would like to run them on a copy of my production database. As far as I can tell, the best way to do this is using fixture loading like so: Run manage.py dumpdata -o app.dump Move the resulting app.dump file to a fixtures directory in the [app name] folder Specify a 'fixtures' class attribute on my django.test.TestCase subclass However, this approach is cumbersome. I have multiple apps, and running manage.py dumpdata for each of them and manually moving around fixtures files every time I want to test my app is a pain. Is there an easier way to automatically generate a copy of my entire production database and test my Django apps against it? -
Django password reset throwing 'Reverse not found' for 'password_reset_done'
The complete error message I'm getting is: Reverse for 'password_reset_done' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I'm trying to use the standard DJANGO auth libraries to implement signin, logoff, password reset and sign up functionality/views to my site. I'm using the Anaconda 4.6 package and I'm importing the DJANGO libraries as below from django.contrib.auth import views as auth_views The (relevant) urlpatterns I have are: url(r'^password_reset/$', auth_views.password_reset, name='password_reset'), url(r'^password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.password_reset_confirm, name='password_reset_confirm'), url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'), If I go to the URL /password_reset/done/ I reach the page. If I go to the URL /password_reset/ I get the failed reverse error. I've been reading the documentation for 2 days but I don't seem to be able to find out why url(r'^password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'), is blocking the django reverse function. Does anyone have any ideas? Thanks a lot! Traceback here too for more details: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/password_reset/ Django Version: 1.10.5 Python Version: 3.5.2 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'bootstrap3', 'app1'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "E:\Programming\Anaconda3_4.2.0\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "E:\Programming\Anaconda3_4.2.0\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File … -
How to use DRF modify FileField to take a different path after object ID is available?
I have an issue with DRF file naming. The file of interest (I believe) is serializers.py. What I want to occur when I upload a file is a creation of a directory in the upload_to directory when the id of the object becomes available. This is simple to do overriding the create method. What I have not figured out how to do is to update the file in the database to reflect the new path. It is easy to change the file to a string containing the desired path for instance, but it is difficult to change the file to the file with the desired path. P.S. I am aware I am obscuring the file keyword. If necessary I will change it. # models.py class TestFile(Model): file = FileField(storage=FileSystemStorage(location=settings.MEDIA_ROOT), upload_to='files', default='{}/files/empty.zip'.format(settings.MEDIA_ROOT)) created_at = CreationDateTimeField() updated_at = ModificationDateTimeField() def __str__(self): return ''.join([str(self.file)]) def __unicode__(self): return unicode(' '.join([str(self.id)])) def __id__(self): return str(self.id) class Meta: managed = True db_table = 'test_files' verbose_name_plural = 'Test Files' # viewsets.py class TestFileViewSet(ModelViewSet): queryset = TestFile.objects.all() serializer_class = TestFileSerializer parser_classes = (MultiPartParser, FormParser) def perform_create(self, serializer): serializer.save(file=self.request.data.get('file') # serializers.py class TestFileSerializer(ModelSerializer): file = serializers.FileField(required=True) def create(self, validated_data): # Calling create(), this will create the object in the … -
Stringing together a series of foreign keys to return a table value in Django
How do I select the ctype knowing the user? models.py: from django.contrib.auth.models import User class CompanyType(models.Model): ctype = models.CharField(max_length=20) class Company(models.Model): name = models.CharField(max_length=50) companytype = models.ForeignKey(CompanyType, on_delete=models.CASCADE) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) I know I can do it this way, but is there a way to chain it altogether in one line? def getcompanytype(request): user_id = request.user.id company_id = Profile.objects.get(user_id__exact=user_id).company_id companytype_id = Company.objects.get(id=company_id).companytype_id companytype = CompanyType.objects.get(id=companytype_id).ctype return(companytype) essentially I want this SQL statement: SELECT ct.ctype From auth_user u left outer join Profile p on p.user_id = u.id left outer join Company c on p.company_id = c.id left outer join CompanyType ct on ct.id = c.companytype_id where u.id = 1 # actually current user ID, not hardcoded "1" -
Change the css class of an element in a Django form that uses ModelForm
I have the following model: class PledgeSettings(models.Model): message = models.CharField(max_length=200, blank=True, null=True) amount = MoneyField( max_digits=6, decimal_places=2, default_currency='CAD', blank=True, null=True, ) and I have the following form that uses that model: class PledgeSettingsForm(forms.ModelForm): class Meta: model = PledgeSettings def __init__(self, *args, **kwargs): super(PledgeSettingsForm, self).__init__(*args, **kwargs) self.fields['message'].widget.attrs = { 'placeholder': _('Everytime I eat a doughnut'), } self.fields['message'].label = False self.fields['amount'].label = _('I pledge to donate $') self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-xs-9' self.helper.field_class = 'col-xs-3' self.helper.layout = Layout( 'message', 'amount' ) self.helper.layout.append( Submit('save', 'Save', css_class='save_button') ) The problem is that self.helper.label_class = 'col-xs-9' and self.helper.field_class = 'col-xs-3' has no effect, and I would like to set the css class of a particular element, e.g., message or amount, and I have no idea how to do that. Can anybody help me to solve this issue? -
a trouble with django and authenticate
a problem with django and authenticate(). Signup works! Does not work login. i don't know how to fix it. My forms.py class UserForm(forms.ModelForm): phone = forms.CharField(widget=forms.TextInput(attrs={'type': 'tel', 'pattern': '8[0-9]{10}', 'placeholder': 'Number phone'})) email = forms.EmailField(widget=forms.TextInput(attrs={'type': 'email', 'placeholder': 'Your email'})) password = forms.CharField(widget=forms.TextInput(attrs={'type': 'password', 'placeholder': 'Your password'})) class Meta: model = MyUser fields = ['email', 'password', 'phone'] class UserLoginForm(forms.Form): email = forms.EmailField(label='Email', widget=forms.TextInput(attrs={'type': 'email', 'placeholder': 'Your email'})) password = forms.CharField(label='Password', widget=forms.TextInput(attrs={'type': 'password', 'placeholder': 'Your password'})) My models.py class MyUserManager(BaseUserManager): def create_user(self, email, phone, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), phone=phone, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, phone, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email=email, phone=phone, password=password ) user.is_admin = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True,) phone = models.CharField(max_length=15, blank=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def get_full_name(self): # The user is identified by their email address return self.email def get_short_name(self): # The user is … -
Is it safe to name field as 'id' in Django model?
class MyModel(models.Model): id = models.IntegerField(primary_key=True) or class MyModel(models.Model): id_ = models.IntegerField(primary_key=True) According to pep8 single_trailing_underscore_ should be used by to avoid conflicts with Python keyword but having column named id_ would look ugly and possibly cause confusion to someone not familiar with python on database level. Django docs use 'id' column name: https://docs.djangoproject.com/en/1.11/ref/models/fields/#uuidfield. Is it safe to name this field as 'id'? -
Javascript event that triggers python script
I have a python script that generates a QR code (saved as a .png) and a webpage. I am trying to make a javascript button trigger the python script to generate an image, and replace the filler image I have on the HTML page. Process: User clicks button --> python script runs --> python returns QR code to webpage Heres the sample HTML: <html> <body> <img id="qrcode_container" src="assets/filler_image.png" width="35%"> <p></p> <button onclick="document.getElementById('qrcode_container').src= 'assets/sampleQR.png'">Generate Code</button> </body> </html> But this simply replaces the image with a pre-made one. Here is the python code: import pyqrcode, uuid, png uuid_raw = uuid.uuid4() uuid_string = str(uuid_raw) print(real_code) qrImage = pyqrcode.create(uuid_string) qrImage.png(uuid_string+'.png', scale=16) So ideally I would like to have the button on the webpage trigger the script to run, then replace the filler image on the webpage with the new QR code, as well as return the UUID. I've checked out frameworks like Django and Flask, but they seem overkill for a webpage I'm only using to generate an image. Should I use PHP to trigger the event? -
Django channels with http post static routes
So I'm trying to convert one my Django application from a WSGI implementation to a ASGI implementation. HTTP GETs seem to be working find, even though they are running on the worker process. I'm currently trying to get HTTP POSTs to work and I've figured out that the data that is being posted to the URL I have defined doesn't actually contain the data I'm looking for. Instead of the classic "HttpResponce" type being returned to my method, it's getting a "AsgiRequest" instead. Is there something fundamental I'm missing in the conversion? -
makemigrations not detecting changes after moving models to a modelsdirectory
My old structure used to be like this: models.py class Model1 class Model2 ... I have since moved this to modelsdir __init__.py model1.py class Model1 model2.py class Model2 models.py from modelsdir.model1 import Model1 from modelsdir.model2 import Model2 After this change, makemigraitons and makemigrations myapp no longer detect any changes done on the models. Any idea how to fix this? -
Django convention for naming a ForeignKey that uses the to_field param?
I'm wondering if there is a convention for naming a foreign key field in Django that is mapped to another field with to_field. For example, should the Django field name be the model name and the database field name be the column name or is that confusing? class Stations(models.Model): name = models.CharField() observations = models.ForeignKey(Observations, to_field='zone_code' db_column='zone_code') class Observations(models.Model): zone_code = models.IntegerField(unique=True) metric_a = models.IntegerField() metric_a = models.IntegerField() It doesn't really make sense to have this: class Stations(models.Model): name = models.CharField() observations = models.ForeignKey(Observations, to_field='zone_code') class Observations(models.Model): zone_code = models.IntegerField(unique=True) metric_a = models.IntegerField() metric_a = models.IntegerField() nor this class Stations(models.Model): name = models.CharField() zone_code = models.ForeignKey(Observations, to_field='zone_code') class Observations(models.Model): zone_code = models.IntegerField(unique=True) metric_a = models.IntegerField() metric_a = models.IntegerField() because then you end up with observations_id or zone_code_id when the column in the database is actually the zone_code. Anyone have this issue before? -
is there a way to refactor this? **kwarg - django
I have been calling the same model over and over again but somethings with different field but there would be a few that would always be the same. I am thinking if there is a way to refactor it? For example. def x(get_filter, **kwargs): # if blah return User.object.get(is_active=True, is_deleted=False, is_staff=False, **kwargs) # if blah return User.object.filter(is_active=True, is_deleted=False, is_staff=False, **kwargs) # if blah return User.object.get(is_active=True, is_deleted=False, **kwargs) # if blah return User.object.get(is_active=True, is_deleted=False, is_staff=False, is_superuser=True, **kwargs) as can be seen, is_active=True and is_deleted=False is always being used. I thought of doing something like is_deleted = {'is_deleted': False} is_active = {'is_active': True} User.object.filter( is_staff=False, **is_active, **is_deleted,**kwargs) in my IDE, it would say duplicate ** is not allowed Can someone give me an idea? Thanks in advance -
AllAuth and missing feilds
Cant seem to find where I am going wrong here. There are two issues, but I feel like a simple config change will fix both. When displaying the below code the password field does not get displayed. Crispy-Forms generates a warning Could not resolve form field 'password' When I add a password field manually, and I submit the form, nothing happens. Ie. I am returned to the signup page with the form filled out. But save_user() or the signin() function never gets called. There are no SQL error messages or any form error messages. Below are the settings: ACCOUNT_SIGNUP_FORM_CLASS = 'house.users.forms.SignupForm' AUTH_USER_MODEL = 'users.User' ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'optional' ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_ADAPTER = 'house.users.adapters.AccountAdapter' Both ACCOUNT_SIGNUP and ACCOUNT_ADAPTER point to the right files as I am able to make changes to see the, reflected. This forms.py class SignupForm(forms.Form): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) def __init__(self, *args, **kwargs): super(SignupForm, self).__init__( *args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.helper.field_class = '' self.helper.layout = Layout( Field('first_name', placeholder='First Name', autocomplete='off'), Field('last_name', placeholder='Last Name', autocomplete='off'), Field('email', placeholder='Email', autocomplete='off'), Field('password', placeholder='Password', autocomplete='off'), Div(Submit('Register', 'Register', css_class='btn btn-primary block full-width m-b'), css_class='form-group'), HTML('<p class="text-muted text-center"><small>Already have an account?</small></p>'), … -
Deploy a Django Site with another folder for static files
My enviroment is with Django 1.10.7, PostgreSQL 9.4 and Nginx 1.6 with Gunicorn I have a global folder called static for common static files to use in sub apps, then i set another folder for production mode with the name 'static_root': in my settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] in my urls.py: from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns += (static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)) urlpatterns += (static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)) when debug is true all work perfect, but in production mode the site not see the static files i set the location in nginx configuration too thank! -
Marking Notifications as Read with JS/Ajax API
I implemented django-notifications into my site and its working quite well (https://github.com/django-notifications/django-notifications). The only and I hope last problem I Got is that the Notifications are never marked as read. There is a possibility to do it with an API call and so I wrote something in JS. Im able to GET the Data but I cannot change/POST them since I always get an 403. I can check/uncheck the Boolean in the Admin-Page but I cannot do it with the API Call. Does anybody have an Idea what I can do? The "documentation" is just one site on Github. The makers only made some short examples without a lot of Context. My code: $(".notiBla").click(function(){ $.ajax({ url:("/inbox/notifications/api/unread_list/?max=3&mark_as_read=false/"), dataType:'json', type: 'POST', data: "unread_list", success:function(response){ response.unread_list[0].unread=false console.log(response.unread_list[0].unread) } }); }); this returns a 403 since im not allowed to do POST. When I use Get it shows me the data correctly but this is useless since I need to change the data... Does anybody know the answer or another way to accomplish my goal? -
Remote Login to CPanel Webmail
I have developed a python version of the get_logged_in_url method of Cpanel's LogMeIn perl module, according to their docs and based on this PHP implementation. My method is as follows: def logmein(user, passwd, hostname, service, goto='/'): service_port = service_ports[service] # Assume we have 2096 here data = {'user': user, 'pass': passwd, 'goto_uri': goto} req_url = 'https://{}:{}/login/'.format(hostname, service_port) response = requests.post(req_url, data=data, headers={'Connection': 'close'}, allow_redirects=False) try: session_id = response.cookies[service_cookies[service]] # Assume we have webmailsession here except KeyError: return None try: sec_token = re.search(r'<META HTTP-EQUIV="refresh" CONTENT="2;URL=/cpsess(\d+)', response.text).group(1) except (TypeError, IndexError): return None try: redirect_url = re.search(r'<META HTTP-EQUIV="refresh" CONTENT="2;URL=(/cpsess\d+/.*?)"', response.text).group(1) except (TypeError, IndexError): redirect_url = '' url_params = urlencode({'session': session_id, 'goto_uri': goto}) return {'url': 'https://{}:{}/cpsess{}/{}'.format(hostname, service_port, sec_token, goto.lstrip('/')), 'cookies': response.cookies, 'redirect_url': redirect_url} This method returns the constructed "logged in" url, the redirect url that the /login/ response generates and even the cookies that must be set. Then I use this method like this (in a django view): class MonitorDashboard(cv.BaseAppTemplateView): allowed_user_profiles = ('staffprofile',) template_name = 'mailmonitor/dashboard.html' cpanel_cookies = {} def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) cpanel_login = cpanel_helper.logmein('contacto@2lmnacional.com.mx', 'sis.admin', 'res180.servconfig.com', cpanel_helper.WEBMAIL, '/paper_lantern/index.html') context.update({'webmail_login_url': cpanel_login['url']}) self.cpanel_cookies = cpanel_login['cookies'] return context def render_to_response(self, context, **response_kwargs): response = super().render_to_response(context, **response_kwargs) for cookie_key, cookie_val in self.cpanel_cookies.items(): response.set_cookie(cookie_key, cookie_val) … -
How can I create a json file from a set of PrimaryKey related objects in Django?
I have an api with several endpoints: item, persona, attributes, and synergies. I can't use 'depth' or nest the serializers to create my nested relationship - I am limited to using PrimaryKeyRelatedField (external constraint - no control over it). I need to get my Item as a json object with the nested relationships intact rather than represented by pks. Is there any way to do this? If need be, I can call each endpoint separately and combine the results to build the object -- and that may be the only way to do this. Serializers.py: class ItemSerializer(serializers.ModelSerializer): personas = serializers.PrimaryKeyRelatedField(queryset=Persona.objects.all(), many=True) name = serializers.CharField(max_length=255) class Meta: model = Item fields = ('id', 'name', 'personas') class PersonaSerializer(serializers.ModelSerializer): name = serializers.CharField(max_length=255) description = serializers.CharField(max_length=255) icon = serializers.CharField(max_length=255) attributes = serializers.PrimaryKeyRelatedField(queryset=Attribute.objects.all(), many=True) synergies = serializers.PrimaryKeyRelatedField(queryset=Synergy.objects.all(), many=True) class Meta: model = Persona fields = ('id', 'name', 'description', 'attributes', 'synergies', 'icon') class AttributeSerializer(serializers.ModelSerializer): name = serializers.CharField(max_length=255) source = serializers.CharField(max_length=64) class Meta: model = Attribute fields = ( 'id', 'name', 'source', ) class SynergySerializer(serializers.ModelSerializer): name = serializers.CharField(max_length=255) strength = serializers.FloatField() pattern = serializers.CharField(max_length=255) attribute_a = serializers.PrimaryKeyRelatedField(queryset=Attribute.objects.all(), many=True) attribute_b = serializers.PrimaryKeyRelatedField(queryset=Attribute.objects.all(), many=True) class Meta: model = Synergy fields = ( 'id', 'name', 'attribute_a', 'attribute_b', 'strength', 'pattern' ) -
Unable to Import Django Application into uWSGI
On my Google Compute Engine instance, I have been trying to setup my application server (uWSGI) following these steps: cd /path/to/project/directory workon virtual_env uwsgi --ini uwsgi.ini Every time I initialize uWSGI, the following error is thrown (a more extensive log below): ImportError: No module named '"adtor' unable to load app 0 (mountpoint='') (callable not found or import error) I'm able to run the development server alone (python manage.py runserver). It is peculiar that there is an extra double quote (") before my django application's name, but am unable to find any instances of an extra double quote within code, the .ini, virtual env hooks (e.g. postactivate). Beyond this, I'm unable to find a potential culprit; I'd assume it is either within my .ini file or improperly installed some third-party library. "pip freeze": appdirs==1.4.3 Django==1.8.5 django-filter==1.0.2 django-model-utils==3.0.0 djangorestframework==3.6.2 mysqlclient==1.3.10 packaging==16.8 pyparsing==2.2.0 six==1.10.0 uWSGI==2.0.15 uwsgi.ini [uwsgi] socket=127.0.0.1:8000 stats=127.0.0.1:9191 http-timeout=1800 uid=www-data gid=www-data virtualenv=/home/tor/.virtualenvs/adtor_prod home=/home/tor/.virtualenvs/adtor_prod chdir=/srv/django/adtor_project/prime module=adtor.wsgi:application master=true vacuum=true thunder-lock=true pidfile=/tmp/project-master.pid daemonize=/var/log/uwsgi/adtor-blog.log threads=2 enable-threads=true for-readline = /etc/srv/vars.txt env = %(_) endfor = Log: *** Starting uWSGI 2.0.15 (64bit) on [Fri May 5 16:00:56 2017] *** compiled with version: 4.8.4 on 02 May 2017 17:47:17 os: Linux-4.4.0-75-generic #96~14.04.1-Ubuntu SMP Thu Apr 20 11:06:30 UTC 2017 … -
How to build URL from template to the admin pages
Once deployed onto a production server my django app URLs are like http://example.com/myapp/Widget/10 I'd like to put a link to the admin forms in my pages. Not sure the correct way to put an <a href="?">Go to admin</a> in my templates so that I can correctly get from a URL like the above for widgets to the admin page which would be http://example.com/myapp/admin I can't do something like <a href="/admin"> because this only works on the dev server but not in production. Is there a way to use the syntax like {% url admin %} to get to the admin page correctly? Not sure how to code the urlpattern if I add something like url(r'^admin$', ?, name='admin') in my urls.py -
GAE don't see gunicorn, but it is already installed
I am trying to deploy Django app with Google App Engine. My app.yaml file: # [START runtime] runtime: python api_version: 1 threadsafe: true env: flex entrypoint: gunicorn -b :$PORT wsgi runtime_config: python_version: 3.4 env_variables: CLOUDSQL_CONNECTION_NAME: ugram-mysql CLOUDSQL_USER: root CLOUDSQL_PASSWORD: Hf_12Gh34Ik__84hfSfPo handlers: - url: / script: wsgi.application # [END runtime] But when I run gcloud app deploy, app deploy is running (5 minutes), but I get an error: Updating service [default]...failed. ERROR: (gcloud.app.deploy) Error Response: [9] Application startup error: /bin/sh: 1: exec: gunicorn: not found But gunicorn is already installed mysupers-beta:~$ gunicorn usage: gunicorn [OPTIONS] [APP_MODULE] gunicorn: error: No application module specified. -
Django - A customer model to a order model that has price values
I was trying to build a restaurant management app using django, my Customer model has a name, orders, a table integer field and an is_active boolean field. I have a working form up that creates a Customer obj and assigns it its orders seperated by commas, which I then render using a model method. What I want to do is have multiple order fields in a Customer field and then a certain order field should be linked directly to a fixed price. I'm quite new to django, so here's how I can explain it best: when you create a customer object, you should see a Name field, multiple order fields which should also have some quantity fields which should both then be linked to a fixed price because I will use that to calculate a total price: fixed_price_of_order multipled by the quantity_ordered. I have tried to find something similar, but I haven't really been able to yet. Django might not be the best tool for this, but this is what I have to use. Would be really glad if someone could link me to a tutorial or a project or perhaps even a library. Even better if you could explain … -
Deprecating fields in django model
I'm normalizing a database associated with a Django project and will be moving fields to different tables. As part of the implementation process, I'd like to throw a deprecation warning to my colleagues if they attempt to use the old attributes after adding the new tables before I actually remove the columns. class Asset(Model): model = models.CharField(max_length=64, blank=True, null=True) part_number = models.CharField(max_length=32, blank=True, null=True) # this will be a redundant column to be deprecated company = models.ForeignKey('Company', models.CASCADE, blank=True, null=True) # this will be a redundant column to be deprecated # other database fields as attributes and class methods My understanding is that I would need to add something along the lines of warnings.warn('<field name> is deprecated', DeprecationWarning) somewhere in the class, but where would I add it? -
Key Error on Wagtail ClusterTaggableManager similar_objects
I'm trying to use similar_objects method for tagged objects within a Wagtail app. Given the recipe on the documentation, instead of using default TaggableManager you have to use the ClusterTaggableManager, I have create it a model structure like on the recipe and as I call the similar_objects method, I get a KeyError: (<someid>, ) on line 350 inside taggit/managers.py file. I check other similar question and inside the taggit project either is a Django error o there is no a concrete solution, at least for this case, using ClusterTaggableManager. Any ideas? My code looks like this: class ContentPageTag(TaggedItemBase): content_object = ParentalKey('BaseDynamicContent', related_name='tagged_items') class BaseDynamicContent(BaseContentMixin): . . tags = ClusterTaggableManager(through=ContentPageTag, blank=True) class SomeOtherstuff(BaseContentMixin): //specific fields If I try with the parent class (BaseDynamicContent) or with child class (SomeOtherstuff) I get the same error. Any ideas? -
PyMODM - Find Document(s)
I'm using PyModm as an ORM layer for MongoDB for my Django CRUD app. I created a MongoModel as in so: class Book(MongoModel): title = fields.CharField(primary_key=True) author = fields.CharField() To create and update documents the pymodm API is really good, but I couldn't find an easy way to retrieve one or more documents, as Book.object.all() returns a QuerySet that seems to be only Json-serializable when iterating over it. So the workaround I found is books = [] for book in Book.objects.all(): books.append({ 'title': book.title, 'author': contact.author }) return JsonResponse(books) And for retrieving one book by it's primary-key: for book in Book.objects.raw({'_id': title}): book = { 'author': book.author, 'title': book.title } return JsonResponse(book) However, this seems not a very sufficient nor pretty way. Is there any better way?