Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image is not saving in database django
form.html <form> {% csrf_token %} <table> <tr> <td> <label for="name">NAME: </label> <input type="text" data-bind="value: $data.name" name="name" class="form-control" id="name" placeholder="name of product"> </td> </tr> <tr> <td> <label for="price">PRICE </label> <input type="text" name="price" data-bind="value:$data.price" class="form-control" id="price" placeholder="price"> </td> </tr> <tr> <td> <label for="description">DESCRIPTION: </label> <textarea cols="10" rows="5" name="description" data-bind="value:$data.description" class="form-control" id="description" placeholder="product description"></textarea> </td> </tr> <tr> <td> <label for="image">IMAGE: </label> <input type="file" class="form-control-file" id="image" name="image" required> </td> </tr> <tr><td><button type="button" id="submit" data-bind="click : save" class="btn btn-success">Submit</button></td></tr> </table> </form></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script> <!-- <script type="application/javascript" src="static/js/knockout-file-bind.js"></script> --> <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); </script> <script> // $(document).on('click', '#submit', function(e) { var ViewModel = function () { var self = this; self.name = ko.observable(""); self.price = ko.observable(""); self.description = ko.observable(""); self.image = $(document).on('click', "#submit", function(e) { formdata = new FormData(); $('#image').get(0).files[0]; formdata.append('image', image); }); // self.image =$('#image').get(0).files[0]; // formdata = new FormData(); // formdata.append("image", image); // console.log(formdata.get("image")); var PerData = { name: … -
Passing an ID parameter to the Django Channel connect handler for single channel layers
I am setting up a Single Channel websocket layer as documented here https://channels.readthedocs.io/en/stable/topics/channel_layers.html#single-channels But the problem is I need to pass a meta data parameter into the connect method from client-wide websocket initilization because otherwise there is no way to reference it outside of the Consumer. E.g. imagine I want to use a SESSION_ID as the channel name lookup key. Only the client knows the SESSION_ID. I want to be able to do something like: client.js (pass the session id to the websocket connection somehow) monitorWS = new WebSocket('ws://localhost:9000/ws/api/monitor/?SESSION_ID=762123') consumer.py (save the session id with the auto-generated channel name) class ChatConsumer(WebsocketConsumer): def connect(self): # Make a database row with our channel name Session.objects.create(channel_name=self.channel_name, id=[SESSION_ID]) How can I pass that ID parameter so that my code outside the Consumer can pick up the single channel name so that I can do something like this: elsewhere.py from channels.layers import get_channel_layer channel_layer = get_channel_layer() session=Session.objects.get(id=762123) # get the session object in the example await channel_layer.send(session.channel_name, { "type": "chat.message", "text": "Hello there!", }) -
is it possible to prevent/bar more than one person from accessing a page with Django?
Is it possible to prevent/bar more than one person from accessing a page with Django? For example: I have an editing screen for a product, and if someone is accessing that page, for that product, I don't want anyone but can enter that url, to be clearer, let's say I'm editing a product called "smartphone " and his route is http://localhost:8000/product/edit/smartphone, when someone tries to edit this product, he cannot enter the page. That's my question. I don't know if it was very clear, but I ask that whoever knows can help me. -
htmx and django: display feedback on successful/failed request
So I'm trying to display a feedback message saying "added" or "failed" when a form is submitted with HTMX to my Django backend. Basically what I have right now is a form that performs an hx-post, and the reply is a div containing the updated information, which is swapped with the current contents of the div. <div id="list"> <!-- The stuff in here is loaded through another template, which is the result of a successful myApp:add operation. --> </div> <form hx-post="{% url 'myApp:add' eid=e.id %}" hx-swap="outerHTML" hx-target="#list"> <!-- Some stuff in here --> </form> <div id="result"> <!-- Here I should print a message saying correct or incorrect depending on the HTMX result (if the entry was added or there was any kind of error, even connection errors) --> </div> The thing is, in case of an error in the form or in the request itself, the list will remain the same, but I would like for it to print something like "error" in the result div. In case the new entry is added correctly I would like to print a "success" message in the result div. I'm also using Alpine.js, if that's any help. -
What is the best way to collect a log of C++ Application, Running in k8s + django Server?
I've tried searching through Google, but I'm confused which one is the best way. There are ways to use stdout and stderr, but I would like to use a more convenient framework. Is there any tip or standardized way you can give me? -
is that possible to add mutiple images save in one column in mysql using dajngo framework
iam a beginner in the field. i currently doing a ecommerce website which sells samrtphone. 1 .I want to add mulitple product images. In order to add the images do i need more columns for every image. How to add mutiple ram and price for product. Samrtphone have mutiple ram according to ram price varies.user can choose ram of the product. How to add this in to my project using mysql. Do ineed more columns for every ram. -
ModuleNotFoundError: No module named 'base'
every time I try to run my program using python manage.py runserver the same error comes up. I have already added my Django app in my settings.py. this error first came up after starting my Django project and installing my Django app. The error: > Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Program Files\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\core\management\commands\runserver.py", line 115, in inner_run autoreload.raise_last_exception() File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\core\management\__init__.py", line 381, in execute autoreload.check_errors(django.setup)() File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\hp\OneDrive\Desktop\jwt-believe-0.0.1\env\lib\site-packages\django\apps\config.py", line 211, in create mod = import_module(mod_path) File "C:\Program Files\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked … -
what technology to use to make a chatapp?
what technologies would be best to add a chat app to your website? Like, I see a live customer support chat box on many websites. I think php and ajax are a common way of doing it. I also think django could be commonly used. However, I was wondering if there's a better or "best" way to do this sort of thing? Such as using javascript like next.js, reactjs, and preactjs. There's twilio and plivo. What's a modern and like high quality approach to accomplish adding a live chat pop-up window to a website? My other related inquiry is what to use for creating a website like omegle or a random chat website? -
How to properly connect models in Django?
In my project I want to have global database of ingredients. I also want for each User to have a possibility to add a ingredient to his own Fridge model but with additional field "numOf". I've stumbled upon errors with PATCH request and im thinking that my database is wrongly connected. Does anyone maybe have a better idea how to arrange my models? Ingredient models class Ingredient(models.Model): name = models.CharField(max_length=100) class UserIngredient(models.Model): ingredient = models.OneToOneField(Ingredient, unique=True, on_delete=models.CASCADE) numOf = models.IntegerField(default=1) Fridge model class Fridge(models.Model): owner = models.OneToOneField(User, related_name='fridge', on_delete=models.CASCADE) ingredients = models.ManyToManyField(UserIngredient, blank=True) def __str__(self): return self.owner.username + "'s Fridge" def save(self, *args, **kwargs): super().save(*args, **kwargs) For example, let 1st user have 2 Apples, 2nd 3 Apples and 3rd 4 Apples in their Fridge. Then in UserIngredient table I have 3 records: Apple 2, Apple 3, Apple 4 which all point to a single Apple Ingredient. How can I avoid this redundancy and just point to a Ingredient instance? -
GDAL path issues in macOSX High Sierra
Had GDAL installed and working on my machine (macOS running 10.13.6) for a Django project running python 3.6.5. Didn't have any issues for 2+ years and haven't changed anything (to my knowledge), but now running into an issue when I try to execute a manage.py command where it will err out with OSError: dlopen(libgdal.so, 6): image not found Trace: Traceback (most recent call last): File "manage.py", line 19, in <module> execute_from_command_line(sys.argv) File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/Users/me/.pyenv/versions/3.6.5/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 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/db/models/base.py", line 124, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/db/models/base.py", line 325, in add_to_class value.contribute_to_class(cls, name) File "/Users/me/.pyenv/versions/3.6.5/lib/python3.6/site-packages/django/db/models/options.py", line 214, … -
How to integrate any company SSO to my Django app?
I have an app for businesses and one of their main requests is to integrate their SSO (some uses Okta, others use Azure). Currently we use python-social-core, but to add a new company we have to modify code. Do you know a better and simpler way to do this? Like a library that allows me to generate the SAML2.0 url or the redirect link of OIDC, without messing with ENV variables on my app. -
Django form not saving to database via ModelForm
I am trying to add my form to the database using the ModelForm but it's not going through or even printing the form in the view, i have also tried doing each field alone in the view via cleaned data still nothing inserted in the database my view.py def index(request): component = Component.objects.all() form = ComponentModelForm() if request == 'POST': form = ComponentModelForm(request.POST) print(form) if form.is_valid(): form.save() return redirect('/maintenance') else: form = ComponentModelForm() context = { 'components': component, 'form':ComponentModelForm(), } return render(request, 'maintenance/index.html', context) models.py class Component(MPTTModel): name = models.CharField(max_length=100) manufacturer = models.CharField(max_length=100) model = models.CharField(max_length=100) serial_number = models.CharField(max_length=255) price = models.IntegerField() note = models.TextField() parent = TreeForeignKey("self", verbose_name=( "Parent Component"), blank=True, null=True, related_name='children', on_delete=models.CASCADE) def __str__(self): return f"{self.id}, {self.name}" forms.py class ComponentModelForm(forms.ModelForm): class Meta: model = Component fields = ("name", "manufacturer", "model", "serial_number", "price", "note", "parent",) the template: <div> <form method='POST' action=''> {% csrf_token %} {{form.as_p}} <input type="submit" value='Create'/> </form> </div> -
How to correctly design a django database?
I have been learning Django recently, before, I used to design the ER models and all that stuff by myself, although I'm not an expert on databases. I have some questions that I couldn't find anywhere. In terms of designing the database, does a Django developer use only the UML diagrams related to the models or does he/she designs the ER models and then the tables? If the developer only uses the UML diagrams, is database normalization necessary or even applicable in this case? In my ignorance I opted to design the models as UML because I like to have diagrams and it seemed appropriate to me. Is this the right approach? UML diagram of django models Thank you. -
my Django website style broken after upload on shared hosting
My site can't locating where it's static and media file after upload on shared hosting. Here is my settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] MEDIA_URL = '/media/' MEDIA_ROOT = '/home/project32/rootfolder/media/' STATIC_ROOT = '/home/project32/rootfolder/static/' ** root urls.py** urlpatterns = [ path('admin/', admin.site.urls), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) where I am doing mistake? why my web site not location the static folder of my shared hosing ? I also run python manage.py collectstatic -
How can I stream a local video in a Django view, in loop?
I am streaming a local video in a Django Response using StreamingHttpResponse and this code, but I am not sure how can I loop the video so it replays after finishing. -
Django APIView data format from AJAX
I was trying to send an array of objects in views.py using APIView to insert multiple rows in 1 post request. This is my JavaScript data format: const data = { group_designation: [ {id: 1}, {id: 2}, {id: 3}, ] } I run an insomnia app and it only accepts this kind of format: { "group_designation": [ {"id": 1}, {"id": 2}, ] } However, if I send a post request using the javascript format stated above, it gives me a bad request error(400). This is the payload in network tab: group_designation[0][id]: 1 group_designation[1][id]: 2 group_designation[2][id]: 3 In Django, this is the request.data result: <QueryDict: { 'group_designation[0][id]': ['1'], 'group_designation[1][id]': ['2'], 'group_designation[2][id]': ['3'] }> My code in Django: def post(self, request): temp_objects = [] new_data_format = {'group_designation': temp_objects} serializer = GroupSerializer(data=new_data_format, many=True) if serializer.is_valid(raise_exception=True): group_data_saved = serializer.save() return Response({ "success": "success!!!" }) I was just trying to rewrite the data format so it will be saved but no luck trying. Please help. Thank you! -
Use pipenv with django heroku
So I began to code a project with python, and I was using a tutorial that told me to use a pip environment as my virtual environment. A problem arose, however, when I performed the git push heroku master command. It could not find the package django-heroku! I was confused, because when I ran python manage.py runserver, the server on my computer ran. I later realized that the problem was that the pip environment was located in a .virtualenvs folder that was outside of the folder I was pushing to heroku. I then changed to a python environment, which was located in the directory I was pushing to heroku. The problem was solved! The virtual environment, and consequently the installed packages, were inside the directory being pushed to git, and I could use them in my website! But the question still remains: can you use a pip environment for a django project being pushed to git? Thanks! -
How to display error when using is_active for Login
I set a user.is_active to false so they can't login. user.is_active=False user.save() I would like to override the login section to show that the account has been disabled. Currently it shows on disabled accounts. Please enter a correct username and password. Note that both fields may be case-sensitive. I am using the auth login path('accounts/', include('django.contrib.auth.urls')), with a simple template {% extends 'base.html' %} {% block title %}Login{% endblock %} {% block content %} <h2>Log In</h2> <form method="POST" action="."enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Log In</button> <button><a href="{% url 'signup' %}">Sign up</a></button> </form> {% endblock %} -
Manager isn't available; 'auth.User' has been swapped for 'reg.User'
I can't seem to find a solution for the error I'm getting when trying to save a user. I wish to save different users. I have searched for previuosly answered questions with the similar problems, and have tried to use get_user_model but the error still clings. Kindly Check my code and guide to the solution. Manager isn't available; 'auth.User' has been swapped for 'reg.User' Here is my Models file from enum import unique from django.db import models from django.db.models.fields import DateField from django.db.models.fields.related import OneToOneField from django.urls import reverse from django.contrib.auth.models import AbstractUser, BaseUserManager, PermissionsMixin import datetime import os from django.db.models.deletion import CASCADE, SET_NULL class CustomUserManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError('Email Address Required') email = self.normalize_email(email) user = self.model(username=username, email=email, password=password) user.set_password(password) user.save(using=self._db) return user class User(AbstractUser): is_agent = models.BooleanField(default=False) is_coordinator = models.BooleanField(default=False) is_regional_director = models.BooleanField(default=False) is_national_director = models.BooleanField(default=False) objects = CustomUserManager() class National_Director(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) user = OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL) gender = models.CharField(max_length=20, null=False, blank=False, choices=GENDER) id_no = id_no = models.CharField(max_length=150, null=False, blank=False, unique=True) address = models.TextField(null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) objects = CustomUserManager() #Views from django.shortcuts import render,redirect from django.http import HttpResponse from django.views.generic import CreateView … -
How to prevent Django save action to avoid repetitive DB calls on already existing data
My current code for saving articles saves new articles and prints 'The Post Already Exists!' if a duplicate is found, but it's still making DB calls and so now I have ID gaps in my articles table because of the false saves caused by duplicate articles not being saved. How can I improve my code to prevent the save action if a duplicate is found to preserve consistency in my article IDs? if not Posts.objects.filter(title=post_title, slug=post_slug).exists(): post = Posts( title = post_title, link = post_link, summary = post_summary, image_url = image_link, slug = post_slug, pub_date = date_published, guid = item.guid, feed_title = channel_feed_title, feed_link = channel_feed_link, feed_description = channel_feed_desc, source_id = selected_source_id, category_id = selected_category_id ) post.save() for i in range(len(article_list)): post_tags = post.tags.add(article_list[i]) else: print("The Post Already Exists! Skipping...") I keeping getting such errors: django.db.utils.IntegrityError: duplicate key value violates unique constraint "Posts_posts_slug_key" DETAIL: Key (slug)=() already exists. -
Django POST is missing positional argument
I'm bypassing the use of a model to get basic filter responses for presentation purposes from the user. Accordingly, I've defined a cardsStatsForm class as below: forms.py from django import forms class cardStatsForm(forms.Form): def __init__(self, filterList, sortList, *args, **kwargs): super(cardStatsForm, self).__init__(*args, **kwargs) self.fields['filts'].choices = filterList self.fields['filts'].label = "Select player rankings for inclusion in statistics:" self.fields['sorts'].choices = sortList self.fields['sorts'].label = "Choose a sort order:" filts = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=(), required=True) sorts = forms.ChoiceField(choices=(), required=True) Unfortunately, when I retrieve the POST command, I am getting a positional argument error. I am confused, however, because I thought the point of the POST is to retrieve values. So why does "post-POST" code typically run the class instance? If i were to submit a positional value, would it not be overwritten by this statement? Isn't request.POST a form of "self" statement? views.py @login_required() def cards(request): f_name = STAT_FILES / 'csv/segment_summary_quart.csv' # pathname = os.path.abspath(os.path.dirname(__file__)) df = pd.read_csv(f_name, index_col=None) pl_name = STAT_FILES / 'pickles/lbounds' pu_name = STAT_FILES / 'pickles/ubounds' lbounds = pickle.load(open(pl_name, "rb")) ubounds = pickle.load(open(pu_name, "rb")) filter_name = [] i = 0 max_i = len(ubounds) while i < max_i: filter_name.append(f'Personal best trophy range: {str(int(lbounds[i])).rjust(4," ")}-{str(int(ubounds[i])).rjust(4," ")}') i += 1 filter_id = range(len(filter_name)) filter_list = list(zip(filter_id, filter_name)) … -
Django " ImproperlyConfigured:"
I have created a blog with django by following some book. The django website works but the terminal keeps on showing this message if i try to interpret the code on spyder(setting.py, models.py) 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. Here ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings the solution which was given for this was: set DJANGO_SETTINGS_MODULE=mysite.settings as in the documentation for django. However if i stop the server and restart it after running the code i am still getting the same error. Could you please advise what setting it is referring to which are not configured? This is perticularly odd because it prints out the same error message if I run this help(models.DateTimeField) -
my background image property cant function in my Django project yet the static files are functioning and my other CSS properties are also functioning
kindly need your help.Ive connected my Django static files(CSS and images) and basically the html and CSS are connected very well, however there is only one CSS property that's not working and that is "background-image".ive tried giving the website a background image but it cant display my image inspite of other CSS properties functioning very well.what do you think may be the problem? -
Mysql query of 200000 rows just crashes before showing on the view
I have a project with this stack: Python, Django, Django REST-Framework, MySQL, Angular. Currently I have an app that has a functionality to list some rows, when you try to list them on the view, they should be shown by pages of 20 rows each, loading in a single query 200000 rows but showing nothing because it crashes. I want to know if I have to optimize my code or do something with the DB. -
Please how can I collect data from multiple forms, having multiple templates using one view
I have all my forms in a list and my templates in a dictionary. I want to collect information from the forms without having to create a model for each form and also without creating separate views for each form. FORMS = [ ('step_1', PersonalDetails()), ('step_2', Summary()), ('step_3', Employment()), ('step_4', Education()), ('step_5', Social()), ('step_6', Skill()) ] form_list = [item[1] for item in FORMS] TEMPLATES = { 'step_1': 'form_1.html', 'step_2': 'form_2.html', 'step_3': 'form_3.html', 'step_4': 'form_4.html', 'step_5': 'form_5.html', 'step_6': 'form_6.html', }