Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setting up Django-Casper
I have installed Django-Casper on my raspberry-pi following this tutorial: http://blog.daviddemartini.com/installing-casperjs-on-raspberry-pi/ I need it to tests the AJAX of my Django app. Everything worked fine but when I tried to run $ casperjs I've an error TypeError: Attempting to change the setter of an unconfigurable property. I have searched a way to fix this issue but with no luck. Has anyone encountered the same issue? -
Django says 'The _imaging C module is not installed' when I try to add images to database entries
I am working on ubuntu server,and this is my first web development project based on django. After I have hosted the site with apache2, mod_wsgi , the site is running but I have encountered two problems: 1)All the users and other database entries have been lost. I have tried makemigrations and migrate , but it didnt solve it. 2) I tried to add all the entries again, but now there is a problem with adding images to the ImageField in the databases using Pillow module.It says The _imaging C module is not installed . The error takes place in sites-packages\PIL\Image.py (I am using a virtualenv) somewhere around line 93 which is from . import _imaging as core . Python version: 3.7, django version: 3.0 , ubuntu version: 18 Here are all fixes I've tried: 1) Changed line 93 in PIL/Image.py from from . import _imaging as core to from PIL import _imaging as core . No changes, the error still occurs. 2)Tried installing libjpeg with the following code- sudo apt-get install libjpeg-dev . Turned out that I already had it globally. 3)Changed the location of virtualenv directory from somewhere inside /var/www/ to /usr/local/ because somewhere I had read that there … -
Query set error when using get_or_create and objects.filter
I am trying to add a default value to a model when creating one my view def index(request, log_id): log = get_object_or_404(LogBook, pk=log_id) logmessages = LogMessage.objects.filter(logbook=log_id) logbook, _ = LogBook.objects.get_or_create(logmessages=logmessages) form = CreateLogMessage(request.POST) if request.method == "POST": if form.is_valid(): instance = form.save(commit=False) instance.reported_by = request.user instance.date = datetime.now() logbook.done_status = False logbook.save() instance.save() Expected result : Logbook should be created using the logmessage instance. I have an error The QuerySet value for an exact lookup must be limited to one result using slicing. I have look up on SO and althougt this error came up a lot nothing work for me, any idea ? -
I am trying to use static files like css and images in my django project but statics files are not displayed in my template page
I want a image to be displayed in my navbar at the top left corner but its not visible and my css styling is also not styling my pages....in short my static files are not displayed in my project. i think i have mentioned all the neccesary things if anything is missing please mention. my settings.py---- STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') STATIC_FILES = os.path.join(BASE_DIR,'static','static_files') STATIC_ROOT = os.path.join(BASE_DIR,'static','static_root') urls.py--- from Devishi import settings from django.conf.urls.static import static urlpatterns = [ path('',views.home,name='home'), path('product/',views.products,name ='product'), path('customer/',views.customer,name ='customer'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) main.html--- {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>{% block title %}DASHBORD||{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="{% static '/css/my.css' %}"> </head> <body> {% include 'app/navbar.html' %} {% block content %} {% endblock %} <hr/> <p>Our Footer</p> </body> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </html> navbar.html--- {% load static %} <style media="screen"> .hello-msg{ font-size:18px; color:#fff; margin-right:20px; } </style> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <img src="{% static "img/logo.png" %}" alt="image"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item … -
Getting TypeError at / expected string or bytes-like object in QuerySet
I tried to run runserver, I checked all the pages, everything was fine except my homepage which issued an error. TypeError at / expected string or bytes-like object. Traceback (most recent call last): File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\views\generic\list.py", line 142, in get self.object_list = self.get_queryset() File "C:\Users\ANTON\Desktop\Learn Django\cloneBlogProject\mySite\blog\views.py", line 19, in get_queryset return Post.objects.filter(published_date__lte = timezone.now).order_by('-published_date') File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\db\models\query.py", line 904, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\db\models\sql\query.py", line 1350, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q child_clause, needed_inner = self.build_filter( File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\db\models\sql\query.py", line 1311, in build_filter condition = self.build_lookup(lookups, col, value) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\db\models\sql\query.py", line 1165, in build_lookup lookup = lookup_class(lhs, rhs) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\db\models\lookups.py", line 22, in __init__ self.rhs = self.get_prep_lookup() File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\db\models\lookups.py", line 72, in get_prep_lookup return self.lhs.output_field.get_prep_value(self.rhs) File "C:\Users\ANTON\Anaconda3\envs\cloneBlog\lib\site-packages\django\db\models\fields\__init__.py", line 1355, in get_prep_value value = super().get_prep_value(value) File … -
How to use template tags inside safe filtered content in django
<strong>{{ var.name }} </strong> The above code is saved inside database with a field name data . While rendering template with {{ data | safe }} , it gives output as {{ var.name }} as strong , but doesn't load the content inside var.name. Is it possible to do so. -
how to edit or modify my booleanfield in django
i would be really glad if anyone could help me with my code,i have a model shows if a user is subscribed or not,so i decided to use a boolean field but i want to edit the field so that i can be able to display Subscribed once a client click on it and perform some payment in another url,and the user would be given a specific generated code to use till the subscription is over to access to actions here is what i have written in my model and my output thanks in advance models.py class Patient(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, related_name="patient") subscribe = models.BooleanField(default=False) def __str__(self): return f'{self.user.username}' views.py @login_required def patient(request): context = { 'patient': Patient.objects.all() } return render(request, 'pages/patient.html', context) template.html <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4 h4 text-center center">Your Email</legend> <legend class=" mb-4 h3 center text-center">{{ user.email }}</legend> </fieldset> <div class="form-group text-center center"> <button class="btn btn-outline-info" type="submit">{{ user.patient.subscribe }}</button> </div> </form> -
Is possible to send a personalized email in django (with context), without use a html template?
Basically, i would like to know if it's possible to do this: views.py ... current_site = get_current_site(request) subject = 'Activate your account!' message = render_to_string('portale/admin/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) account_activation_email.html {% autoescape off %} Hi {{ user.username }}, Please click on the link below to confirm your registration: http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} but without using the html template. Any ideas? -
How to configure Cookiecutter Django to use Gmail SMTP
Can anyone help me with to configure my django cookiecutter production setup to work with Gmail SMTP. I have deployed my application using docker. Cookiecutter gives you to configure your app to anymail providers. I've chosen Mailgun however I didn't have an email address that has been verified by my domain provider. So, I couldn't register any user to my app because ( https://cookiecutter-django.readthedocs.io/en/latest/deployment-with-docker.html#configuring-the-stack) here it says you can't :) I have tried to override the default email verification setting from "mandatory" to "none". However, it still threw 500. In below, I've added all-auth settings. I had to decide either to buy an email address or configure my app to work with Gmail Smtp or get rid of this email verification process. settings/base.py ACCOUNT_ALLOW_REGISTRATION = env.bool("DJANGO_ACCOUNT_ALLOW_REGISTRATION", True) # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_AUTHENTICATION_METHOD = "username" # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_EMAIL_REQUIRED = True # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_EMAIL_VERIFICATION = "none" # https://docs.djangoproject.com/en/dev/ref/settings/#email-backend EMAIL_BACKEND = env( "DJANGO_EMAIL_BACKEND", default="django.core.mail.backends.smtp.EmailBackend" ) Any way to get rid of this 500 would be awesome. -
How to authenticate fsspec for azure blob storage
From a django REST API view I am trying to access a file that is stored in an azure storage blob. I would like to open it without downloading it into a file, as shown here. Read access is sufficient. For this I scetched out my view like so: import os from fsspec.implementations.http import HTTPFileSystem @api_view() def my_view(request): url = "https://storageaccount.blob.core.windows.net/container/" filename = "file.f" fs = HTTPFileSystem( container_name=os.environ["AZURE_STORAGE_CONTAINER"], storage_options={ "account_name": os.environ["AZURE_STORAGE_ACCOUNT"], "account_key": os.environ["AZURE_STORAGE_KEY"], }, ) with fs.open(url + filename, "r") as fobj: ds = somehow.open_dataset(fobj) return Response({"message": "Data manipulated"}, status=200) This gives a FileNotFoundError. My questions are: Is this even possible with azure blob storage? If not, what would be the closest thing? How would I authenticate the HTTPFileSystem? I feel like I more or less made those keywords up but wasn't able to find any information about it... -
Looping through nested dicts in Django Template
I have a nested dict that I am passing as context to a template of the following structure: cWeeks{ 1: { 'receivables': { 'customer': 'x', 'amount': 'y', ...} 'payables': { 'customer': 'x', 'amount': 'y', ...} } 2: { etc } } In my template I have a for loop iterating over each number and then another nested for loop that should iterate over all items in 'receivables'. Unfortunately that second loop never begins. This is the relevant code in the template: {% for cw in cWeeks %} <div class="kw1"> <div class="card"> <h5 class="card-header text-center">KW {{ cw }}</h5> <ul class="list-group list-group-flush"> {% for receivable in cw.receivables %} <li class="list-group-item zahlung payment-receivable"> <div class="payment-content"> <div class="typ">Zahlung</div> <div class="kunde">{{ receivable.customer }}</div> <div class="kwSelektor"> <form action="#" method="POST"> <div class="form-group formKwSelektor"> <select class="form-control form-control-sm" id="kwxxSelektor"> <option value="10">KW 10</option> <option value="11">KW 11</option> </select> </div> <button type="submit" class="btn btn-primary">KW ändern</button> </form> </div> <div class="betrag">{{ receivable.amount }}</div> <div class="bank">{{ receivable.account }}</div> </div> </li> {% endfor %} </ul> </div> </div> {% endfor %} My views.py: from django.shortcuts import render from django.http import HttpResponse from .models import * def home(request): """ Calendar Weeks payments overview """ cWeeks = {1: dict(), 2: dict(), 3: dict(), 4: dict()} for week in range(1, … -
500 Error on a Django page that uses Ajax
I'm having a 500 error after trying to submit a csv file. The 500 error says having a problem in DeproAjaxView. Up until November this was working fine. Now the live site is giving the 500 error, but the local development server is giving a 403 forbidden error (csrf token missing or incorrect). I checked that, and it does have a token. class DeprovisionView(LoginRequiredMixin,UserPassesTestMixin,TemplateView): template_name = "technology/deprovision.html" login_url = reverse_lazy('login') def test_func(self): user = self.request.user.id groups = User.objects.filter(pk=user,groups__name__exact='HARDWARE_ADMIN').exists() return groups class DeproAjaxView(LoginRequiredMixin,UserPassesTestMixin,View): login_url = reverse_lazy('login') def test_func(self): user = self.request.user.id groups = User.objects.filter(pk=user,groups__name__exact='HARDWARE_ADMIN').exists() return groups def post(self, request, *args, **kwargs): device_list = defaultdict(list) error_list = [] success_list = [] devices = [] deprovision = [] csv_data = json.loads(request.body.decode("utf-8")) data = list(chain.from_iterable(csv_data.get('data'))) loop = asyncio.new_event_loop() response = sorted(loop.run_until_complete(async_get_chromebook(data, loop)), key=itemgetter('status')) for item in response: device_list[item['status']].append(item) for key, value in device_list.items(): if key == 'ACTIVE': devices.extend(value) else: error_list.extend(value) if not devices: data = {'status': 'error','error_list': error_list} else: for item in devices: deprovision.append(item.get('deviceId')) depro_resp = loop.run_until_complete(async_deprovision(deprovision, loop)) for item in depro_resp: if item['status'] == 'SUCCESS': success_list.append(item) else: error_list.append(item) data = {'status': 'success', 'success_list': success_list, 'error_list': error_list} return HttpResponse(json.dumps(data)) -
Django - How to join two querysets with different key values (but from same model)
I am trying to join two querysets in Django with different key values, but from the same model, is there any way to do so? Here is my code: models.py class CustomerInformation(models.Model): status = ( ('lead', 'Lead'), ('client', 'Client'), ) customer_id = models.AutoField(primary_key=True) customer_name = models.CharField(max_length=100) status = models.CharField(max_length=100, choices=status, default='lead') conversion_date = models.DateField(null=True, blank=True) created_date = models.DateField(default=timezone.localdate) def save(self, *args, **kwargs): if self.customer_id: if self.status != CustomerInformation.objects.get(customer_id=self.customer_id).status and self.status == 'client': self.conversion_date = timezone.now() elif self.status != CustomerInformation.objects.get(customer_id=self.customer_id).status and self.status == 'lead': self.conversion_date = None super(CustomerInformation, self).save(*args, **kwargs) here is my filtering start = date.today() + relativedelta(days=-30) client_qs = CustomerInformation.objects.filter(conversion_date__gte=start).values(date=F('conversion_date')).annotate(client_count=Count('date')) lead_qs = CustomerInformation.objects.filter(created_date__gte=start).values(date=F('created_date')).annotate(lead_count=Count('date')) Basically what I am trying to achieve is to get the count of CustomerInformation instances created in the past 30 days (by annotating the count of the field 'created_date'). Also, I want to get the count of CustomerInformation instances that have converted to 'client' status within the past 30 days (by annotating the count of the field 'conversion_date'). Is there any way for me to do so and receive them in a single queryset, preferably with a single date field? For example, my desired output would be [ {'date': '170620', 'lead_count': 2, 'client_count': 1}, {'date': '180620', … -
How to create view for both user and super user in a classbased view in Django? I am trying to use single link for both user and super user
class LoginCBV: def loginview(self, request): if request.user.is_authenticated: return redirect("collage_dashboard") else: if request.method == 'POST': email = request.POST.get('email') password =request.POST.get('password') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) return redirect("collage_dashboard") else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'auth/log-in.html', context) #@user_passes_test(lambda x: x.is_superuser) def loginview2(self, request): if request.user.is_authenticated: return redirect("collage_dashboard") else: if request.method == 'POST': email = request.POST.get('email') password =request.POST.get('password') user = authenticate(request, email=email, password=password) if user is not None and user.is_superuser: login(request, user) return redirect("dashboard") else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'auth/log-in.html', context) -
How do I extend my Django Default UserCreationForm?
here is my "forms.py" class CreateUser(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] and here is my "views.py" def register(request): form = CreateUser() if request.method == 'POST': form = CreateUser(request.POST) if form.is_valid(): form.save() # messages.sucess(request, 'Acccount created!') return redirect('login') context = {'form':form} return render(request, 'register.html', context) and here is my basic register.html so far. <h3>Register</h3> <form method="POST" action=""> {% csrf_token %} {{form.as_p}} <input type="submit" name="Create User"> <a href="/login">I already have a user!</a> {{form.errors}} </form> The thing is, I need to add a lot of stuff to the registration. The default user/password login is ideal, but the registration needs to have other fields for things like address and credit card number. How do I properly extend this registration, in a way that the login is still the same? -
Is there a way of triggering an action when a specific field is changed in Django models
I am looking for a way to trigger an action whenever a specific field on a model is changed, regardless of where it is changed. To add some context, I have been experiencing an elusive bug, where occasionally a date field is being set to the 13th of January 2020, I have absolutely no idea where in the codebase this is happening, it is also happening seldom enough that I have not been able to pick up any pattern as to what could be causing it. What I would like to do is trigger some kind of an alert whenever this field is changed to the 13th of Jan 2020, so I can attempt to isolate what is causing it. -
How do I find the name and its count for a FK object?
Having these models: class AccidentJob(models.Model): name = models.CharField(max_length=50) class Accident(TimeStampedModel, models.Model): job = models.ForeignKey(AccidentJob, on_delete=models.CASCADE) I want something like this: [ {'job__name': 'Auxiliar de surtido', 'count': 2}, {'job__name': 'Técnico de mantenimiento', 'count': 1} ] but I am getting this: [ {'job__name': 'Auxiliar de surtido', 'count': 1}, {'job__name': 'Auxiliar de surtido', 'count': 1}, {'job__name': 'Técnico de mantenimiento', 'count': 1} ] This is my query: from django.db.models import Count Accident.objects.values( "job__name" ).annotate( count=Count('job__name') ).values("job__name", "count") I can do it with Python, but I would prefer having PostgreSQL do the work. -
Django form field values filter by multiple queries
I am working with form logic now and my task sounds pretty easy - I need to implement form with dependent fields: 1) Country 2) Region 3) District (area) So I have my simple models: class CountryModel(models.Model): name = models.CharField('Country name', unique=False, max_length=128, blank=False, null=False) class RegionModel(models.Model): name = models.CharField('Region name', unique=False, max_length=128, blank=False, null=False) country = models.ForeignKey(CountryModel, on_delete=models.CASCADE, blank=True, null=True) class DistrictModel(models.Model): name = models.CharField('District name', unique=False, max_length=128, blank=False, null=False) region = models.ForeignKey(RegionModel, on_delete=models.CASCADE, blank=True, null=True) class FormModel(MetaModel): country = models.ForeignKey(CountryModel, on_delete=models.CASCADE, blank=True, null=True) region = models.ForeignKey(RegionModel, on_delete=models.CASCADE, blank=True, null=True) area = models.ForeignKey(AreaModel, on_delete=models.CASCADE, blank=True, null=True) It means that District queryset is depends on chosen Region and Region queryset is depends on chosen Country. I put my logic in the init form method and it looks like this: class SignCreateForm(ModelForm): data_url = '/sign-form-data/' class Meta: model = FormModel fields = ['country', 'region', 'district'] dependencies = {'district': ('region', 'country'), 'region': ('country',)} class Media: # ajax form refreshing script js = ('js/formset.js',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.is_bound: if self.data['country']: self.fields['district'].limit_choices_to = {'country': self.data['country']} apply_limit_choices_to_to_formfield(self.fields['district']) Dut it doesn’t works and raises an error: "Cannot resolve keyword 'country' into field. Choices are: id, name, region.." The question is: Is there … -
Wagtail admin_order_field attribute not sorting correctly
I have admin_order_field attribute set on method in ModelAdmin class but it's giving wrong sort results. Upon clicking sort button, it displays some duplicates and some of the values("All Clients", No Client Selected") are not grouped together. `class PermissionsModelAdmin(ModelAdmin): def clients_list(self, obj): all_clients = "All Clients" c_name = [c.name for c in obj.clients.all()] if c_name: selected_clients = ", ".join([c.name for c in obj.clients.all()]) else: selected_clients = "No Client Selected" return all_clients if obj.is_accessible_to_all_clients else selected_clients clients_list.short_description = "Clients" clients_list.admin_order_field = "clients"` -
how can i open bash_profile? i tried subl ~/.bash_profile . But i got
C:\Users\PC\PycharmProjects\django\mysite>subl ~/.bash_profile 'subl' is not recognized as an internal or external command, operable program or batch file. -
Django filter a queryset based on another table without specified relationship
Ok so this is probably a bit of an odd question, but here is my problem. With out getting into too much detail I need to send a notice to properties but only if there is a corresponding title search. Here are my models. There is specified relationship between the two. But they share a common value in a common field. They both have a properties parcel number (the parcel number for the notice is in a related field accessible by the foreign key) class Notice(models.Model): status_choice = [ ("SendNotice", "SendNotice"), ("NoticeSent", "NoticeSent") ] violation_fk = models.OneToOneField(Violation, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) notice_number = models.CharField(max_length=10) date_sent = models.DateTimeField(blank=True, null=True) status = models.CharField(choices=status_choice, max_length=10) instructions = models.TextField(blank=True, null=True) class TitleSearch(models.Model): address = models.CharField(max_length=50) parcel_number = models.CharField( max_length=24) title_search_date = models.DateField(auto_now=False, auto_now_add=False) expiration_date = models.DateField(auto_now=False, auto_now_add=False) owner = models.CharField(max_length=100) attn_line = models.CharField(max_length=150, blank=True) street_address = models.CharField(max_length=150) city = models.CharField(max_length=25) state = models.CharField(max_length=2) zip_code = models.CharField(max_length=5) So. here is my problem. I cannot send a notice to a property without a title search. BUT the title searches expire after a set period of time, so I don't necessarily want to tie them together. I am trying to get a queryset that will select all … -
Im using django-bootstrap4 in my Django project, how would I add the option for "$enable-responsive-font-sizes"?
Im just having a few issues trying to get this to work. --please correct me if I'm wrong-- But Django-bootstrap4 has a pretty recent release of bootstrap meaning enable-responsive-font-sizes should be included. I have added the option $enable-responsive-font-sizes:true; to my scss file, but it does not seem to change anything. I feel that im missing something here. Any help would be greatly appreciated. -
If a user post is potentially offensive then set Active to false
I don't want users to be able publish offensive comments on my posts. I know a way of censoring out s***, f***, c*** etc. But if you apply a blanket ban to offensive words then you may unintentionally end up banning a word such as Scunthorpe (a place in the UK) because it contains an offensive substring. In forms.py I want to set the comment active property to false if the comment potentially contains an offensive word. Therefore I could manually check any potentially controversial posts. models.py class Comment(models.Model): #The foriegn key is linked to the ID field in the Post model #id = models.IntegerField(primary_key=True, blank=False) post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') nameid = models.ForeignKey(User,on_delete=models.CASCADE,related_name='commentsid') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on= models.DateTimeField(default = timezone.now()) active = models.BooleanField(default=True) forms.py I have tried setting active to false in at least 4 different ways but have so far had no luck. Does anyone have any suggestions? def clean_body(self): body = self.cleaned_data.get("body") active = active if "f***" in body or "s***" in body : self.data['active'] = False self.fields['active'].initial = False self.cleaned_data.get("active")=False form.fields['active'].initial = False return body -
How can I create 2 forms simultaneously in just one view in django
I have two forms in the same template('index.html'), one form is to contact me and when the user send the form I receive an email. And the Other form is to 'register' in the system, so then i can enter in contact. The problem is that the two forms are in the same template and I want put them in the same view. This is the way that my view is. class IndexView(FormView): template_name = 'index.html' form_class = ContatoForm success_url = reverse_lazy('index') def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['servicos'] = Servico.objects.order_by('?').all() context['funcionarios'] = Funcionario.objects.order_by('?').all() context['portfolios'] = Portfolio.objects.order_by('?').all() context['testimonials'] = Testimonial.objects.order_by('?').all() return context def form_valid(self, form, *args, **kwargs): form.send_mail() messages.success(self.request, 'E-mail enviado com sucesso') return super(IndexView, self).form_valid(form, *args, **kwargs) def form_invalid(self, form, *args, **kwargs): messages.error(self.request, 'Erro ao enviar e-mail') return super(IndexView, self).form_invalid(form, *args, **kwargs) This is the modelform that i want to put in the view class RegistroModelForm(forms.ModelForm): class Meta: model = Registro fields = ['nome', 'email', 'phone', 'area'] -
Trouble with simple Django programm
dear participants! I'm studying Python developer course at JetBrains Academy (hyperskill.org) with current project: HyperNews Portal. I'm stuck on stage 1 - Main page header with task descripted below. Description You're working on a college newspaper called Hypernews. You are comfortable in the digital world, so you came up with the idea of broadcasting the news online and decided to create a website for this. Creating the Hypernews site will be a long road, so let's take our first step forward and make the first page. For now, you won't have actual news on the site, so until that happens you can respond to the users with the "Coming soon" message. Objectives Create the first handler for your server. If you start the project on your computer with python manage.py runserver command, your server should respond with the text "Coming soon" at the address localhost:8000. The problem I'm getting the disired result: after start of the project on my computer with "python manage.py runserver" command, my server is responding with the text "Coming soon" at the address localhost:8000. But EduTools plugin is responding "Wrong answer in test #1". I'm trying to understand why server of academy see wrong answer in …