Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
VueJs data won't display
I use Django and VueJs. I tried to use Vue in Django template but when try to display data from my script nothing appear. This is my html file : {% load static %} <body> <p>No polls are available.</p> <div id="app"> {{message}} </div> <script src="{% static "app.js" %}" defer></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"> </script> </body> And in my app.js : new Vue({ el: '#app', data: { message: 'Hello Vue!' } }) My script is loaded but Hello Vue! won't appear. -
Django: List Products of each Categories in a page
I have a few categories and I would like to list the products per category in the format below (categories is an FK to products): Category 1 bunch of products .... Category N bunch of products I have tried many ways but so far I only get the categories but not the products to show in my HTML. models.py class Category(models.Model): title = models.CharField(max_length=225) slug = models.SlugField(unique=True, blank=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('category_detail', kwargs={'slug': self.slug}) @property def get_products(self): return Products.objects.filter(category=self.title) class Products(models.Model): title = models.CharField(max_length=225) image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) blank=True, on_delete=models.CASCADE) categories = models.ForeignKey(Category, related_name='Category', blank=True, on_delete=models.CASCADE) #this gender = models.CharField(max_length=20, choices=GENDER_CHOICES, default="male") objects = ProductManager() def get_absolute_url(self): return reverse('product_detail', args=(self.id,)) def __str__(self): return self.title views.py def categories_m(request): query_Set = models.Category.objects.all() page = request.GET.get('page', 1) paginator = Paginator(query_Set, 20) try: cat = paginator.page(page) except PageNotAnInteger: cat = paginator.page(1) except EmptyPage: cat = paginator.page(paginator.num_pages) return render(request, 'products/categories.html', {'categories': cat}) html {% extends 'base.html' %} {% block content %} {% for category in categories %} <h1>{{ category }}</h1> {% for product in categories.get_products %} <p>{{ product }}</p> {% endfor %} {% endfor %} {% endblock %} -
DateTimeField & TimeField Error
my code is working perfectly working fine but due to my change in requirements i had to make DateTimeField to TimeField but after making the changes in my code i face any error Exception Value: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' my code is about salary Calculation class salary(models.Model): #employee = models.ForeignKey('employee', on_delete=models.CASCADE) base_salary = models.IntegerField(default=0) time_in = models.TimeField(default=tz.now, null=True, blank=True) time_out = models.TimeField(default=tz.now, null=True, blank=True) total_salary = models.CharField(max_length=20, default='0') def calculate_salary(self): worked_hours = (self.time_out - self.time_in).total_seconds() / 60 / 60 overtime_hours = 0 # make sure you use timezone aware objects # https://docs.djangoproject.com/en/2.0/topics/i18n/timezones/#naive-and-aware-datetime-objects same_day_8pm = self.time_out.replace(hour=16, minute=0, second=0, microsecond=0) if self.time_out > same_day_8pm: overtime_hours = (self.time_out - same_day_8pm).total_seconds() / 60 / 60 salary_1 = worked_hours * self.base_salary salary_2 = overtime_hours * self.base_salary * 0.2 total_salary = salary_1 + salary_2 # careful: this will be a 'float', not an 'int' # with round() using 0 decimal digits you get an 'int' # total_salary = round(total_salary, 0) return total_salary def save(self,*args,**kwargs): # are you really sure that you want to save a string ??? self.total_salary = str(self.calculate_salary()) super().save(*args, **kwargs) -
Pass QuerySet to Celery Task in Django 1.11
I want to move some long query to the async task in Celery and next retrieve that extra-info with AJAX. Now I get QuerySet like this: brands = Brand.objects.filter(shops__shop_name__in=[shop]) Task: @task() def brand_count(querystr): querystr.annotate(amount_of_products=Count('products')) I want to do: task_run = brand_count.delay(brands) The question is: How to pass a QuerySet to Celery task? Now it throws an error that this couldn't be done. I have found that pickle might be used here, but I can't get the right way to use it. Specially - what does # Assuming 's' is the pickled string. in query = pickle.loads(s) mean. -
Django ManyToManyField inline list values
I have two Django models related by a ManyToManyField relationship. Everything works fine except for the inline add dropdown which lists ugly automatically created object names instead of allowing me to format it. How can I specify that? Models: class Job(models.Model): type = models.CharField(max_length=32, choices=JobChoices) guid = models.CharField(max_length=32) title = models.CharField(max_length=256) started_time = models.DateTimeField() ended_time = models.DateTimeField(blank=True, null=True) enabled = models.BooleanField(default=False) running = models.BooleanField(default=False) working_job_status = models.CharField(max_length=32, choices=StatusCoices) working_job_length = models.IntegerField(blank=True, null=True) working_job_progress = models.IntegerField(blank=True, null=True) working_job_eta_sec = models.IntegerField(blank=True, null=True) RepeatUnit = ( ('s', 'Second'), ('m', 'Minute'), ('h', 'Hour'), ('d', 'Day'), ('W', 'Week'), ('M', 'Month'), ('Y', 'Year'), ) class Schedule(models.Model): title = models.CharField(max_length=128) job = models.ManyToManyField(Job, blank=True, null=True) start_time = models.DateTimeField(null=False) end_time = models.DateTimeField(blank=True, null=True) repeat_unit = models.CharField(blank=True, null=True, max_length=1, choices=RepeatUnit) repeat_every = models.IntegerField(blank=True, null=True) repeat_max_count = models.IntegerField(blank=True, null=True) def __unicode__(self): return f'{self.title}' Admin: class ScheduleAdmin(admin.ModelAdmin): list_display = ['id', 'title', 'start_time', 'end_time', 'repeat_unit', 'repeat_every', 'repeat_max_count'] class ScheduleInline(admin.TabularInline): model = Schedule.job.through min_num = 0 extra = 0 # fields = ('title', ) verbose_name = "Schedule" verbose_name_plural = "Schedules" class JobAdmin(admin.ModelAdmin): list_display = ['id', 'type', 'guid', 'title', 'started_time', 'ended_time', 'enabled', 'running', 'progress'] inlines = [ScheduleInline,] admin.site.register(Schedule, ScheduleAdmin) admin.site.register(Job, JobAdmin) And, when I click on the inlines drop-down menu I get: -
Django Rest Framework get attributes from foreign key's class
here's my models: class Recruteur(models.Model): entrepriseName = models.CharField(max_length=50) emplacement = models.CharField(max_length=50) class Offre(models.Model): title = models.CharField(max_length=100, blank=True, default=0) idRecruteur = models.ForeignKey(Recruteur,verbose_name = "idRecruteur", on_delete=models.CASCADE, default=None) and here's my api.py: class VilleViewSet(ModelViewSet): queryset = Offre.objects.values('idRecruteur__emplacement').distinct() serializer_class = VilleSerializer serializers.py: class EmplacementSerializer(serializers.ModelSerializer): class Meta: model = Recruteur fields = ('emplacement',) class VilleSerializer(serializers.ModelSerializer): emplacements = EmplacementSerializer(source='idRecruteur', read_only=True) class Meta: model = Offre fields = ( 'emplacements',) i was expecting a result like this but i got nothing instead .. Any ideas why? -
Why is DRF Pagination not working with GenericAPISerializer?
settings.py REST_FRAMEWORK = { 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 1, } views.py class example(GenericAPIView): queryset = example.objects.all() serializer_class = ExampleSerializer def get(self, request, format=None): query = request.GET.get('name') if query: bla = example.objects.filter(name=query) else: bla = example.objects.all() if bla: serializer = ExampleSerializer(bla, many=True) return Response(serializer.data) else: return Response(status=status.HTTP_404_NOT_FOUND) Now if I go to the endpoint ?page=1 there are still 5000 records being returned. Is putting pagination in my settings.py not enough? Do I need to add pagination specific code to my views? -
Pytest models not getting imported due Apps aren't loaded yet
nas_apps nas_apps -__init__.py -environments.py -settings.py -urls.py -wsgi.py -pytest.ini usecase1 -conf -logs -management -migrations -services -templates -utils -__init__.py -apps.py -controllers.py -forms.py -models.py -serializers.py -urls.py -views.py usecase2 usecase3 tests -fixtures -conftest.py -input_data.json -test_usecase1.py =============================================================== platform linux -- Python 3.5.2, pytest-3.4.1, py-1.5.2, pluggy-0.6.0 -- /home/.../Envs/venv/bin/python3 cachedir: .pytest_cache rootdir: /home/..../Desktop/dev2/NAS/nas_apps/tests, inifile: plugins: sanic-0.1.8, django-3.1.2, cov-2.5.1 collected 0 items / 1 errors ========================================================================================= ERRORS __________________________________________________________________________ ERROR collecting test_maintenance.py ___________________________________________________________________________ test_usecase1.py:17: in from usecase1.services.db_helper import DbHelper ../usecase1/services/db_helper.py:16: in from .log_service import LogRunner ../usecase1/services/log_service.py:17: in class LogRunner: ../usecase1/services/log_service.py:18: in LogRunner _config_manager = ConfigManager() ../usecase1/utils/config.py:24: in init curr_app_dir = apps.get_app_config('usecase1').verbose_name.lower() /home/.../Envs/uscc01/lib/python3.5/site-packages/django/apps/registry.py:145: in get_app_config self.check_apps_ready() /home/.../Envs/uscc01/lib/python3.5/site-packages/django/apps/registry.py:127: in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") E django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Can someone please help me resolve this? Appreciate your help. -
Link column with link to a file in static (django-tables2, Django)
I generate a table with django-tables within Django. I want to create a column with links to txt files in my static directory. When the user clicks on the link, the txt file should be displayed. To create a link to the txt file within an html, I simply do: <a href="{% static co.log %}">txtfile</a> However, I have problems finding the right way to do this using django-tables. I tried to define the link column as follows: logfiles = tables.LinkColumn('{static', text='txtfile', args=[A('log')], orderable=False, empty_values=()) This gives the error "Reverse for '{static' not found. '{static' is not a valid view function or pattern name." I also tried this: tables.py logfiles = tables.LinkColumn('logfile', text='bla', orderable=False, empty_values=()) urls.py: url(r'^logfile/', views.logfile, name='logfile') views.py: def logfile(request): return HttpResponse('<p>yeah</p>') So I can find a way to open a new url, but how to open a specific static file, i.e.how to pass the info from [A('log')], which is basically the filename? Any help is appreciated. -
relation "wagtailcore_page" does not exist
It's not a bug, it's a problem caused by me, and I would be grateful if someone can help me. I am using django-1.11 and postgresql database. I wanted to implement blog using puput django package. I have deleted all the tables for wagtail and puput (a big mistake). Now when I run puput_initial_data I get the following error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/ubuntu/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/ubuntu/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/.local/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/.local/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/ubuntu/.local/lib/python3.5/site-packages/puput/management/commands/puput_initial_data.py", line 20, in handle rootpage = Page.objects.first() File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/models/query.py", line 564, in first objects = list((self if self.ordered else self.order_by('pk'))[:1]) File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/models/query.py", line 250, in __iter__ self._fetch_all() File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/models/query.py", line 1118, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/models/query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch) File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 894, in execute_sql raise original_exception File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 884, in execute_sql cursor.execute(sql, params) File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/ubuntu/.local/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise … -
HTML code inside templates isn't processing Django code
I'm a complete beginner in Django.I'm not able to extract data from my database inside the template. Please cooperate and help! mysite/books/templates/books/index.html <!DOCTYPE html> <html> {% for book in object_list %} <h>{{book.name }}</h> {% endfor %} </html> mysite/books/views.py # Create your views here. from django.views import generic from .models import Book from django.views.generic.edit import CreateView class IndexView(generic.ListView): template_name = 'books/index.html' def get_queryset(self): return Book.objects.all() class BookCreate(CreateView): model = Book fields = ['name', 'author', 'price', 'type', 'book_image'] class DetailView(generic.DetailView): model = Book template_name = 'books/detail.html' mysite/books/models.py # Create your models here. from django.db import models from django.core.urlresolvers import reverse class Book(models.Model): def get_absoulte_url(self): return reverse('books:detail', kwargs={'pk':self.pk}) def __str__(self): return self.name + '-' + self.author name = models.CharField(max_length=100) author = models.CharField(max_length=100) price = models.CharField(max_length=100) type = models.CharField(max_length=100) book_image = models.CharField(max_length=1000) output {{book.name}} is not getting processed in the template -
Add() method not saving many to many field
I am creating a website that allows users to follow stocks and see articles based on what they follow. After registering, the user selects the stocks they want to follow. def follow_stocks_post_registration(request): all_stocks = Stock.objects.all() if request.method == 'POST': stocks_user_selected = request.POST.getlist('stocks_selected') user_profile = request.user.profile for stock_name in stocks_user_selected: stock = Stock.objects.get(name=stock_name) user_profile.followed_stocks.add(stock) models.py: class Stock(models.Model): name = models.CharField(max_length = 50) ticker = models.CharField(max_length = 50) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) followed_stocks = models.ManyToManyField(Stock, blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() In the view, stocks_user_selected = request.POST.getlist('stocks_selected') gets the correct list of stocks, butuser_profile.followed_stocks.add(stock) does not succesfully add any stocks to the user's followed_stocks. I am not sure what's wrong? -
Django - SuspiciousOperation, request session deleted
I'm getting this error and I have no idea why: SuspiciousOperation at /file/path/ The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example. I know the user isn't logging out (no account to log in to in the first place). The error is occurring in one of my views when I make a call to request.session and try to pull some chart data that I have stored. It's causing my charts to not display on the page since it can't pull the data in time. Here is the stack trace: /opt/name/env/lib/python2.7/site-packages/django/core/handlers/base.py in get_response 131. response = middleware_method(request, response) /opt/name/env/lib/python2.7/site-packages/django/contrib/sessions/middleware.py in process_response 61. "The request's session was deleted before the " Any idea what I could be doing wrong here? -
Django Migration with SQL Server
I am having following issue when migrate database from SQLite to MSSQL. Searched online but have no clue how to solve. Please help. Thank you in advance. I am sure my setting.py is correct, at least "DATABASES" part. python manage.py migrate Traceback (most recent call last): File "manage.py", line 23, in <module> execute_from_command_line(sys.argv) File "/home/jzuo/repos/vb/vbenv/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/jzuo/repos/vb/vbenv/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/jzuo/repos/vb/vbenv/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/jzuo/repos/vb/vbenv/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/jzuo/repos/vb/vbenv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 83, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/home/jzuo/repos/vb/vbenv/lib/python2.7/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/home/jzuo/repos/vb/vbenv/lib/python2.7/site-packages/django/db/migrations/loader.py", line 52, in __init__ self.build_graph() File "/home/jzuo/repos/vb/vbenv/lib/python2.7/site-packages/django/db/migrations/loader.py", line 209, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/jzuo/repos/vb/vbenv/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/home/jzuo/repos/vb/vbenv/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/home/jzuo/repos/vb/vbenv/lib/python2.7/site-packages/django/db/backends/base/base.py", line 254, in cursor return self._cursor() File "/home/jzuo/repos/vb/vbenv/lib/python2.7/site-packages/django/db/backends/base/base.py", line 229, in _cursor self.ensure_connection() File "/home/jzuo/repos/vb/vbenv/lib/python2.7/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/home/jzuo/repos/vb/vbenv/lib/python2.7/site-packages/django/db/backends/base/base.py", line 190, in connect self.set_autocommit(self.settings_dict['AUTOCOMMIT']) File "/home/jzuo/repos/vb/vbenv/lib/python2.7/site-packages/django/db/backends/base/base.py", line 411, in set_autocommit self._set_autocommit(autocommit) File "/home/jzuo/repos/vb/vbenv/lib/python2.7/site-packages/sql_server/pyodbc/base.py", line 487, in _set_autocommit allowed = self._get_trancount() > 0 File "/home/jzuo/repos/vb/vbenv/lib/python2.7/site-packages/sql_server/pyodbc/base.py", line 448, in _get_trancount with self.connection.cursor() as cursor: AttributeError: __exit__ -
links = SerializerMethodField() is not a string
I am facing the below mentions issue in DRF (HATEOAS) TypeError at /api/users/ key UserSerializer(<QuerySet [<User: prakash>]>, context={'request': <rest_framework.request.Request object>, 'format': None, 'view': <board.views.UserViewSet object>}): id = IntegerField(label='ID', read_only=True) username = CharField(help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, validators=[<django.contrib.auth.validators.UnicodeUsernameValidator object>, <UniqueValidator(queryset=User.objects.all())>]) full_name = CharField(read_only=True, source='get_full_name') is_active = BooleanField(help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', label='Active', required=False) links = SerializerMethodField() is not a string Here is my code(issue is in def get_links(self, obj):): class TaskSerializer(serializers.ModelSerializer): status_display = serializers.SerializerMethodField() links = serializers.SerializerMethodField() assigned = serializers.SlugRelatedField( queryset=User.objects.all(), slug_field=User.USERNAME_FIELD, required=False) class Meta: model = Task fields = ('id', 'name', 'description', 'sprint', 'status', 'status_display', 'order', 'assigned', 'started', 'due', 'completed', 'links') def get_links(self, obj): request = self.context['request'] return { self:reverse('task-detail', kwargs = {'pk':obj.pk}, request = request) } def get_status_display(self, obj): #return 1#obj.get_status_display() return obj.status -
Jinja "==" (compare condition) doesn't work?
while writing an application in django, I've encountered a problem. I want to make page-number links, with current page not being a link. So in template I do this: {% for i in pages %} {% if i == curr_page %} {{ i }} {% else %} <a href="...">{{ i }}</a> {% endif %} Only problem? Jinja doesn't seem to notice two numbers being equal. I've changed the 2nd line to {% if i != curr_page %} {{i}}!={{curr_page}} and got "... 5!=6 6!=6 7!=6 ...". What should I do? -
Best skill for a BCA fresher in terms of time to learn the technology, career path and, salary in India, Salesforce, AWS or Django (Python)?
I am a BCA (bachelor or computer applications) last semester student. I want to know Which skill is better for a BCA fresher in terms of time to learn the technology, career path and, salary in India: Salesforce, AWS or Django (Python)? I will pursue MCA latter on but at present I am concerned about job. Please suggest me which skill will be better? -
How to avoid repeated django prefetch related database hits
When i fetch a client i want to also prefetch all related probes and probe channels, and when i fetch a probe i also want to fetch all related probe channels. But it seems that when i get a client object, or view the admin, it runs the get_queryset methods from both the client and the probe manager. so it will prefetch the probechannels twice. This can be seen both in the number of sql queries in debug toolbar, and by adding print statements in the get_queryset methods. so i've got class ClientManager(models.Manager): def get_queryset(self, *args, **kwargs): return super(ClientManager, self).get_queryset(*args, **kwargs).prefetch_related('probe_set__probechannel_set') class Client(models.Model): objects = ClientManager() class ProbeManager(models.Manager): def get_queryset(self, *args, **kwargs): return super(ProbeManager, self).get_queryset(*args, **kwargs).prefetch_related('probechannel_set') class Probe(models.Model): Client = models.ForeignKey('Client') objects = ProbeManager() class ProbeChannel(models.Model): Probe = models.ForeignKey('Probe') Is there a way to avoid this? I have read about _base_managers being used for related objects, but the _base_manager here is just models.Manager. I'm using django 1.11 and this trendy new thing called python 2.7. -
Django: "Cannot add foreign key constraint" when creating test tables before running unit tests
I am trying to run unit tests that I've written for my Django project, but testing fails at the database creation stage. I have a single database "test", one of which as a foreign key relationship with another. I run the following: python3 manage.py test --settings myapp.settings_test And see the following output: Creating test database for alias 'test'... Got an error creating the test database: (1007, "Can't create database 'test_test'; database exists") Type 'yes' if you would like to try deleting the test database 'test_test', or 'no' to cancel: yes Destroying old test database for alias 'test'... Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.5/dist-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python3.5/dist-packages/MySQLdb/cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "/usr/local/lib/python3.5/dist-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler raise errorvalue File "/usr/local/lib/python3.5/dist-packages/MySQLdb/cursors.py", line 247, in execute res = self._query(query) File "/usr/local/lib/python3.5/dist-packages/MySQLdb/cursors.py", line 411, in _query rowcount = self._do_query(q) File "/usr/local/lib/python3.5/dist-packages/MySQLdb/cursors.py", line 374, in _do_query db.query(q) File "/usr/local/lib/python3.5/dist-packages/MySQLdb/connections.py", line 277, in query _mysql.connection.query(self, query) _mysql_exceptions.IntegrityError: (1215, 'Cannot add foreign key constraint') I've seen many answers such as this: Django MySQL error when creating tables. Such answers show that, in general, this error is caused … -
How to create inline for a model with common referenced model in Django admin?
So I have these kind of models: def Profile(models.Model): user = ForeignKey(User) def Item(models.Model): user = ForeignKey(User) And I want to have ItemInline in ProfileAdmin. I tried doing it like this: class ItemInline(admin.TabularInLine): model = Item @admin.register(Profile) class ProfileAdmin(admin.ModelAdmin): inlines = [ItemInline] However, this shows me this error: <class 'app.admin.AddressInline'>: (admin.E202) 'api.Item' has no ForeignKey to 'api.Profile'. How do I put the ItemInline into ProfileAdmin? -
Create additional fields in models on foreign key (Django query)
models.py from django.db import models class person(models.Model): name = models.CharField(max_length=100, blank=true) characteristics = models.ManyToManyField(characteristics, default = '', on_delete=models.SET_DEFAULT) def __str__(self): return self.name class characteristics(models.Model): name = models.CharField(max_length=100, blank=true) def __str__(self): return self.name I have some troubles with queryset. I create 3 persons: Jim, John, Jack. Then create 4 characteristics: strength, agility, wisdom, intelligence Connect Jim with strength and agility( he is strong and dexterous) Connect John with wisdom and intelligence( he is a smart guy) Connect Jack with strength, agility, wisdom, intelligence( he is jack of all trades) Output will be like: Jim: strength, agility John: wisdom, intelligence Jack: strength, agility, wisdom, intelligence Is there a posibility to add values to these characteristics? For example: Jim: strength=10 , agility=10 John: wisdom=10, intelligence=10 Jack: strength=9, agility=8, wisdom=8, intelligence=9 I think, this values need to be stored in "person" table. I can create additional fields in models.py, but my goal is to make additional field in "person" model when creating new charactaristics. Thereis a way to make it using 0...1000 empty int fields in "person" model, then giving additional number(like id) to charecteristics and then connect that characteristics id with "person" 0...1000 empty fields from django.db import models class person(models.Model): name = … -
templated-docs library setup error
I want to be able to populate office document templates with fields from my django site's database. I found this library, and the example is as so: def get_document(request): """ A view to get a document filled with context variables. """ context = {'patient.Title': patient.Title, 'patient.First_Name': patient.First_Name, 'patient.Surname': patient.Surname} filename = fill_template('template.odt', context, output_format='pdf') visible_filename = 'greeting.pdf' return FileResponse(filename, visible_filename) I have put the template I have made in the templates folder for the app i am in. When i try to runserver, i get the error TypeError: get_template_sources() takes 2 positional arguments but 3 were given My url is: path('template', views.fill_template(template_name='template.odt', context={'patient.Title': patient.Title, 'patient.First_Name': patient.First_Name, 'patient.Surname': patient.Surname}, output_format='pdf')) What am i doing wrong? -
Horizontal radio fields support of django-baton in Django Admin
radio fields defined as horizontal in Django Admin is displayed vertically after django baton installed. Will there be a fix for this issue. Thank you.. -
django python share date between 2 files
I have a problem about connecting two web pages with the django framework, here is my question: how to make the connection between two web pages with django, let me explain, I realized a form with django that I named for the first page contact.html and for the second page, I named home.html, I would like the data of the first page ie contact.html to be displayed on the second page named home.html, I applied an url, but unfortunately the data of the form of the first page named contact.html and not appear on the second page named home.html, I have a solution, if you like. -
How to create python script to add row inside database in Django
I tried to run this script but definitely something missing here... mysite this is the app, School is the class from mysite.models import School school1 = School(name='Oxford school', address='Shole St.33', email='ox-scholl@gmail.com', phone_number='3445348910') school1.save() And get this error: raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.