Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'str' object has no attribute 'makefile'
Traceback (most recent call last): File "C:\Users\Rochak.virtualenvs\GFG\GFG\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Rochak.virtualenvs\GFG\GFG\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Rochak.virtualenvs\GFG\GFG\Scripts\authentication\views.py", line 7, in home return HTTPResponse("Hello Rochak!") File "C:\Program Files\Python310\lib\http\client.py", line 256, in init self.fp = sock.makefile("rb") Exception Type: AttributeError at /authentication/hello/ Exception Value: 'str' object has no attribute 'makefile' -
Django UUID Filtering
I have the following model: class MyModel(models.Models): uuid = models.UUIDField(default=uuid.uuid4, db_index=True, editable=False, unique=True) name = models.CharField(max_length=200) In my django admin, I have the following search_fields: search_fields = ["uuid__exact", "name"] This should translate to the following query: MyModel.objects.filter(Q(uuid__exact=query) | Q(name__icontains=query)) However, running that query throws the following error: ValidationError: ['“test name” is not a valid UUID.'] How do I prevent the uuid portion of the query from throwing a ValidationError? I want to be able to search my model by either the uuid or the name field in the django admin. -
need to write a migration file to update paymentTransaction from session to E-commerce
from django.db import migrations, models from payment.models import PaymentTransaction from config import constants class Migration(migrations.Migration): def forwards_func(apps, schema_editor): PaymentTransaction = apps.get_model("session", "PaymentTransaction") db_alias = schema_editor.connection.alias payment_transaction=[] for payment_txn in PaymentTransaction: payment_transaction=PaymentTransaction.objects.using(db_alias).session().update(type=constants.E_COMMERCE) payment_transaction.save() return payment_transaction dependencies = [ ('payment', '0019_auto_20211119_1447'), ] operations = [ migrations.RunPython(forwards_func) ] ** But still have the type"session" it's not updated to E-commerce ** -
How to get real path instead of fakepath while using AJAX with DJANGO?
I am trying to get real path of image where it is uploaded in the local directory instead of fakepath. Before using AJAX, I was able to get the real path but to stop the page refreshing on each time form is submitted ( the reason is I wanted the current values present and not to go back to the default values each time form is submitted ), I incorporated AJAX. I understand its a security measure and all that but I am working in local environment and does anyone have any work around that? What I want is something in the top link ( I got this link by submitting values through admin ) but what I am getting is something in bottom ( through submit button on form ). I am also attaching relevant parts of my DJANGO code as well: MODELS.py from django.db import models from django.db import IntegrityError from django.http import HttpResponse from datetime import datetime import uuid # lists of options cities_name_list=(("Abbotabad","Abbotabad"),("Bahawalpur","Bahawalpur"),("Charsaddah","Charsaddah"),("Dera Ghazi Khan","Dera Ghazi Khan"),("Faisalabad","Faisalabad"),("Gawadar","Gawadar"),("Islamabad","Islamabad"),("Rawalpindi","Rawalpindi"),("Karachi","Karachi"),("Lahore","Lahore"),("Multan","Multan"),("None","None")) massavi_sheets=(("Alif-1","Alif-1"),("Bay-1","Bay-1"),("Jeem-1","Jeem-1"),("Daal-1","Daal-1"),("Hay-1","Hay-1"),("Wao-1","Wao-1"),("None","None")) # define upload path function def content_file_name(instance, filename): name, ext = filename.split('.') file_path = 'images/{mauza}/{form_id}.{ext}'.format( form_id=instance.form_id, mauza=instance.mauza, ext=ext) return file_path # Create your models here. class UploadImage(models.Model): form_id … -
How to have two workers for heroku.yml?
I have the following heroku.yml. The 'containers' share the same Dockerfile: build: docker: web: Dockerfile celery: Dockerfile celery-beat: Dockerfile release: image: web command: - python manage.py migrate users && python manage.py migrate run: web: python manage.py runserver 0.0.0.0:$PORT celery: celery --app=my_app worker --pool=prefork --concurrency=4 --statedb=celery/worker.state -l info celery-beat: celery --app=my_app beat -l info I intended to have three containers, but it turns out that Heroku accepts only one web and the other should be workers. So what do I modify at heroku.yml to have celery and celery-beat containers as worker? -
Double filter django
I started learning django and decided to create a clothing store. I would like to know how to make a filter to display products like men's - t-shirt || Female - T-shirt? At the moment, I have learned to display only by category T-shirts, hoodies and so on. How to make double filtering so that there is sorting by female and male? views.py class StuffCategory(ListView): model = Stuff template_name = 'shop/shop.html' context_object_name = 'stuffs' def get_queryset(self): return Stuff.objects.filter(category__slug=self.kwargs['category_slug'], draft=False) class StuffView(ListView): model = Stuff template_name = 'shop/shop.html' context_object_name = 'stuffs' paginate_by = 3 models.py class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=200, unique=True) class Meta: verbose_name = 'Категория' verbose_name_plural = 'Категории' def __str__(self): return self.name def get_absolute_url(self): return reverse('category', kwargs={'category_slug': self.slug}) class Gender(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=200, unique=True) class Meta: verbose_name = 'Гендер' verbose_name_plural = 'Гендеры' def __str__(self): return self.name def get_absolute_url(self): return reverse('gender', kwargs={'gender_slug': self.slug}) class Stuff(models.Model): name = models.CharField(max_length=100) price = models.FloatField() description = models.TextField() composition = models.CharField(max_length=150) instruction = models.CharField(max_length=150) manufacturer_country = models.CharField(max_length=150) category = models.ForeignKey(Category, on_delete=models.PROTECT) gender = models.ForeignKey(Gender, on_delete=models.PROTECT) size = models.ManyToManyField(Size) photo = models.ImageField(upload_to='items/') slug = models.SlugField(max_length=200, unique=True) draft = models.BooleanField("Черновик", default=False) class Meta: verbose_name = 'Вещь' verbose_name_plural = 'Вещи' def __str__(self): … -
Why do I have duplicate views in my Django rest framework urls.py?
I'm trying to figure out how these endpoints work in django rest framework. urls.py urlpatterns = [ path('api-auth', include('rest_framework.urls', namespace='rest_framework')), path('login', django_views.LoginView.as_view(template_name='rest_framework/login.html'), name='login'), path('logout', django_views.LogoutView.as_view(), name='logout'), path('register', views.UserCreate.as_view()), path('get_jwt_token', obtain_jwt_token), path('eos_verify_jwt_token', views.EOSVerifyJSONWebToken.as_view()), ] I get the following patterns: Using the URLconf defined in ugh_studios_webservices.urls, Django tried these URL patterns, in this order: api/ api-auth login/ [name='login'] api/ api-auth logout/ [name='logout'] api/ login [name='login'] api/ logout [name='logout'] api/ register api/ get_jwt_token api/ eos_verify_jwt_token admin/ The current path, api/api-auth, didn’t match any of these. Why is there two login endpoints? What I'm trying to do is have the following endpoints: Login Endpoint Logout Endpoint User registration endpoint JWT Token request + validation endpoints - this seems to work Custom Validate user login (username + password) endpoint (response needs to be custom for integration with a separate application, it expects a certain response body) Needs to be viewable in the browsable API https://www.django-rest-framework.org/topics/browsable-api/ - Why are none of my urls viewable except for the 'register' url? Needs to be able to work with both an HTTP POST request (for validation/login) as well as an html template/view I do not want to create duplicate code either, it seems like the rest_framework comes with some … -
Google app engine Django app is crashing intermittently but the log files aren't showing me why
I have a Django 4.0 application running on google app engine, and for the most part it works fine. However I have a particular page which seems to crash the application after I load the page several times. On my laptop I don't see this behavior, so I'm trying to debug what is going wrong when it is running on GAE but I don't have much visibility into what is happening. Watching the logs doesn't tell me anything interesting, just that the workers are shutting down and then that they are restarting: gcloud app logs tail -s default 2022-01-26 16:02:38 default[fixeddev] 2022-01-26 08:02:38,933 common.views INFO Application started 2022-01-26 16:03:40 default[fixeddev] "GET /organization/clean_up_issues/ HTTP/1.1" 200 2022-01-26 16:03:56 default[fixeddev] "GET /organization/clean_up_issues/ HTTP/1.1" 200 2022-01-26 16:04:10 default[fixeddev] "GET /organization/clean_up_issues/ HTTP/1.1" 500 2022-01-26 16:04:15 default[fixeddev] [2022-01-26 16:04:15 +0000] [12] [INFO] Handling signal: term 2022-01-26 16:04:15 default[fixeddev] [2022-01-26 08:04:15 -0800] [22] [INFO] Worker exiting (pid: 22) 2022-01-26 16:04:15 default[fixeddev] [2022-01-26 08:04:15 -0800] [25] [INFO] Worker exiting (pid: 25) 2022-01-26 16:04:15 default[fixeddev] [2022-01-26 08:04:15 -0800] [27] [INFO] Worker exiting (pid: 27) 2022-01-26 16:09:49 default[fixeddev] "GET /_ah/start HTTP/1.1" 200 2022-01-26 16:09:49 default[fixeddev] [2022-01-26 16:09:49 +0000] [10] [INFO] Starting gunicorn 20.1.0 2022-01-26 16:09:49 default[fixeddev] [2022-01-26 16:09:49 +0000] [10] … -
Django how to handle 2 Post Requests
I have a micro ticket system. The user has information about the ticket, a button to mark as solved/mark as waiting and a message box to add new messages in to the ticket for the admin. You can ignore the most stuff in the forms, important are the GET/POST requests of the forms. \\views.py def ticket_system_view(request, id): obj = Ticket.objects.get(id=id) waiting_message = "Mark as 'Waiting'" solved_message = "Mark as 'Solved'" if obj.reopened_counter > 5: solved_message = 'Ticked solved forever' waiting_message = 'Ticked solved forever' button_form = TicketSolved(request.POST) time.sleep(2) if button_form.is_valid: obj.reopened_counter += 1 if obj.reopened_counter > 5: obj.ticket_waiting = True obj.ticket_solved = False if obj.ticket_waiting == False and obj.ticket_solved == True: obj.ticket_waiting = True obj.ticket_solved = False else: obj.ticket_waiting = False obj.ticket_solved = True obj.save() user_form = TicketMessagesForm( request.POST, instance=TicketMessages(id=id)) if user_form.is_valid(): instance = user_form.save(commit=False) #this form doesnt work yes instance.save() return render(request, 'ticket-system.html', {'obj': obj, 'waiting_message': waiting_message, 'solved_message': solved_message, 'button_form': button_form, 'user_form': user_form}) \\forms.py class TicketSolved(forms.Form): delete = forms.CharField( label='', max_length=0).widget = forms.HiddenInput() class TicketMessagesForm(forms.ModelForm): class Meta: model = TicketMessages fields = ( 'user_message', ) \\models.py if you need class Ticket(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) title = models.CharField(max_length=200) description = models.TextField() creator_adress = models.GenericIPAddressField(null=True) start_date … -
Django query to filter only first objects with particular field names
model class UserAction(models.Model): ACTION_CHOICES = ( ("LogIn", "Entered"), ("LogOut", "Gone Out"), ("Away", "Away from Computer"), ("Busy", "Busy"), ("DoNotDisturb", "Do not disturb"), ("Online", "Online and Available"), ) action_name = models.CharField(choices=ACTION_CHOICES, default="LogIn") user = models.ForeignKey(Profile, related_name="actions") action_time = models.DateTimeField(default=timezone.now(), editable=False) class Profile(models.Model): name = models.CharField(max_length=120) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now()) I need to query UserAction, in such a way that I want only the last UserAction of each user. My solutions were too much time consuming. That's why looking for an optimised answer. -
Adding values from monthly status update progress into the assigned project progress in django
I have this process that every time a project manager creates a monthly status update they must enter the project progress value, now I want to add all of the values set in that column into the assigned project progress value and the values that are add up shouldn't exceed 100. Models.py class Projects(models.Model): id=models.AutoField(primary_key=True) project_name=models.CharField(max_length=255) project_manager=models.ForeignKey(CustomUser,on_delete=models.CASCADE, limit_choices_to={'is_project_manager' : True}) client_name=models.ForeignKey(Clients,on_delete=models.CASCADE, null=True) project_pic=models.ImageField(upload_to='static/website/project-images') project_start_date=models.DateField(null=True) project_end_date=models.DateField(null=True) project_description=models.TextField(null=True) project_progress = models.PositiveIntegerField(null=True, default=0, validators=[ MaxValueValidator(100), MinValueValidator(0) ]) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) is_draft = models.BooleanField(default=True) objects=models.Manager() class Meta: verbose_name_plural = 'Project' def __str__(self): return f'{self.project_name}' class MonthlyProjectStatus(models.Model): id=models.AutoField(primary_key=True) project_name=models.ForeignKey(Projects,on_delete=models.CASCADE) project_manager=models.ForeignKey(CustomUser,on_delete=models.CASCADE, null=True) client_name=models.ForeignKey(Clients,on_delete=models.CASCADE, null=True) attachments = models.FileField(upload_to='static/website/files', null=True) project_update=models.TextField(null=True) project_progress=models.PositiveIntegerField(null=True, default=1, validators=[ MaxValueValidator(100), MinValueValidator(1) ]) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) is_draft = models.BooleanField(default=True) class Meta: verbose_name_plural = 'Monthly Status' def __str__(self): return f'{self.project_name}' Forms.py class ProjectForm(forms.ModelForm): class Meta: model = Projects fields = ['project_name', 'project_manager', 'client_name', 'project_pic', 'project_start_date', 'project_end_date', 'project_description'] class MonthlyStatusForm(forms.ModelForm): class Meta: model = MonthlyProjectStatus fields = ['project_name', 'client_name', 'project_update', 'attachments', 'project_progress'] views.py def client_monthly_staff(request): monthly = MonthlyProjectStatus.objects.all() if request.method == 'POST': form = MonthlyStatusForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.project_manager = request.user instance.save() project_name = form.cleaned_data.get('project_name') messages.success(request, f'{project_name} status has been successfully added.') return redirect('client-monthly-staff') else: form = MonthlyStatusForm() context = { 'monthly' : monthly, 'form' … -
how to access second field in django choice field in django template
In my django models i have a charfield status which is filled by choices status = [ ('Accepted','Accepted'), ('Pending','Acceptance Pending'), # ('Document_Pending','Document Pending'), ('Rejected','Rejected'), ('Pending_email_verification','Pending Email Verification'), ('pending_document','Document Pending'), ('pending_document_verification','Cerificate Verification Pending'), ] in my template i want to print cerificate verfication pending but it always print pending_document_verfication which is expected because in the data it is stored but how can i print Certificate Verfication Pending -
Django: Importing Json file using Url instead of a relative path
I'm currently using a json file to import data into my database. Right now the file is located in the "leads/resources" folder. But the file gets regularly updated on an external server which is why i need to be able to use a url instead of a relative path (line 13). The url would look like this (goes straight to a json file): https://testdomain.com/cache.json Any idea how i can achieve this? Can i just point to it somehow on line 13 or is there more to it? import os import json from leads.models import Facility, FacilityAddress, FacilityInspectionInfo, FacilityComplaints from django.core.management.base import BaseCommand from datetime import datetime from seniorpark.settings import BASE_DIR, STATIC_URL class Command(BaseCommand): def import_facility_from_file(self): print(BASE_DIR) data_folder = os.path.join(BASE_DIR, 'leads', 'resources') for data_file in os.listdir(data_folder): with open(os.path.join(data_folder, data_file), encoding='utf-8') as data_file: data = json.loads(data_file.read()) for key, data_object in data.items(): UUID = data_object.get('UUID', None) Name = data_object.get('Name', None) IssuedNumber = data_object.get('IssuedNumber', None) Capacity = data_object.get('Capacity', None) Licensee = data_object.get('Licensee', None) Email = data_object.get('Email', None) AdministratorName = data_object.get('AdministratorName', None) TelephoneNumber = data_object.get('TelephoneNumber', None) ClosedTimestamp = data_object.get('ClosedTimestamp', None) MostRecentLicenseTimestamp = data_object.get('MostRecentLicenseTimestamp', None) PrimaryAddress = data_object["AddressInfo"]["PrimaryAddress"] SecondaryAddress = data_object["AddressInfo"]["SecondaryAddress"] City = data_object["AddressInfo"]["City"] RegionOrState = data_object["AddressInfo"]["RegionOrState"] PostalCode = data_object["AddressInfo"]["PostalCode"] Geolocation = data_object["AddressInfo"]["Geolocation"] ComplaintRelatedVisits = data_object["InspectionInfo"]["ComplaintRelatedVisits"] … -
Django dropdown filter queryset with FilterView
I want to filter apartments by selecting subcity field in a dropdown in my django app. I'm using django-filters and django-bootstrap-form. But the dropdown does not populate with database querysets. How can I make the dropdown work? views.py: class ApartmentFilterView(FilterView): model = Apartment context_object_name = 'apartments' filter_class = ApartmentFilter template: {% extends 'base.html' %} {% load bootstrap %} {% block title %} የተገኙ ቤቶች | Apartment List {% endblock title %} {% block content %} <form action="" method="get"> {{ filter.form.as_p }} <input type="submit"> </form> {% for obj in filter.qs %} {{obj.apt_id}} - Birr {{obj.apt_cost}} {% endfor %} {% endblock %} -
django: Unable to login user after successfull registration
When I am trying to log in after registering successfully I keep getting error. Maybe it has something to do with password not getting hashed to confirm with password saved in the database because after registering I can see a hashed password. I have also set the user is_active to true. I am thoroughly confused why this is happening models.py from locale import normalize from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager # Create your models here. class MyAccountManager(BaseUserManager): def create_user(self,first_name,last_name,username,email,password=None): if not email: raise ValueError("Enter valid email address") if not username: raise ValueError("User must have a username") user = self.model( email = self.normalize_email(email), username = username, first_name = first_name, last_name = last_name, ) user.set_password(password) user.save(using=self._db) return user #Creating a user with admin like privileges def create_super_user(self,first_name,last_name,username,email,password=None): user = self.create_user( first_name=first_name, last_name=last_name, username=username, email=self.normalize_email(email), password=password ) #assigning privileges to the super user user.is_active=True user.is_admin=True user.is_superadmin=True user.is_staff=True user.save(using=self._db) return user class Account(AbstractBaseUser): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) username = models.CharField(max_length=100,unique=True) email = models.CharField(max_length=100,unique=True) password = models.CharField(max_length=100) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_superadmin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) #customizing the default admin panel fields USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username','first_name','last_name'] objects = MyAccountManager() def … -
WinError 10061 Подключение не установлено, т.к. конечный компьютер отверг запрос на подключение Django
Знаю, много форумов на эту тему в Инете, но либо я тупой, либо рещения не подошли. Пытаюсь сделать деплой написанного сообщения, используя Channels. Всё бы работало как следует, если бы новое сообщение сохранялось в БД. Для этого я пытался напрямую импортировать модели в cunsomers но там вилетает ошибка. Сейчас я хочу пост запрос кинуть, но не выходит. settings.py: from pathlib import Path import os, sys # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent PROJECT_ROOT = os.path.dirname(__file__) sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps')) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-*v_b!0syzph7hda)gml0rlks2vep8iydlj5r7v+dk$s_6l777u' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'Chat.apps.ChatConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'ShibGraph.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(PROJECT_ROOT, 'templates'), ], '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', ], }, }, ] WSGI_APPLICATION = 'ShibGraph.wsgi.application' ASGI_APPLICATION = 'ShibGraph.asgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', } } # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases … -
Django - M2M relations on save model
I have a Django Model that I use as Job for exporting the entire list of Users to a csv file. Now I'm trying to do some modifications to this Job to make it possible to export a list of Users filtered by a few criteria such as Gender, DOB, Country, etc. This is my model for the ExportUsersJob: class ExportUsersJob(models.Model): name = models.CharField(max_length=255, verbose_name=_('Name')) from_dob = models.DateField(blank=True, null=True, verbose_name=_('Filter by Date of Birth, from')) to_dob = models.DateField(blank=True, null=True, verbose_name=_('Filter by Date of Birth, to')) gender = models.ForeignKey(Gender, on_delete=models.PROTECT, blank=True, null=True, verbose_name=_('Filter by Gender')) countries = models.ManyToManyField(Country, blank=True, verbose_name=_('Filter by Country')) csv = models.FileField(upload_to=users_export_bucket, blank=True, null=True, verbose_name=_('CSV')) state = models.CharField(max_length=64, default='creating', choices=JOB_STATE_OPTS, verbose_name=_('Job state')) created_at = models.DateTimeField(blank=True, null=True, verbose_name=_('Created at')) completed_at = models.DateTimeField(blank=True, null=True, verbose_name=_('Completed at')) def __str__(self, *args, **kwargs): return self.name def save(self, *args, from_job=False, **kwargs): if from_job: return super(ExportUsersJob, self).save(*args, **kwargs) self.state = 'creating' self.created_at = timezone.now() super(ExportUsersJob, self).save(*args, **kwargs) from_dob = str(self.from_dob) if self.from_dob else None to_dob = str(self.to_dob) if self.to_dob else None gender = self.gender.pk if self.gender else None countries = [c.pk for c in self.countries.all()] # This will query the DB and print the results in a csv file export_users.delay(self.pk, from_dob, to_dob, gender, countries) The … -
django |safe template not working properly
django |safe template not working properly I tried to use a textarea as rich text in django admin, all good, but when I try to show in front with {{ date|safe }} it only shows a maximum height of poximate 200 cm which doesn't allow to show all the text I already read the Django docs article. I do not know what to do. display in front https://i.stack.imgur.com/SzjF5.png code html {% block content %} <div style="height: 1000vh; " > {{ personaje.bio|safe }} </div> {% endblock %} use summernote for this rich text box https://i.stack.imgur.com/stHIT.png I had used it before but I don't know what the problem is -
How to create record when click on button
I'm trying to convert lead to an account in a crm app. From my lead detail template, if i click "Convert" button, it need to add new row in account table with few information from the leads. I tried to pass value using id to view so I can filter the lead object using the ID and then add those values in account table. kindly note that, i have written views code with my limitted knowledge on Django. It maybe completely wrong. I have tried many options and read many post, but i couldnt figure it out. model: class Lead(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) annual_revenue = models.IntegerField(null=True, blank=True) company_name = models.CharField(max_length=30, null=True, blank=True) website = models.CharField(max_length=30, null=True, blank=True) city = models.CharField(max_length=30, null=True, blank=True) country = models.CharField(max_length=30, null=True, blank=True) description = models.TextField(max_length=255, null=True, blank=True) class Account(models.Model): account_name = models.CharField(max_length=30, null=True, blank=True) # company name from Lead annual_revenue = models.IntegerField(null=True, blank=True) phone = models.CharField(max_length=30, null=True, blank=True) website = models.CharField(max_length=30, null=True, blank=True) Views: class LeadConvert(generic.CreateView): def get_success_url(self): return "/leads" def ConvertLead(self, **kwargs): lead = self.queryset account = Account.objects.create( account_name = lead.company_name, annual_revenue = lead.annual_revenue, website = lead.website ) account.save def get_queryset(self, **kwargs): queryset = Lead.objects.filter[id == id] return queryset urls path('lead/converted/<int:pk>', … -
Is there a way to create a Django migrations not in the last position?
suppose that this is the migrations history to my project: [X] 0001_initial . . . [X] 0010_auto_20211202_0923 [X] 0011_auto_20211202_1050 [X] 0012_auto_20211202_1240 [X] 0013_auto_20211202_1522 [X] 0014_auto_20211202_1534 [X] 0015_auto_20211202_1555 [X] 0016_auto_20211202_1567 . . . [X] 0021_data_migration I would like to create a new migration in the middle of the history, between 000_13 and 000_14. -
How do I get clean data from foreign-key model's field in django?
I have two models class Tennx(models.Model): this_a = models.CharField(max_length=100) And class reed(models.Model): ten = models.ForeignKey(Tennx) tennxname = #get data from this_a How can I get clean data from Tennx model's this_a field? -
Apache2 Ubuntu Default Page after pointing my domain
I deployed my python Django-web app to a Linux Ubuntu server. I used the linode reverse DNS and it worked fine. My website was live on the Linodes reverse dns ip. So I pointed my DNS to the server and now when I go to my domain name it give me the : Apache2 Ubuntu Default Page I eddited my Django settings to this ( I hidded private information for privacy) : ALLOWED_HOSTS = ['www.mydomainname.com', '172.xxx.19.xxx'] and I also updated my : /etc/apache2/sites-available/mysite.conf and I modified the linodes Reverse DNS for my domain name <VirtualHost *:80> ServerName mydomainname.com ErrorLog ${APACHE_LOG_DIR}/mysite-error.log CustomLog ${APACHE_LOG_DIR}/mysite-access.log combined WSGIDaemonProcess mysite processes=2 threads=25 python-path=/var/www/mysite WSGIProcessGroup mysite WSGIScriptAlias / /var/www/mysite/mysite/wsgi.py Alias /robots.txt /var/www/mysite/static/robots.txt Alias /favicon.ico /var/www/mysite/static/favicon.ico Alias /static/ /var/www/mysite/static/ Alias /static/ /var/www/mysite/media/ <Directory /var/www/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/mysite/static> Require all granted </Directory> <Directory /var/www/mysite/media> Require all granted </Directory> </VirtualHost> What I am missing? Any idea ? -
Was such an error observed at log out in Django?
I do not fix That. TypeError: logoutUser() missing 1 required positional argument: 'request' -
what widget we give to URLFIELD in django
what widget we give to URLField in forms django i wanna set placeholer and some class to input link = forms.URLField(widget=forms.????) -
Filtring queryset for a current week using Django and Chart.js
How to filter django queryset for a current week using Django and Chart.js? In my program below, the result obtained only displays the information concerning the event of the last day of the current week. def area_chart_week(request): labels = [] data1 = [] data2 = [] data3 = [] today = datetime.datetime.now() current_year=today.year current_month=today.month current_week = date.today().isocalendar()[1] queryset = Even.objects.filter(date__week=current_week).filter(date__year=current_year).filter(date__month=current_month).values('date').annotate(date_positif=Sum('positif')).annotate(date_negatif=Sum('negatif')).annotate(date_null=Sum('null')).order_by('-date') for rm in queryset: labels.append(rm['date']) data1.append(rm['date_positif']) data2.append(rm['date_negatif']) data3.append(rm['date_null']) return JsonResponse(data={ 'labels': labels, 'data1': data1, 'data2': data2, 'data3': data3, })