Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to alter the auto created model of a ManyToManyField in Django
I have two Django models Authors and Books. Authors has a reference to Books using a ManyToManyField as: books = models.ManyToManyField(Books) As per Django's documentation a table will be auto-created for us. How do I alter the id field of this auto-created table from AutoField to BigAutoField(as I have reached the maximum limit of the table) without losing data or moving the data around, and without running any SQL commands. Note: The model was auto created by Django and not manually defined. A table exists in the database but not a model which can be directly modified by the user. Please correct me if this is wrong. I could not find a solution where we can simply alter the id column of an auto-generated "through" table using Django with the above restrictions. This answer https://stackoverflow.com/a/40654521 helped. But it involves creating a through model, which does not allow using add, create or set in Django v2.0 and I strongly prefer to use them. -
How can i add a new tab in user edit interface on wagtail admin
I want to add a new tab so my custom class Profile can be edited in user edit wagtail user edit interface And here is my very basic profile to associate with django user models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') iframe = models.CharField("iframe", max_length=500, blank=True, null=True) name = models.CharField("iframe", max_length=500, blank=True, null=True) class Meta: verbose_name = "Prefil" verbose_name_plural = "Prefil" def __str__(self): return self.name I tried following the documentation from wagtail, but I'm not really understanding it admin.py # wagtail_hooks.py from wagtail.admin.views.account import BaseSettingsPanel, SettingsTab from wagtail import hooks from .forms import CustomProfileSettingsForm custom_tab = SettingsTab('custom', "Custom settings", order=300) @hooks.register('register_account_settings_panel') class CustomSettingsPanel(BaseSettingsPanel): name = 'custom' title = "My custom settings" tab = custom_tab order = 100 form_class = CustomProfileSettingsForm form.py from django import forms from .models import Profile class CustomProfileSettingsForm(forms.ModelForm): class Meta: model = Profile fields = ["iframe"] -
django webrtc and django channels
I've been on the lookout for a comprehensive step-by-step tutorial guiding me through the process of creating a video chat app using Django, WebRTC, and Django Channels. Despite my efforts, I haven't come across any truly helpful resources. While I've consulted the Django Channels documentation, I'm struggling to grasp how all the components seamlessly come together. It's worth mentioning that I'm not a novice with Django, having used it for some time. However, I've never delved into the realm of Django Channels or implemented live chat or video features before, making this a novel experience for me. I'd greatly appreciate any assistance, insights, or suggestions you can offer. Thank you in advance for your help! -
How can I filter and display only the expenses and incomes associated with the currently logged-in user?
Can I get something like roadmap that i should follow when i am creating a Income and Expense tracker using django that should have authentication and authorization like which and how many models to create? I have set up the environment and just wondering how do the user only have the access for what they have entered -
operational error in showed in my page saying no such table found
MY ERROR PAGE---------> enter image description here THIS IS MY VIEW.PY------------> enter image description here i am currently new to django and dont know how to solve this problem please help me get pass over this error -
What is the safe and right way of storing information from a form into an SQL Database integrated to your django project?
I am currently sending my potential clients emails related to their Form query but I am not sure what the next step would look like such as storing the information they have provided(safely) and automating for the new messages I will possibly receive when the site is up on the web. 1- Is it a good idea to have a database integrated for this, if not, what kind of drawbacks I might encounter? 2- Are there any tutorials or websites related to this that provide industry-standard safety tips? -
Django 5 GeneratedField with values from foreign (prefetched) relationships
I am messing around with Django 5's GeneratedField and I am curious if I can use it to total values from a foreign, prefetched, relationship. For example: class Balance(SafeDeleteModel, TimestampModel, UUID): id = models.AutoField(primary_key=True) current_total = models.DecimalField(default=0, max_digits=1000, decimal_places=2) # new, I want to calculate the total amounts of Charges and Payments which are prefetched relationships. generated_total = GeneratedField( expression=F(self.charges.values_list('total_amount', flat=True)) - F(self.payments.values_list('total_amount', flat=True)), output_field=models.BigIntegerField(), db_persist=True, ) Where my Charges and Payments models have an FK of Balance I know the expressions self.charges.values_list('total_amount', flat=True) and self.payments.values_list('total_amount', flat=True) are not valid in the F expression, but I am trying to accomplish something like it. Is this possible yet? -- I am guessing not given the docs: The expressions should be deterministic and only reference fields within the model (in the same database table) -
what could cause tables created in Django via models and migrations not to be queryable via PgAdmin
In my Django app I created models and ran migrations to create tables in my database which I have properly configured in my settings.py file. The tables are created in my database and can be queried using query manager, but I want to use raw SQL but when I do I get the "relation doesn't exist" error including when I query these tables in PgAdmin. All relations created via models are not queryable via regular SQL. What could be the cause of this. def test2(request): user = User.objects.get(username=request.user.username) if user.is_authenticated: print(user) with connection.cursor() as cursor: cursor.execute("SELECT first_name FROM auth_user WHERE username = %s", [user.username]) row = cursor.fetchone() print(row[0]) cursor.execute("SELECT no_of_projects FROM Machine_projects WHERE First_Name = %s", [row[0]]) row2 = cursor.fetchone() pro = Projects.objects.get(pk=2) print(pro, row2[0]) all_tables = connection.introspection.table_names() print(all_tables) return redirect('register2') else: return render(request, 'test2.html') this the error I get. django.db.utils.ProgrammingError: relation "machine_projects" does not exist LINE 1: SELECT no_of_projects FROM Machine_projects WHERE First_Name...type here I've deleted the tables by running py manage.py migrate zero and redoing the migrations. Only for the same thing to happen. -
Django imports nested in a class not working after moving to the top
I have this piece of code in the project I'm working on: from django.apps import AppConfig from django.contrib.auth import get_user_model class UsersConfig(AppConfig): name = 'apps.users' verbose_name = 'Users' def ready(self): """Monkey-patches auth.User models to provide Student and Employee.""" super(UsersConfig, self).ready() def get_student(self): if hasattr(self, 'student_ptr'): return self.student_ptr else: return None def get_employee(self): if hasattr(self, 'employee_ptr'): return self.employee_ptr else: return None UserModel = get_user_model() setattr(UserModel, 'student', property(get_student)) setattr(UserModel, 'employee', property(get_employee)) from django.contrib.auth import models as auth_models setattr(auth_models.AnonymousUser, 'student', None) setattr(auth_models.AnonymousUser, 'employee', None) import apps.users.signals # noqa: F401 After moving import from django.contrib.auth import models as auth_models from inside the class to the top of the file, the project stops working. Does it really matter in python/django where exactly in the code is the import located or is this a problem of other nature? -
HttpPlatformHandler error with Django app hosted in IIS
I have a Django site I'm developing, which uses Waitress as the WSGI server. When I run the server.py file from the command line, everything works as expected. As a next step toward rolling it out, I'm trying to "wire in" the application to the Windows IIS web server. After a lot of searching around I found this article which is fairly recent and provides a comprehensive set of steps to get it working with HttpPlatformHandler (which I take to be the preferred option, as Microsoft reports they are no longer maintaining WFastCGI). I also took into account the author's caveat regarding lack of expertise, which is why I'm using Waitress rather than the Django development server as he did. The issue I'm having is that with IIS configured to host the Django app, the browser connection never goes through. While the browser makes its connection attempt, the Windows event log on my server shows a recurring error every minute or so: Note, each time the error is triggered, the process number and port number are both different; the Error Code of -2147023436 however is always the same. Additionally, each time the error occurs a new log file is generated … -
Issue with CKEditor 6.7.0 not displaying in Heroku deployment. It should render as it is called in `requirements.txt.`
Issue with CKEditor 6.7.0 not displaying in Heroku deployment. It should render as it is called in requirements.txt. the key error message is in the console which was discovered through debugging steps Failed to load resource: the server responded with a status of 404 (Not Found) ckeditor-init.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) coach-matrix-d2cd1e717f81.herokuapp.com/:1 Refused to execute script from 'https://coach-matrix-d2cd1e717f81.herokuapp.com/static/ckeditor/ckeditor-init.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. coach-matrix-d2cd1e717f81.herokuapp.com/:1 Refused to execute script from 'https://coach-matrix-d2cd1e717f81.herokuapp.com/static/ckeditor/ckeditor/ckeditor.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. /favicon.ico:1 Failed to load resource: the server responded with a status of 404 (Not Found) debugging steps inspecting the page on heroku <div class="container"> <!-- If there is no primary key, we are creating a new question --> <h2>Ask a Question</h2> <form method="post" action="/ask_question/"> <input type="hidden" name="csrfmiddlewaretoken" value="Xhq7PrqzWagKDSpNDbdMmIUZwWSRQo4TZYzHeCasEyemlqb5Xpwf6vectROc1n8w"> <div id="div_id_subject" class="form-group"> <label for="id_subject" class=" requiredField"> Enter your question heading here<span class="asteriskField">*</span> </label> <div> <input type="text" name="subject" maxlength="100" class="textinput textInput form-control" required id="id_subject"> <small id="hint_id_subject" class="form-text text-muted">Enter a subject line for your question.</small> </div> </div> <div id="div_id_content" class="form-group"> <label for="id_content" class=" requiredField"> Content<span class="asteriskField">*</span> </label> <div> … -
Django-crontab, setting cronjobs
I'm currentrly developing my Django app with various notifications. To avoid frequently querrying DB I tried to make cronjobs with an hour intervals, that querry for all planed for next hour notifications, count delays, orepare personalized messages etc. For end it should iter on QuerySet send some tasks to celery queue by apply_async on task. I am working with django = "==4.2.1", django-crontab = "==0.7.1" and docker-compose. Whenever I build a container I make a resheduling of all tasks. By this lines in docker-compose.yml: web: build: . ports: - "8000:8000" volumes: - .:/app depends_on: postgres_db: condition: service_healthy queue: condition: service_started environment: - PYTHONUNBUFFERED=1 entrypoint: ["/bin/bash", "-c"] command: - | python manage.py makemigrations python manage.py migrate python manage.py crontab remove python manage.py crontab add python manage.py sync_cronjobs python manage.py runcrons python manage.py runserver 0.0.0.0:8000 and Dockerfile: FROM python:3.11.3 LABEL authors="AM" WORKDIR /app COPY Pipfile Pipfile.lock ./ RUN python -m pip install --upgrade pip && \ pip install --no-cache-dir pipenv && \ pipenv install --dev --system --deploy RUN apt-get update && \ apt-get install -y cron COPY . . As a result I have a couple of active crons. The problem is, all works fine when I run cronjobs manualy by commands: … -
CORS errors in Tradingview integration in Django Python
I have configured TradingView in Django Python and I am getting CORS errors in console and chart not loading, Already configured CORS for python, and rest external scripts working fine, In settings.py... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1:8000", ] below are configuration scripts added in HTML, <script type="text/javascript" src="https://charting-library.tradingview-widget.com/charting_library/charting_library.standalone.js"></script> <script type="text/javascript" src="https://charting-library.tradingview-widget.com/datafeeds/udf/dist/bundle.js"></script> <script> function initOnReady() { var widget = window.tvWidget = new TradingView.widget({ library_path: "https://charting-library.tradingview-widget.com/charting_library/", debug: true, // uncomment this line to see Library errors and warnings in the console fullscreen: true, symbol: 'AAPL', interval: '1D', container: "tv_chart_container", datafeed: new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"), locale: "en", disabled_features: [], enabled_features: [], }); }; window.addEventListener('DOMContentLoaded', initOnReady, false); </script> errors shown in the console are... Access to script at 'https://charting-library.tradingview-widget.com/charting_library/bundles/runtime.22cd9f6fe908159906ae.js' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. blob:http://127.0.0.1:8000/283852f3-3565-423f-aeb4-75fc0a81c15e:2 GET https://charting-library.tradingview-widget.com/charting_library/bundles/runtime.22cd9f6fe908159906ae.js net::ERR_FAILED 200 (OK) blob:http://127.0.0.1:8000/283852f3-3565-423f-aeb4-75fc0a81c15e:7 Access to script at 'https://charting-library.tradingview-widget.com/charting_library/bundles/en.3732.1bd67796122e14c1a819.js' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. blob:http://127.0.0.1:8000/283852f3-3565-423f-aeb4-75fc0a81c15e:3 GET https://charting-library.tradingview-widget.com/charting_library/bundles/en.3732.1bd67796122e14c1a819.js net::ERR_FAILED 200 (OK) blob:http://127.0.0.1:8000/283852f3-3565-423f-aeb4-75fc0a81c15e:7 Access to script at 'https://charting-library.tradingview-widget.com/charting_library/bundles/9401.1a253c12a3b43291d008.js' from origin 'http://127.0.0.1:8000' has been … -
Issue with Django Channels. Not able to recieve the message in javascript nor print the message in python terminal
I am adding the django channels, where I want to get the progress of each task in for loop that it is being done or not and update the task progress accordingly on the frontend, My views.py has a view as, @login_required def view_create_job_bulk(request): """ Author : Aroosh Ahmad Modified Date : Jan-02-2024 Modified By : None Description : Written to automate the Job creation process. """ if config_operator.debug_flag: printf("In Create job Bulk View") # Fetching user details username = request.user.username user_id = request.user.user_id user_role = request.user.role context = { 'username': username, 'user_role': user_role, } if config_operator.debug_flag: printf(f"View create job Called by user id:{user_id} with role:{user_role}") if request.method == 'POST' and request.FILES['file']: # Getting data details file = request.FILES.get('file') data = pd.read_csv(file) file_paths = data[1:]["File Link Local PC"] channel_layer = get_channel_layer() print("Channel Layer is: ", channel_layer) for i, filepath in enumerate(file_paths, start=1): print(f"File path is : {filepath}") async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'}) channel_layer.group_send( 'notifications_group', {'type': 'send.notification', 'message': f'Iteration {i}'} ) time.sleep(10) response_data = {'message': 'post request complete!!'} return JsonResponse(response_data) return render(request, 'create_bulk_job.html', context) The asgi.py is as follow import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from ttsf.routing import websocket_urlpatterns os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ttsf.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter( … -
different results with icontains in django ORM
I'm filtering results from django database (mysql) with the following: queryset = ( MyModel.objects.select_related("value__value_type") .filter(value__value_name__icontains=search) .order_by("pk") ) class MyModel(models.Model): ... value_name = models.CharField(unique=True, max_length=255) ... class Meta: managed = False db_table = "my_table" When the value of search = "bin" I'm getting one set of results, Results are having substring "bin" in them. and when the value of search="Bin" i'm getting another set of results. Results are having substring "Bin" in them. The results of both of these don't have any intersection. It looks like a collation issue, how to fix this? I can't change anything on the database, as I only have read access. My django version is 3.2. I tried this but it did not work. value_name = models.CharField(unique=True, max_length=255, db_collation='utf8_general_ci') -
There are a better place for put our load tags?
I have a .html with some tags that is used in a auth system. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% block title %} <title>Sign In</title> {% endblock %} </head> <body> {% block content %} <h1>Sign in</h1> {% load socialaccount %} <!-- Loading --> <a href="{% provider_login_url 'google'%}">Login with google</a> {% endblock %} </body> </html> But this way isn't good for readability. I want to know if there are better places to put the load templates into. Because this way the readability is predicated. -
How to implement a scheduled task in a web application made with django
I have a hosted web app made with django and react. now i want to implement a system like- one user request for posting a blog at a specific time specific date. and on that day the post is posted even if the user is not logedin or open the app. how to automate this type of task. for database i am using sqlite3. Now How can i implement this type of task schedulling system using Django and React -
I got some errors related to tailwind at VSCode
[enter image description here](https://i.stack.imgur.com/Jmf8i.png) "I am trying to integrate Tailwind CSS into my Django project, but I keep encountering an error. I would like to find a solution to this problem so that it doesn't happen repeatedly. Can you please help me troubleshoot and advise me on how to proceed?" -
Django - AttributeError at /blog/cat1 'NoneType' object has no attribute 'views'
Would appreciate some help understanding whenever I try to fetch blog posts by category I am getting the following error: AttributeError at /blog/cat1 'NoneType' object has no attribute 'views' 'cat1' is name of category which i have created for test in django admin panel categories are displaying correctly with post but when try to fetch posts by category i am getting error pls check error image Here's my models.py file from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now from ckeditor_uploader.fields import RichTextUploadingField # Create your models here. class Post(models.Model): sno = models.AutoField(primary_key=True) title = models.CharField(max_length=255) content = RichTextUploadingField() thumbnail = models.ImageField(upload_to='featured_image/%Y/%m/%d/') categories = models.ManyToManyField('Category', related_name='posts') author = models.CharField(max_length=15) slug = models.CharField(max_length=255) views = models.IntegerField(default=0) timeStamp = models.DateTimeField(blank=True) def __str__(self): return self.title + ' by ' + self.author class Category(models.Model): name = models.CharField(max_length=50) class Meta: verbose_name_plural = "categories" def __str__(self): return self.name class BlogComment(models.Model): sno = models.AutoField(primary_key=True) comment = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True) timestamp = models.DateTimeField(default=now) def __str__(self): return self.comment[0:13] + "..." + "by " + self.user.username Views.py from django.shortcuts import render, redirect, get_object_or_404 from blog.models import Post, BlogComment, Category from django.contrib import messages from blog.templatetags import … -
raise e.__class__( ValueError: Field 'id' expected a number but got 'face picture from actor'
in windows 10 , i'm using react-router-dom 5.2.0 and react-redux 7.2.5 and react 17.0.2 and axios 0.21.4 and WebStorm 2023.1.3 IDE and PyCharm Community Edition 2023.2 and djangorestframework==3.14.0 and Django==4.2.4 and djangorestframework-simplejwt==5.3.0 frontend Consider - manager_room.js: {loadingGetProductCategories ? <Loader /> : errorGetProductCategories ? <div className="alert alert-danger" >{errorGetProductCategories}</div>:productCategoriesRedux ? <div className="mb-3"> <div className="form-label" htmlFor="categories">select category</div> <select className="form-select" id="categories" value={category} options={productCategoriesRedux} onChange={(e) => handleChangeNormalSelect(e)} multiple> {productCategoriesRedux && productCategoriesRedux.map && productCategoriesRedux.map(category => ( <option value={category.title}>{category.title}</option> ))} </select> </div>:""} 2.backend Consider - product_views.py: @api_view(http_method_names=['POST']) @csrf_exempt @permission_classes([IsAdminUser]) def upload_new_product(request): try: data = request.data file = request.FILES id = data.get('id') CustomUser = get_user_model() user = CustomUser.objects.filter(id=id).first() print("do") reqUser = request.user if user == reqUser: product = Product.objects.create(user=user, name=data.get('productName'), image=file.get('productImage'), brand=data.get('brand'), description=data.get('description'), rating=data.get('rating'), price=data.get('price'), countInStock=data.get('countInStock')) product.categories.set(data.getlist('category')) product.save() srz_data = ProductSerializer(instance=product, many=False) return Response(srz_data.data, status=status.HTTP_201_CREATED) else: return Response({'detail': 'you are not this account\'s user'}, status=status.HTTP_401_UNAUTHORIZED) except APIException as err: return Response(str(err), status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: print("Nothing went wrong") finally: print("The 'try except' is finished") error is in line product.categories.set(data.getlist('category')) by raise: raise e.__class__( ValueError: Field 'id' expected a number but got 'face picture from actor'. [03/Jan/2024 13:39:44] "POST /api/v1/products/upload_new_product/ HTTP/1.1" 500 130849 Actually the save category is not saved in manyTmanyField and it shows me the mentioned error Consider - … -
TypeError in CustomScaler using StandardScaler in scikit-learn
I'm facing an issue with a custom scaler class in Python using scikit-learn. I have a CustomScaler class that inherits from BaseEstimator and TransformerMixin, and it utilizes the StandardScaler. However, I'm encountering a TypeError during the initialization. Here's the relevant code: from sklearn.base import BaseEstimator, TransformerMixin from sklearn.preprocessing import StandardScaler class CustomScaler(BaseEstimator,TransformerMixin): def __init__(self,columns,copy=True,with_mean=True,with_std=True): self.scaler = StandardScaler(copy,with_mean,with_std) self.columns = columns self.mean_ = None self.var_ = None def fit(self, X, y=None): self.scaler.fit(X[self.columns], y) self.mean_ = np.mean(X[self.columns]) self.var_ = np.var(X[self.columns]) return self def transform(self, X, y=None, copy=None): init_col_order = X.columns X_scaled = pd.DataFrame(self.scaler.transform(X[self.columns]), columns=self.columns) X_not_scaled = X.loc[:,~X.columns.isin(self.columns)] return pd.concat([X_not_scaled, X_scaled], axis=1)[init_col_order] unscaled_input.columns.values columns_to_scale = ['Month Value', 'Day of the Week', 'Transportation Expense', 'Distance to Work', 'Age', 'Daily Work Load Average', 'Body Mass Index', 'Children', 'Pets'] absenteeism_scaler = CustomScaler(columns= columns_to_scale) // Getting error in this step absenteeism_scaler.fit(unscaled_input) I checked the scikit-learn documentation for the StandardScaler class to ensure correct usage, but I can't find any solution for this error. What might be causing this issue? Any alternative approaches to resolve it? Error Message: TypeError Traceback (most recent call last) Cell In[24], line 1 ----> 1 absenteeism_scaler = CustomScaler(columns_to_scale) Cell In[20], line 7, in CustomScaler.__init__(self, columns, copy, with_mean, with_std) 6 def __init__(self, columns, copy=True, … -
Unable to run my django server connectinng changing database engine to msql
I am trying to connnect MySQL to my django app. I keep on receive an error message suggesting me to install my SQL client first. When I run: python manage.py runserver Here is the errro message I receive: > (guessgame) Maiks-MBP:guessgame maiknoungoua$ python manage.py runserver > Watching for file changes with StatReloader > Exception in thread django-main-thread: > Traceback (most recent call last): > File "/Users/maiknoungoua/.local/share/virtualenvs/guessgame-o_cdbTdf/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 15, in <module> > import MySQLdb as Database > ModuleNotFoundError: No module named 'MySQLdb' > Can anyone help ? Thanks in advance for the help. I tried sourcing my export path in the bash profile # Setting PATH for Python 3.9 # The original version is saved in .bash_profile.pysave PATH="/Library/Frameworks/Python.framework/Versions/3.9/bin:${PATH}" export PATH export PATH=$HOME/omnetpp-5.6.2/bin:$HOME/omnetpp-5.2.1/tools/macosx/bin:$PATH export QT_PLUGIN_PATH=$HOME/omnetpp-5.6.2/tools/macosx/plugins alias ll='ls -lGaf' export PATH="/usr/local/mysql/bin:$PATH" -
Does django forms block fields other than those specified by default?
class CreatePost(LoginRequiredMixin,CreateView): model = Post template_name = 'create.html' form_class = CreateForm @transaction.atomic def form_valid(self, form): form.instance.user = self.request.user form.instance.content = post_filters(form.cleaned_data['content']) response = super().form_valid(form) PostIp.objects.create( postip=get_client_ip(self.request), postid=form.instance.id ) return response createForm fields = ("title", "content") If a malicious person specifies an id, would it be a security issue? I read some of the code but lost interest in reading it because of its difficulty. -
Can multiple images be uploaded from one selection field in Django?
Can multiple images be uploaded from one selection field for slides in Django? I will use these images in a slide, my slides have over 50. I use manyToManyField but i couldn't do it. I will take your suggestions into consideration, folks. -
exporting a postgresql backup from my local pgadmin into my postgresql dabase in ubuntu vps server
I very much preferred to have a subdirectory for my pgadmin4 like myweb.com/pgadmin4 but could not have it the right way. I already had my gunicorn_start file which showed me the web fine, but when I tried to reach that subdirectory it was always badgateway 502. I was just adding another binding command in here below, first this is a file SOCKFILE=/home/boards/run/gunicorn.sock exec ../venv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=unix:$SOCKFILE \ <-------TRYING TO ADD ANOTHER unix: for pgadmin --log-level=$LOG_LEVEL \ --log-file= And of course, I had created another location in my nginx file like this: location /pgadmin4/ { include proxy_params; proxy_pass http://unix:/tmp/pgadmin4.sock; proxy_set_header X-Script-Name /pgadmin4; } It wouldn't work (probably because in my gunicorn_start file I didn't know what syntax to write) Something like this? --bind unix:/tmp/pgadmin4.sock --workers=13 --threads=25 --chdir ~/venv/lib/python3.10/site-packages/pgadmin4 pgAdmin4:app I yes managed to launch that subdirectory by using an artificial command like this: gunicorn --bind unix:/tmp/pgadmin4.sock --workers=13 --threads=25 --chdir ~/venv/lib/python3.10/site-packages/pgadmin4 pgAdmin4:app I say artificial because it is a one-off launch, it is not in the gunicorn_start file restarted by supervisor and when I entered the subdirectory, all I had was a blank page with some error messages. That messed up …