Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'ChatForm' object has no attribute 'img'
I'm trying create image form field, but it gives an error and is not creating image form field. maybe I'm doing something wrong. It gets message. With messages I have no troubles. models.py from django.db import models def upload_to(instance, filename): return '{filename}'.format(filename=filename) class Chat(models.Model): username = models.CharField(max_length=255, blank=True, null=True) message = models.TextField() img = models.ImageField(upload_to=upload_to, null=True, blank=True) created_time = models.DateTimeField(auto_now_add=True) forms.py from django import forms from .models import Chat class ChatForm(forms.ModelForm): message = forms.CharField(widget=forms.TextInput(attrs={ 'class' : 'form-control', 'autofocus' : True })) img = forms.ImageField() class Meta: model = Chat fields = ['message', 'img'] views.py @login_required(login_url='/authentication/login/') def index(request): forms = ChatForm() if request.method == 'GET': chats = Chat.objects.all().order_by('-created_time') if request.user.groups.all()[0].name != 'superadmin': user = 'user' else : user = 'admin' context = { 'chats': chats, 'forms': forms, 'user' : user, } return render(request, 'chat/index.html', context) forms = ChatForm(request.POST) print(forms.img) if forms.is_valid(): message = forms.save(commit=False) message.username = request.user.username message.save() return redirect('chat:index') It must work, but doesn't create img field. template <form action="" method="post"> {% csrf_token %} <div> {{ forms.message.label }}: {{ forms.message }} </div> <div> {{ forms.img.label }}: {{ forms.img }} </div> <div class="d-flex justify-content-end mt-2"> <button class="btn btn-success" type="submit">Send</button> </div> </form> -
class EmployeeForm(ModelForm): class Meta: model = Employee Fields ='__all__'
not working this error throwing django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form EmployeeForm needs updating. not tried any thing else -
Manage dependency of django model relations for migrating database
I'm working on a Django project using Oracle database. I'm going to migrate all of data from Oracle database to Postgres database. My database has many tables with too many ForeignKeys, ManyToMany and OneToOne relations together. I can migrate drips and drapes in the first solution, which requires too much resources. I'm going to migrate these by only one command. I need a sorted list of all tables managed by django which are sorted by their dependencies. In other words a table which is referred by other tables through ForeignKeys should be sorted first. What shall I do to handle this? -
DJANGO - FOREIGN KEY FILTER IN FORMS
I a transaction model and pallet model, class Transaksi(models.Model): transaction_type = models.CharField(max_length=10, choices=transaction_type_CHOICES) palletnumber = models.ForeignKey(Pallet, on_delete=models.CASCADE) class Pallet(models.Model): nama_pallet = models.CharField(max_length=100, unique=True) pallet_weight = models.IntegerField() status = models.BooleanField(default=False) the thing that i do def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) transaction_type = self.initial.get('transaction_type') or self.instance.transaction_type if transaction_type == 'in': self.fields['palletnumber'].queryset = Pallet.objects.filter(status=False) elif jenis_transaksi == 'keluar': self.fields['palletnumber'].queryset = Pallet.objects.filter(status=True) i want to filter the pallet in transaction form if the type = in (status = false) if the type = out (status = true) -
ModuleNotFoundError: No module named '"travelApp'
I am using Django to create a web app, and when I tried to use the py manage.py runserver command, I got this error: ModuleNotFoundError: No module named '"travelApp' This is the full error: Traceback (most recent call last): File "C:\Users\n_mac\OneDrive\Desktop\Coding\Python\Django\travelApp\.venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\n_mac\OneDrive\Desktop\Coding\Python\Django\travelApp\.venv\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\n_mac\OneDrive\Desktop\Coding\Python\Django\travelApp\.venv\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\n_mac\OneDrive\Desktop\Coding\Python\Django\travelApp\.venv\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\n_mac\OneDrive\Desktop\Coding\Python\Django\travelApp\.venv\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\Users\n_mac\OneDrive\Desktop\Coding\Python\Django\travelApp\.venv\lib\site-packages\django\conf\__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "C:\Users\n_mac\OneDrive\Desktop\Coding\Python\Django\travelApp\.venv\lib\site-packages\django\conf\__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\n_mac\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named '"travelApp' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\n_mac\OneDrive\Desktop\Coding\Python\Django\travelApp\manage.py", line 21, in <module> main() File "C:\Users\n_mac\OneDrive\Desktop\Coding\Python\Django\travelApp\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\n_mac\OneDrive\Desktop\Coding\Python\Django\travelApp\.venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line … -
aldjemy/sqlalchemy engine timeout with google cloud
I have a django app where I am using graphql, it's running on google cloud with 60 minutes timeout. The DB is POSTGRES. At some point I had to use sqlalchemy to upload a large csv file to the databse, and graphql is not fast enough for that. 20 minutes into the upload I get the following error: ERROR in app: Exception on / [GET] and Traceback (most recent call last): File "/layers/google.python.pip/pip/lib/python3.9/site-packages/urllib3/connectionpool.py", line 703, in urlopen httplib_response = self._make_request( File "/layers/google.python.pip/pip/lib/python3.9/site-packages/urllib3/connectionpool.py", line 449, in _make_request six.raise_from(e, None) File "<string>", line 3, in raise_from File "/layers/google.python.pip/pip/lib/python3.9/site-packages/urllib3/connectionpool.py", line 444, in _make_request this is how I am uploading the file: with pd.read_csv("prices.csv", chunksize=500000) as reader: for prices in reader: engine = get_engine(connect_args={'connect_timeout': 3600, 'pool_size': NullPool}) with engine.begin() as conn: conn.exec_driver_sql( f"CREATE TEMPORARY TABLE {temp_table_name} AS SELECT * FROM {table_name} WHERE false" ) prices.to_sql(temp_table_name, conn, if_exists="append", index=False) conn.exec_driver_sql(stmt) engine.execute(f'DROP TABLE "{temp_table_name}"') I do not get the error when i run the code locally and I can't find any reference to the 20 minutes anywhere on google cloud, except for the function timeout, which is set to 60 minutes in my case. -
Django get Models ID from Zip_longest() function data on HTML
I am working a Django application where I have used python zip_longest function with a the for loop for displaying both the Customer Deposits and Withdrawals in an HTML Table, and I want to get the second zipped list item ID unto a url in a button. How do I achieve this. Here is my Model: class Witdrawal(models.Model): account = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) transID = models.CharField(max_length=12, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) withdrawal_amount = models.PositiveIntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.account}- Withdrawn - {self.withdrawal_amount}' Here is my first view: @login_required(login_url='user-login') def account_statement(request, id): try: customer = Account.objects.get(id=id) #Get Customer ID customerID = customer.customer.id except Account.DoesNotExist: messages.error(request, 'Something Went Wrong') return redirect('create-customer') else: deposits = Deposit.objects.filter(customer__id=customerID).order_by('-date')[:5] #Get Customer Withdrawal by ID and order by Date minimum 5 records displayed withdrawals = Witdrawal.objects.filter(account__id=customerID).order_by('-date')[:5] context = { "deposits_and_withdrawals": zip_longest(deposits, withdrawals, fillvalue='No Transaction'), } return render(request, 'dashboard/statement.html', context) Here is my HTML code: {% if deposits_and_withdrawals %} <tbody> {% for deposit, withdrawal in deposits_and_withdrawals %} <tr> <td style="background-color:rgba(231, 232, 233, 0.919); color:blue;">Deposit - </td> <td style="background-color:rgba(231, 232, 233, 0.919)">{{ deposit.acct }}</td> <td style="background-color:rgba(231, 232, 233, 0.919)">{{ deposit.transID }}</td> <td style="background-color:rgba(231, 232, 233, 0.919)">N{{ deposit.deposit_amount | intcomma }}</td> <td style="background-color:rgba(231, 232, 233, 0.919)">{{ deposit.date … -
How to redirect after deleting a detail view object?
Unable to redirect because the object no longer exists after deletion. URLs: urlpatterns = [ # home page path('', views.index, name='index'), path('forums/forum_create/', views.forum_create, name='forum_create'), path('forums/forum_edit/<int:id>/', views.forum_edit, name='forum_edit'), path('forums/forum_delete/<int:id>/', views.forum_delete, name='forum_delete'), path('forums/<int:id>/', views.thread_list, name='thread_list'), path('thread/<int:year>/<int:month>/<int:day>/<slug:thread>/', views.thread_detail, name='thread_detail'), path('thread_comment/<int:id>/', views.thread_comment, name='thread_comment'), path('thread_create/<int:id>/', views.thread_create, name='thread_create'), path('thread_edit/<int:id>/', views.thread_edit, name='thread_edit'), path('thread_delete/<int:id>/', views.thread_delete, name='thread_delete'), path('search/', views.site_search, name='site_search'), ] view: def thread_list(request, id): forum = Forum.objects.get(id=id) threads = forum.threads.all() paginator = Paginator(threads, 20) page_number = request.GET.get('page', 1) try: threads = paginator.page(page_number) except PageNotAnInteger: threads = paginator.page(1) except EmptyPage: threads = paginator.page(paginator.num_pages) return render(request, 'forum/thread_list.html', {'forum': forum, 'threads': threads}) (...) # cut @login_required def thread_delete(request, id): thread = get_object_or_404(Thread, id=id) forum = thread.forum if request.method == 'POST': thread.delete() return redirect('forum/thread_list.html', id=forum) return render(request, 'forum/thread_delete.html', {'thread': thread, 'forum': forum}) thread_delete.html: {% extends 'forum/base.html' %} {% block content %} <h1 class="mt-5 pb-4">Forums > Threads > Delete {{ thread.title }}</h1> <p>Are you sure you want to delete thread "{{ thread.title }}"? All replies and other associated objects will be deleted along with it.</p> {% load django_bootstrap5 %} <form action="" method='post'> {% csrf_token %} {% bootstrap_button button_type="submit" content=" Confirm and delete" %} </form> {% endblock content %} The forum = thread.forum will not work because thread. no longer exists after deletion? This … -
how do you use docker to install packages (trying to install flake8 to help me debug) locally to keep the image as light as possible
I am trying to install flake8, to help me debug but it's not installing, note that I do not want to install it in the image here is my docker-compose.yml version: "3.9" services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" Dockerfile FROM python:3.9-alpine3.13 LABEL maintainer="jcmbisa" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./requirements.dev.txt /tmp/requirements.dev.txt COPY ./app /app WORKDIR /app EXPOSE 8000 ARG DEV=false RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /tmp/requirements.txt && \ if [ $DEV = "true"]; \ then /py/bin/pip install -r /tmp/requirements.dev.txt ; \ fi && \ rm -rf /tmp && \ adduser \ --disabled-password \ --no-create-home \ django-user ENV PATH="/py/bin:$PATH" USER django-user reuirement.txt Django>=4.0.10,<4.1 djangorestframework>=3.12.4,<3.13 requirement.dev.txt flake8>=3.9.2,<3.10 ready to learn thanks -
Django duplicate tables with multiple databases
I have multiple databases one is sqlite and the others in postgresql using one app, when i migrate bases 'using routers' all the tables in models.py gets created in all the bases including sqlite or nothing if i added return false to the allow_migrate function. how to stop duplicate tables from happening ?? this is my code 'example' settings.py DATABASE_ROUTERS = ['routers.router.sqlite_Router','routers.router.postgres_router_1','routers.router.postgres_router_2'] DATABASES = { 'default': {}, 'auth_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'postgres_db_1': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'options': '-c search_path=test' }, 'NAME': 'test1', 'USER': 'postgres', 'POSRT':'5432', 'PASSWORD': 'postgres', 'HOST':'localhost', }, 'postgres_db_2': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'options': '-c search_path=test' }, 'NAME': 'test2', 'USER': 'postgres', 'POSRT':'5432', 'PASSWORD': 'postgres', 'HOST':'localhost', } } router.py class sqlite_Router: route_app_labels = {'auth', 'contenttypes','admin','sessions','messages','staticfiles'} database = 'auth_db' .... def allow_migrate(self, db, app_label, model_name=None, **hints): model = hints.get('model') if model: usedb = getattr(model._meta, 'database', None) if app_label in self.route_app_labels and usedb == self.database: return db == self.database # True #else: return False # <== i only get django_migrations, no other tables return None class postgres_router_1: route_app_labels = {'test'} database = 'postgres_db_1' .... def allow_migrate(self, db, app_label, model_name=None, **hints): model = hints.get('model') if model: usedb = getattr(model._meta, 'database', None) if app_label in self.route_app_labels and … -
Formsets are returning as valid=False and not saving
I'm trying to create a form that allows teachers to create lessons, which are linked to multiple activities (ManyToMany), which are in turn linked to many Items (ForeignKey). As such, I am using formsets for activities and items. However, activity_formset is coming back as invalid and not saving. The View class N_LessonEditAllView(LoginRequiredMixin, UpdateView): model = Lesson template_name = 'lessons/edit-lesson.html' form_class = LessonForm def get_object(self): return get_object_or_404(Lesson, pk=self.kwargs.get('pk')) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) lesson = self.get_object() activity_formset = ActivityFormSet(queryset=lesson.activity.all()) item_formsets = [] for activity_form in activity_formset: item_formset = ItemFormSet(queryset=Item.objects.filter(activity_id=activity_form.instance.id)) item_formsets.append(item_formset) context['activity_formset'] = activity_formset context['item_formsets'] = item_formsets return context def form_valid(self, form): context = self.get_context_data() activity_formset = context['activity_formset'] item_formsets = context['item_formsets'] print('activity_formset is valid:', activity_formset.is_valid()) print('activity_formset errors:', activity_formset.errors) for activity_form in activity_formset: item_formset = ItemFormSet(queryset=Item.objects.filter(activity_id=activity_form.instance.id)) item_formsets.append(item_formset) print(f'activity_formset for activity {activity_form.instance.id} is valid: {item_formset.is_valid()} --- data {activity_formset.data} --- errors: {activity_formset.errors} --- payload {self.request.POST}') if activity_formset.is_valid() and all(item_formset.is_valid() for item_formset in item_formsets): self.object = form.save() activity_formset.instance = self.object activity_formset.save() print('Form is valid:', form.is_valid()) print('Activity formset is valid:', activity_formset.is_valid()) for item_formset in item_formsets: print('Item formset is valid:', item_formset.is_valid()) item_formset.instance = self.object item_formset.save() raise ValueError('Intentional error') print(form.cleaned_data) return super().form_valid(form) else: return self.form_invalid(form) The Template <div class="card"> <form method="post"> <div class="card-header"> {% csrf_token %} {{ form|crispy … -
How to make Django ModelForm filed to update the attrs, so the style can be displayed successfully
from django.forms import ModelForm from django import forms from .models import Project class ProjectForm(ModelForm): class Meta: model = Project fields = ['title', 'featured_image', 'description', 'demo_link', 'source_link', 'tags'] widgets = { 'tags': forms.CheckboxSelectMultiple(), } def __int__(self, *args, **kwargs): super().__int__(*args, **kwargs) # self.fields['title'].widget.attrs.update({'class': 'input'}) for name, field in self.fields.item(): field.widget.attrs.update({'class': 'input'}) I AM TRYING TO DISPLAY MY DYNAMIC FORM WITH THE CORRECT STYLING, BUT THIS METHOD DOESN'T SEEM TO WORK Does anybody know how to fix it? Thank you so much for the help in advance ` def __int__(self, *args, **kwargs): super().__int__(*args, **kwargs) # self.fields['title'].widget.attrs.update({'class': 'input'}) for name, field in self.fields.item(): field.widget.attrs.update({'class': 'input'})` This doesn't seem to work -
Displaying an image stored in a Django database
I have a website dedicated to pets (dead ones), and I have some stock images in the database stored under the pet using a manytomany field (so, any number of pets can be in an image, and a pet can have any number of images associated with it--seems logical so far). I am trying to display the pet photos in any way at all in one of the templates. My problem is, I have NO IDEA what the correct syntax for iterating over a context_dictionary data structure I have made to store pets and pet photos for the purpose of accessing in the associated template file. I am having to do this because I think (correct me if I'm wrong) a view can only have one associated model, and I need a few models, their data, to display in one view. So. It is what it is. I think it's probably about time I showed some of my code. Here is one after another: pet_profile/models.py from django.db import models from django.utils.crypto import get_random_string import uuid from django.urls import reverse class PetPhoto(models.Model): slug = models.SlugField(max_length = 5, primary_key = True, blank = True, null=False) title = models.CharField(max_length = 255) id = … -
Incorrect floating label positioning on responsive input form
I've created a form using Django, Crispy Forms and Bootstrap. At screen widths above 575px the form and labels look as expected with fields of the correct width and floating labels in the correct position, however at screen widths below 575px the floating labels appear in the wrong position. I'd appreciate any guidance as to how I can make the floating labels remain in the correct position relative to the input field regardless of screen width. Expected: >575px Unexpected: <575px I believe this happens because, in order to force the responsive resizing of the input fields, I manually amended the CSS to reduce the the field width to 85% at screen widths lower than 575px by using a media query as follows: CSS .form-floating { position: relative; } .form-floating > .form-control, .form-floating > .form-select { height: calc(3.5rem + 2px); line-height: 1.25; } .form-floating > label { position: absolute; top: 0; left: 0; height: 100%; padding: 1rem 0.75rem; pointer-events: none; border: 1px solid transparent; transform-origin: 0 0; transition: opacity 0.1s ease-in-out, transform 0.1s ease-in-out; } @media (max-width: 575px) { .form-floating > .form-control, .form-floating > .form-select { display: block; width: 85%; padding: 0.375rem 0.75rem; margin: 0 auto; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: … -
Django model-chain, im not reaching bottom from top
class Firma(models.Model): #company isim = models.CharField(max_length=20) def __str__(self): return f"{self.isim}" class Proje(models.Model): #project isim = models.CharField(max_length=20) #name projeBedeli = models.DecimalField(max_digits=20, decimal_places=0) #total project cost projeKalantutar = models.DecimalField(max_digits=20, decimal_places=0) #remaining project cost projeTarih = models.DateField() #project date firma = models.ForeignKey(Firma, on_delete=models.CASCADE) #company def __str__(self): return f"{self.isim} {self.projeBedeli} {self.projeKalantutar} {self.projeTarih}" class Odeme(models.Model): #payment hakedisAdi = models.CharField(max_length=20) #WpName hakedisTutar = models.DecimalField(max_digits=20, decimal_places=0) #WpPrice hakedisTarih = models.DateField() #Date proje = models.ManyToManyField(Proje, through='Santiye') #project def __str__(self): return f"{self.hakedisAdi} {self.hakedisTutar} {self.hakedisTarih} {self.proje}" class Araclar(models.Model): #tools tip = models.CharField(max_length=20) #type def __str__(self): return f"{self.tip}" class Santiye(models.Model): #Work field butce = models.ForeignKey(Odeme, on_delete=models.CASCADE, null=True, default=0) #budget proje = models.ForeignKey(Proje, on_delete=models.CASCADE) #project isim = models.CharField(max_length=50) #name araclar = models.ManyToManyField(Araclar) #tools def __str__(self): return f"Birim : {self.isim} / Şantiye Bütçesi : {self.butce} / Bağlı Olduğu Proje : {self.proje} / Kullanılan Araçlar : {self.araclar}" class Personel(models.Model): #Workers ad = models.CharField(max_length=50) #name cinsiyet = models.CharField(max_length=10) #gender yas = models.DecimalField(max_digits=4, decimal_places=0) #age baslamaTarih = models.DateField() #date resim = models.FileField(default="static/images/avatar.jpg") #avatar birim = models.ForeignKey(Santiye, on_delete=models.CASCADE, null=True, default='') #which work field def __str__(self): return f"{self.ad} {self.cinsiyet} {self.yas} {self.baslamaTarih} {self.birim}" I am not sure this models.py perfectly fits with this diagram to be honest.. Here is the link of ERD Diagram : https://ibb.co/7GchYCM Actually I want … -
wfastcgi-enable.exe is not recognize on python 3.10.10
How can I configure a Django Project on IIS without wfastcgi.py? I don't found any wfastcgi.py in python's 3.10.10 folder. Anyone could help me? I tried at least 5 tutorials on youtube, but everyone requires wfastcgi.py. I've expected anyone could help me to solve this issue. -
Html Form Posting Values to Django Backend only when submitted twice, or rather hit back to form and then submit again
So I have stumbled upon a case where my form does not post values after I click the submit button once, it goes to the next page indeed but my Django View can not fetch the post values. But soon after I hit back button on browser and then clicks the submit button again it works ; I can then see the POSTed values in my DJango Views. Here's my HTML form. (Please note I have removed the unnecessary code which is long) <form action="" method="POST" id="quizform"> {% csrf_token %} <fieldset class="cfield" id="box1"> <p id="question" class="fs-title"> 1. {{data.0.question}}</p> <div class="row"> <div class="{% if data.0.correct_answer2 == "" %}col-12{% else %}col-9{% endif %}"> <div class="form-check"> <label class="form-check-label"> <img id="a1-icon-{{data.0.pk}}" src="/static/assets/img/correct.png" class="answer_icon" width="20px" style="z-index: 99;" hidden> <input id="a1{{data.pk}}" style="z-index: -1;" type="radio" class="radiobox form-check-input radio-box ans" name="q{{data.0.pk}}" qid="{{ data.0.pk }}" value="{{data.0.a1}}" required {% if data.0.correct_answer2 != "" %}disabled{% endif %}> <span class="cspan" style="color: white;">TES</span> </label> <span id="a1" class="cspan">{% if data.0.a1_image.url != None %}<img src="{{ data.0.a1_image.url }}" class="" width="100px">{% endif %} {{data.0.a1}} </span> </div> <div class="form-check"> <label class="form-check-label"><img id="a2-icon-{{data.0.pk}}" src="/static/assets/img/correct.png" class="answer_icon" width="20px" style="z-index: 99;" hidden> <input id="a2{{data.pk}}" style="z-index: -1;" type="radio" class="radiobox form-check-input radio-box ans" name="q{{data.0.pk}}" qid="{{ data.0.pk }}" value="{{data.0.a2}}" required {% if data.0.correct_answer2 != "" … -
My comment form does not appear on the template page (django)
My codes work on local but not work on the net :) Here is my simple django blog website. When i tested these codes work but when i try live version, it doesnt work. Where is the my fault? If you wanna see the live page you can look this page https://www.endustri.io/kaynak-perdesi-nedir-ne-ise-yarar-cesitleri-fiyatlari/ I added two types comment section the template page but none of them work. Here is my codes; blog post codes page (detail.html) {% extends 'blog/base1.html' %} {% load static %} {% block content %} <head>{% block title %}<title>{{ post.title }} - Endustri.io</title>{% endblock %}</head> <div class="card"> <h5 class="card-header">{{ post.title }}</h5> <div class="card-body"> <h6 class="card-title">Yazar: {{ post.author.first_name }} {{ post.author.last_name }} - Tarih: {{post.date_added}} - Kategori: <a href="{% url 'category' post.category.slug %}"> {{ post.category.title }}</a> <hr/></h6> <p class="card-text">{{ post.body|safe }}</p> </div> </div> <div class="card"> <h5 class="card-header">Yorumlar</h5> <div class="card-body"> <h6 class="card-title"> {% for comment in comments %} <article> <strong>{{ comment.name}} at {{ comment.date_added }}</strong></br> {{ comment.body }} </article> {% endfor %}</h6> </div> </div> <form method="POST" class="form-group"> {% csrf_token %} {{ form.as_p }} <button type="submit">Yorum Ekle</button> </form> <br> <form method="POST"> {% csrf_token %} <div class="form-group"> {{ form.as_p }} <button type="submit">Add comment</button> </div> </form> {% endblock %} Comment model class Comment(models.Model): … -
(No asignation direction ipv6 in docker) /usr/bin/env: ‘bash\r’: No such file or directory
Soy nuevo en esto, estoy tratando de clonar un repositorio de GitHub, trabajo con el docker, en el powershell, creo la carpeta, descargo el repositorio, abro la carpeta del repositorio, ejecuto la instrucción docker compuse build, pero al ejecutar el docker compouse up, me da la direccion ipv4 pero la direccion ipv6 no, en el docker me crear los contenedores pero al iniciarlos, no hace nada. Intenté de nuevo, creando otra carpeta, sigue igual -
How to decode uidb64 from activation link's url Django
i hope you are all doing well. I am working on a django project with MySQL. I am working on the signup part for the candidate with an activation link sent in the email. When i connected django to MySQL Workbench, It generated a Model file including the "Candidats form" which iam using in my view. The problem is that i cannot decode the uidb64 from the url. I can send a link in the email but it always return "Activation went wrong" and when i debugged my code i found out that my methid is not returing the uid but None. This is my view.py from django.urls import reverse from .tokenssss import token_generator from django.core.mail import EmailMessage from django.contrib.sites.shortcuts import get_current_site from django.shortcuts import render from django.http import HttpResponse from django.utils.encoding import force_bytes, force_str from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.views import View from .models import Candidats, Recruteurs # Create your views here. def sign_up_candidat(request): if request.method == "POST": nom = request.POST.get('nom') prenom = request.POST.get('prenom') date = request.POST.get('date') sexe = request.POST.get('sexe') telephone = request.POST.get('telephone') email = request.POST.get('email') password = request.POST.get('pass') password_c = request.POST.get('pass_c') if password != password_c: return HttpResponse("Confirmation password went wrong") else: my_user = Candidats(nomcandidat=nom, prenomcandidat=prenom, datenaissance=date, sexe=sexe, … -
Is there anyway to activate 'venv' on Pycharm?
**Hello i'm using pycharm for Django on windows and when i use this code .\venv\Scripts\activate system shows me this error this is my error what should i do to activating my virtual enviroment ** i just try this code .\venv\Scripts\activate -
How to properly extend user model in Django
I am working on a Django employee management system, I want the employee bio data on the same table as the user object used for registration and login I tried adding the user model as a OnetoOneField on the employee table, but I don’t like having to register the user and then fill the employee form separately. I want the users to be able to create their bio data while creating an account -
Trying to retrieve array from django QueryDict
I want to transfer an array from an Inertia form array to django. In the debug window it's shown as test[0] = 1, test[1] = 2. Neither calling request.POST.get("test") nor request.POST.getlist("test") nor request.POST.getlist("test[]") returns me a usable list. My form object looks as follows (data is hard coded for test purposes): let form = useForm({ "test": [1, 2, 3] }) -
I'm trying to deploy a django site on a hosting. But I don't have SSH access. Are there any other options to do this? [closed]
Я пытаюсь задеплоить сайт на джанго на хостинг. Но у меня нет доступа к SSH. Есть какие нибудь другие способы это сделать? How to deploy django project on host without usinng SSH? Я пытался через wsgi/ htaccess. Но что то не получилось ничего -
psql Cannot open extension control file, but the file exists
psql command line: postgres=# CREATE EXTENSION pg_tgrm; ERROR: extension "pg_tgrm" is not available DETAIL: Could not open extension control file "C:/Program Files/PostgreSQL/15/share/extension/pg_tgrm.control": No such file or directory. HINT: The extension must first be installed on the system where PostgreSQL is running. postgres=# yum install postgresql14-contrib postgres-# CREATE EXTENSION pg_tgrm; The directory: enter image description here What am I doing wrong? The file is definately there and I've installed it on another postgresql server just beforehand on the same machine? This is for a Django project on Windows 11. Tried to install the pg_tgrm; extension and expected it to work.