Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Migrations ends up inside virtual environment?
installed djang-carrot package, added it to installed apps and ran python manage.py makemigrations, but the migrations ended up inside the virtual environment... Why is that? $ python manage.py makemigrations carrot Migrations for 'carrot': venv/lib/python3.6/site-packages/carrot/migrations/0001_initial.py - Create model MessageLog - Create model ScheduledTask The problem is, as the virtual environment is not checked in to source controll I cannot check in the migration, which normally how things are done in Django. What's the thought here? What I'm I doing wrong? -
How can i pass one variable from a method to another method using same class?
How can i get variable qid in the 2nd method(form) from 1st method(contect_data). now i getting error : NameError: name 'tmp' is not defined class AnswerView(FormView): template_name = 'answer.html' form_class = AnsForm success_url='success' def get_context_data(self, *args, **kwargs): context = super(AnswerView,self).get_context_data(**kwargs) qid = self.kwargs['qid'] print(qid) self.qid=qid q_obj = Quest.objects.get(id=qid) context['question'] = q_obj return context def form_valid(self, form): answ1 = form.cleaned_data['txta'] tmp = self.get_context_data().qid obj4=Ans.objects.create(answer=answ1,status=0,questid=tmp) obj4.save() return super().form_valid(form) -
Foreign Key Fields creating new objects instead of creating links
I am trying to create an object with Foreign Keys, and it appears to be working when creating the object, but when I get the object from the database the keys appear to have incremented from the previous instance. @csrf_exempt @api_view(['POST']) def StartGame(request) : card = Card.objects.create(game_id = 1, cardType = 1, owner_id = 1) return JsonResponse({ "card": serializers.serialize('json', [card])}) For testing, I am just running this code. When I make a call to this view I get the following JSON Response. "card": "[{\"model\": \"Billionapp_App.card\", \"pk\": 150, \"fields\": {\"owner\": 1, \"game\": 1, \"cardType\": 1, \"trade\": null}}]" However, if I query just that object now by going to its url I get the following response: { "url": "http://127.0.0.1:8000/card/150/", "owner": "http://127.0.0.1:8000/profile/150/", "game": "http://127.0.0.1:8000/game/150/", "cardType": 1, "trade": null } Where I am expecting the game and owner to be 1 (instead of 150). I have tried getting the game and owner and using those instead of game_id and owner_id as the following: Card.objects.create(game = Game.objects.get(id = gameId), cardType = card.cardType, owner = Profile.objects.filter(id = profileId)) And had the same problem. This is the model: class Card(models.Model) : owner = models.ForeignKey(Profile, related_name = "cards", on_delete = models.CASCADE) game = models.ForeignKey(Game, related_name = "cards", on_delete … -
apache2 (mod_wsgi-express): Syntax error
I accidentally deleted the virtual environment from the apache server holding my Django website. I created new virtual env and reinstalled everything on the server but when I try to restart the server using command: sudo /etc/mod_wsgi-express-80/apachectl restart I get the error: apache2 (mod_wsgi-express): Syntax error on line 155 of /etc/mod_wsgi-express-80/httpd.conf: Cannot load /www/site_name/venv/lib/python3.5/site-packages/mod_wsgi/server/mod_wsgi-py35.cpython-35m-x86_64-linux-gnu.so into server: /www/site_name/venv/lib/python3.5/site-packages/mod_wsgi/server/mod_wsgi-py35.cpython-35m-x86_64-linux-gnu.so: cannot open shared object file: No such file or directory I checked the venv/lib/python3.5/site-packages/ folder and there is no folder named mod_wsgi in it. Should I create the folder manually? I am new to server handling and am not sure weather this is right solution. (Earlier I had done a git clean -fd which deleted the virtual env from the server ending up in this situation.) A piece of /etc/mod_wsgi-express-80/httpd.conf looks like this: (line 155 being the line starting with "LoadModule.." ) <IfModule mpm_prefork_module> <IfDefine MOD_WSGI_WITH_PHP5> <IfModule !php5_module> Loadmodule php5_module '${MOD_WSGI_MODULES_DIRECTORY}/libphp5.so' </IfModule> AddHandler application/x-httpd-php .php </IfDefine> </IfModule> LoadModule wsgi_module '/www/site_name/venv/lib/python3.5/site-packages/mod_wsgi/server/mod_wsgi-py35.cpython-35m-x86_64-linux-gnu.so' <IfDefine MOD_WSGI_SERVER_METRICS> <IfModule !status_module> LoadModule status_module '${MOD_WSGI_MODULES_DIRECTORY}/mod_status.so' </IfModule> </IfDefine> Please help! -
Unhandled exception in thread started by <function wrapper at 0x7f8c05fc8a28>
nandu@nandu-Lenovo-ideapad-320-15IKB:~/Django$ cd newproject nandu@nandu-Lenovo-ideapad-320-15IKB:~/Django/newproject$ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function wrapper at 0x7f8c05fc8a28> Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 116, in inner_run self.check_migrations() File "/usr/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 168, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/usr/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 19, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 47, in __init__ self.build_graph() File "/usr/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 191, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/lib/python2.7/dist-packages/django/db/migrations/recorder.py", line 59, in applied_migrations self.ensure_schema() File "/usr/lib/python2.7/dist-packages/django/db/migrations/recorder.py", line 49, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/usr/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 162, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/usr/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 135, in _cursor self.ensure_connection() File "/usr/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 130, in ensure_connection self.connect() File "/usr/lib/python2.7/dist-packages/django/db/utils.py", line 98, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 130, in ensure_connection self.connect() File "/usr/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 119, in connect self.connection = self.get_new_connection(conn_params) File "/usr/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py", line 204, in get_new_connection conn = Database.connect(**conn_params) django.db.utils.OperationalError: unable to open database file -
Django: pre_save & request
I have a pre_save function and want to get the session_id with session_order_id = request.session['order_id’] The problem I am currently facing is that I am always getting the error name 'request' is not defined. Does anyone know how I can fix that? Or is it possible to pass this variable form my views.py as a kwarg? (I just couldn’t figure out how.) class TransactionProfile(models.Model): [...] def transaction_profile_pre_save_receiver(sender, instance, *args, **kwargs): session_order_id = request.session['order_id’] o = Order.objects.get(order_id=session_order_id) o.transaction_profile = instance Marc -
Django - using model manager method in Admin filter
I'm using Django 2.0 I have a model class with custom Manager in models.py class MockTestQuerySet(models.query.QuerySet): def upcoming(self): return self.filter(start_date__gte=datetime.now()) def past(self): return self.filter(end_date__lte=datetime.now()) class MockTestManager(models.Manager): def get_queryset(self): return MockTestQuerySet(self.model, self._db) def upcoming_tests(self): return self.get_queryset().upcoming() def past_tests(self): return self.get_queryset().past() def is_past(self, mock_pk): mock_test = self.get_queryset().past().filter(pk=mock_pk).first() if mock_test is not None: return True return False def is_future(self, mock_pk): mock_test = self.get_queryset().upcoming().filter(pk=mock_pk).first() if mock_test is not None: return True return False class MockTest(models.Model): title = models.CharField(max_length=250, null=False, blank=False) start_date = models.DateTimeField() end_date = models.DateTimeField() modified = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) objects = MockTestManager() class Meta: db_table = 'mock_tests' ordering = ['start_date'] Now, I'm working on Admin module and want to create filter which filters upcoming or past tests by calling past_tests() or upcoming_tests() Till now, I have tried this in admin.py class InPast(admin.SimpleListFilter): def lookups(self, request, model_admin): pass title = _('Past Mock Tests') parameter_name = 'past' def queryset(self, request, queryset): return queryset.past_tests() @admin.register(MockTest) class MockTestAdmin(admin.ModelAdmin): list_display = ['title', 'start_date', 'end_date', 'duration'] list_filter = [ InPast ] I know, I'm doing it wrong but could not figure out how to do it. -
`django.db.models.Model` replaced `django.db.models.base.Model`
When I configue a model: from django.db import models class Topic(models.Model): """A topic the user is learning about."""" text = models.charField(max_length=200) data_added = models.DateTimeField(auto_now_add=True) The path of class Model is django.db.models.Model However,it's true path is django.db.models.base.Model from module django/django/db/models/base.py django/base.py The base level is jumped. How Django achieve it? -
Compressed jQuery File Causing Content Security Policy Error in Chrome
I have a hosted jquery file that I'm compressing using django compressor and serving via cloudflare. Compression looks like this: {% compress js %} <!-- JavaScript --> <script type="text/javascript" src="{% static 'js/jquery-3.1.1.js' %}"> </script> {% endcompress %} I'm getting an error in Chrome console tools that says this: jquery.js:39 Refused to execute inline script because it violates the following Content Security Policy directive: "script-src https:". Either the 'unsafe-inline' keyword, a hash ('sha256-bksOHsIG1boMjydqSfvQ5M7P7lTKHlinbm+hRfOd128='), or a nonce ('nonce-...') is required to enable inline execution. after searching around here i see that you can add some meta tags when loading an external js source...but how about in this case of a compressed file? -
How do I configure Apache using pip install mod_wsgi? (Invalid command 'WSGIScriptAlias')
In the process of getting my Django app running in production, I became aware that apt-get mod_wsgi didn't install the correct version of mod_wsgi. And the advice was to pip install mod_wsgi in my virtual environment. I'm running an AWS Small Ubuntu 16.04.4 LTS server and Python 3.5. My virtual environment is /usr/local/pulseenv and contains mod-wsgi 4.6.4. My vhost file (/etc/apache2/sites-available/000-default.conf) has: <VirtualHost *:80> ServerAdmin webmaster@localhost #DocumentRoot /var/www/html DocumentRoot /var/www/pulsemanager/pulsemanager Alias /static /var/www/pulsemanager/pulsemanager/static <Directory /var/www/pulsemanager/pulsemanager/static> Require all granted </Directory> <Directory /var/www/pulsemanager/config> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /var/www/pulsemanager/config/wsgi.py #WSGIDaemonProcess pulsemanager WSGIPythonHome /usr/local/pulseenv WSGIPythonPath /var/www/pulsemanager #WSGIProcessGroup pulsemanager WSGIApplicationGroup %{GLOBAL} </VirtualHost> But when I try to start apache, I get this error: ubuntu@ip-172-31-84-213:~$ systemctl status apache2.service ● apache2.service - LSB: Apache2 web server Loaded: loaded (/etc/init.d/apache2; bad; vendor preset: enabled) Drop-In: /lib/systemd/system/apache2.service.d └─apache2-systemd.conf Active: failed (Result: exit-code) since Fri 2018-05-04 01:35:16 UTC; 13s ago Docs: man:systemd-sysv-generator(8) Process: 6697 ExecStart=/etc/init.d/apache2 start (code=exited, status=1/FAILURE) May 04 01:35:16 ip-172-31-84-213 apache2[6697]: * The apache2 configtest failed. May 04 01:35:16 ip-172-31-84-213 apache2[6697]: Output of config test was: May 04 01:35:16 ip-172-31-84-213 apache2[6697]: AH00526: Syntax error on line 42 of /etc/apache2/sites-enabled/000-default.conf: May 04 01:35:16 ip-172-31-84-213 apache2[6697]: Invalid command 'WSGIScriptAlias', perhaps misspelled or defined by a … -
positional arguments celerybeat scheduling error
I'm having trouble getting celerybeat to schedule my function due to positional arguments. reading the documentation I don't understand why some functions refer to a number and some don't. I've tried to add in the args as the same as my functions but I get the following error check_arguments(*(args or ()), **(kwargs or {})) celery.beat.SchedulingError: Couldn't apply scheduled task list_market_catalogue: list_market_catalogue() takes 1 positional argument but 3 were given Can anyone point me in the right direction? tasks.py ET_TENNIS = 2 @shared_task(bind=True) def list_market_catalogue(self): logger.warning('+' * 80) trading = get_betfair_client() time_ago = timezone.now() + datetime.timedelta(minutes=1000) time_fwd = timezone.now() + datetime.timedelta(minutes=6000) mfilter = market_filter( event_type_ids=[ET_TENNIS] , market_start_time=time_range( from_=time_ago.strftime('%Y-%m-%dT%H:%I:%S.000Z') , to=time_fwd.strftime('%Y-%m-%dT%H:%I:%S.000Z') ) ) res = trading.betting.list_market_catalogue( mfilter , market_projection=[ 'EVENT' , 'MARKET_START_TIME' , # 'MARKET_DESCRIPTION', # 'RUNNER_METADATA', ] , sort='FIRST_TO_START' , max_results=100 , lightweight=True) if not len(res): logger.error('Market catalogue listing is empty') trading.session_token = None raise self.retry(countdown=5 , max_retries=12) for cat in res: if 'venue' not in cat['event']: logger.error(f'No event venue in {cat}') continue try: event = parse_event(cat['event']) market = parse_market(event , cat) runners = parse_runners(market , cat['runners']) except: logger.warning(cat) raise logger.warning(f'BETFAIR: Scraped {len(res)} from market catalogue') @shared_task def parse_event(event: object) -> object: """Parses event from Event object""" event , created = … -
Django not reading my HTML with CSS
I'm not a web developer but however, I'm in a project where we want to deploy a Django web app based in HTML and CSS front end. We have deployed an HTML code that looks like : Unfortunately, when we deploy this in a login template for Django the fancy model is screwed up we get: Check out my code here: https://jsfiddle.net/Andres/hmpbkc9n/# -
transaction.atomic function blocks other operation of writing of different table?
I am working on django-postgres. I have two functions working simultaneously, FuncA is @transaction.atomic to write to a Table A; while another FuncB is to update another Table B. Table A model has the ForeignKey of Table B model as below: Table A: id x y B_id 1 1 1 valueB 2 1 2 valueB ... Table B: id z valueB some_value FuncA is to update the x,y, and B_id; Func B is to update z. And I noticed that Func B has to wait for the Func A finished to continue. Is that normal? Is that how transaction.aotmic works? Is there a way I can avoid the waiting? (besides the way of removing @transaction.atomic) Thanks! -
Django - Models - Custom User who Inherites from built-in User
I created CustomUser field and CustomUser has foreign key with built-in User. class CustomUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) website = models.URLField(blank=True) def __str__(self): return self.user.username In .html (template) I wish to call to website variable, like: {{user.website}}. Unfortunately it doesn't work, but {{user}} and {{user.username}} works, what the hack? Apparently I don't understand smth. Another issue is that I want to have relationship with Post by User, so inside template .html I want to show specific user and his all posts :( I built already Post model, but I don't know how to call to specific user's posts. I am sure if you can explain how to call to "website", I will do the same to pots/user. -
How Django retreive the varialbe `__all__`
In django/django/db/models/fields/__init__.py django/init.py There's varialbe: __all__ = [ 'AutoField', 'BLANK_CHOICE_DASH', 'BigAutoField', 'BigIntegerField', 'BinaryField', 'BooleanField', 'CharField', 'CommaSeparatedIntegerField', 'DateField', 'DateTimeField', 'DecimalField', 'DurationField', 'EmailField', 'Empty', 'Field', 'FieldDoesNotExist', 'FilePathField', 'FloatField', 'GenericIPAddressField', 'IPAddressField', 'IntegerField', 'NOT_PROVIDED', 'NullBooleanField', 'PositiveIntegerField', 'PositiveSmallIntegerField', 'SlugField', 'SmallIntegerField', 'TextField', 'TimeField', 'URLField', 'UUIDField', ] How Django retreive the varialbe __all__,? fields.__init__.__all__ or fields.__all__ -
Gunicorn --bind Error
I'm using Ubuntu 14.04 with Django 2.0.5. I am trying to start a Django server on DigitalOcean and i'm validating whether out not gunicorn works, but it doesn't. Following this guide: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-debian-8 This is is my terminal error when I run gunicorn --bind 0.0.0.0:8000 application.wsgi:application root@django-manaland:/home/django/manaland# gunicorn --bind 0.0.0.0:8000 application.wsgi:application [2018-05-04 00:03:02 +0000] [13969] [INFO] Starting gunicorn 19.4.5 [2018-05-04 00:03:02 +0000] [13969] [INFO] Listening at: http://0.0.0.0:8000 (13969) [2018-05-04 00:03:02 +0000] [13969] [INFO] Using worker: sync [2018-05-04 00:03:02 +0000] [13973] [INFO] Booting worker with pid: 13973 [2018-05-04 00:03:02 +0000] [13973] [ERROR] Exception in worker process: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 515, in spawn_worker worker.init_process() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 122, in init_process self.load_wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 130, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python2.7/dist-packages/gunicorn/util.py", line 366, in import_app __import__(module) ImportError: No module named application.wsgi Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 515, in spawn_worker worker.init_process() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 122, in init_process self.load_wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 130, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 65, … -
related objects queries django rest framework
I have the following models class STUser(AbstractBaseUser): email = models.EmailField(unique=True) name = models.CharField(max_length=255) companyname = models.CharField(max_length=200, blank=True, null=True) ... class VenuePermissions(models.Model): user = models.ForeignKey(STUser, on_delete=models.CASCADE) venue = models.ForeignKey(Venue, on_delete=models.CASCADE, blank=True, null=True) signupvaildatestring = models.CharField(max_length=200, blank=True, null=True) ... I want to grab all the STUser objects and grab all their permissions. So what I would like is to grab all the VenuePermissions objects. And grab the user and venue object of each venuePermission Two ways I can do this. use the VenuePermissions_set attribute on STUser but then how do I grab the venue when its just going to be a pk value? Or focus on the VenuePermissions objects and grab the user and venue from the pk values but how? I remember nested queries, and I kinda did one in my browse code. here is an example: rooms = Room.objects.filter(venue=OuterRef('pk'), sixtyroundseatingoption= True) venuelist = venuelist.annotate(sixtyrounds=Exists(rooms)) venuelist = venuelist.filter(Q(sixtyrounds = True) | Q(fullbuyoutsixtyroundseatingoption = True)) I've done the set objects in a serializer before Example serializer: class RoomAndImageSerializer(serializers.ModelSerializer): roomimage_set = RoomImageSerializer(many=True, read_only=True) class Meta: model = Room fields = ('pk','name') any help with this query would be appreciated! -
apache2 error log. Call to 'site.addsitedir()' failed for '(null)', stopping
I would like to connect Python and Apache 2 server in Ubuntu. So aws have to enter the following code ubuntu server. pip install Django sudo apt-get install appache2 sudo apt-get install libapache2-mod-wsgi-py3 Then I created the Python project and the app folder as Python venv. The code for Apache 2 000-default.conf looks like this: <virtualhost *:80> WSGIDaemonProcess bot python-path=/home/ubuntu/Django/bot:/home/ubuntu/Django/myvenv/lib/python3.5/site-packages ServerAdmin webmaster@localhost WSGIScriptAlias /52.78.108.223 /home/ubuntu/Django/bot/wsgi.py <Directory /home/ubuntu/Django/bot> <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </virtualhost> The location is correct. There is no typing miss. The first argument to 'WSGIScriptAlias /' should be blank, but if you put it in a blank space, you will not see the 'it walked' page when you hit that IP. So I put the external IP of the server. Then it walked well. Looking at the Apache 2 error log. [Wed May 02 21:32:28.100569 2018] [wsgi:warn] [pid 22648:tid 140282945054592] mod_wsgi: Compiled for Python/3.5.1+. [Wed May 02 21:32:28.100633 2018] [wsgi:warn] [pid 22648:tid 140282945054592] mod_wsgi: Runtime using Python/3.5.2. [Wed May 02 21:32:28.101406 2018] [mpm_event:notice] [pid 22648:tid 140282945054592] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/3.5.2 configured -- resuming normal operations [Wed May 02 21:32:28.101426 2018] [core:notice] [pid 22648:tid 140282945054592] AH00094: Command line: '/usr/sbin/apache2' [Wed May … -
In Django, how to annotate a queryset with the string representation each object?
I'm working on a view which inherits from Django's ListView and uses a search form through a SearchMixin. Here is the (simplified) view: class ListBase(DashboardAccessMixin, SearchMixin): queryset = CheckInType.objects.all() def get_queryset(self): queryset = super().get_queryset() query = self.search_data('q') if query: queryset = queryset.filter( Q(title__icontains=query) | Q(description__icontains=query)) return queryset class CheckInTypeList(ListBase, ListView): template_name = 'check_in_types/index.html' The template, however, does not actually show the {{ object.title }}, but shows just {{ object }}, which corresponds to the string representation of the CheckInType. This is defined as follows: class CheckInType(TimeStampedModel, TimingMixIn): title = models.CharField(blank=True, max_length=255) description = models.TextField(blank=True) # Timing is_prenatal = models.BooleanField(default=False) min_weeks = models.IntegerField(default=0) max_weeks = models.IntegerField(default=0) def __str__(self): if self.title: return self.title else: prenatal = 'Prenatal' if self.is_prenatal else 'Postpartum' return f'{prenatal} Check-In: {self.timing}' I'll omit the details of the TimingMixin for brevity, but self.timing is basically a string like "0-4 weeks" composed from the min_weeks and max_weeks fields. The result of this, however, is that the filtering does not exactly correspond to what the user sees. Consider this example: Here, the first entry in the list entitled "Postpartum Check-In: 0 weeks" is an automatically generated 'title'. So if I search for "Postpartum" in the search bar and press Enter, I … -
My view to login keeps saying that "User with this Email already exists."
I have a customized User model class User(AbstractBaseUser): email = _models.EmailField (max_length=252, unique=True) username = _models.CharField (max_length=252, blank=True, null=True) staff = _models.BooleanField (default=False) superuser = _models.BooleanField (default=False) active = _models.BooleanField (default=True) This is the form class UserLoginForm(_f.ModelForm): password = _f.CharField(widget=_f.PasswordInput()) class Meta: model = User fields = ['email', 'password'] And this is the view from django.contrib.auth import authenticate, login from django.views.generic import FormView, from .forms import UserRegistrationForm, UserLoginForm class UserLoginView(FormView): form_class = UserLoginForm success_url = '/' template_name = 'accounts/user_login.html' def form_valid(self, form): email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = authenticate(request=self.request, email=email, password=password) if user: login(self.request, user) return super(UserLoginView, self).form_valid(form) return super(UserLoginView, self).form_invalid(form) After registrating as new user, the user is redirected to the login page, with the credentials, the login keeps saying "User with this Email already exists." Note: The email field on the model User is unique. Is obvious that the login page is trying to make another registration somehow, and this "somehow" is what it's confusing me. What could I possibly be doing to solve this "User with this Email already exists."? -
How to change the display of Django admin when use ManyToManyField
I'm coding a news website.News model has a ManyToManyField foreign key named tag. Here is my News model: class News(models.Model): title = models.CharField(max_length=100, verbose_name='title') category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="cate", blank=True, verbose_name='Category') tag = models.ManyToManyField(Tag, blank=True, verbose_name='Tags') class Meta: verbose_name = "新闻" verbose_name_plural = verbose_name def __str__(self): return self.title Here is my tag model: class Tag(models.Model): name = models.CharField(max_length=40) class Meta: verbose_name = "Tag" verbose_name_plural = verbose_name def __str__(self): return self.name Now I find a issue is, in the admin, the display of tag menu window is too small as this screen shot: However in practical projects for example a high traffic news website, there will be dozens of tags or maybe nearly 100 tags need to, it is really hard and frustrated to select a tag among so many tags in such a small menu window. So is any good idea can make it easier?By the way I'm using Xadmin. I think maybe I should change the css of that place. Any friend can help?Thank you so much! -
How do I test a component in my django application that reaches to an external service?
I have a method that reaches out to an external API and pulls in some content, then it performs some logic and proceeds. The problem is, while testing, I don't want my test cases to trigger this external API but I do want it to mock the response. Example def create_animals(candidate): if ExternalService.get_candidate_validity(candidate): print('Things are good, go ahead') #creates the animal objects etc.... But ExternalService.get_candidate_validity reaches out to an API that I want to mock. I know I can mock instances if it's like this: get_candidate_validity_value = {'response': True} c = ExternalService('someparamsthatineed') c.get_candidate_validity = MagicMock(return_value=get_candidate_validity_value) But how do I handle cases where the class is instantiated in a method that I end up calling to test? -
I can not get the data type when passing to a method
I begin study Django ORM and faced with problem, how transfer querset a field to other a method? I'm need add new filed in each queryset object, Before this, get the coordinates and transfer to check_coorinates method. But in check_coorinates method I get only type . How in 'check_coorinates' method get .int type, transfered from get_queryset? def check_coorinates(lat, long): #other field print(type(lat)) #Get <str> type def get get_queryset(self): get_cinema = Cinema.object.get(active=t) queryset = get_cinema.annotate(distance=models.Max(self.check_coorinates(F('lat)', F('long')), output_field=models.FloatField()) Model Cinema is contains fields: land and long -
Unable to create the django_migrations table (database is locked) error when creating sqlite from scratch
I am trying to deploy an update to a Django project as part of that update i want to create a new (sqlite3) DB. So I deleted my current DB and all of the migrations that had been created during early testing. Then I ran manage.py mikemigrations with no issue. But when i ran manage.py migrate I started getting the following error. Unable to create the django_migrations table (database is locked) my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db1.sqlite3'), } } full message: Operations to perform: Apply all migrations: account, admin, auth, contenttypes, people, sessions, sites, socialaccount Running migrations: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/base.py", line 239, in _commit return self.connection.commit() sqlite3.OperationalError: database is locked The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/recorder.py", line 55, in ensure_schema editor.create_model(self.Migration) File "/usr/local/lib/python3.5/dist-packages/django/db/backends/sqlite3/schema.py", line 28, in exit super().exit(exc_type, exc_value, traceback) File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/schema.py", line 92, in exit self.atomic.exit(exc_type, exc_value, traceback) File "/usr/local/lib/python3.5/dist-packages/django/db/transaction.py", line 212, in exit connection.commit() File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/base.py", line 261, in commit self._commit() File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/base.py", line 239, in _commit return self.connection.commit() File "/usr/local/lib/python3.5/dist-packages/django/db/utils.py", line 89, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/base.py", line 239, in _commit return … -
Django Query Best Practices
I have been having a difficult time finding a relevant example within the Django documentation or a similar example online about how to most efficiently query the below models. These models store data about sales employees, their teams, their weekly goals, and their actual production. class Employee(models.Model): employee_id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) email = models.EmailField() status = models.CharField(max_length=100) class Team(models.Model): name = models.CharField(primary_key=True,max_length=100) manager = models.ForeignKey(Employee, on_delete=models.CASCADE) status = models.CharField(max_length=100) start_date = models.DateField() end_date = models.DateField() class TeamMembers(models.Model): team_name = models.ForeignKey(Team, on_delete=models.CASCADE) employee_id = models.ForeignKey(Employee, on_delete=models.CASCADE) status = models.CharField(max_length=100) start_date = models.DateField() end_date = models.DateField() class Goal(models.Model): employee_id = models.ForeignKey(Employee, on_delete=models.CASCADE) goal = models.DecimalField(max_digits=6, decimal_places=2) start_date = models.DateField() end_date = models.DateField() class Production(models.Model): employee_id = models.ForeignKey(Employee, on_delete=models.CASCADE) week = models.DateField() quantify = models.DecimalField(max_digits=6, decimal_places=2) Given a prompted date range I would like to display a page with a table for each team, the team members during that range (teams can change members), and their performances against their goals (goals can change weekly) as such: Time Period: 4/1/2018 - 4/28/2018 TEAM EAST Week 4/1 Week 4/7 Team Member Goal Actual Goal Actual Joe 1000 1100 900 750 Mel 750 600 650 650 TEAM WEST Week 4/1 Week 4/7 Team Member …