Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i update user model extended via "OneToOneField"
I have some issues with updating my database, in my serializer i use extended via OneToOneField django user model with two extra fields with user image and his motto. So i think the problem with instance in my serializer, but i can't figure out how to do that. #core.models class MangaUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_image = models.ImageField(upload_to='upicks') user_motto = models.CharField(max_length=256) #api.serializers class UserSerializer(serializers.ModelSerializer): #mangauser_set = serializers.SerializerMethodField() user_image = serializers.ImageField(source='mangauser.user_image') user_moto = serializers.CharField(source='mangauser.user_motto') class Meta: model = User fields = ['id', 'username', 'email', 'password', 'user_image', 'user_motto'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance def update(self, instance, validated_data): for attr, value in validated_data.items(): if attr == 'password': instance.set_password(value) else: setattr(instance, attr, value) instance.save() return instance #api.view class GetUserInfo(APIView): permission_classes = (IsAuthenticated,) serializer_class = UserSerializer def get(self, request, *args, **kwargs): # serializer to handle turning our `User` object into something that # can be JSONified and sent to the client. serializer = self.serializer_class(request.user, context={"request":request}) return Response(serializer.data, status=status.HTTP_200_OK) def put(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) #response ValueError at /api/v1/userinfo/ Cannot assign "{'user_motto': 'js Π³ΠΎΠ²Π½ΠΎ'}": "User.mangauser" must be a "MangaUser" β¦ -
Script timed out before returning headers: wsgi.py; Django app on elastic beanstalk
I am deploying a Django app, but in the past 2 days I randomly started receiving the Script timed out before returning headers: wsgy.py with the following logs: [Sun Feb 16 03:02:30.697009 2020] [mpm_prefork:notice] [pid 20719] AH00163: Apache/2.4.41 (Amazon) mod_wsgi/3.5 Python/3.6.8 configured -- resuming normal operations [Sun Feb 16 03:02:30.697031 2020] [core:notice] [pid 20719] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' [Sun Feb 16 03:03:33.906331 2020] [mpm_prefork:notice] [pid 20719] AH00169: caught SIGTERM, shutting down [Sun Feb 16 03:03:34.352673 2020] [suexec:notice] [pid 29207] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Sun Feb 16 03:03:34.368938 2020] [so:warn] [pid 29207] AH01574: module wsgi_module is already loaded, skipping [Sun Feb 16 03:03:34.371217 2020] [http2:warn] [pid 29207] AH10034: The mpm module (prefork.c) is not supported by mod_http2. The mpm determines how things are processed in your server. HTTP/2 has more demands in this regard and the currently selected mpm will just not do. This is an advisory warning. Your server will continue to work, but the HTTP/2 protocol will be inactive. [Sun Feb 16 03:03:34.371234 2020] [http2:warn] [pid 29207] AH02951: mod_ssl does not seem to be enabled [Sun Feb 16 03:03:34.371790 2020] [lbmethod_heartbeat:notice] [pid 29207] AH02282: No slotmem from mod_heartmonitor [Sun Feb 16 03:03:34.371850 2020] [:warn] [pid β¦ -
Error Using CheckConstraint in Model.Meta along with Django GenericForeignKey - Joined field references are not permitted in this query
I am trying to restrict GFK to be pointed to objects of a few models only, and I thought CheckConstraint will be a great way to do this, however I get this error class ManualAdjustment(Model): content_type = models.ForeignKey(ContentType, null=True, on_delete=models.CASCADE) object_id = models.PositiveIntegerField(null=True) booking_obj = GenericForeignKey('content_type', 'object_id') # should point to a app1.Booking1 or app2.Booking2 or app3.Booking3 only - trying to enforce this via CheckConstraint class Meta: constraints = [ models.CheckConstraint( check= Q(content_type__app_label='app1', content_type__model='booking1') | Q(content_type__app_label='app2', content_type__model='booking2') | Q(content_type__app_label='app3', content_type__model='booking3'), name='myconstraint_only_certain_models'), ] Error I get on migrate execute_from_command_line(sys.argv) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/core/management/commands/sqlmigrate.py", line 30, in execute return super().execute(*args, **options) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/core/management/commands/sqlmigrate.py", line 64, in handle sql_statements = executor.collect_sql(plan) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/db/migrations/executor.py", line 225, in collect_sql state = migration.apply(state, schema_editor, collect_sql=True) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/db/migrations/operations/models.py", line 827, in database_forwards schema_editor.add_constraint(model, self.constraint) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 343, in add_constraint sql = constraint.create_sql(model, self) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/db/models/constraints.py", line 47, in create_sql check = self._get_check_sql(model, schema_editor) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/db/models/constraints.py", line 37, in _get_check_sql where = query.build_where(self.check) File "/Users/myuser/.virtualenvs/xenia371/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1296, β¦ -
On page navigation with anchor tag on dropdown menu
I'm currently building a top navigation bar that shows dropdown on hover on some of the nav-items. It currently looks like this <nav class="navbar navbar-expand-lg"> <div class="container-fluid"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ml-auto"> <li class="nav-item dropdown"> <a href="#information" class="nav-link dropdown-toggle" id="navbarDropdown1" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> About Us </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown1"> <a class="dropdown-item" href="#">Who we are</a> <a class="dropdown-item" href="#">What we do</a> </div> </li> <li class="nav-item"> <a class="nav-link" href="#">Events</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Contact Us</a> </li> </ul> </div> </div> </nav> So what I want to do is having both dropdown on hover working as well as using the dropdown same button(nav-item) to work as a button that navigates the user to specified section. In the above code, it would be "About Us" that will show its following dropdown on hover. And when "About Us" is clicked, it would navigate the user to specified section ("#information"). I can only get one or the other working. If i get dropdown on hover, navigation doesn't work, if i get navigation work, then dropdown doesn't appear on hover. Any help would be much appreciated Thank you. -
Django: How to add static files in shared templates?
I have shared templates that doesn't belongs to any particular app. Here's my project tree: . βββ root_app β βββ asgi.py β βββ forms.py β βββ __init__.py β βββ __pycache__ β βββ settings.py β βββ urls.py β βββ views.py β βββ wsgi.py βββ db.sqlite3 βββ another_app β βββ admin.py β βββ api_services.py β βββ apps.py β βββ __init__.py β βββ migrations β βββ models.py β βββ __pycache__ β βββ templates β βββ tests.py β βββ urls.py β βββ utils.py β βββ views.py βββ manage.py βββ Pipfile βββ Pipfile.lock βββ README.md βββ requirements.txt βββ static β βββ css β βββ styles.css βββ templates βββ base.html βββ home.html In my settings file I have: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = [ ... ... 'django.contrib.staticfiles', ] STATIC_URL = '/static/' STATIC_DIR = [os.path.join(BASE_DIR, 'static')] In my base.html template, I'm trying to call the styles.css from static/css/styles.css this way: {% load static %} <link rel="stylesheet" type="text/css" href="{% static "css/styles.css" %}" /> But the server responds with a not found: "GET /static/css/styles.css HTTP/1.1" 404 What I'm doing wrong? -
how to count matches in different querysets
I want to count different querysets in my template after doing a search over all models but it seems that the different querysets are in a list of lists. my view function: class Search(ListView): template_name='artdb/searchResult.html' def get_queryset(self): # override get_queryset() has to have that name... q=self.request.GET.get('seastr') models=[Person,Activity,Member,Comment] fields=[l._meta.fields for l in models] res=[] for i,j in enumerate(models): sq=[Q(**{x.name + "__icontains" : q}) for x in fields[i] if not isinstance(x,ForeignKey)] res+=[j.objects.filter(k) or None for k in sq] res=[k for k in res if k] if q: return res else: return Person.objects.none() # SELECT ... WHERE headline ILIKE '%Lennon%'; def get_context_data(self,*args,**kwargs): #q=self.request.GET.get('seastr') context=super().get_context_data(*args,**kwargs) context['member']=Member.objects.all() return context context dict: {'page_obj': None, 'view': <artdb.views.Search object at 0x7f415ec88080>, 'is_paginated': False, 'object_list': [<QuerySet [<Person: David Bolander>, <Person: adam something>]>, <QuerySet [<Comment: david bolander comment>]>], 'member': <QuerySet [<Member: 2019-11-21>, <Member: 2020-02-10>]>, 'paginator': None} my template: {% extends "artdb/index.html" %} {% block sr1 %} <ul> <a class="btn btn-light btn-outline-success my-2 my-sm-0" role="button" href="{% url 'artdb:search' %}"> Persons: {{object_list.count}} </a> <a class="btn btn-light btn-outline-success my-2 my-sm-0" role="button" href="{% url 'artdb:search' %}"> Activities: {{activity.count}} </a> <a class="btn btn-light btn-outline-success my-2 my-sm-0" role="button" href="{% url 'artdb:search' %}"> Members: {{member.count}} </a> <a class="btn btn-light btn-outline-success my-2 my-sm-0" role="button" href="{% url 'artdb:search' %}"> β¦ -
502 error caused my multiple hosts in django
I am trying to allow multiple hosts that are pulled from database. Its working fine locally but in production I am getting 502 error. Hereβs my production setting file from .settings import * DEBUG = False DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'projectname_settings', 'USER': '******', 'PASSWORD': '******', 'HOST': 'localhost', 'PORT': '', } } ALLOWED_HOSTS = [ "mydomain.com", ] + get_allowed_hosts(DATABASES['default']) Allowed_hosts.py def get_allowed_hosts(db_params): connection = None if db_params['ENGINE'] == 'django.db.backends.postgresql_psycopg2': import psycopg2 connection = psycopg2.connect(user=db_params['USER'], password=db_params['PASSWORD'], host=db_params['HOST'], port=db_params['PORT'], database=db_params['NAME']) elif db_params['ENGINE'] == 'django.db.backends.sqlite3': import sqlite3 connection = sqlite3.connect(db_params['NAME']) if connection is not None: cursor = connection.cursor() sites_query = cursor.execute("SELECT domain FROM django_site") sites_result = cursor.fetchall() cursor.close() connection.close() I am thinking if thereβs special nginx setting needed for this kind of setting -
Django ModuleNotFoundError when making migrations
First of all: I am well aware that there are several questions with this exact error but I've read at least 20 of them and none helped me correct this error. This being said, the problem is the following: I created a directory called 'api' inside my Django project to store all the code related to the api. Inside this directory I created an app called 'profiles_app'. There, in the models.py file I defined a UserProfile class to override the default Django UserProfile class. I then added the app to the INSTALLED_APPS variable in the settings.py file and overrid the default UserProfile class with the following line: AUTH_USER_MODEL = 'profiles_api.UserProfile' Finally I tried to make the migrations to see the new table in the database and this is when the error occurred. This is the stack trace: (venv) C:\Users\Juan Pablo\Documents\backend\backend_django>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\JUANPA~1\Envs\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\JUANPA~1\Envs\venv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\JUANPA~1\Envs\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\JUANPA~1\Envs\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\JUANPA~1\Envs\venv\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) β¦ -
Django Unhasable Type List even though im passing in an object ?(many to many field)
I am trying to run a migration script for my django app, but I keep getting TypeError: unhashable type: 'list' even though I am clearly passing in an Object: I get: error line 87, in buildCisc c.exclusions.add(exclus) line 944, in add self._add_items( line 1119, in _add_items target_ids = self._get_target_ids(target_field_name, objs) line 1059, in _get_target_ids target_ids.add(target_id) TypeError: unhashable type: 'list' when I run the following code ... for ex in exclusionList: if len(Course.objects.filter(ID=ex)) > 0: # exclusion course already exsists exclus = Course.objects.filter(ID=ex) c.exclusions.add(exclus[0]) else: # exclusion course does not exsist yet so we must create it first exclus = Course(ID=ex) exclus.save() c.exclusions.add(exclus) #this is line 87 causing the error where c is a Course object create in prior code, and exclusions is a many to many field from Course to itself. if I try using exclus = Course.objects.create(ID=ex) instead that also gives the same error. The error seems to be saying that the exclus that I am passing in to c.exclusions.add is a list, but it is very clearly an object. I even tried switching exclus to exclus[0] to see if it somehow thought it was a list, but this gave me error: Course Object not iterable so it is β¦ -
how h can convert DICOM image to image of type .png in python
i'm working on django project that make operations on DICOM images and i want to convert Dicom to image of type .png so ican render it to frontend . how i can convert this DICOM to .png type? -
Foreign key in Ajax POST request in Django
I have some problems with my web app . When I try to add new item I get an error: TypeError: Field 'id' expected a number but got . Is the any solutions ? Here is my code: views.py if request.method == 'POST': if request.is_ajax(): form = AddTask(request.POST) if form.is_valid(): form.cleaned_data form.save() user_membership = User.objects.get(id=request.user.id) expence_object = model_to_dict(Task.objects.get(pk=user_membership)) return JsonResponse({'error': False, 'data': expence_object}) models.py class Task(models.Model): title=models.CharField(max_length=200) date = models.DateTimeField(default=datetime.now,blank=True) is_published=models.BooleanField(default=True) usertask=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True) Ajax form $('#taskpost').submit(function (e) { // console.log("Creating the book"); e.preventDefault(); // get the form data var formData = { 'title': $('#id_title').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), contentType: 'application/x-www-form-urlencoded', encode: true, }; $.ajax({ type: 'POST', url: 'create/', data: formData, dataType: 'json', }).done(function (data) { -
How to download a file from FileField django
I am building an application that should allow users to upload and download files using Django. I have a model that stores files: class Document(models.Model): description = models.CharField(max_length=255, blank=True) unit_code = models.CharField(max_length=6) input = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) @property def filename(self): return os.path.basename(self.document.name) I am able to display the list of uploaded files in my template from my view as such: def Document(request, str): documents = Document.objects.filter(unit_code=str) And in the template an anchor tag to download the file using the url as seen here: {% for document in documents %} {{document.filename}}<a href="{{document.input.url}}"> Download Document </a> {% endfor %} Right now I'm getting an error page not found (The url is directing to 127.0.0.1:8000/media/documents/file_name Is it possible to download the file using the anchor tag with the Django development server? -
(Django) How to send the same data to some clients instead of others?
I need your help! I have a server running into django with clients connecting to it. Once they are connected some objects "User" are added to the database with some property, such as user_id etc.. I'd like to write a function that send the same data (e.g. a color) back to only some of them to color the body of the html, and other data to others..how can I identify the clients to which the server should send the data? I was thinking to trigger the function with a button that make an ajax call to the server, but then I don't know how to take track of the "identification" of the client in the server. -
Django profile pic upload saves picture in two folders
I've made a group picture upload in Django, but it saves in /media folder and in /media/group_pics folder. Expected behaviour: It only saves to /media/group_pics folder models.py: class Group(models.Model): name = models.CharField(max_length=15, unique=True) date_created = models.DateField(default=timezone.now) image = models.ImageField(default='group_pics/default-group.jpg', upload_to='group_pics/') def __str__(self): return self.name def image_url(self): if self.image and hasattr(self.image, 'url'): return self.image.url def save(self, *args, **kwargs): try: group = Group.objects.get(id=self.id) if not ('default-group.jpg' in group.image.url) and group.image != self.image: group.image.delete() except: pass if not self.slug: self.slug = self._get_unique_slug() super().save(*args, **kwargs) forms.py class GroupUpdateForm(ModelForm): image = forms.ImageField(max_length=150, allow_empty_file=False) x = forms.FloatField(widget=forms.HiddenInput(), required=False) y = forms.FloatField(widget=forms.HiddenInput(), required=False) width = forms.FloatField(widget=forms.HiddenInput(), required=False) height = forms.FloatField(widget=forms.HiddenInput(), required=False) class Meta: model = Group fields = ['image'] def save(self): group = super(GroupUpdateForm, self).save(commit=False) if self.cleaned_data.get('x') != None: x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') image = Image.open(group.image) cropped_image = image.crop((x, y, w+x, h+y)) resized_image = cropped_image.resize((350, 350), Image.ANTIALIAS) resized_image.save(group.image.path) group.save() return group and views.py if request.method == 'POST': update_form = GroupUpdateForm(request.POST, request.FILES, instance=group) if update_form.is_valid(): update_form.save() Where is my mistake that causes the double image save? -
Wagtail rendering if referenced pages in an inlineModel
In my Article pageModel I have an InlinePanel('technologies', label="Technologies"), which loads up an ArticlesPageTechnologies(Orderable) which is using PageChooserPanel('technologies', 'rb_tech_portfolio.TechnologiesPage'),. This is all working nicely. But what I want to do is to list links to these referenced pages, but I cannot seem to work out the best way to do this. The closest I have gotten is with {% for technology in page.technologies.all %} but this simply gives me the object which connects the 2 page models, whereas I want the referenced object. Is this all there ready to use, or do I need to do an extra query in def_context to do this? Thanks, Dan -
Where to build database objects in Django(without using shell)?
I have created my database models in my model.py file, but I want to be able to populate them with data. I have the code written that reads in the data from a text file I have and create the objects for my models. But I am not sure where to actually run this code, all the tutorials I can find they only create the objects through the shell, but since I am reading in from a text file and since the code is quite long I dont want to use the shell. My solution was to create a file called buildDB in my application folder, and run the code there, but this will not work: if I try to import my models at top of file using from .models import * I get ImportError: attempted relative import with no known parent package when I run it. If I try using from applicatonName.models import* I get django.core.exceptions.ImproperlyConfigured: 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. When I google the second error message, it would appear that this happens becasue I am not using manage.py shell, and β¦ -
NOT NULL constraint failed: community_comment.posts_id?
how can I fix this issue? the page runs perfectly. when I do post the post. it posts but when I want to type the comment and send by 'GET' I get this error. so, how can I ignore this error this my first question? - also, I need anyone to give me the best way to make a relationship between post and comment models.py from django.db import models from django.contrib.auth.models import User class Publication(models.Model): title = models.CharField(max_length=30) class Meta: ordering = ['title'] def __str__(self): return self.title class Article(models.Model): publications = models.ManyToManyField(Publication) headline = models.CharField(max_length=100) class Meta: ordering = ['headline'] def __str__(self): return self.headline class Post(models.Model): users = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) question = models.TextField(max_length=500) def __str__(self): return self.title class Comment(models.Model): posts = models.ForeignKey(Post, on_delete=models.CASCADE) comment = models.TextField(max_length=500) def __str__(self): return self.comment views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User from .models import Post, Comment from .forms import PostForm, CommentForm def index(request): # All questions posts = Post.objects.all() return render(request, 'community/index.html', {'posts': posts}) def post_view(request): post_form = PostForm context = {'posted': post_form} # Create post if request.method == 'GET': post_form = PostForm(request.GET) if post_form.is_valid(): user_post = post_form.save(commit=False) user_post.title = post_form.cleaned_data['title'] user_post.question = post_form.cleaned_data['question'] post = Post.objects.create(users=User.objects.get(username=request.user), title=user_post.title, β¦ -
How can I get a members list from a discord bot and then display it on my site?
import random from discord.ext import commands client = commands.Bot(command_prefix = '.') channel = None @client.event async def on_ready(): channel = client.get_channel(677999369642836037) async def members_list(request): curMembers = [] for member in channel.members: curMembers.append(member) return render(request, "discordTool/discordTool.html", { 'members_list': curMembers, }) client.run('my token') This is my views.py, I use django and I am well aware of the fact that I need to place the bot code in a different file, my main issue is that I don't know how I would get the members list from the bot if it's placed in a different file? or how to call the bot and run it only whenver I need it to run? -
Cannot import class from models in Django project
So I made the following class in models.py class MovieTile(models.Model): movie_name = models.CharField(max_length=200) movie_picture = models.CharField(max_length=200) movie_link = models.CharField(max_length=200) I want to import this class into a .py file by using from scraper import models or from scraper.models import MovieTile But then I get the following error: C:\Users\CLeen\Anaconda3\envs\WebsitescraperV1\python.exe "C:\Users\CLeen\PycharmProjects\WebsitescraperV1\locallibrary\bs4 test.py" Traceback (most recent call last): File "C:\Users\CLeen\PycharmProjects\WebsitescraperV1\locallibrary\bs4 test.py", line 4, in <module> from scraper import models File "C:\Users\CLeen\PycharmProjects\WebsitescraperV1\scraper\models.py", line 4, in <module> class Search(models.Model): File "C:\Users\CLeen\Anaconda3\envs\WebsitescraperV1\lib\site-packages\django\db\models\base.py", line 103, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Users\CLeen\Anaconda3\envs\WebsitescraperV1\lib\site-packages\django\apps\registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "C:\Users\CLeen\Anaconda3\envs\WebsitescraperV1\lib\site-packages\django\apps\registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "C:\Users\CLeen\Anaconda3\envs\WebsitescraperV1\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\Users\CLeen\Anaconda3\envs\WebsitescraperV1\lib\site-packages\django\conf\__init__.py", line 64, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: 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. Process finished with exit code 1 So I figured I had to add the class into my settings file like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'scraper.apps.ScraperConfig', 'scraper.models.MovieTile', ] But when I try to make migrations I get the following Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File β¦ -
In Django I am unable to pass pk value through url when creating new child instance
This is an issue I have been struggling with for a long time, so posting it on here hoping for some guidance. When I am creating a new child instance of an item, I am struggling to pass the pk value from the parent, so the child instance is created under the correct parent. Parent Models.py class listofbooks(models.Model): booktitle = models.CharField(max_length = 100) description = models.TextField(null=True) Child Models.py class author(models.Model): listofbooks = models.ForeignKey("books.listofbooks",on_delete=models.CASCADE, blank=True, null=True) authorname= models.CharField(max_length = 100, null=True) authorage = models.IntegerField() Parent urls.py app_name = 'books' urlpatterns = [ path('', BookListView.as_view(), name='book-list-view'), path('new/', BookCreateView.as_view(), name='book-create'), path('<int:listofbooks_pk>/', BookDetailView.as_view(), name='book-detail'), ] Child urls.py app_name = 'author' urlpatterns = [ path('<int:listofbooks_pk>/authors', AuthorListView.as_view(), name='author-list'), path('<int:author_pk>', AuthorInfoView.as_view(), name='author-detail'), path('<int:listofbooks_pk>/new/', AuthorCreateView.as_view(), name='author-create'), ] Child views.py class AuthorInfoView(DetailView): model = author pk_url_kwarg = "author_pk" class AuthorListView(ListView): model = author pk_url_kwarg = "author_pk" context_object_name = 'listofauthors' def get_queryset(self, *args, **kwargs): return author.objects.filter(listofbooks=self.kwargs['listofbooks_pk']) class AuthorCreateView(CreateView): model = author pk_url_kwarg = "listofbooks_pk" fields = ['authorname','authorage'] def get_success_url(self, *args, **kwargs): return reverse('author:author-detail',kwargs={'author_pk':self.object.pk}) Here is the author_list.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>This is the list of Authors page</h1> {% for item in listofauthors %} <br> {{ item.authorname }} <br> {{ β¦ -
PostgreSQL/psycopg2 Password Authentication using SSH Tunneling
I am trying to connect to a PostgreSQL Database via ssh tunnel. I am able to connect using the psql command, but for some reason when I attempt to use psycopg2, I get the error FATAL: password authentication failed for user Here is part of my pg_hba.conf for reference: local all postgres peer # TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all peer # IPv4 local connections: host all all 127.0.0.1/32 md5 # IPv6 local connections: host all all ::1/128 md5 # Allow replication connections from localhost, by a user with the # replication privilege. local replication all peer host replication all 127.0.0.1/32 md5 host replication all ::1/128 md5``` -
Django ArrayField on Frontend Form?
I'm currently in the process of rebuilding my WordPress website into a full Django web app. With WordPress, I had made great use of the awesome Advanced Custom Fields plugin, and I'm struggling to get the same functionality with Django. One field in particular with ACF is called a "Repeater Field" that lets me click a button to add another row to an array. I did manage to get something similar working with Django, but only in the Admin part. I've used this plugin "Django Better Admin ArrayField" - https://github.com/gradam/django-better-admin-arrayfield and it displays the arrayfield exactly as I want: Django Better Admin ArrayField How can I get this to work on the frontend of the site, like in a user-submitted form? -
Django: Passing context to another view
I'm trying to pass my context of items to another view, with only the specific item's details, but I'm having trouble to even find the correct documentation on how this works. I need to get my specific package to another view, and have all of it's properties with it, like dependencies, description, homepage etc. Views: from django.shortcuts import render import re, random def index(request): packages = {} latset_header = None with open("app/packages/status.real.txt", encoding="UTF-8") as f: for l in f: l = l.strip() # if line contains a keyword if "Package: " in l: latset_header = l.replace("Package: ", "") packages[latset_header] = {'name': latset_header} elif "Depends: " in l: packages[latset_header]['depends'] = l.replace("Depends: ", "") elif "Description: " in l: packages[latset_header]["description"] = l.replace("Description: ", "") elif "Homepage: " in l: packages[latset_header]["homepage"] = l.replace("Homepage: ", "") context = {'items': packages} return render(request, 'packages_index.html', context) def show_package_details(request, package): context = {'item': package} return render(request, 'packages_details.html', context) Urls: from django.urls import include, path from . import views urlpatterns = [ path('', views.index, name='index'), path('<str:package>', views.show_package_details, name='package-details') ] packages_index.html - template: {% extends "home.html" %} {% block container %} <h2>The packages</h2> {% if items %} <ul> {% for item, value in items.items %} <li> <a href="{{item}}">{{ item β¦ -
Django and HTML : Too many values to unpack (expected 2)
I'm new to django and html and I have to do a project for school. I tried to learn how forms works with django and I think I got it django forms right. But I simply don't know how to make it work with my html. I got the too many values to unpack (expected 2). Here is the important part of my form: class ConfiguratorForm(forms.Form): queryOfProject = TypeOfProgram.objects.values('name') queryOfFramework = Framework.objects.values('name','version') listOfProject = [] listOfFramework = [] listOfFramework += queryOfFramework listOfProject += queryOfProject listFramework=[] listProject = [] for i in range(0,len(listOfFramework)): listFramework.append(listOfFramework[i]['name'] + " " +listOfFramework[i]['version']) for i in range(0,len(listOfProject)): listProject.append(listOfProject[i]['name']) typeOfTheproject = forms.ChoiceField(choices = listProject) wantedFramework = forms.MultipleChoiceField(choices = listFramework) Where listProject and listFramework are both list containing elements. And I know it is no good code but I'm learning how everything works and I haven't much time. For the html code. I absolutly don't know what exactly I wrote. I've search so lang and tried a lot of things I've seen. {% block content %} <form method="post"> {% csrf_token %} {{form}} <input type="submit" value="Submit"> </form> {% endblock %} If anyone could tell me how to correct the html file or if my form is wrong? -
Failed to load the native tensorflow runtime when we use command python manage.py runserver
Failed to load the native TensorFlow runtime. See https://www.tensorflow.org/install/errors for some common reasons and solutions. Include the entire stack trace above this error message when asking for help.