Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, inline and nested, formsets in a single form
A part the broader problem of a great and mature framework not fully complete at some of its edges ( but this is mostly a rant...), my current issue is not with inline formsets but with inline nested formsets. For example: 1) a warehouse registration heading, with: number, date, type, etc. 2) several related articles (1 to many), with: code, upload/download flag; 3) several line items related to the article (1 to many): quantity, volume of container, identification of container, etc. So two levels of relationships to be maintained through a single form, that is: created and updated. Should I keep trying with something like: https://www.yergler.net/2013/09/03/nested-formsets-redux/, which the author itself warns to be careful at, or should I think of implementing just this form in Vue, let’s say, and use Django only as a backend engine? -
Replicate databases within AWS RDS
I have two database (db1) and (db2) created in one Postgres RDS, Is it possible to configure one as master and another as a slave to replicate data. -
Fields not sent in POST for ModelForms are overwritten as blank values
Just realised that we have been silently losing data on our web platform because some of the fields in the ModelForm are hidden in some contexts and not being sent in the POST request. As a result, these fields were being overwritten as blank values and erasing the previous value. (Thank God, we use django-reversion to track changes, though we need to spend some time to recover the data). I saw this old post on django-developers group that discusses exactly this issue. Has anyone been able to figure out a good work around for this yet (apart from not using Model Forms) so that fields that are not sent in the POST request in ModelForms remain untouched? (Note that we do need these fields in the Meta class in the ModelForm since they are used in some contexts but not all) -
Django in shared hosting/cpanel
hey guys i have the issue with my django app so what should i do?i have shared hosting account on which i am trying to upload my django app, please help this is the code of .htaccess file DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN PassengerAppRoot "/home/dasawork/store" PassengerBaseURI "/test" PassengerPython "/home/dasawork/virtualenv/store/3.5/bin/python3.5" # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END it worked at night first and then in the morning it wasn't working and giving the error "/home/dasawork/public_html/test/.htaccess: Invalid command 'PassengerAppRoot', perhaps misspelled or defined by a module not included in the server configuration". hosting providers changed my root dir name! like when it worked it was "'/newhome/dasawork/...." but on the morning it was changed to "/home/dasawork/..." so can this cause the problem ? please help -
How to make loop variables accessible from block-endblock
I am trying to write code for the index page of a blogging site. The index page will fetch blog title, date, author details and blog content and put it on the index page. I am having an issue making jinja2 templates work for this. Here is my base.html templates, which will be used site wide. <head> <meta charset="UTF-8"> <link type="text/css" rel="stylesheet" href="{{ static ('css/style.css') }}"/> <title>{% block title_block %}{% endblock %}</title> </head> <body> <div class="jumbotron"> <div class="container-fluid"> <div class="row"> <div class="col-2"> </div> <div class="col-10"> <h3 class="hdr hrborder">{% block posttitle scoped %}{% endblock %}</h3> </div> </div> <div class="row"> <div class="col-2 vrborder text-right"> Published: {% block postdate %}{% endblock %} Author: {% block postauthor %} {% endblock %} </div> <div class="col-10"> {% block postcontent %}{% endblock %} </div> </div> </div> </body> And here is the child template {% extends 'core/base.html' %} {% block title_block %} Blogs {% endblock %} {% for post in posts %} {% block posttitle scoped %}{{ post.post_title }}{% endblock %} {% block postdate scoped %}{{ post.post_date }}{% endblock %} {% block postauthor scoped %}{{ post.post_author }}{% endblock %} {% block postcontent scoped %}{{ post.post_content }}{% endblock %} {% endfor %} But this is not workin. I am … -
Django. Error in "create_superuser()"
I got error when i trying to create "super user" by "manage.py createsuperuser". Traceback: File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/mnt/e/Work/WEB/django/72tob/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/mnt/e/Work/WEB/django/72tob/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/mnt/e/Work/WEB/django/72tob/env/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/mnt/e/Work/WEB/django/72tob/env/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 59, in execute return super().execute(*args, **options) File "/mnt/e/Work/WEB/django/72tob/env/lib/python3.5/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/mnt/e/Work/WEB/django/72tob/env/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 179, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) TypeError: create_superuser() got an unexpected keyword argument [model.py] from time import timezone from django.db import models from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin class TemporaryBanIp(models.Model): class Meta: db_table = "TemporaryBanIp" ip_address = models.GenericIPAddressField("IP адрес") attempts = models.IntegerField("Неудачных попыток", default=0) time_unblock = models.DateTimeField("Время разблокировки", blank=True) status = models.BooleanField("Статус блокировки", default=False) def __str__(self): return self.ip_address class TemporaryBanIpAdmin(admin.ModelAdmin): list_display = ('ip_address', 'status', 'attempts', 'time_unblock') search_fields = ('ip_address',) class AuthUserManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, patronymic, birth_day, inn_id, passport_s, passport_n, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=AuthUserManager.normalize_email(email), username=username, last_name=last_name, first_name=first_name, patronymic=patronymic, birth_day=birth_day, inn_id=inn_id, passport_s=passport_s, passport_n=passport_n, ) user.is_admin = True user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name, patronymic, birth_day, inn_id, passport_s, passport_n, … -
Run program on server forever without manually starting it
I have created an application which resides on a server. The application uses Django to connect. So, if I want to access the web page I have to run the following command to start the server - python manage.py runserver ip adress:port number What is the way to keep it running all the time even after shutting down my computer? -
django no module name 'config'
I wrote these apps using python2 and now am using python 3. I've tried: 1) Changing to a new virtualenv and reinstalling requirements 2) pip install config -> returns a new Syntax error in an Exception... 3) pip install django-config 4) I keep getting the following error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'config' I'm really stuck because i can't run these project that … -
How to synchronise algolia with database only when deleteing, adding and updating model instance
According to algoliasearch-django document: 'AUTO_INDEXING: automatically synchronize the models with Algolia (default to True).' For my understand, if I set AUTO_INDEXING to True, whatever I update a model instance or update model (e.g. add a new field), it will synchronise Algolia with my own database (or model). However, what I want to do is synchronise Alogolia on demand, for example, only synchronise them when a model instance is change, added or deleted. Are there any way to implement this? Thanks. -
Make detail page for each A/B test experiment result
I have been making A/B testing system using Django and dashboard using django controlcenter. Now I have a dashboard page including results of all active experiments. What I want to do is spliting a dashboard page for each experiment. I have tried a way using urlpatterns = [url(r'^admin/dashboard/mydash/(?P<exp_id>[0-9])/$', views.exp_dashboard), ] in urls.py and def exp_dashboard(request, exp_id): exp = get_object_or_404(Experiment, pk=exp_id) exp = Experiment.objects.get(pk=exp_id) return HttpResponse('experiment %s'%exp_id) in views.py But I do not know how to return dashboard page from exp_dashboard, not returning HttpResponse as usual. Do you have any advice to do this? -
Django 2.0 UpdateView NoReverseMatch
Trying to use UpdateView to update a model object with name "Tag" Here is the model: NAME_REGEX = r'^[a-zA-Z0-9\s.\-]+$' class Tag(TimeStampModel): name = models.CharField(max_length=40, validators = [ RegexValidator(regex=NAME_REGEX, message='name must be alphanumeric, may contain - _', code='invalid tag name')], unique=True) slug = models.SlugField(max_length=60, unique=True, blank=True) text = models.TextField(blank=True) def __str__(self): return self.name def get_absolute_url(self): url = reverse('tags:tag_detail', kwargs={'slug':self.slug}) print('Tag *************** 010 ********************') print(url) return url def save(self, *args, **kwargs): self.slug = make_slug(self.name) super().save() I am able to create a Tag using CreateView, list the Tags using ListView and access the Tag detail using DetailView. I am also able to edit the tag using a function based view. However, it falls down with UpdateView. Here are the urls: urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('tag_list/', views.TagListView.as_view(), name='tag_list'), path('tag_detail/<slug:slug>/', views.TagDetailView.as_view(), name='tag_detail'), path('create_tag/', views.CreateTagView.as_view(), name = 'create_tag'), path('update_tag/<slug:slug>/', views.UpdateTagView.as_view(), name = 'update_tag'), path('category_list/', views.CategoryListView.as_view(), name = 'category_list'), path('category_detail/<slug>/', views.CategoryDetailView.as_view(), name = 'category_detail'), ] In a template called "tag_detail.html" I provide a link that should take the user to an edit form as follows: <p class="slm-red"> {{ tag_dict.slug }} <br> <a href="{% url 'tags:update_tag' tag_dict.slug %}">Edit Tag</a> </p> (I've printed the value of the slug before the link. That is not the problem. The … -
Can not assign must be a instance. Django
Error : Cannot assign "'1'": "OrderInfo.ordertype" must be a "Orders" instance. I know that it means 'string' must to be an 'instance' (maybe model object) But, I have no idea why string is not allowed. This is my code. Models.py : class OrderInfo(models.Model): post = models.OneToOneField(Post) ordertype = models.ForeignKey(Orders) company = models.CharField(max_length=50, blank=True, null=True) position = models.CharField(max_length=50, blank=True, null=True) class Post(models.Model): board = models.ForeignKey(Board) writer = models.CharField(max_length=50, blank=True, null=True) writtendate = models.DateTimeField(blank=True, null=True) editeddate = models.DateTimeField(blank=True, null=True) subject = models.CharField(max_length=50, blank=True, null=True) text = RichTextField() hits = models.IntegerField(default=0) class Orders(models.Model): order = models.CharField(max_length=50, blank=True, null=True) Forms.py : class OrderEditForm(forms.ModelForm): qs = Orders.objects.all() list = [(order.id, order.order) for order in qs] ##### list's value is [('1', 'A'), ('2', 'B')] ordertype = forms.CharField(widget=forms.RadioSelect(choices=list)) class Meta: model = OrderInfo fields = ('ordertype', 'company', 'position') class PostForm(forms.ModelForm): class Meta: model = Post fields = ('subject', 'text') def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['subject'].required = True views.py def order_post_edit(request, board_id, post_id): post = get_object_or_404(Post, id=post_id) if request.method == "POST": form = PostForm(request.POST, instance=post) orderform = OrderEditForm(request.POST, instance=post.orderinfo) if form.is_valid(): print(request.POST['ordertype']) print(orderform.fields) post = form.save(commit=False) post.editeddate = timezone.now() post.save() orderform.save() return redirect('order_post', board_id=board_id, post_id=post.id) else: form = PostForm(instance=post) orderform = OrderEditForm(instance=post.orderinfo) return render(request, 'board/order/order_post_edit.html', {'form': … -
Accessing relative import beyond top-level package
i have searched across stackoverflow and i havent been able to come up with an answer. I have this directory: project/ util/ utility.py models.py So here is a description of what each file does models.py : contains a list of my django models utility.py: from ..models import * [...] May i know why i keep getting this error: ValueError: attempted relative import beyond top-level package? And how can i solve this? -
Protect third party iframe like from being used elsewhere
I am using a third party (Company X) service for a part of my app (Django based), which is behind a secure login. The content from X is delivered in an iframe that is simply embedded in one of my pages. I have spent a lot of time building the custom content in X's app (it is a custom, interactive geology tool) and my subscription with X is pricey as well. I want to protect against the possibility of one of my users sharing the iframe link with other coworkers or even users in other companies and simply using my content from X without even having to log into my app. Unfortunately, X has no way to limit the iframe content by IP or any other type of link security. I know, sounds crazy but that's the way it is right now. What would be the best way to build my own security solution? Is there a way to use another server as an intermediary, so that when the client opens the page my live server hits my intermediary server that fetches the content from X? Then I only accept requests on my intermediary server from my live server. Thanks … -
nginx config for flower celery as a subdomain
I am trying to setup nginx config to run my flower instance in a subdomain. here is the config: upstream myapp { server unix:///var/www/myapp/application/live.sock; } server { listen 80; server_name app.myapp.com; charset utf-8; client_max_body_size 75M; # Django media location /media { alias /var/www/myapp/application/app/media; expires 60d; add_header Cache-Control public; } location /static { alias /var/www/myapp/application/app/static; } location / { uwsgi_pass myapp; include /etc/nginx/uwsgi_params; } } server { listen 80; server_name flower.myapp.com; charset utf-8; error_log /var/log/nginx/error.log debug; location / { proxy_pass http://localhost:5555; proxy_set_header Host $host; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } } The config for app.myapp.com is working. But if I go to flower.myapp.com it is giving me 504 Gateway Time-out after loading for some seconds. what am I doing wrong? -
Django filter tag not working: AttributeError at / 'str' object has no attribute 'filter_function
According to the Document model below, the 'document.upload.name' in the template will display like "user_NAME/smile.jpg". I want to split the "user_NAME/smile.jpg" by '/'. So in the template, it will only display "smile.jpg". I use the 'value.split' in the filter of 'upload_extras'. but the error was: 'str' object has no attribute 'filter_function'. this is the template: <td><a href="{{ document.upload.url }}" target="_blank">{{ document.upload.name|filename_extract }}</a></td> this is my function in upload_extras.py #upload_extras.py from Django import template register =template.Library @register.filter('filename_extract') def filename_extract(value): '''extract the file name from the upload_to_path''' folder, filename = value.split('/') return filename And the last is the model: # Create your models here. def upload_to_path(instance, filename): return 'user_{0}/{1}'.format(instance.user.username, filename) class Document(models.Model): uploaded_at = models.DateTimeField(auto_now_add=True) upload = models.FileField(upload_to=upload_to_path) user = models.ForeignKey(User, on_delete=models.CASCADE) -
UnboundLocalError : local variable 'album' referenced before assignment
i need help... im a beginner script display -
django - context processor variables are not being updated
I have several variables within a navbar that are to be displayed on every single template, so I've made a custom context processor to handle the fetching of those variables. Everything is working, except that when the data is changed in the database, the values of the context variables are not refreshed(for example it'll only get updated once I quit runserver and rerun). Here's my basic pseudo code: context_processor.py: foo = db.get('foo') bar = db.get('bar') def default(request): return {'foo': foo, 'bar': bar} base.html: {% block header %} foo value is: {{ foo }}, bar value is {{ bar}} {% endblock %} {% block content %} {% endblock %} some_other_template.html: {% extends "base.html" %} {% block content %} ...blabla {% endblock %} Is there something I am missing or is this normal behavior? Have I used the wrong approach of using a context processor here? -
What happens behind the scenes in 'Q' complex database queries?
I am trying to write a query that is as efficient as possible. Here is my problem: Assume I have 10 teachers objects, and each teacher has a 100 test objects (The test is related to the teacher by OneToOne relation). I have the unique slug of the each test, and so I can just look it up like this: CreateTest.objects.filter(slug__iexact= slug_name) But, this way seems very inefficient because Django will look for every test that has been created, and there is 1000 of them out there because there are 10 teachers. Instead, I am trying to do something like this: teacher=TeacherUser.objects.filter(user__username__iexact=self.request.user) teacher_test = teacher.createtest_set.filter(slug__iexact=slug_name) Now, it is getting all the tests from a specific user, and then it is searching for that test that is needed. I want to write that same thing using 'Q'. I thought about writing this: CreateTest.objects.filter(teacher__user__username=self.request.user, slug__iexact=self.kwargs['slug']) But, for some reason, I think that this is not doing what I want. It is checking if the teacher is the same, and the slug is the same. I want it first to get all the tests for a specific teacher. After that I wanted to query the test from only from that list. Any ideas … -
Django settings.py "psycopg2.OperationalError"
In my django project, I had a sqlite3 database, and I wanted to add another postgresql one, I followed the django docummentation and my settings code is : # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'users': { 'NAME': 'app_data', 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres_user', 'PASSWORD': 'pgdjango', 'HOST': 'localhost' } } and like the docummentation say, I should do a migrate like this : python manage.py migrate --database=users When I do that, I get an error : Traceback (most recent call last): File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\base\base.py", line 213, in ensure_connection self.connect() File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\base\base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\postgresql\base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\psycopg2\__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\migrate.py", line 83, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\elmou\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\loader.py", line … -
How do I set the value of a model object's property after using `get_field()`?
I'm making a terminal command for my Django app: from django.core.management.base import BaseCommand, CommandError from django.core.exceptions import FieldDoesNotExist from django.apps import apps class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( "--app", dest="app", required=True, ) parser.add_argument( "--model", dest="model", required=True, ) parser.add_argument( "--col", dest="col", required=True, ) def handle(self, *args, **options): app_label = options.get('app') model_name = options.get('model') column_name = options.get('col') try: model = apps.get_model(app_label=app_label, model_name=model_name) except LookupError as e: msg = 'The model "%s" under the app "%s" does not exist!' \ % (model_name, app_label) raise CommandError(msg) try: column = model._meta.get_field(column_name) except FieldDoesNotExist as e: msg = 'The column "%s" does not match!' % column_name raise CommandError(msg) else: print(column, type(column)) # Do stuff here with the column, model. Right now, column is <django.db.models.fields.IntegerField: column_name>. I want this instance of model to have column_name set to 100. How can I set and save this instance in this manner? -
django.core.exceptions.FieldError: Unknown field with datetime field in django modelform
I'm using django 1.8. When I use a datetime field, I get an error saying that the field is unknown. I checked many times that the name is spelled right. Any ideas what's going on here? class MyTable(models.Model): origin = models.PositiveIntegerField(null=True, blank=True) last_modified = models.DateTimeField(auto_now=True) class MyTableForm(ModelForm): class Meta: model = MyTable fields = ['origin', 'last_modified'] Traceback (most recent call last): File "manage.py", line 19, in <module> execute_from_command_line(sys.argv) File "/home/user/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/home/user/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute django.setup() File "/home/user/venv/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/user/venv/lib/python2.7/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/home/user/venv/lib/python2.7/site-packages/django/contrib/admin/apps.py", line 22, in ready self.module.autodiscover() File "/home/user/venv/lib/python2.7/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/user/venv/lib/python2.7/site-packages/django/utils/module_loading.py", line 74, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/user/src/biosys/myapp/myapp/admin.py", line 6, in <module> from forms import * File "/home/user/src/biosys/myapp/myapp/forms.py", line 46, in <module> class InterpForm(ModelForm): File "/home/user/venv/lib/python2.7/site-packages/django/forms/models.py", line 295, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (last_modified) specified for MyTable -
Mysql error 1049 prevents access to make corrections
I have developed a Django application and now find myself trying to host it on ubuntu 16.04. I'm following the DigitalOcean guides as far as possible. I started a database for a Django application, created a user for the application, granted privileges to that user and then decided to dump the database for some reason (I think I was planning to ensure that the Django model could be migrated from scratch, but this was just before Christmas.) If I try to log in to mysql I get Error 1049 (42000): Unknown database, and kicked back out to the shell - no interactive mysql. How can I fix this? It seems that mysql won't listen to me. -
Testing `CharField(unique=True)` in django with py.test
I'm working to move all tests for a django application over to py.test. One case I have not been able to overcome is testing that uniqueness constraints on model fields are enforced. An example test: # requirements.txt pytest pytest-django ... # myapp/models.py from django.db import models class UniqueModel(models.Model): unique_field = models.CharField(max_length=100, unique=True) # myapp/tests/test_unique_model.py from django.db import IntegrityError import pytest from myapp.models import UniqueModel def test_unique(self, db): unique_1 = UnqiueModel(unique_field='not-unique') unique_1.save() unique_2 = UniqueModel(unique_field='not-unique') with pytest.raises(IntegrityError): unique_2.save() This test fails: ... with pytest.raises(IntegrityError): > unique_2.save() E Failed: DID NOT RAISE <class 'django.db.utils.IntegrityError'> ... Any guidance? Thanks! -
Django Admin, accessing reverse many to many
I would like to have access to reverse many to many relationship on Django Admin (django.contrib.admin). class Company(models.Model): name = models.CharField(max_length=100) status = models.BooleanField() users = models.ManyToManyField(User, related_name='company') Right now I am able to see the User through Company on Django Admin but I cannot access the company through User. What is the correct way to have access to reverse relationship?