Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to type the elements of the dictionary that is returned by a serializer?
I use the serializers that come from django-rest-framework to validate many of the request on my app end. I have found thhat is very useful to get the objects on the serializer, but the dictionary the serializer returns with the serializer.validated_data is not typed This is how I perform the validation: On views.py def post(self, request): body_serializer = ExampleSerializer(data=request.data) body_serializer.is_valid(raise_exception=True) body_data = body_serializer.validated_data # to get the object object_one = body_data['object_one'] On the serializers.py class ExampleSerializer(serializers.Serializer): field_one = serializers.CharField(required=True, help_text='field_one') field_two = serializers.CharField(required=True, help_text='field_two') field_three = serializers.CharField(required=True, help_text='field_three') def validate(self, attrs): object_one:ObjectOne = ObjectExample.objects.get(field=field_one) attrs['object_one'] = object_one return attrs Is there a way I can type the return dictionary? -
How to import my views from user in my urls.py file
I am using Pycharm for my Django Project. It says that it is a unresolved reference. In Startup/urls.py I have following code: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('vereinsapp/', include('vereinsapp.urls')), path('', include('vereinsapp.urls')), #Users path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('delete_user/', user_views.deleteuser, name='delete_user'), path('profile_confirm_delete/', user_views.profile_confirm_delete, name='profile_confirm_delete'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I also tried startup.users but then I get the error Message "no module named..": -
bootstrap alert-dismissable not working in django
here is my html code <div class="msg"> {% if messages %} {% for message in messages %} <div class="alert alert-dismissible alert-success"> <button type="button" class="close" data-dismiss="alert"> × </button> <strong>{{message}}</strong> </div> {% endfor %} {% endif %} </div> message is showing after form submission, but x button not working of collapse, how to resolve it, please help me. -
Django Model form is showing invalid with initialized values and file
I have a model like this: ` class Cohortpdfs(models.Model): id = models.AutoField(primary_key=True,editable=True) title= models.CharField(max_length=200,validators=[MaxLengthValidator(100)]) content=models.FileField() cohort_id=models.ForeignKey(Cohort,on_delete=models.CASCADE,default=0,db_constraint=False) ` I want to initialize and save data from views. views.py: ` if requests.method == 'POST': initialvalue={ 'cohort_id':id, 'title':requests.POST.get('title'), 'content':requests.FILES['content'], } if contentform.is_valid(): print("form valid") else: print("FORM ERROR") ` Forms.py class CohortpdfsForm(forms.ModelForm): class Meta: model = Cohortpdfs fields = [ "title","content","cohort_id", ] widgets={ 'title' : forms.TextInput(attrs={'class': 'form-control','max_length':20}), 'content': forms.FileInput(attrs={'class': 'form-control'}), 'cohort_id': forms.TextInput(attrs={'type': 'hidden'}), } ` This is showing my form is not valid. How can I initialize the form with uploaded file(PDF) and save it into the model database. This is showing my form is not valid. How can I initialize the form with uploaded file(PDF) and save it into the model database. -
What is the correct way to end a Watchdog observer without a sleep loop?
I am relatively new to python and programing in general. This is my first question on Stack Overflow so thank you for any responses in advance! My question is this. I have a Python web application that is using the django framework. A new feature of that web application requires the use of a locally installed command line tool on the server, that tool dumps an output file to a directory previously created. I want to watch that directory and when a file is created in it that ends in .json call a parsing function. Enter the Watchdog library. I have followed a number of tutorials/checked on here for how to correctly setup an observer. They all have the observer being started and then immediately going into a time.sleep(1) loop while waiting for something to happen. However since this is a django webapp I don't want to sit and wait while the watchdog observer is looking for the file to be created. Here is an example code from Geeks for Geeks: if __name__ == "__main__": # Set the format for logging info logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') # Set format for displaying path path = sys.argv[1] if len(sys.argv) > … -
No module named 'manage_db.tools'; 'manage_db' is not a package
I have a Package that works with the Django Framework. I'm trying to import two packages that are outside the Django package, so that I can work with their Python files. In order for Django to recognize the packages, I added the following lines to the Django settings file: manage_db = os.path.join(BASE_DIR.parent.parent, "manage_db") g = os.path.join(BASE_DIR.parent.parent, "g") sys.path.append(manage_db) sys.path.append(g) And in the views.py file I wrote: from g.globals import Globals from manage_db.tools import Tools The error I got is: For the first package - No module named 'manage_db.tools'; 'manage_db' is not a package For the second package - No module named 'g' . I read from people who had similar problems that they changed the names of the directories, and it worked for them, I tried, and I change the name to "g", but it didn't work. Note: I created the packages, they are not packs that require pip install Thanks in advance to all the helpers. -
How to receive the value of an html attribute through the submitted form DJANGO
How can I get the value of the "data" attribute of this select's options? With request.POST.get() <select name="installments" id="installments"> <option value="1" data="239.8">239,80</option> <option value="2" data="125.31">125,31</option> <option value="3" data="84.76">84,76</option> <option value="4" data="64.5">64,50</option> <option value="5" data="52.35">52,35</option> <option value="6" data="44.25">44,25</option> </select> I tried this: installments = request.POST.get('installments.attrs=["data"]') -
create new objects from list only if its not in django database
I am having a list of python objects. suppose py_objs_list = [...data...] Model is Card I want to create a new object in django database only if database already dont have object My solution is to do objects.all() on my Card and run a for loop on py_objs_list and check if py_obj in objects.all(). If not present im taking that py_obj into seperate list. Finally creating objects using bulk_create py_objs_list = [...data...] cards = list(Card.objects.al()) <--- i know db hits here ---> emails = [card.email for card in cards] <--- does db hit here also everytime in a loop ---> empty_list = [] for py_obj in py_objs_list: if py_obj[some_data] not in emails: empty_list.append(py_obj) ---bulk_create--- Is this the best way to tackle this problem? pls tell me if not (want the best one). thnks:) Now my doubt is does db hit everytime in list comprehension as mentioned above my solution for this problem -
'Category' object is not subscriptable Django
I am learning Django. I wrote a simple model and some views method in Django rest framework so that I can modify some particular attributes when needed to all the records that need that. Here is the model: from django.db import models class Category(models.Model): name = models.CharField(max_length=255) isActive = models.BooleanField(default=True) def __str__(self): return self.name Then, I created this view to modify the isActive session when I call it: class CategoriesChangeActiveView(views.APIView): def post(self, request, format=None): try: categories = request.data.get('categories') for category in categories: category = Category.objects.get(id=category['id']) category.isActive = category['isActive'] category.save() except Exception as e: return Response({'error': 'Bad request'}, status=status.HTTP_400_BAD_REQUEST) return Response({'success': 'Active changed'}, status=status.HTTP_200_OK) Even when the format of my request is correct ( I debugged each line ) when it comes to the line category.isActive = category['isActive']it throws the error that'Category' object is not subscriptable`. I don't know why or how to fix it. I saw in the official documentation, on older StackOverflow questions that this is doable, but I don't understand why I can't. Can someone please suggest what I am doing wrong? Thank you -
How to improve search faster inside json file?
Here I have a sample JSON file with size more than 10MB(which will increase eventually). I have a python function which will try to match the entire json object from the json file and if matches it returns the next json object. This is my current implemention.It does the work but not sure it is the right way. I want some suggestions so that I can make this function much faster and scalable since this function is going to be used in several rest apis. { "all_checks": [ { "key":"value", "key2": { "key": "val" } }, { "key":"value", "key2": { "key": "val" } }, { "key":"value", "key2": { "key": "val" } }, ] } python func import os import json from django.conf import settings def get_value(value): with open(os.path.join(settings.BASE_DIR, "my_json.json")) as file: data = json.load(file) # for i,v in enumerate(data["all_checks"]): # if json.dumps(value) == json.dumps(v): # return data["all_checks"][i + 1] ls = [data["all_checks"][i + 1] for i, v in enumerate(data["all_checks"]) \ if json.dumps(value) == json.dumps(v)] return dict(ls[0]) This function will be used in several apis -
502 bad gateway error pointing django model.py to other database
i'v setup a wagtail website. I altered models.py from my home-page model. In this models.py i try to acces a database running on another external server. Before i altered models.py the website was running fine, but after altering models.py i get a 502 bad-gateway error. I'm using Nging and gunicorn to serve the website. I followed this tutorial to set it up: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-22-04 I noticed this error in gunicorn: Dec 05 22:36:50 ip-172-31-30-62 gunicorn[1853]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Dec 05 22:36:50 ip-172-31-30-62 systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Dec 05 22:36:50 ip-172-31-30-62 systemd[1]: gunicorn.service: Start request repeated too quickly. Dec 05 22:36:50 ip-172-31-30-62 systemd[1]: gunicorn.service: Failed with result 'exit-code'. This is my models.py for accessing the external database. (With help of @Richard Allen) class CasPage(Page): .... @property def plot(self): try: conn = psycopg2.connect( database="xxxx", user="xxxx", password="xxxx", host="xxxxxxxxxxxxx", port=xxxxx, ) cursor = conn.cursor() strquery = (f'''SELECT t.datum, t.grwaarde - LAG(t.grwaarde,1) OVER (ORDER BY datum) AS gebruiktgas FROM XXX''') data = pd.read_sql(strquery, conn) fig1 = go.Figure( data = data, layout=go.Layout( title="Gas-verbruik", yaxis_title="aantal M3") ) return plotly.plot(fig1, output_type='div', include_plotlyjs=False) except Exception as e: print(f"{type(e).__name__} at line {e.__traceback__.tb_lineno} of {__file__}: {e}") return None I can acces the external database (no … -
how to call kedro pipline or nodes in Django framework
I have to call Kedro nodes or pipelines in Django API, and need to use Kedro pipelines or nodes output as input in Django API. Not getting any solution. Please suggest some solution for this. How to call Kedro pipeline or nodes in Django APIs? -
how to create a time limit object in django
In this project I create some objects and I want to filter only objects that are created 120 seconds ago . I tried this Line : Model.objects.filter(start_time__gte=Now() - timedelta(minutes=2) , user = request.user , code = data['code']) But It does not work for me . any other solution? (and django timezone is set on Asia/china) -
DJANGO - Unable to refresh my edit profile page
Good day, I am making a Django application, I want to call my data that the user signs up with and to display the information they submitted as: Name Email Then I want to be able to change that data and then I want to save it, and reload back into the dashboard, but when I am updating my 'update_profile.html' the info is not updating, I can; add form data and change it What am I doing wrong? My code below: views.py from django.shortcuts import render, redirect, HttpResponse from django.contrib import messages, auth from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from contacts.models import Contact def register(request): if request.method == 'POST': # Get form values first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] # Check if passwords match if password == password2: # Check username if User.objects.filter(username=username).exists(): messages.error(request, 'That username is taken') return redirect('register') else: if User.objects.filter(email=email).exists(): messages.error(request, 'That email is being used') return redirect('register') else: # Looks good user = User.objects.create_user( username=username, password=password, email=email, first_name=first_name, last_name=last_name) # noqa # Login after register auth.login(request, user) messages.success(request, 'You are now logged in') return redirect('index') # user.save() # messages.success( # request, 'You … -
django : AttributeError: 'str' object has no attribute 'utcoffset'
template: <h2>Summary Details</h2> <table class="center"> <thead> <tr> <th>scrapper_id</th> <th>scrapper_jobs_log_id</th> <th>external_job_source_id</th> </tr> </thead> <tbody> {% for stud in scrappers %} {% csrf_token %} <tr> <td>{{stud.scrapper_id}}</td> <td>{{stud.scrapper_jobs_log_id}}</td> <td>{{stud.external_job_source_id}}</td> </tr> {% endfor %} views.py from django.db.models import Q from django.utils import timezone import pytz import warnings warnings.filterwarnings("ignore") get_records_by_date = "" def index(request): if request.method == "POST": from_date = request.POST.get("from_date") f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d') print(f_date) to_date = request.POST.get("to_date") t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d') print(t_date) new_records_check_box_status = request.POST.get("new_records", None) print(new_records_check_box_status) error_records_check_box_status = request.POST.get("error_records", None) print(error_records_check_box_status) drop_down_status = request.POST.get("field",None) print(drop_down_status) global get_records_by_date if new_records_check_box_status is None and error_records_check_box_status is None: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)) get_records_by_date = check_drop_down_status(get_records_by_date,drop_down_status) elif new_records_check_box_status and error_records_check_box_status is None: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)).filter(new_records__gt=0) get_records_by_date = check_drop_down_status(get_records_by_date, drop_down_status) elif error_records_check_box_status and new_records_check_box_status is None: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)).filter(error_records__gt=0) get_records_by_date = check_drop_down_status(get_records_by_date, drop_down_status) else: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)).filter(Q(new_records__gt=0)|Q(error_records__gt=0)) get_records_by_date = check_drop_down_status(get_records_by_date, drop_down_status) # print(get_records_by_date) else: roles = Scrapper.objects.all() return render(request, "home.html",{"scrappers": roles}) return render(request, "home.html", {"scrappers": get_records_by_date}) AttributeError: 'str' object has no attribute 'utcoffset'. It was running correctly when I run another project and change the url the error is showing. Is there any solution what is the reason for the error. Its showing error in view page and html page return render(request, "home.html",{"scrappers": roles}) . … -
How to refer to main database instead test one Django TestCase
I am using Django TestCase class to run some test in my project. Few of these test using selenium driver to test forms via browser. Creation of new instance of database table (Recipe for ex.) Point is. Since im using a browser and fill forms fields with Selenium driver, new recipe instance is creating for main database, not test one. I am trying to delete last added row from Recipe table with Recipe.objects.using('default').latest('id').delete() after successful test run. 'default' is single database connection. But this query is targeting test database, which us creating while tests run. How make query refer to main database instead? -
Django AUTO INCREMENT for PK
I have some models in my Django app and I saw the field 'auto_increment_id' (as PK) doesn't work as 'AUTO INCREMENT' (the DB is Postgres). I made 2 records with auto_increment_id 1 and 2, delete record 2 and make a new one with auto_increment_id=3 instead of auto_increment_id=2. models.py class Testme(models.Model): auto_increment_id = models.AutoField(primary_key=True) year = models.ForeignKey( Year, verbose_name="Year", blank=False, on_delete=models.CASCADE, ) def __str__(self): return str(self.auto_increment_id) How can I fix it? Thanks a lot! -
Django I can't pull data from database. DoesNotExist error in web
Admin can change the web title,keywords or description. But it's not working rn. When i entry website i have a error: DoesNotExist at / Setting matching query does not exist. This is my home/models.py from django.db import models class Setting(models.Model): title = models.CharField(max_length=150) keywords = models.CharField(max_length=255) description = models.CharField(max_length=255) company = models.CharField(max_length=50) address = models.CharField(blank=True, max_length=150) phone = models.CharField(blank=True, max_length=15) fax = models.CharField(blank=True, max_length=15) email = models.CharField(blank=True, max_length=50) smptpserver = models.CharField(blank=True, max_length=30) smptemail = models.CharField(blank=True, max_length=30) smptpassword = models.CharField(blank=True, max_length=150) smptport = models.CharField(blank=True, max_length=15) icon = models.ImageField(blank=True, upload_to='images/') facebook = models.CharField(blank=True, max_length=50) instagram = models.CharField(blank=True, max_length=50) twitter = models.CharField(blank=True, max_length=50) aboutus = models.CharField(max_length=50) contact = models.CharField(max_length=50) contact_map = models.CharField(max_length=50) references = models.CharField(max_length=50) status = models.CharField(max_length=10, choices=STATUS) create_at = models.DateTimeField(auto_now_add=True) uptade_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title This is my home/views.py from django.http import HttpResponse from django.shortcuts import render from home.models import Setting def index(request): setting=Setting.objects.get(pk=1) context={'setting':setting} return render(request,'index.html',context) This is my home/temp/index.html {% block title %} {{ setting.title }} {% endblock %} {% block keywords %} {{ setting.keywords }} {% endblock %} {% block description %} {{ setting.description }} {% endblock %} -
Django csrf ajax form not submitting data on server but working on local
I am working on a form submission process. Everything is working fine on my local server but when I am hosting the site on my server then the form submission doing nothing. Here is my template file : ` {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/> <meta name="description" content=""/> <meta name="author" content=""/> <link href="{% static 'css/bootstrap.css'%}" rel="stylesheet"/> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <!-- <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script> --> <script src="{% static 'js/emp1.js'%}" type="text/javascript"></script> <link href="{% static 'css/style.css'%}" rel="stylesheet"/> <script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script> <link rel="shortcut icon" href="{% static 'images/favicon.ico' %}"> <!-- <meta name="csrf_token" content="{{ csrf_token }}"> --> <title>Application Upload</title> </head> <body> <header> <section class="bg-white"> <div class="container"> <div class="row"> <nav class="bg-dark mt-1 navbar navbar-expand-lg navbar-light p-1 sticky-top"> <div class="bg-dark container-fluid "><a class="navbar-brand text-white" href="/">Nitin Mandhare <br/> Law Associates LLP</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarColor01"> <ul class="mb-2 mb-lg-0 ms-auto navbar-nav "> <li class="nav-item"><a class="nav-link active" aria-current="page" href="/">Home</a> </li> <li class="nav-item"><a class="nav-link" href="#">Features</a> </li> <li class="nav-item"><a class="nav-link" href="#">Pricing</a> </li> <li class="nav-item"><a class="nav-link" href="#">About</a> </li> </ul> </div> </div> </nav> </div> </div> </section> </header> <main> <section> <div class="bg-secondary container mb-3 mt-3"> <div … -
PyCharm debugger can't connect to Django app inside docker
I try to debug a Django app inside Docker container, the app is launched under uWSGI. Unfortunately, PyCharm debugger can't connect to the container and stops by timeout. My run configuration: I've added up --build to run all containers in debug mode. docker-compose.yml: version: "2.4" services: rabbitmq: image: rabbitmq:3.10.7-management-alpine container_name: bo-rabbitmq rsyslog: build: context: . dockerfile: docker/rsyslog/Dockerfile image: bo/rsyslog:latest container_name: bo-rsyslog platform: linux/amd64 env_file: - .env volumes: - shared:/app/mnt api: build: context: . dockerfile: docker/api/Dockerfile image: bo/api:latest container_name: bo-api platform: linux/amd64 ports: - "8081:8081" - "8082:8082" env_file: - .env volumes: - shared:/app/mnt apigw: build: context: . dockerfile: docker/apigw/Dockerfile image: bo/apigw:latest container_name: bo-apigw platform: linux/amd64 ports: - "8080:8080" env_file: - .env volumes: - shared:/app/mnt depends_on: - api volumes: shared: Dockerfile (for api): FROM nexus.custom.ru/base/python27:2.7.17 # CentOS 7 with Python 2.7 # Environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV PYTHONPATH /app/ ENV PATH /app/:$PATH ENV PIP_DEFAULT_TIMEOUT=100 \ PIP_DISABLE_PIP_VERSION_CHECK=1 \ PIP_NO_CACHE_DIR=1 # Install required software RUN yum -y install enchant # Working directory WORKDIR /app # Install and configure Poetry RUN pip install --no-cache-dir poetry \ && poetry config virtualenvs.create false # Install project dependencies COPY pyproject.toml . COPY poetry.lock . RUN poetry install --no-root --no-interaction # Copy project files COPY … -
Is it possible to use Django ORM with JSON object?
I got two json objects that I need to do sorts of ORM operations, such as count, filter, all Here is the first object comments: in views.py comments_response = requests.get('https://jsonplaceholder.typicode.com/comments') comments_data = json.loads(comments_response.text) so below is what print(comments_data) looks like: [ { "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" }, { "userId": 1, "id": 2, "title": "qui est esse", "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla" }, ] This is second json object: in views.py posts_response = requests.get( 'https://jsonplaceholder.typicode.com/posts') posts_data = json.loads(posts_response.text) so below is what print(posts_data) looks like: [ { "postId": 1, "id": 1, "name": "id labore ex et quam laborum", "email": "Eliseo@gardner.biz", "body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium" }, { "postId": 1, "id": 2, "name": "quo vero reiciendis velit similique earum", "email": "Jayne_Kuhic@sydney.com", "body": "est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati … -
Exclude django-simple-history from a child model
I am actually stuck in a problem where I need to exclude HistoricalRecords (django-simple-history) from a child class without making any changes in the parent class. Here is my code looks like from simple_history.models import HistoricalRecords class BaseModel(models.Model): id = models.UUIDField(...some args...) created_at = models.DateTimeField(...some args...) created_by = models.ForeignKey(...some args...) history = HistoricalRecords(inherit=True) class Meta: abstract = True default_permissions = Constants.STANDARD_ACTIONS def save(self, suppress_modified=False, from_publish=False, **kwargs): super(BaseModel, self).save(**kwargs) class CommonWithExtraFieldsWithoutVersioning(BaseModel, CommonWithoutVersioning, models.Model): class Meta(CommonWithoutVersioning.Meta): abstract = True class Manager(CommonWithExtraFieldsWithoutVersioning): from_branch = models.CharField(...some args...) to_branch = models.CharField(...some args...) from_version = models.IntegerField(...some args...) to_version = models.IntegerField(...some args...) history = None # this is also not working for me def __init__(self, *args, **kwargs): # this I have tried but not working super(DSLJourneyMergeHistory, self).__init__(*args, **kwargs) self.clean_fields('history') But when I try to makemigration it is creating HistoricalRecords for the manager as well and I want HistoricalRecords should not be maintained for the class manager. How do I exclude this as BaseModel and CommonWithExtraFields Models are used across the application and I cannot make any modification in that model -
is possible open python file with os.path.join and execute some function
I work with Django Framework, and I try to open a Python file from outside the Django package. I use the OS library to get to the path that is outside the Django package, like this: file_path = OS.path.join(settings.FILES_DIR, 'execute_get_symbols.py') In file_path I got only the file path Now, I need to execute a function on this python file (execute_get_symbols.py). My questions are: It is possible? And if it is possible, so how. And if it's not possible, So... how can I import files that are outside the Django package and execute the function? Like from package.file_name import function -
Django I can't pull data from database
Admin can change the web title,keywords or description. But it's not working rn. When i entry website everything is fine i don't have any error but informations didn't come from database. This is my home/models.py from django.db import models class Setting(models.Model): title = models.CharField(max_length=150) keywords = models.CharField(max_length=255) description = models.CharField(max_length=255) company = models.CharField(max_length=50) address = models.CharField(blank=True, max_length=150) phone = models.CharField(blank=True, max_length=15) fax = models.CharField(blank=True, max_length=15) email = models.CharField(blank=True, max_length=50) smptpserver = models.CharField(blank=True, max_length=30) smptemail = models.CharField(blank=True, max_length=30) smptpassword = models.CharField(blank=True, max_length=150) smptport = models.CharField(blank=True, max_length=15) icon = models.ImageField(blank=True, upload_to='images/') facebook = models.CharField(blank=True, max_length=50) instagram = models.CharField(blank=True, max_length=50) twitter = models.CharField(blank=True, max_length=50) aboutus = models.CharField(max_length=50) contact = models.CharField(max_length=50) contact_map = models.CharField(max_length=50) references = models.CharField(max_length=50) status = models.CharField(max_length=10, choices=STATUS) create_at = models.DateTimeField(auto_now_add=True) uptade_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title This is my home/views.py from django.http import HttpResponse from django.shortcuts import render from home.models import Setting def index(request): setting=Setting.objects.all() context={'setting':setting} return render(request,'index.html',context) This is my home/temp/index.html {% block title %} {{ setting.title }} {% endblock %} {% block keywords %} {{ setting.keywords }} {% endblock %} {% block description %} {{ setting.description }} {% endblock %} -
Why does my registration form not work ? (Django Framework)
I am creating a website using Django. Somehow I cannot register as a user as I always get the following error message: UnboundLocalError at /register/ local variable 'context' referenced before assignment views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) pform = UserProfileForm(request.POST) if form.is_valid() and pform. is_valid(): user = form.save() profile = pform.save(commit=False) profile.user = user profile.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to login') return redirect('login') else: context = { 'form': UserRegisterForm, 'p_form': UserProfileForm } return render(request, 'users/register.html', context) register.html {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted">Already have an Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a></small> </div> </div> {% endblock content %} Does anyone have an idea why my context is false or won't be accepted ?