Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
building 'MySQLdb._mysql' extension error: [WinError 3]
i tried to install python mysqlclient to connect django with mysql server i already use but it gives me error like this C:\Users\FADHIL_000201498\Downloads\mysqlclient-python-master>python setup.py install C:\Users\FADHIL_000201498\AppData\Local\Programs\Python\Python38-32\lib\site-packages\setuptools\dist.py:471: UserWarning: Normalizing '2.0.0dev1' to '2.0.0.dev1' warnings.warn( running install running bdist_egg running egg_info writing mysqlclient.egg-info\PKG-INFO writing dependency_links to mysqlclient.egg-info\dependency_links.txt writing top-level names to mysqlclient.egg-info\top_level.txt reading manifest file 'mysqlclient.egg-info\SOURCES.txt' reading manifest template 'MANIFEST.in' writing manifest file 'mysqlclient.egg-info\SOURCES.txt' installing library code to build\bdist.win32\egg running install_lib running build_py copying MySQLdb\release.py -> build\lib.win32-3.8\MySQLdb running build_ext building 'MySQLdb._mysql' extension error: [WinError 3] The system cannot find the path specified: 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\PlatformSDK\\lib' i dont understand what the connection with visual studio thankyou -
Django How to Populate Table with Data Migration?
I need to populate a database table, and according this post the proper way to do this is using a data migration. I have an aux function, lets call it get_my_values that returns a dictionary of dictionaries with the following shape: { origin1: { key2: value2, key3: value3, ..., keyN: valueN }, origin2: { key1: value1, key3: value3, ..., keyN: valueN }, ... originN: { key1: value1, key2: value2, ..., keyN-1: valueN-1 }, } For e.g: { 'ABC': { 'DEF': 1, 'GHI': 2 }, 'DEF': { 'ABC': 1, 'GHI': 3 }, 'GHI': { 'ABC': 2, 'DEF': 3 }, } And the table that I want to populate have this shape: ORIGIN | 'ABC' | 'DEF' | 'GHI' | char | float | float | float | So, following this post I created the following migration: from django.db import migrations from myapp.utils import get_my_values def populate_my_table(apps, schema_editor): Data = apps.get_model('myapp', 'Table') my_data_dict = get_my_values() for origin in my_data_dict.keys(): # insert into Data.origin the current origin # if the Data.origin == Data.column, insert in this column the value 0 # else, insert in each Data.column, the corresponding value from my_data_dict['column'] class Migration(migrations.Migration): dependencies = [ ('myapp', 'the_table_migration'), ] operations = [ migrations.RunPython(populate_my_table), … -
NoReverseMatch at / error on production server, but no issues in local
I added a tos.html page to my django app, and it works great in local, but once I pull it into production, it shows this NoReverseMatch at / Reverse for 'tos' not found. 'tos' is not a valid view function or pattern name. Request Method: GET Request URL: http://www.flythecoop.io/ Django Version: 2.2.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'tos' not found. 'tos' is not a valid view function or pattern name. Exception Location: /home/reviews/venv/lib/python3.8/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 673 Python Executable: /home/reviews/venv/bin/python3.8 Python Version: 3.8.0 Python Path: ['/home/reviews/venv/bin', '/home/reviews/reviews', '/home/reviews/venv/lib/python38.zip', '/home/reviews/venv/lib/python3.8', '/home/reviews/venv/lib/python3.8/lib-dynload', '/usr/lib/python3.8', '/home/reviews/venv/lib/python3.8/site-packages'] Server time: Tue, 11 Feb 2020 01:02:33 +0000 It's in my base.html file 63 </body> 64 <footer> 65 <br> 66 <p class="text-center"> 67 <a class="btn btn-link btn-sm" href="{% url 'tos' %}" role="button">Terms of Service </a> 68 <a class="btn btn-link btn-sm" href="{% url 'about' %}" role="button">About </a> 69 <a class="btn btn-link btn-sm" href="{% url 'faq' %}" role="button">FAQ </a></p> 70 </footer> 71 </html> Here is my urls.py in the pages app from django.urls import path from . import views urlpatterns = [ path('', views.HomePageView.as_view(), name='home'), path('tos/', views.TosPageView.as_view(), name='tos'), path('about/', views.AboutPageView.as_view(), name='about'), path('faq/', views.FaqPageView.as_view(), name='faq'), ] Here is my views.py from django.shortcuts import render from django.views.generic import TemplateView # … -
django.db.utils.OperationalError: (2026, 'SSL connection error: SSL_CTX_set_tmp_dh failed') while connecting to localhost MYSQL
I am trying to connect to Mysql server on localhost from my django application on Ubuntu 19.04. The database connection section in settings.py looks like this: 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'app_datastore', 'HOST' : '127.0.0.1', 'USER': 'root', 'PASSWORD': 'xxxx', 'OPTIONS': { 'ssl': { 'ca': '/var/lib/mysql/ca.pem', 'cert': '/var/lib/mysql/client-cert.pem', 'key': '/var/lib/mysql/client-key.pem' } } } }``` It gives the error : django.db.utils.OperationalError: (2026, 'SSL connection error: SSL_CTX_set_tmp_dh failed') I can however connect to my mysql from both terminal and Dbeaver. mysql server is up. **Stackoverflow threads which I have already tried and doesnt work :** https://stackoverflow.com/questions/53385113/django-db-utils-operationalerror-2026-ssl-connection-error-ssl-ctx-set-tmp https://stackoverflow.com/questions/54485148/ssl-connection-error-while-using-mysql-connector-with-python/54493292 https://stackoverflow.com/questions/53819554/python-sql-connection-error-2006-ssl-connection-error-ssl-ctx-set-tmp-dh-fai -
Python packages not installing in any sys.path directory
I see there are questions that are somewhat related to this one, but their answers don't help me clarify my doubt. Please note that this is not about how to successfully import django, it's about the differences between folders and why an installation fell in a specific directory. I installed django via pip, just as I have installed other packages, but I realized it installed in a directory that's not in any sys.path directory. Specifically, it installed in "C:\Users\User\Anaconda3\pkgs\python-3.7.0-hea74fb7_0\Lib\site-packages". Actually, other packages I have installed are there, but they're also in "C:\Users\User\Anaconda3\lib\site-packages", which is in the sys.path list. I don't know why django was installed in that directory. I added that path as an environment variable but I still couldn't import it. Oddly, I could run !django-admin startproject and it created a new project, but nothing else could be run. I managed to import django successfully by doing sys.path.append(), but my questions remain. Why did django install there? What is the difference between these two directories? Is there a way to control this when I do the next package installation? Why did !django-admin startproject run if it couldn't import it? Thank you. -
manage.py runserver not doing anything
Upon using this command, nothing happens. No error or anything. Python is in environment variables and I'm not having any problem with the python directory. I am running the most recent versions of Django and Python. Image of problem -
Error code when installing psycopg2 in requirements.txt in django
I've tried to manually install only the psycopg2 module. As well as with a pip3 install -r requirements.txt. If anybody has encountered this error before, please provide appreciated guidance! ERROR: Failed building wheel for psycopg2 Running setup.py clean for psycopg2 Failed to build psycopg2 Installing collected packages: psycopg2 Running setup.py install for psycopg2 ... error ERROR: Command errored out with exit status 1: command: /Users/DavidKronish/dev/citram/MyCampus-Backend/citramenv/bin/python3.8 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/8x/lls1w4m94l90p8qszpnrvzgw0000gp/T/pip-install-c2yxmbq8/psycopg2/setup.py'"'"'; file='"'"'/private/var/folders/8x/lls1w4m94l90p8qszpnrvzgw0000gp/T/pip-install-c2yxmbq8/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /private/var/folders/8x/lls1w4m94l90p8qszpnrvzgw0000gp/T/pip-record-3aciztvp/install-record.txt --single-version-externally-managed --compile --install-headers /Users/DavidKronish/dev/citram/MyCampus-Backend/citramenv/bin/../include/site/python3.8/psycopg2 cwd: /private/var/folders/8x/lls1w4m94l90p8qszpnrvzgw0000gp/T/pip-install-c2yxmbq8/psycopg2/ Complete output (144 lines): running install running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.8 creating build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/_json.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/extras.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/compat.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/errorcodes.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/tz.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/_range.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/_ipaddress.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/_lru_cache.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/init.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/extensions.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/errors.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/sql.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 copying lib/pool.py -> build/lib.macosx-10.9-x86_64-3.8/psycopg2 running build_ext building 'psycopg2._psycopg' extension creating build/temp.macosx-10.9-x86_64-3.8 creating build/temp.macosx-10.9-x86_64-3.8/psycopg gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -DPSYCOPG_VERSION=2.8.4 (dt dec pq3 ext lo64) -DPG_VERSION_NUM=120001 -DHAVE_LO64=1 -I/Library/Frameworks/Python.framework/Versions/3.8/include/python3.8 -I. -I/usr/local/include -I/usr/local/include/postgresql/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.9-x86_64-3.8/psycopg/psycopgmodule.o gcc -Wno-unused-result -Wsign-compare -Wunreachable-code … -
Pyo Python DSP Module Won't Deploy to Heroku
So I'm trying to put up a demo of a django project on Heroku that runs fine locally and loads when I uninstall the package Pyo, but it throws an OSerror when I reinstall it (OSError at / Exception Value: /app/.pyo/3.6_64/libs/libasound-fb332ab3.so.2.0.0: cannot open shared object -- see below for full traceback). I've added a buildpack that installs the libasound and recommened packages, but I still get the error. What am I missing? I see the Linux wheel fix symlink (https://github.com/belangeo/pyo/blob/master/pyo/_linux_wheel_fix_symlinks.py). Is the issue here? Any help greatly appreciated. Error: Request Method: GET Request URL: --- Django Version: 3.0.3 Python Version: 3.6.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'core', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 100, in _get_response resolver_match = resolver.resolve(request.path_info) File "/app/.heroku/python/lib/python3.6/site-packages/django/urls/resolvers.py", line 544, in resolve for pattern in self.url_patterns: File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.6/site-packages/django/urls/resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.6/site-packages/django/urls/resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) … -
if statement in html (based on search query)
I have got a page that displays some content, but I would like to remove the content after a serach query and display the results. I believe that there should be two if statements, one for the current content (if not searching display this) and other one (if searching display other content and hide previous one). views.py def HomeView(request): item_list = Item.objects.all() query = request.GET.get('q') if query: item_list = Item.objects.filter(title__icontains=query) paginator = Paginator(item_list, 10) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) context = { 'items': items } return render(request, "home.html", context) What would I have to put inside the html template to get this to work? -
Django database migration not working, new table not created
I initially created a database in mysql and used inspectdb to create all the models. So far so good, but then I started trying to make changes to the models and migrating them. I added columns to no avail, there were no changes in the database even though the migrations folder showed the changes. I began to wonder if it was something to do with case, so I tried again with a second model TestTwoT with table name and all fields in lower case. I then ran the make migrations which produced this output: Migrations for 'testdb': testdb/migrations/0010_testtwot.py - Create model TestTwoT The generated .py file in the migrations folder (which looks fine to me): # Generated by Django 3.0.1 on 2020-02-10 22:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('testdb', '0009_auto_20200210_2241'), ] operations = [ migrations.CreateModel( name='TestTwoT', fields=[ ('id', models.AutoField(db_column='id', primary_key=True, serialize=False)), ('name', models.CharField(blank=True, db_column='name', max_length=1000, null=True)), ], options={ 'db_table': 'test_two_t', 'managed': True, }, ), ] I then ran the migrate script which produced this output suggesting there were no problems creating the table: Operations to perform: Apply all migrations: admin, auth, contenttypes, testdb, sessions Running migrations: Applying testdb.0010_testtwot... OK However, still no sign of my … -
Django-filter and Django-tables2 filter with ModelChoice values not filtering
I have a filter using ModelChoiceFilter from a DB column called 'semanas' (Weeks) and the values that are stored there at the moment are: 2020-W5 2020-W6 I have the data being displayed in a table (django-tables2), when I select any of these 2 values it does blank like it does not find anything even though I see them displayed in the table. filters.py class PagosFilter(django_filters.FilterSet): semana = django_filters.ModelChoiceFilter( queryset=Pagos.objects.values_list('semana', flat=True).distinct()) class Meta: model = Pagos fields = ['semana', ] models.py class Pagos(models.Model): carro = models.ForeignKey( Carros, on_delete=models.CASCADE, blank=False, null=False) pago = models.DecimalField(max_digits=6, decimal_places=2) fecha = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) semana = models.CharField(max_length=20) startweek = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) endweek = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) renta = models.ForeignKey( Renta, on_delete=models.PROTECT, blank=False, null=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Pagos" def get_absolute_url(self): return reverse('pagos') tables.py class PagosTable(tables.Table): detalles = TemplateColumn( '<a class="btn btn btn-info btn-sm" href="{% url "pagos_edit" record.id %}">Abrir</a>') class Meta: model = Pagos template_name = "django_tables2/bootstrap-responsive.html" fields = ('carro', 'pago', 'fecha', 'semana', 'renta') attrs = {"class": "table table-hover table-sm"} views.py class PagosListView(SingleTableMixin, FilterView): model = Pagos table_class = PagosTable template_name = 'AC/payments.html' filterset_class = PagosFilter paginate_by = 10 here is an image displaying … -
Ckeditor 5 image upload to AWS s3
I can upload images in my s3 bucket but the urls expire after some time. In general, with ckeditor I upload some HTML code to a field in my database which contains the initial urls of the images along with other html tags. After they expire, they are not accessible. Is there any way of updating those urls? Or another solution? In my website I can only upload images but they can be viewed by public. -
Django-admin collectstatic is an unknown command
Trying to collect my static files as I will be deploying my website soon. Receiving: Unknown command: 'collectstatic' After checking django-admin help I receive this warning: (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.). Here is my manage.py: def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'xwordsite.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) I have tried running manage.py shell, which did not solve the issue. Also I'm unsure if it matters but all my static files are in the project dir. Also static settings: STATIC_URL = '/static/' STATIC_ROOT = "C:/Users/Joseph/Desktop/xwordsite/static" -
ModuleNotFoundError: No module named 'django.test' while python manage.py test
File "/home/aleksander/python_apps/insta_clon/instavenv/lib/python3.6/site-packages/django/core/management/commands/test.py", line 44, in add_arguments test_runner_class = get_runner(settings, self.test_runner) File "/home/aleksander/python_apps/insta_clon/instavenv/lib/python3.6/site-packages/django/test/utils.py", line 308, in get_runner test_module = import(test_module_name, {}, {}, test_path[-1]) ModuleNotFoundError: No module named 'django.tests' -
object_list Django ListViews
class django.views.generic.list.ListView¶ A page representing a list of objects. While this view is executing, self.object_list will contain the list of objects (usually, but not necessarily a queryset) that the view is operating upon. Example views.py: from django.utils import timezone from django.views.generic.list import ListView from articles.models import Article class ArticleListView(ListView): model = Article paginate_by = 100 # if pagination is desired def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() return context What exactly is object_list? Is it inherited? DO you have to define it? I wish the documentations would have clearly explanations rather than having to look through modules and modules and still not being able to find it, thanks guys -
Django 3 Protecting Access to Media files to a specific user/folder
In this view I have a check on whether a user is logged in or not before loading a media file from django.urls import path, include, re_path from . import views from django.conf import settings from django.conf.urls.static import static from django.contrib.auth.decorators import login_required from django.views.static import serve ### require login for showing media ## todo restrict to specific patterns ? e.g. an authenticated user can only access ## files in his own folder @login_required def protected_serve(request, path, document_root=None, show_indexes=False): return serve(request, path, document_root, show_indexes) urlpatterns = [ path('', views.home, name='home'), re_path (r'^%s(?P<path>.*)$' % settings.MEDIA_URL[1:], protected_serve, {'document_root': settings.MEDIA_ROOT}), ] what I want to achieve is having a check on the user accessing only a folder with his own username e.g. user "FOO" can only access files in the media sub-folder with the same name. -
Docker and Django Inconsistently Returns 504
I'm trying to learn how to Dockerize my Django projects but I'm getting some confusing and inconsistent results. The stack I'm using is Django, Gunicorn, Nginx, and Postgres. Sometimes when I run docker-compose up the Django application runs and is accessible at 127.0.0.1:8000 but with significant frequency the application will run but not be available at 127.0.0.1:8000 and instead I will get a 504 Gateway Time-out error from Nginx. Why is this happening? Sometimes restarting the server works, other times it doesn't and I have to restart it several more times before I can access the application. Any idea what's going on here? Thanks. -
how to make two and more ajax calls in a single django view
I'm developing personal spending diary and I faced the problem. For better UX I need to make process of adding new items without reloading page . I make single ajax form but I need two . I'm trying to solve this problem for 3 days . Have anybody any suggestions ? Here is my forms.py class AddIncome(forms.ModelForm): class Meta: model = Income fields = ( 'title','value',) class AddExpence(forms.ModelForm): class Meta: model = Expence fields = ( 'title_exp','value_exp',) Here is views.py if request.method == 'POST': if request.is_ajax(): addincome = AddIncome(request.POST) if addincome.is_valid(): addincome.cleaned_data addincome.save() latest = Income.objects.latest('id').id income_object = model_to_dict(Income.objects.get(pk=latest)) return JsonResponse({'error': False, 'data': income_object}) else: ... if request.method == 'POST': if request.is_ajax(): addexpence = AddExpence(request.POST) if addexpence.is_valid(): addexpence.cleaned_data addexpence.save() latest = Expence.objects.latest('id').id expence_object = model_to_dict(Expence.objects.get(pk=latest)) return JsonResponse({'error': False, 'data': expence_object}) else: ... Here is Page forms <form method="POST" name="create_incomefrm" id="create_incomefrm" action="{% url 'create_income_record' %}"> {% csrf_token %} {{ addincome_html.as_p } <button type="submit" id="popup-button-2" class="dashboard__popup-button" name="createincomefrmbtn">Add <span>&rarr;</span></button> </form> <form method="POST" name="create_expencefrm" id="create_expencefrm" action="{% url 'create_expence_record' %}"> {% csrf_token %} <div class="dashboard__popup-2" id="dashboardpopup-4"> {{ addexpence_html.as_p }} <button id="popup-button-3" name="createexpencefrmbtn" class="dashboard__popup-button">Add<span>&rarr;</span></button> </form> Here is ajax forms $('#create_incomefrm').submit(function (e) { e.preventDefault(); var formData = { 'title': $('#id_title').val(), 'value': $('#id_value').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), contentType: 'application/x-www-form-urlencoded', encode: … -
Django Threaded Comments template
I code a social media site using Django. have a model for commenting my articles class ArticleComment(models.Model): parent = models.ForeignKey('self', null=True, blank=True, related_name='replies', on_delete=models.CASCADE) article = models.ForeignKey( Article, on_delete=models.CASCADE, related_name="comments") created_at = models.DateTimeField(auto_now_add=True) class Meta: # sort comments in chronological order by default ordering = ('created_at',) def __str__(self): return 'Comment by {}'.format(self.user.username) Now I try to render my threaded comments in my template. But i can not figure how to render my sub-comments in the same level. This is how I ended but this means only first level of replies. <ul class="comments-list style-3" id="articleComments"> {% for comment in comments %} <li class="comment-item has-children moreList"> <div class="comments-content"> <p>{{comment.content}}</p> //toggle answer reply form <a data-toggle="collapse" href="#{{comment.id}}"class="reply" role="button" aria-expanded="false" aria-controls="collapseExample">{% trans 'Reply' %}</a> <a href="#" class="report">Report</a> <div> <form id="{{comment.id}}" class="collapse" method="post"> <br> {% csrf_token %} <input type="hidden" name="parent" value="{{comment.id}}"> <div class="crumina-module crumina-heading with-title-decoration"> <h5 class="heading-title">{% trans 'Write a Reply' %}</h5> </div> <div class="row"> <div class="col col-6 col-xl-6 col-lg-6 col-md-6 col-sm-6"> <div class="form-group label-floating is-empty"> <label class="control-label">{% trans 'Reply Comment' %}</label> <textarea class="form-control" placeholder="" name="content"></textarea> </div> <button class="btn btn-primary btn-lg full-width" type="Submit">{% trans 'Post your Reply' %}</button> </div> </div> </form> </div> </div> //try to loop comments with parent {% if parent %} <ul class="children … -
django.db.utils.IntegrityError: UNIQUE constraint failed when calling my .save() function on the serializer
So I've created a singleton class to store a file on my server that gets replaced every time a new file is added, but I'm getting the following error: sqlite3.IntegrityError: UNIQUE constraint failed: api_app_onixfile.id Models.py class SingletonModel(models.Model): class Meta: abstract = True def save(self, *args, **kwargs): self.pk = 1 super(SingletonModel, self).save(*args, **kwargs) def delete(self, *args, **kwargs): pass @classmethod def load(cls): obj, created = cls.objects.get_or_create(pk=1) return obj class OnixFile(SingletonModel): onix_file = models.FileField(blank=False, null=False, validators=[validate_xml]) def __str__(self): return self.onix_file.name Views.py from django.shortcuts import render from rest_framework.parsers import FileUploadParser from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from .serializers import XMLFileSerializer from .models import OnixFile import onixcheck from .utils import OnixParser from django.http import JsonResponse class FileUploadView(APIView): parser_class = (FileUploadParser,) def post(self, request, *args, **kwargs): file_serializer = XMLFileSerializer(data=request.data) if(file_serializer.is_valid()): onix_file = request.data['onix_file'] onix_errors = onixcheck.validate(onix_file) if len(onix_errors) > 0: file_serializer.save() print("Onix Errors") return Response(onix_errors, status=status.HTTP_400_BAD_REQUEST) else: file_serializer.save() print(OnixFile.load()) return Response(OnixFile.load().__str__(), status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializers.py from rest_framework import serializers from .models import OnixFile class XMLFileSerializer(serializers.ModelSerializer): class Meta: model = OnixFile fields = "__all__" I assumed my SingletonModel save function would handle the fact that I can't have a unique PK by overwriting the current function with new info. -
django .values, joining children with commas
Lets say I have the following models: class Group(models.Model): name = models.CharField(max_length=255) class GroupMember(models.Model): first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='members') What I would like to do is get a list of values, with the group ID, group name, and a comma separated list of group members. E.g.: [ {'id': 1, 'name': 'Group Name', 'members': 'Jill Smith, Jack Peterson, Mike Frank'}, {'id': 2, 'name': 'Another Group', 'members': 'Another Person, Jack Peterson'}, ... ] Can this be done using a query on groups, and django's values method? Something like: group_data = Group.objects.all().values('id', 'name', F('members__first_last_joined_by_comma')) where 'members__first_last_joined_by_comma' would obviously be something else. -
Django master detail query set from the same model
In django I have a Model like this: class Orders(models.Model): customer = models.ForeignKey('Customer'), on_delete=models.CASCADE) price = models.DecimalField(blank=True, null=True, max_digits=10, decimal_places=3) isbn = models.CharField(max_length=17, null=True, blank=True) title = models.CharField(max_length=100, null=True) I need to define a queryset where first I need the data grouped by isbn and title annotated with count (and this part seems to be working fine). def get_queryset(self): return Orders.objects.values('isbn','titolo').annotate(orders_count=Count('pk')).distinct() But I would like to be able to return in the same queryset each order with the same ISBN in a sort of master-detail table. Any suggestion ? -
ModuleNotFoundError: No module named 'config'
I know there is a similar question to this: django-admin startproject results in "ModuleNotFoundError: No module named 'config'" But the answer does not worked for me. I have a VPS running Ubuntu (18.04) + Apache (2.4.29). The applications runs well by this command line: python3 manage.py runserver 0.0.0.0:8000 --settings=config.settings.production My Apache conf look like this: WSGIDaemonProcess myapp python-home=/home/my_repository/ENV WSGIProcessGroup myapp WSGIApplicationGroup %{GLOBAL} WSGIScriptAlias / /home/my_repository/config/wsgi.py <Directory /home/my_repository/> Require all granted </Directory> I am seeing this error on the Apache.log: mod_wsgi (pid=32745): Target WSGI script '/home/my_repository/config/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=32745): Exception occurred processing WSGI script '/home/my_repository/config/wsgi.py'. Traceback (most recent call last): File "/home/my_repository/config/wsgi.py", line 39, in <module> application = get_wsgi_application() File "/usr/local/lib/python3.6/dist-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/usr/local/lib/python3.6/dist-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/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 … -
Django Channels 2.x or Ajax?
I have a jQuery dataTable, with lots of data(10000+ rows), which can be used/updated in the real time from lots of users and I need that table to be refreshed and up to date all the time. I've tried with Ajax calls on 1 second, and I figured that that's not good, since every user is sending Ajax request every second * 50 or more users, and I think that there must be a better solution. I've been thinking to use Django Channels, or something similar(?) and i was wondering is that possible? Basically I need to set up some kind of listener on the model(database), and to pull the new data on change(that is almost every second). I would love to here an opinion from someone who has more experience than I do. Thank you in advance. Ps. I've been told to use web sockets for that. -
Form submit do not save to database
i have problem showing/saving my image file in Admin from Django. I do not know if i explain this properly but an image attachment could. I want the image i commented on to display/save in commented_image as shown empty in Admin. class Comments (models.Model): comment_post = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True) commented_image = models.ForeignKey('Image', on_delete=models.CASCADE, related_name='comments', null=True, blank=True) date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Comment' verbose_name_plural = 'Comments' ordering = ['-date'] def __str__(self): return self.author.__str__() def home(request): all_images = Image.objects.filter(imageuploader_profile=request.user.id) users = User.objects.all() next = request.GET.get('next') if next: return redirect(next) form = CommentForm(request.POST) if request.method == "POST": if form.is_valid(): text = form.save(commit=False) text.author = request.user text.save() return redirect('/') else: form = CommentForm() context = { 'all_images': all_images, 'users': users, } return render(request,'home.html', context,)