Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make Nginx config file for Django Project?
I made Nginx config for My Django project. For DNS I associate with my IP. But this config not working, when I'm checking xyz.com in web but getting error ERR_CONNECTION_REFUSED. server { listen 80; server_name xyz.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/project; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/project/project.sock; } } Please correct me if i'm doing wrong. -
how to set username to python request explicitly
Trying to set token and username to python request.get session, so that next consecutive session.post must have both the session and username. I am able to set the token, however I tried setting the username, but next post call doesn't carry it. request.session['account_token'] = encoded_token - this works request.user = username - doesn't work Expected result should be - with the get call, I should be able to set the username and encoded token to the session and using these set values next post call should be able to authenticate the request and proceed as intended. -
Save data from radio button to database Django
I need to know how to save data to database if I use radio button and it name is inconstant becuase I use template tag for name value. I want to save item.id in database, I can use function save() but in this case I don't know what is parameter that I should to save. models.py (It's in different app) #in item app class Item(models.Model): item_name = models.CharField(max_length=255, blank=True, null=True) #in borrow app class Borrow(models.Model): borrow_date = models.DateField(auto_now=False, auto_now_add=True, editable=False) return_date = models.DateField(auto_now=True, auto_now_add=False) class Borrow_Item(models.Model): borrow_id = models.ForeignKey(Borrow, on_delete=models.PROTECT) item_id = models.ForeignKey(Item, on_delete=models.PROTECT) item\views.py def item(request): item_list = Item.objects.all() items = request.GET.get([some parameter that I don't know]) items = Borrow_Item.save([some parameter]) context = { 'item_list': item_list, } return render(request, 'item/main-item.html', context) main-item.html <form method="GET" action="{% url 'item' %}"> <input type="submit" value="SAVE"> {% for item in item_list %} <input type="checkbox" name="item{{item.id}}" value="{{item.id}}">{{item.item_name}} {% endfor %} </form> -
How can i perform PUT request using ajax and jquery in Django?
I have been struggling for hours trying to update my database in django using PUT request. I'm gathering my data from a form and I want to update a database entry based on the text which the user types. I specifically have to use PUT request method but I have no idea how to do it. Any help would be greatly appreciated Here i am getting the data from the form: $("#modify-btn").click(function(){ console.log('modify pressed') $.ajax({ url : "{% url 'modify item' %} ", method : "POST", data: $("#detailsForm").serializeArray(), success : function (data) { console.log(data.id,data.name,data.brand,data.model) ///// $.ajax({ /// this is where i need to use the PUT request url : }) /// } }) }) This is my views.py file: from django.shortcuts import render from django.http import HttpResponse from django.http import JsonResponse from django.template import loader from phonemodels.models import Phone def index(request): return render(request,'phonemodels/index.html',{ 'phones' : Phone.objects.all(), }) def items_json(request): return JsonResponse({ 'phones' : list(Phone.objects.values()) }) def new_item(request): phone_name = request.POST['Brand'] phone_model = request.POST['Model'] phone_price = request.POST['Price'] phone = Phone (brandName=phone_name,phoneModel=phone_model,phonePrice=phone_price) phone.save() return JsonResponse({ 'id' : phone.id, 'brand': phone.brandName, 'model' : phone.phoneModel, 'price' : phone.phonePrice }) def modify_item(request): phone_name = request.POST['BrandModify'] phone_model = request.POST['ModelModify'] phone_price = request.POST['PriceModify'] phone = Phone.objects.get(brandName=phone_name,phoneModel=phone_model,phonePrice=phone_price) phone.id … -
SQLite 3.8.3 or later is required (found 3.7.17)
I completed my project and uploaded into the host using cpanel and install all my necessary packages. but now when run the server I have this error : SQLite 3.8.3 or later is required (found 3.7.17). I can't upgrade the sqlite3 with pip install --upgrade sqlite3 my database is sqlite3 how can i fix this problem???? -
Django How can I unittest a wait function for db written in bash script when using dockerized database service?
After searching stackoverflow for a while, I found plenty of ways to check if dockerized database service is ready before connection. So I include both of them here. first one is written in bash script and I found it in here if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi python manage.py flush --no-input python manage.py migrate exec "$@" The second one is written in python and I found it in here: class Command(BaseCommand): """Django command that waits for database to be available""" def handle(self, *args, **options): """Handle the command""" self.stdout.write('Waiting for database...') db_conn = None while not db_conn: try: connection.ensure_connection() db_conn = True except OperationalError: self.stdout.write('Database unavailable, waiting 1 second...') time.sleep(1) self.stdout.write(self.style.SUCCESS('Database available!')) I use this docker command ENTRYPOINT ["/usr/src/app/entrypoint.sh"] to run the first one. I know how to write unit tests for the second one, because it's in python. But can anyone help me find a way to write tests for the first one? In addition, Can anybody name what are the drawbacks and advantages of each method and also if there exists some other important considerations for writing such function? Thanks -
(migrations table) django.db.utils.IntegrityError: null value in column "id" violates not-null constraint
When I run migrate it raises this error. I can't figure out where can be the problem because it is caused by the built-in functionality of adding migration data inside the migrations table. Running migrations: Applying matches.0023_auto_20191102_1717...Traceback (most recent call last): File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, matches, 0023_auto_20191102_1717, 2019-11-02 17:17:38.046421+01). The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 200, in handle fake_initial=fake_initial, File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/db/migrations/executor.py", line 250, in apply_migration self.recorder.record_applied(migration.app_label, migration.name) File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 71, in record_applied self.migration_qs.create(app=app, name=name) File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/db/models/query.py", line 417, in create obj.save(force_insert=True, using=self.db) File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/db/models/base.py", line 729, in save force_update=force_update, update_fields=update_fields) File "/home/milano/.virtualenvs/sport_database/lib/python3.6/site-packages/django/db/models/base.py", line 759, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, … -
Login page as startpage in Django
Currently I have my home view as my homepage by the following in urls.py: url(r'^$', views.home) I added a login form today with a template in /templates/registration/login.html and the following in urls.py: path('', include('django.contrib.auth.urls')) This works great but I have been trying to find how I can set a login path as homepage, I tried with the following uncommented lines: from django.conf.urls import url from . import views from django.urls import path, include #from django.contrib.auth.views import LoginView urlpatterns = [ path('', include('django.contrib.auth.urls')), #url(r'^$', views.login), #url(r'^login/$', include('django.contrib.auth.urls')), url(r'^$', views.home), -
Django 'ImageFileDescriptor' object has no attribute 'save'
I'm trying to save this Image to the db with a ForeignKey attached also, so I can look it up later. When trying to save it , I just get this error 'ImageFileDescriptor' object has no attribute 'save' Models.py class Usertasks(models.Model): TaskID = models.CharField(max_length=55) user = models.ForeignKey(User, unique=False, on_delete=models.CASCADE) TaskStatus = models.CharField(max_length=15, default="missing") class TaskImages(models.Model): UserTasks = models.ForeignKey(Usertasks, related_name='images', on_delete=models.CASCADE) image = models.ImageField() views.py def task_info(request, taskid): task = Usertasks.objects.get(TaskID=taskid) files = os.listdir(task.OutputPath) fullpath = task.OutputPath print(files) for img in files: imagepath = fullpath + "/" + img with open(imagepath, 'rb') as f: data = File(f) TaskImages.image.save(img, data, True, UserTasks=task) return render(request, 'dashboard/task.html', {'path':fullpath, 'image':files}) -
are there any ways to add paginator to search results page in django?
I want to ask if there any way for add paginator to my search results when i'm using chian i mean like this (Multi Databases) I have tried many ways for do this but it's doesn't work I have this in views.py : def search(request): if request.method == 'GET': query= request.GET.get('q') submitbutton= request.GET.get('submit') if query is not None: home_database= Homepage.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) pcprograms_database= PCprogram.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) androidapk_database= AndroidApks.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) androidgames_database= AndroidGames.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) antiruvs_database= Antivirus.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) systems_database= OpratingSystems.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) pcgames_database= PCgames.objects.filter(Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)) # results= sorted(chain(home_database,pcprograms_database,androidapk_database,androidgames_database,antiruvs_database,systems_database,pcgames_database),key=attrgetter('name')) results = sorted( chain(pcprograms_database,home_database,androidapk_database,androidgames_database,antiruvs_database,systems_database,pcgames_database), key=attrgetter('name'),reverse=True) paginator = Paginator(results, 2) # Show 25 rows per page page = request.GET.get('page') results = paginator.get_page(page) context={'results': results, 'submitbutton': submitbutton} return render(request, 'html_file/enterface.html', context) else: return render(request, 'html_file/enterface.html') else: return render(request, 'html_file/enterface.html') -
DRF nested instance update has blank validated_data
I'm using Django 2.x and DRF. I have two models class Component(Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100, default='Unnamed') group = models.ForeignKey(AnalyticsGroup, on_delete=models.CASCADE) class ComponentData(Model): component = models.ForeignKey(Component, on_delete=models.CASCADE, related_name='data') analytics_type = models.ForeignKey(AnalyticsType, on_delete=models.PROTECT) User can create/update ComponentData object using Component serializer and for that, I have class ComponentDataSerializer(serializers.ModelSerializer): class Meta: model = ComponentData fields = [ 'id', 'analytics_type', ] class ComponentSerializer(serializers.ModelSerializer): data = ComponentDataSerializer(many=True) class Meta: model = Component fields = [ 'name', 'group', ] def create(self, validated_data): component_data = validated_data.pop('data') component = Component.objects.create(**validated_data) for data in component_data: ComponentData.objects.create(component=component, **data) return component def update(self, instance, validated_data): component_data = validated_data.pop('data') # Update instance for attr, value in validated_data.items(): setattr(instance, attr, value) instance.save() # Update or create component data for data in component_data: # data.items() has no data and prints # Updating with data: odict_items([]) print('Updating with data: {}'.format(data.items())) return instance def to_representation(self, instance): response = super().to_representation(instance) response['group'] = AnalyticsGroupSerializer(instance=instance.group).data return response I have overridden create and update method to create nested objects as well. create is working fine but with update method, there are OrderedDict() objects in the validated_data.pop('data') field but the OrderedDict object has no data in it. The request body has data: group: "2" data[0].id: "1" data[0].analytics_type: … -
Why can I retrieve environment variable in one part of my code, but not another?
I've stored an API token as an environment variable in my wsgi file. I'm able to retrieve it in one instance in my Django app, but not another. I'm able to use the token successfully during a save_model operation in my admin. When I use nearly identical code in a management command I get an auth error. My wsgi.py file: import os import sys from django.core.wsgi import get_wsgi_application os.environ['SLACK_TOKEN'] = '12344567890qazxswedcvfrtgbnhyujmkiolp' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') application = get_wsgi_application() Working admin.py usage: import os from slacker import Slacker def save_model(self, request, obj, form, change): if obj.condition == True: super().save_model(request, obj, form, change) token = os.getenv('SLACK_TOKEN') slack = Slacker(token) slack.chat.post_message('#test-channel', 'mymessage') Not working management command usage: import os from slacker import Slacker def handle(self, *args, **options): try: #test condition except: token = os.getenv('SLACK_TOKEN') slack = Slacker(token) slack.chat.post_message('#newsflow-test', 'mymessage') Troubleshooting indicates the env variable isn't loading -- print(token) produces None response when I run the management command or try to retrieve the token in the Django shell. -
Django doesn't pull data from fetch()
I'm using fetch() to make an ajax call to my server. request.POST returns an empty QueryDict while request.body retuns my actual data. Why am I doing wrong?!? Here's my js code: fetch(url, { method: "post", credentials: 'same-origin', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, 'X-Requested-With': 'XMLHttpRequest' }, body: JSON.stringify(data) }) .then(async res => ({ status: res.status, body: await res.json(), isOk: res.ok })) -
I have problem with connect django and mysql
I have a problem connecting the mysql database with django. I have already tried to find solutions on the internet but nothing helped me. When I change the code in the 'setting.py' file and then enter 'python manage.py migrate' in the console: (blog) PS C:\Users\kacpe\Dev\blog\blog\blog> python manage.py migrate Traceback (most recent call last): File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\db\backends\base\base.py", line 217, in ensure_connection self.connect() File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\db\backends\base\base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\db\backends\mysql\base.py", line 227, in get_new_connection return Database.connect(**conn_params) File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\MySQLdb\__init__.py", line 84, in Connect return Connection(*args, **kwargs) File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\MySQLdb\connections.py", line 166, in __init__ super(Connection, self).__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (2059, <NULL>) The above exception was the direct cause of the following exception: 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\kacpe\Dev\blog\blog\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\core\management\base.py", line 361, in execute self.check() File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\core\management\base.py", line 387, in check all_issues = self._run_checks( File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\core\management\commands\migrate.py", line 64, in _run_checks issues = run_checks(tags=[Tags.database]) File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\core\checks\database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\db\backends\mysql\validation.py", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "C:\Users\kacpe\Dev\blog\blog\lib\site-packages\django\db\backends\mysql\validation.py", … -
Blank Page right after django form submit
I have a django code that is supposed to post the comments to a detailview but right after I click the submit button in the form, it directs me to a blank page and it also didn't post the comment in the detail view I have added a get_absolute_url but it still doesn't work, it keeps directing me to the blank page #views.py class MessageDetailView(DetailView): model = Message template_name = "messaging/detail.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = Comment.objects.filter(message=self.object) context['form'] = CommentForm() return context #detail.html <form method="POST"> {% csrf_token %} <h3>Write a New Comment</h3> <div class="messagebox"> {{ form|crispy }} <button class="btn" type="submit"> Post Comment </button> </div> </form> #forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['comment'] #models.py class Comment(models.Model): message = models.ForeignKey(Message,on_delete=models.CASCADE) comment = models.TextField(max_length=50) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return "Comment on {}".format(str(self.date_posted)) def get_absolute_url(self): return reverse("messaging-detail",kwargs={"id":self.id}) Any help would be appreciated, Please provide some code instead of just linking me to a documentation -
Loop in Django Template via JSON Data
i will to loop through this Json data in my Django Template. However, I have achieve it but I have some similar array which I find difficult to loop through because of the Similarity in their name. Like I have two flightSegment. {'segments': [{'flightSegment': {'departure': {'iataCode': 'JFK', 'terminal': '4', 'at': '2020-02-02T19:31:00-05:00'}, 'arrival': {'iataCode': 'AMS', 'at': '2020-02-03T09:10:00+01:00'}, 'carrierCode': 'KL', 'number': '6007', 'aircraft': {'code': '76W'}, 'operating': {'carrierCode': 'DL', 'number': '6007'}, 'duration': '0DT7H39M'}, 'pricingDetailPerAdult': {'travelClass': 'ECONOMY', 'fareClass': 'N', 'availability': 9, 'fareBasis': 'NLSRNG'}}, {'flightSegment': {'departure': {'iataCode': 'AMS', 'at': '2020-02-03T10:20:00+01:00'}, 'arrival': {'iataCode': 'CDG', 'terminal': '2F', 'at': '2020-02-03T11:45:00+01:00'}, 'carrierCode': 'KL', 'number': '2007', 'aircraft': {'code': '321'}, 'operating': {'carrierCode': 'AF', 'number': '2007'}, 'duration': '0DT1H25M'}, 'pricingDetailPerAdult': {'travelClass': 'ECONOMY', 'fareClass': 'L', 'availability': 9, 'fareBasis': 'NLSRNG'}}, {'flightSegment': {'departure': {'iataCode': 'CDG', 'terminal': '2E', 'at': '2020-02-03T13:15:00+01:00'}, 'arrival': {'iataCode': 'ABV', 'at': '2020-02-03T19:20:00+01:00'}, 'carrierCode': 'KL', 'number': '2054', 'aircraft': {'code': '332'}, 'operating': {'carrierCode': 'AF', 'number': '2054'}, 'duration': '0DT6H5M'}, 'pricingDetailPerAdult': {'travelClass': 'ECONOMY', 'fareClass': 'N', 'availability': 9, 'fareBasis': 'NLSRNG'}}]} -
Django save ImageField to ForeignKey object
I'm trying to save images in a folder and bind it to another database object using ForeignKey, so I can look it up later. I have the code for grabbing the images in the folder and now i'm just trying to save them. My current error is: 'ImageFileDescriptor' object has no attribute 'save' Models.py class Usertasks(models.Model): TaskID = models.CharField(max_length=55) user = models.ForeignKey(User, unique=False, on_delete=models.CASCADE) TaskStatus = models.CharField(max_length=15, default="missing") class TaskImages(models.Model): UserTasks = models.ForeignKey(Usertasks, related_name='images', on_delete=models.CASCADE) image = models.ImageField() views.py def task_info(request, taskid): task = Usertasks.objects.get(TaskID=taskid) files = os.listdir(task.OutputPath) fullpath = task.OutputPath print(files) for img in files: fullpath = os.path.abspath(img) with open(fullpath, 'rb') as f: data = File(f) TaskImages.image.save(img, data, True, UserTasks=task) return render(request, 'dashboard/task.html', {'path':fullpath, 'image':files}) -
TemplateDoesNotExist at / app/school_list.html CBS in Django
Hi Every one i want to see my home page but i get this error again and again TemplateDoesNotExist at / app/school_list.html I'm Using CBS ~ Class Based Views Here is my Settings.py TEMPLATE_DIR = os.path.join(BASE_DIR,"app/templates") INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "app", ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Here is my Tree View Here is my Views.py from django.shortcuts import render from django.views.generic import (ListView) from . import models # Create your views here. class SchoolListView(ListView): model = models.School Here is my urls.py from django.contrib import admin from django.urls import path from app import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.SchoolListView.as_view(),name="index"), ] -
How to create django model objects where one of the field is datetime
I have a model class Fixture(models.Model): fixture_id=models.IntegerField(primary_key=True) league_id =models.ForeignKey('League',null=True, on_delete=models.SET_NULL) event_date = models.DateTimeField(null=True) event_timestamp = models.DateTimeField(null=True) I am trying to create object from this model. I am using Postgresql and in settings.py activated USE_TZ = True fixt = Fixture.objects.create(fixture_id = fixture_id,league_id_id = league_id,event_date=event_date, event_timestamp = event_timestamp) while i am trying to create object get the folowing traceback django.core.exceptions.ValidationError: ["'event_date' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] -
Django-Admin custom ImageField
I wanna add additional ImageField which obtains image from static folder to the model. I've tried to use some answers from the same questions, but there're nothing about ImageField. -
Django DRY model attributes, classes, and triggers
I'm hacking on an graph-based app with about 50 different types of relationships. They all look like this. class SomeModel(CustomClazz): created_at = DateTimeProperty(default_now=True) updated_at = DateTimeProperty(default_now=True) class Meta: app_label = 'custom_relation' def save(self, *args, **kwargs): self.updated_at = datetime.now() super(SomeModel, self).save(*args, **kwargs) When I started writing this post, I was just looking for a one-liner for class Meta: but I realized most of these lines are duplicates for each model. Although I view the integrity and human-readability of the model as sacred, part of that is keeping my model file short enough that I don't need to split it up into many files. If the model definition becomes extremely dry, I'd still like to be able to set custom attributes for SomeModel. -
How to get the plain password from the password field in the signup form in Django
I have the sign up form in django through which I am taking the entry for the new user. The data can be saved using the u_form.save method but I also need the plain password that the user has entered as that password will be needed to create account in other website through the REST API and hence both password needs to be same. I am able to access the password from the form but when I receive it Django has already encrypted it. How can I get the original plain password? This is what I have tried : views.py from users.forms import SignUpForm, ProfileForm def create(request): context = {} if(request.method == 'POST'): u_form = SignUpForm(request.POST) # fill it with user details p_form = ProfileForm(request.POST, request.FILES) if u_form.is_valid() and p_form.is_valid(): user = u_form.save() email = user.email username = user.username first_name = user.first_name # Accessing plain password password = user.password Profile.objects.filter(user=user).delete() profile = p_form.save(commit=False) profile.user = user profile.save() messages.success(request, f'Account Created') return render(request, 'mainapp/homepage.html', context) forms.py from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User from .models import Profile class SignUpForm(UserCreationForm): email = forms.EmailField(required=True, label='Email', error_messages={'exists': 'Oops'}, widget=forms.TextInput(attrs={'readonly':'readonly'})) username = forms.Field(widget=forms.TextInput(attrs={'readonly':'readonly'})) first_name = forms.Field(widget=forms.TextInput(attrs={'readonly':'readonly'})) readonly_fields = ('username', 'first_name', … -
Testing a form. What'happening? is this really working?
I have a django form with a field directed to a foreignkey. Initially is empty, I mean without any option. Javascript will add options based on another form field. It's working but I want to test it, without using Selenium (and so, without using javascript). After numerous attempts I write this code and apparently it's working but I don't know why and I'm not sure it's really working. def test_form_validation(self): maschio = Gender.objects.create(name_en='Male', name_it='Maschio') nome = NameType.objects.create(name_en='Name', name_it='Nome') romani = NameLanguage.objects.create( name_en='Romans', name_it='Romani') romani.syntax.add(nome) form = NameForm({'nametype': nome.id, 'gender': maschio.id, 'name': 'Remo', 'namelanguage': romani.id}) # print('1', form) form.fields['nametype'].initial = nome.id form.fields['gender'].initial = maschio.id form.fields['name'].initial = 'Remo' form.fields['namelanguage'].initial = romani.id print('2', form) form.save() self.assertEqual(Name.objects.all().count(), 1) my_name = Name.objects.first() self.assertEqual(my_name.name, 'remo') self.assertEqual(my_name.nametype, nome) self.assertEqual(my_name.gender, maschio) self.assertEqual(my_name.namelanguage, romani) print('end of test') # print('1', form) is commented out because with that the test will be give error on line form.save() (ValueError ... the data didn't validate). Without that line the test pass (!?!). I will expected an error when I call my form bounded because nametype has no option to choose from. nome.id is not one of the ammissible choices. And in effect, as I said, it will give an error if I ask … -
Django Custom Setting Size Attribute on Model Form Not Working
I am trying to specify the length in characters on a model field. I cannot get it to render on the page and drop in the size attribute to the input field. The basic form looks like: class QuestionForm(ModelForm): question = forms.CharField(label="Question") class Meta: model = Question fields = ["question"] I have tried the following: class QuestionForm(ModelForm): question = forms.CharField(label="Question",widgets=forms.TextInput(attrs={'size':'50'})) class Meta: model = Question fields = ["question"] And class QuestionForm(ModelForm): question = forms.CharField(label="Question") class Meta: model = Question fields = ["question"] widgets = { 'question': forms.TextInput(attrs={'size':'50'}) } And class QuestionForm(ModelForm): question = forms.CharField(label="Question") def __init__(self, *args, **kwargs): super(QuestionForm,self).__init__(*args, **kwargs) self.fields['question'].widget.attrs['size'] = '50' The form is part of a formset factory, do you need to do anything different when using that? ApplicationForm = forms.formset_factory(QuestionForm) ModelApplicationForm = forms.modelformset_factory(Question, fields=('question',)) -
django , angular :- How to render the page according to the session status?
We are checking the session details from Django-sessions. If the session is active the "Layout.html" page should open else "login.html" page should open. Both "Layout.html" and "login.html" are in Angular 7. I have tried to send the JSONdata(status of login) using render() from django to angular and according to that status I used "*ngIf" to open the files, but I was not able to access the JSONdata outside the index.html