Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Airbrake throwing error "pybrake - ERROR - strconv.ParseInt: parsing "None": invalid syntax"
I'm trying to use the Airbrake logger in a Django project following the steps described in https://github.com/airbrake/pybrake#django-integration. I've configured my LOGGING setting like so: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'airbrake': { 'level': 'ERROR', 'class': 'pybrake.LoggingHandler', } }, 'loggers': { 'lucy_web': { 'handlers': ['airbrake'], 'level': 'ERROR', 'propagate': True, } } } Then, in a particular file in the lucy_web hierarchy called lucy_web/lib/session_recommendation.py, I have the following test function: import logging logger = logging.getLogger(__name__) def log_something(): logger.error("Logging something...") However, if I try to call this function from the Django shell, pybrake itself logs an error: strconv.ParseInt: parsing "None": invalid syntax Here is the full sequence of commands: (venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py shell Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28) Type 'copyright', 'credits' or 'license' for more information IPython 6.3.1 -- An enhanced Interactive Python. Type '?' for help. In [1]: from lucy_web.lib.session_recommendation import * In [2]: log_something() In [3]: 2018-05-30 17:25:32,201 - pybrake - ERROR - strconv.ParseInt: parsing "None": invalid syntax It would appear from https://golang.org/pkg/strconv/#ParseInt that strconv.ParseInt is actually a built-in function of the Go language, so I don't understand why pybrake, which is a Python package, is throwing this error, or how to debug it. … -
how to get only results in many to many relationship in django
I have the following relationships: class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Post(models.Model): customer = models.ForeignKey('common.Customer', mentions = models.ManyToManyField('common.Customer',related_name='mentions') I want to get all of the users that are mentioned in a post. I'm thinking something like this: customer = Customer.objects.get(user=request.user) posts = Post.objects.filter(mentions__in=customer).order_by('-created_at') Is this close to what I'm trying to accomplish? -
How to remove a form from formset
views.py formset = ComparisonScoreFormSet(initial=[ {'comparison': comparison} for comparison in Comparison.objects.all() ]) I initialized a formset with initial values. This adds forms with initial values and also one form with no initial value. I need to remove the form with no initial value. I need to do something like the following del formset[-1] #since the form with no initial value is at the last -
How to use Airbrake's pybrake Django integration?
I'm trying to apply the Django integration steps described for pybrake, a Python exception notifier for Airbrake. The Django project contains several apps, one of which is called lucy_web. In my setttings, I've defined the AIRBRAKE setting like so: AIRBRAKE = dict( project_id=os.getenv('AIRBRAKE_API_KEY'), project_key=os.getenv('AIRBRAKE_PROJECT_ID'), environment=os.getenv('AIRBRAKE_ENVIRONMENT', default='production'), root_directory=os.path.dirname(os.getcwd())) The LOGGING setting is: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', } }, 'handlers': { 'console': { 'level': os.environ.get('LOG_LEVEL', 'ERROR'), 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', }, 'airbrake': { 'level': 'ERROR', 'class': 'pybrake.LoggingHandler', } }, 'loggers': { 'django.db.backends': { 'level': os.environ.get('LOG_LEVEL', 'ERROR'), 'handlers': ['console'], }, 'lucy_web': { 'handlers': ['airbrake'], 'level': 'ERROR', 'propagate': True, } } } Note that I've replaced the key 'app' in the README by 'lucy_web', the name of one of the apps in the project. Now, as I understand from Python's logging documentation (https://docs.python.org/3/library/logging.html), any Logger object with a name like 'lucy_web.foo.bar' should propagate to the 'lucy_web' logger and get handled by its handler, which is defined above to be the pybrake.LoggingHandler. To test this, I tried the following test in lucy_web/tests/test_airbrake.py: import os import logging import pybrake from django.test import SimpleTestCase logger = logging.getLogger(__name__) class AirbrakeTest(SimpleTestCase): def test_1(self): notifier = pybrake.Notifier( project_id=os.getenv('AIRBRAKE_PROJECT_ID'), project_key=os.getenv('AIRBRAKE_PROJECT_KEY'), environment='production', root_directory=os.path.dirname(os.getcwd())) … -
Restrict access to a part of a template to users that is part of a group using Class based views. Django 2.0
I want to restrict users in certain groups from accessing parts of the HTML template. I have a class based view that looks like this: Views.py class PostListView(ListView): model = BlogPost paginate_by = 10 template_name = 'main/mysite.html' With function based views I can restrict access on a template based on someones group using request.user.groups.filter(name='GROUP_NAME').exists() from In Django, how do I check if a user is in a certain group? I tried changing my view.py and HTML template like this: views.py class PostListView(ListView): model = BlogPost paginate_by = 10 template_name = 'main/mysite.html' def dispatch(self, request): in_group = request.user.groups.filter(name='GROUP_NAME').exists() return in_group HTML TEMPLATE .... {% if in_group %} some code here shows up if user belong to group {% endif %} .... This will give me the correct display when the user is not a member of the group, but when they are a member of the correct group I get an attribution error: Exception Type: AttributeError at /mysite Exception Value: 'bool' object has no attribute 'get' -
Django many-to-many relationship doesn't return set object
I've the following User model class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, max_length=255) mobile = PhoneNumberField(null=True) username = models.CharField(null=False, unique=True, max_length=255) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) Which has a ManyToMany relationship with a Room class Room(Base): name = models.CharField(unique=True, max_length=255) room_type = models.CharField(max_length=50, null=True) users = models.ManyToManyField(User, related_name='users') When I run the following query, rooms = user.room_set.all() I get this error, AttributeError: 'User' object has no attribute 'room_set' What am I doing wrong here? -
CircleCI not picking up environment variable defined in run step?
I'm trying to run CircleCI tests for a Django project in which the manage.py determines the version of settings.py to apply (development.py, staging.py, or production.py) from an environment variable, ENV_ROLE. Previously, ENV_ROLE was set to default to development if not defined, but I'm in the process of changing it so that Django instead throws an ImproperlyConfigured error if it is not defined. In order to make the tests pass, I need to define the ENV_ROLE environment variable in our CircleCI test environment. Following https://circleci.com/docs/2.0/env-vars/#setting-an-environment-variable-in-a-step, I've added the following to the run step: - run: environment: ENV_ROLE: development However, I am still getting this error from CircleCI: #!/bin/bash -eo pipefail cd lucy-web source venv/bin/activate python manage.py compilescss --verbosity 0 python manage.py collectstatic --clear --no-input --verbosity 0 flake8 python manage.py test Traceback (most recent call last): File "/root/lucy/lucy_web/lucy-web/env.py", line 5, in <module> ENV_ROLE = os.environ['ENV_ROLE'] File "/usr/local/lib/python3.6/os.py", line 669, in __getitem__ raise KeyError(key) from None KeyError: 'ENV_ROLE' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 4, in <module> from env import ENV_ROLE File "/root/lucy/lucy_web/lucy-web/env.py", line 8, in <module> "No 'ENV_ROLE' environment variable is defined. " django.core.exceptions.ImproperlyConfigured: No 'ENV_ROLE' environment variable is defined. Please … -
Django runserver doesn't respond on browser despite port on 'LISTEN'
I have stumbled on this issue that I have no clue how to resolve. When I run python manage.py runserver, I open http://127.0.0.1:8000/ on my browser, which shows the following result: enter image description here I tried all the solutions proposed on StackOverflow for similar problems. I tried running python manage.py runserver 0.0.0.0:8000 but it didn't change anything. I checked my port was listening using sudo nmap -sT -O localhost and the result was this: enter image description here but when running netstat -anv, I get this: enter image description here I even tried killing it using sudo lsof -t -i tcp:80 then kill -9 xxxx (with xxx being the pid). All my proxies are deactivated (see below) so I have no clue what's going. enter image description here I have been trying to resolve this issue for the past two days. I am a beginner in Django and would like to know what is going on. I have been reading all threads on the website but haven't found a solution that suits me. I am looking forward to your answer. Thank you!! -
Django migrations file missing
I have a Django project where I have an app 'create'.The 'showmigrations' are correct and app works fine. But I could not find the latest 0006_XXXX.py file to add and push to subversion(GIT). I tried faking back to the previous migration(0005_XXXX) and then 'migrate' to latest migration '0006_XXXX'. I can see 'Applying create.0006_XXXXX... OK' message in output. But the 0006_XXXX.py file is not getting created in 'create/migrations' directory. Any idea why the file is not created? -
Djagno: upload csv file and stays in memory
I'm trying to build a web app using Django where the user will upload some csv file, possibly a big one. Then the code will clean the file for bad data and then user can use it to make queries with clean data. Now I believe whenever a user will make a query, the whole code will run again which means it will start cleaning again and so on. Question: Is there any way that once the csv data in clean, it stays in memory and user can make queries to that clean data? import pandas as pd def converter(num): try: return float(num) except ValueError: try: num = num.replace("-", '0.0').replace(',', '') return float(num) except ValueError: return np.nan def get_clean_data(request): # Read the data from csv file: df = pd.read_csv("data.csv") # Clean the data and send JSON response df['month'] = df['month'].str.split("-", expand=True)[1] df[df.columns[8:]] = df[df.columns[8:]].astype(str).applymap(converter) selected_year = df[df["Departure Datetime: Year (YYYY)"] == 2015] data_for_user = (selected_year.groupby( by="route").sum().sort_values(by="revenue").to_json() return JsonResponse(data_for_user, safe=False) -
Djang template main.html didnot see user logged
hi i have a problem with login function in django ,when i loggin succes see when user is logged but main.html didnot . wiews def user_login(request): context = {} if request.method == "POST": username = request.POST['username'] password = request.POST["password"] user = authenticate(request,username=username,password=password) if user.is_authenticated: print("1") login(request, user) if request.GET.get('next',None): print("2") return HttpResponseRedirect(request.GET['next']) return HttpResponseRedirect(reverse('success')) else: print("3") context["error"] = "nieprawidlowe dane" return render(request,'auth/login.html',context) else: print("4") return render(request,'auth/login.html',context) @login_required(login_url="/login/") def success(request): c = {} c['user'] = request.user return render(request,'auth/success.html',c) and in here is succes and on this page django can see when user is logged {% extends 'main.html' %} {% block article %} <p>User <b>{{ user.username }}</b> jestes zalogowony</p> <form method="post" action="/logout/"> {% csrf_token %} <input type="submit" value="Logout"> </form> {% endblock %} but main.html didnot see user -
Django template language unpacking a dict
I have a dictionary passed (as part of another object) to the django template language. The object, called 'poll' has attributes self.text and self.votes, where the former is a string, and the latter is a dict. The dict, looks like this: {'a1': 45.92422502870264, 'a2': 53.50172215843857} I am trying to list each label, with its accompanying number, using the following: {% for l, x in poll.votes %} <p>{{ l }} {{ x }}</p> {% endfor %} Django responds with Exception Type: ValueError Exception Value: Need 2 values to unpack in for loop; got 3. I tried .iteritems - The docs explain that .iteritems is not the correct way to do this, but they don't explain what the correct way is. -
Django multiple database error
I have one Django project that contains a database with data that I need for another database. So, I found some code online and start using it. However, even the code is wrong or I’m doing it wrong. I’m guessing the latter. The database “reservation” is the “external’ database. I made models for those tables in the Django project which is going to import the data. I also give class Meta in the other database in “reservation”. The migration gave no errors and I did do: python manage.py migrate --database=reservation. I tried to get data from the “external’ database, however I keep getting the error: “no such table: res_room”. This is my settings file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'reservation': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(RES_DIR, 'db.sqlite3'), } } #Define the database manager to setup the various projects DATABASE_ROUTERS = ['app.router.DatabaseAppsRouter'] DATABASE_APPS_MAPPING = {'res': 'reservation'} This is my router: from django.conf import settings class DatabaseAppsRouter(object): def db_for_read(self, model, **hints): print("Facebook") print(model) """"Point all read operations to the specific database.""" if model._meta.app_label in settings.DATABASE_APPS_MAPPING: return settings.DATABASE_APPS_MAPPING[model._meta.app_label] return None def db_for_write(self, model, **hints): """Point all write operations to the specific database.""" if model._meta.app_label in settings.DATABASE_APPS_MAPPING: return settings.DATABASE_APPS_MAPPING[model._meta.app_label] … -
Python Relative Imports "Above Top Level"
This is my directory structure src\ dirCode\ dirSubCode\ test.py Django\ DjangoApp\ Home\ views.py From within views.py I'm trying to import a class (let's call it Main) from test.py. The line in test.py is simply from dirCode.dirSubCode.test import Main and I'm getting a ModuleNotFoundError when I try to run the server. I printed out the os.sys.path and the second entry points to 'src\' while the first entry is simply ''. Since this is not the only app from where I'm going to need to call "external" code I'm trying to avoid hard-coding sys.path.insert(0,'path\to\src\dirCode\dirSubCode\') if that would even work. I've tried looking through documentation, looking at other StackOverflow questions, etc. but I'm at a loss as to how to do this. I've tried going into the src\Django\DjangoApp\Home directory and just running a python console and simply trying to import the class but it's giving me the same error. One odd development that I'm running into is that when I try to run it from the Anaconda Prompt (yes, I'm running Windows) it doesn't work but when I run the file in PyCharm it does work. If that helps provide some insight as to what might be going on I'd appreciate the help. -
How can we configure Apache Solr-6 in Django-1.11.5?
Need to install and configure Apache Solr-6 in Django project. Currently using Solr-4.10.1, need to upgrade. -
Missing files in Django admin dashboard
I'm a newbie in Django and I have this problem. When I enter to my admin dashboard, css and js files aren't shown. When I follow the URL, it appears 404 Not Found. I'm using Nginx + Gunicorn. This is my Nginx configuration: server { server_name MYPROJECT.COM; access_log off; location /static { alias /opt/myenv/myenv/MYPROJECT/static/; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } Also this is settings.py static configuration: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") My css admin files are stored in/opt/myenv/myenv/MYPROJECT/static/admin , but also in /opt/myenv/myenv/static/admin I've uploaded the files in both directories and run collectstatic Can anyone help me? Thanks everyone! -
Using Ajax change state of a clicked button
I am building a page in a Django project which has multiple comments each of which can be liked/unliked with a button next to the text. So the page has multiple like/unlike buttons. The buttons display fine when the page is loaded, and I can use Ajax to send data to Django and update my database which works fine, and I can return data back to the Ajax success function. What I can't work out is - how can I update the status of the actual button which was clicked. I am able to update the status of all of the buttons together on the page as per the code below (pointless I know!), but can't see how I reference the clicked button. I've tried passing and then returning the button id which I can display in an alert, but not sure if this is what I should be using or where I go from here? HTML Template {% for comments in comments_page %} <p> <b>{{ comments.created_at }} ({{ comments.user_type }})</b> {% if comments.comment_liked is False %} <button class="comment btn btn-primary btn-xs" id={{ forloop.counter0 }} data-surveyid="{{ comments.id }}" data-commentliked="True" type="button"> <span class="glyphicon glyphicon-star-empty"></span> </button> {% else %} <button class="comment btn … -
Django Rest Framework - Marking extra actions for routing
I have the next view on my API class CapsuleViewSet(viewsets.ModelViewSet): queryset = Capsule.objects.all() serializer_class = CapsuleSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) @action(detail=True) def modules(self, request, pk=None): capsule = self.get_object() capsule_modules = Module.objects.filter(capsule=capsule) serializer = ModuleSerializer(capsule_modules, many=True) return Response(serializer.data) When i try to get all the modules related to a capsule, the URL of the imageField of a module is incomplete. When i call http://0.0.0.0:8000/api/capsules/1/ it returns: { "capsuleID": 1, "capsuleName": "sdfads", "capusuleDetails": "asdf", "capsuleImageURL": "http://0.0.0.0:8000/media/capsulas/logocitbm.png", "userStars": 0, "pallete": { "palleteID": 1, "palleteName": "Default smartraining", "colors": [ { "colorID": 1, "colorName": "A1", "colorCode": "#sdfs" }, { "colorID": 2, "colorName": "A2", "colorCode": "#dsfksdoif" }, { "colorID": 3, "colorName": "A3", "colorCode": "#sdjfjgioj" } ] } } but when i call http://0.0.0.0:8000/api/capsules/1/modules/ i get: [ { "moduleID": 1, "moduleName": "sdfa", "moduleDetails": "así", "moduleImageURL": "/media/modulos/9_-_4._Detalle_C%C3%A1psula.png", "userScore": 0 } ] the moduleImageURL is incomplete, why? these are my serializers: class CapsuleSerializer(serializers.ModelSerializer): pallete = PalleteSerializer(read_only=True) class Meta: model = Capsule fields = ('capsuleID', 'capsuleName', 'capusuleDetails', 'capsuleImageURL', 'userStars', 'pallete') class ModuleSerializer(serializers.ModelSerializer): class Meta: model = Module fields = ('moduleID', 'moduleName', 'moduleDetails', 'moduleImageURL', 'userScore') -
How do I post data to a django api endpoint using angularjs
i am trying to post data to my database from my html form through the api endpoint using angularjs? here's the angularjs code angular.module('myApp').config(function ($routeProvider) { $routeProvider.when('/userurl', {template : "<form>" + "<p>name:<input type='text' ng-model='myUser' value=''></p>" + "<input type='submit' value='add user' ng-click='postUser()'>" + "</form>" }); }); and here is the function i created for the ng-click to post the data angular.module('myApp').controller('myAppCtrl', function ($scope, $http) { $scope.postUser = function () { $http({ url : "http://127.0.0.1:8000/users/", method: "POST", data : { username : $scope.myUser }, headers : {'Content-Type' : 'application/json', 'Accept':'application/json'} }).then(function onSuccess(response) { console.log(response); }).catch(function onError(error) { console.log(error); }); }; }); -
Connecting to MySQL with Django caching_sha2_password cannot be loaded
I had this error when I originally used my localhost for the Django application I am working on. I am now getting it when I am trying to connect to a new server. I cannot remember what I did to fix it. Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x031F1E88> Traceback (most recent call last): File "C:\Users\LL67773\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection self.connect() File "C:\Users\LL67773\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\base\base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\LL67773\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\mysql\base.py", line 236, in get_new_connection return Database.connect(**conn_params) File "C:\Users\LL67773\AppData\Local\Programs\Python\Python36-32\lib\site-packages\MySQLdb\__init__.py", line 86, in Connect return Connection(*args, **kwargs) File "C:\Users\LL67773\AppData\Local\Programs\Python\Python36-32\lib\site-packages\MySQLdb\connections.py", line 204, in __init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: The specified module could not be found.\r\n") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\LL67773\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\LL67773\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "C:\Users\LL67773\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "C:\Users\LL67773\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\LL67773\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\LL67773\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\model_checks.py", line 27, in check_all_models errors.extend(model.check(**kwargs)) File "C:\Users\LL67773\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 1200, in check errors.extend(cls._check_fields(**kwargs)) File "C:\Users\LL67773\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 1272, in _check_fields errors.extend(field.check(**kwargs)) File "C:\Users\LL67773\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\fields\__init__.py", line 894, in check errors … -
Interval in Django template
I have an interval type field that contains hours and minutes in this format: "28:00". But in my template, it is translated to "1 day, 4:00:00" How can I keep this "28:00" in my template? My template: <table class="table table-bordered "> <thead align="center"> <th class="text-center" scope="col">User</th> <th class="text-center" scope="col">Week number</th> <th class="text-center" scope="col">Total H</th> </thead> <tbody> {% for tp in resume_h %} <tr scope="row"> <td class="text-center col-md-1">{{ tp.user_name }}</td> <td class="text-center col-md-1">{{ tp.num_semaine }}</td>> <td class="text-center col-md-1">{{ tp.hours_total|linebreaksbr }}</td> </tr> {% endfor %} </tbody> </table> My model: class hours(models.Model): user_name = models.CharField(max_length=50, blank=True, null=True) num_semaine = models.IntegerField(("No:"),blank=True, null=True) hours_total = models.TimeField(("H"),blank=True, null=True) def __str__(self): return str(self.user_name) Thank you -
Unable to send variable from views to html python
Am Unable to sent the temp_k variable from my views to index.html. I have made a request from weather API and trying to pass it to my html. Please suggest how we are supposed to send the variable from views to template. views.py from django.template.loader import render_to_string import requests from django.shortcuts import render from django.http import HttpResponse def hello(request): my_dict = {'insert_me': "From andu.py"} return render(request, 'mywebapp/index.html', context=my_dict) def temperature(request): #zip=requests.form['zip']ss r=requests.get('http://samples.openweathermap.org/data/2.5/weather?zip=94040,us&appid=b6907d289e10d714a6e88b30761fae22') json_object=r.json() my_dict1={'temp_k' :json_object['main']['temp']} return render(request,'mywebapp/index.html', context=my_dict1) index.html <!DOCTYPE html> {% load staticfiles%} <html lang="en"> <head> <meta charset="UTF-8"> <title>Hey</title> <link rel="stylesheet" href={% static "cs/style.css" %}/> </head> <body> <h1>This is the Header</h1> <img src="{% static "images/youownme.jpeg" %}" atl="Uh Oh"> <h2> Temperature:{{temp_k}}</h2> </body> </html> -
Django on_delete SET_NULL not working
I have models set up like so: class User email = models.EmailField(unique=True) class Store owner = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) My expectation is that the on_delete=models.SET_NULL means that if a User is deleted, the Store will not be deleted. However, this suspicion is not confirmed by my tests (see below). Can someone help explain my misunderstanding? And yes, I did run migrations before doing my tests! This first test tests whether the deletion of a Store leads to the deletion of a User, which should not be the case. This test passes as expected. def test_delete_store(self): self.store.delete() with self.assertRaises(Store.DoesNotExist): Store.objects.get(pk=self.store.pk) self.assertEqual(User.objects.get(pk=self.user.pk), self.user) The following test tests whether the deletion of a user leads to the deletion of the store. The second assert in this test FAILS. def test_delete_user_deletes_store(self): self.user.delete() with self.assertRaises(User.DoesNotExist): User.objects.get(pk=self.user.pk) # Check that store is not deleted (this unexpectedly raises a DoesNotExist error) self.assertEqual(Store.objects.get(pk=self.store.pk), self.store) -
Django organization app & models
I'm beginner in python and django (but i have 5 years experience in php, with a enterprise framework). I make a web site who have two clearly separated front office. When you come on the home page you have to choose witch part of the site you want. So i had choose to make two app like this : website |context.py |settings.py |etc. |front1 |models.py |view.py |urls.py |etc. |front2 |models.py |view.py |urls.py |etc. My problem is I need a model [customer] who will used by the two app. So, where i have to put it ? I had try to add a models.py in website's directory but django ignore it. Is it possible ? Maybe two apps for that is not a good idea ? Thanks ! ps: use simple and clear english please because is not my mother tongue, thanks a lot. -
Python Django Ubuntu Server 16.04 aws Internal Server Error
Hi so I am trying to deploy my portfolio to Ubuntu Server 16.04 but I keep getting internal server error. To walk through what i have done i created the instance and changed the HTTP and HTTPs security settings to anywhere. After that i launched the instance then running these commands ubuntu@54.162.31.253:~$ sudo apt-get update ubuntu@54.162.31.253:~$ sudo apt-get install python-pip python-dev nginx git ubuntu@54.162.31.253:~$ sudo apt-get update ubuntu@54.162.31.253:~$ sudo pip install virtualenv ubuntu@54.162.31.253:~/myRepoName$ virtualenv venv --python=python3 ubuntu@54.162.31.253:~/myRepoName$ source venv/bin/activate (venv)ubuntu@54.162.31.253:~/myRepoName$ pip install -r requirements.txt (venv) ubuntu@54.162.31.253:~/myRepoName$ pip install django bcrypt django-extensions (venv) ubuntu@54.162.31.253:~/myRepoName$ pip install gunicorn i edited the settings.py # Inside settings.py # modify these lines DEBUG = False ALLOWED_HOSTS = ['{{yourEC2.public.ip}}'] # add the line below to the bottom of the file STATIC_ROOT = os.path.join(BASE_DIR, "static/") then run, (venv) ubuntu@54.162.31.253:~myRepoName$ python manage.py collectstatic followed by, ubuntu@54.162.31.253:~myRepoName$ sudo vim /etc/systemd/system/gunicorn.service where I add [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/{{repoName}} ExecStart=/home/ubuntu/{{repoName}}/venv/bin/gunicorn --workers 3 -- bind unix:/home/ubuntu/{{repoName}}/{{projectName}}.sock {{projectName}}.wsgi:application [Install] WantedBy=multi-user.target followed by a gunicorn reboot ubuntu@54.162.31.253:~$ sudo systemctl daemon-reload ubuntu@54.162.31.253:~$ sudo systemctl start gunicorn ubuntu@54.162.31.253:~$ sudo systemctl enable gunicorn finally, ubuntu@54.162.31.253:~$ sudo vim /etc/nginx/sites- available/{{projectName}} adding server { listen 80; server_name {{yourEC2.public.ip}}; location = /favicon.ico { access_log off; log_not_found …