Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display the latest 3 items in django
Is there a way to query django model to display the latest 3 items in a section of my template and display the next 3 on the next part of my template in order? -
how paginate json response data django - jquery
I'm trying to paginate django JsonResponse data , which is an ajax call , here is my views.py def lists(request): lists = CostType.objects.all().order_by('-pk') data = [] for i in lists: item = { 'id':i.id, 'cost_type':i.cost_type, 'admin':i.admin.username, 'user':request.user.username, } data.append(item) return JsonResponse({'data':data}) i want to show 10 posts per page ! and here is my ajax call function listCostTypes(){ $.ajax({ type:'GET', url:'/posts/list_posts', success:function(data){ cost_types = data.data var k = '<tbody>' if(cost_types.length > 0){ for(i = 0;i < cost_types.length; i++){ const id = parseInt(cost_types[i]['id']) k+= '<tr>'; k+= '<td class="p-2 text-xs border border-purple-900 md:text-base textpurple">' + cost_types[i]['id'] + '</td>'; k+= '<td class="p-2 text-xs border border-purple-900 md:text-base textpurple">' + cost_types[i]["admin"] + '</td>'; k+= '<td class="p-2 text-xs border border-purple-900 md:text-base textpurple">' + cost_types[i]["cost_type"] + '</td>'; k+= '</tr>' } } else{ k+= '<td class="p-2 text-xs border border-purple-900 md:text-base textpurple" colspan=4>no data found</td>' } k+='</tbody>' document.getElementById('types_list').innerHTML = k },});} <table class="table table-bordered table-striped text-center" id="lists" > <thead> <tr> <th>#</th> <th>admin</th> <th>costs</th> </tr> </thead> <tbody id="types_list"> </tbody> </tfoot> </table> please is there away to make a pagination with JsonResponse data ?! or combine backend pagination with data table pagination please ?! Thank you in advance .. -
Running unit test with TestCase on async method causes django.db.utils.InterfaceError: connection already closed
I want to test some async method that I use on an async view, but I want to be very clear that right now I am not testing my view, I already saw the documentation on django but it is only for views.... So I have this class containing multiple method and even contacting database asynchronously. class SessionService: """ Session service. Attributes: uuid (str): system uuid gcloud (str): console gcloud_id start (str): start time of the period end (str): end time of the period """ def __init__(self, uuid: str, gcloud: str, start: str, end: str): self.system_uuid: str = uuid self.gcloud_id: str = gcloud self.start: str = start self.end: str = end @database_sync_to_async def __vision_data(self) -> Tuple[List[str], List[str], List[int]]: """ Async method to get vision module's data from a uuid Returns ---------- QuerySet List where 1st element are gcloud id, 2nd UUID and last system IDs """ return System.objects.get_vision_conf_data(self.system_uuid) @async_property async def __vision_system_ids(self) -> List[int]: """ get visions Ids Returns: List[int] """ data = await self.__vision_data() return data[2] async def get_session_list(self) -> List[Dict[str, Union[str, bool, int]]]: """ Get all session for a period for a system Returns: List[Dict[str, Union[str, bool, int]]] """ spraying_session: SprayingSessionSumUpGetter = SprayingSessionSumUpGetter(self.gcloud_id, self.start, self.end) vision_systems_ids: List[int] = … -
PayPal SDK - AttributeError: 'HttpResponse' object has no attribute 'get'
I am using the PayPal SDK with Django (Django REST Framework) to create and capture transactions. Following this guide I get the error in the title. It looks like self.client.execute(request) returns paypalhttp.http_response.HttpResponse object but Django won't let me return that from my view. Any ideas? Thank you. -
Django ValueError The given username must be set from form self on form overridden save method
I´m in a django simple 3.2.9 project. When i try to override my form save method, y get next error: ValueError The given username must be set from form self It´s quite annoying, cause if I don´t override and call the save functionality from the view, it works just fine, but if I override method, it seems it can´t get self attributes from form, though it can do that on other validation methods within the class. This, my RegisterForm class. class RegisterForm(forms.Form): username=forms.CharField( required=True, min_length=4,max_length=50, widget=TextInput(attrs={ 'class':'form-control' }) ) email=forms.EmailField( required=True, min_length=4,max_length=50, widget=TextInput(attrs={ 'class':'form-control' }) ) pwd=forms.CharField( required=True, min_length=4,max_length=50, widget=PasswordInput(attrs={ 'class':'form-control' }) ) pwdr=forms.CharField( required=True, min_length=4,max_length=50, widget=PasswordInput(attrs={ 'class':'form-control' }) ) def clean_username(self): username=self.cleaned_data.get('username') if User.objects.filter(username=username).exists(): raise forms.ValidationError('Ese nombre de usuario ya se encuentra en uso') return username def clean_email(self): email=self.cleaned_data.get('email') if User.objects.filter(email=email).exists(): raise forms.ValidationError('Ese email ya se encuentra en uso') return email def clean(self): cleaned_data=super().clean() if cleaned_data.get('pwd')!= cleaned_data.get('pwdr'): self.add_error('pwdr','Las contraseñas no coinciden') return redirect('register') return redirect('home') def save(self): username=self.cleaned_data.get('username') email=self.cleaned_data.get('email') pwd=self.cleaned_data.get('pwd') return User.objects.create_user( username, email, pwd ) This self contents from print(self) inside save method label for="id_username">Username:<input type="text" name="username" value="vidalon" class="form-control" maxlength="50" minlength="4" required id="id_username"> Email: Pwd: Pwdr: Thanks in advance -
TypeError: 'NoneType' object is not callable in [class CacheableModel(models.Model):] with Django (2.2.6) and Python 3.8.10
I am getting the error "TypeError: 'NoneType' object is not callable" as shown. Any help would be really appreciated! Traceback (most recent call last): File "C:\DCT\dct-server\Move-DCT-Server-to-AWS-with-azure-dev-secrets-manager-codepipeline-082019\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Python\Python38-32\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\DCT\dct-server\Move-DCT-Server-to-AWS-with-azure-dev-secrets-manager-codepipeline-082019\server\models.py", line 15, in <module> class CacheableModel(models.Model): File "C:\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 117, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Python\Python38-32\lib\site-packages\django\db\models\base.py", line 321, in add_to_class value.contribute_to_class(cls, name) File "C:\Python\Python38-32\lib\site-packages\django\db\models\options.py", line 204, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "C:\Python\Python38-32\lib\site-packages\django\db\__init__.py", line 28, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "C:\Python\Python38-32\lib\site-packages\django\db\utils.py", line 202, in __getitem__ conn = backend.DatabaseWrapper(db, alias) File "C:\Users\yhuang\AppData\Roaming\Python\Python38\site-packages\mysql\connector\django\base.py", line 336, in __init__ super(DatabaseWrapper, self).__init__(*args, **kwargs) File "C:\Python\Python38-32\lib\site-packages\django\db\backends\base\base.py", line 102, in __init__ self.client = self.client_class(self) TypeError: 'NoneType' object is not callable the code … -
Is there a proper way to make factory boy connect to the test database
I'm experiencing a very annoying error on my project's test suites, because factory boy is running every test case on the main/default database, instead of running the queries on the proper test database. I tried adding the Meta class configuration to a factory class (as recomended in this post), but as soon as I try to run the django test suite, the application throws an error stating that the connection to the test database does not exist. I would very much appreciate any help, since the documentation is not clear at all about this situation. My settings.py: DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": 'DB_NAME', "USER": 'DB_USER', "PASSWORD": 'DB_PSSWD', "HOST": 'DB_HOST', "PORT": 3306, "TEST":{ "NAME": 'TEST_DB_NAME', }, "OPTIONS": { "init_command": "SET sql_mode='STRICT_TRANS_TABLES'; SET foreign_key_checks = 0;", }, } } my factory.py: import factory class CustomModelFactory(factory.django.DjangoModelFactory): class Meta: model = models.CustomModel database = 'TEST_DB_NAME' django_get_or_create = ('nu_cnpj',) nm_razao_social = factory.Faker(locale='pt_BR', provider='company') nu_cnpj = factory.Faker(locale='pt_BR', provider='company_id') my model.py: from django.db import models class CustomModel(models.Model): nu_cnpj = models.CharField(unique=True, max_length=20, blank=True, null=True) nm_razao_social = models.CharField(max_length=255, blank=False, null=False) The error: python manage.py test flux.tests.test_data_leak_main_db --keepdb Traceback (most recent call last): File "C:\Users\project\venv\lib\site-packages\django\db\utils.py", line 172, in ensure_defaults conn = self.databases[alias] KeyError: 'TEST_DB_NAME' During handling of … -
How to access and use Django's SchemaEditor?
The docs say Each database backend in Django supplies its own version of SchemaEditor, and it’s always accessible via the connection.schema_editor() context manager: with connection.schema_editor() as schema_editor: schema_editor.delete_model(MyModel) Note: In this question, they have the object and method reversed from the docs: schema_editor.connection! But how do you find it to use it? I tried this in the repl: with connection.schema_editor() as schema_editor: NameError: name 'connection' is not defined ModuleNotFoundError: No module named 'SchemaEditor' ModuleNotFoundError: No module named 'DatabaseSchemaEditor' NameError: name 'BaseDatabaseSchemaEditor' is not defined import BaseDatabaseSchemaEditor ModuleNotFoundError: No module named 'BaseDatabaseSchemaEditor' Then i dove into the source, after which I tried: from django.db.backends.base import base from django.db.backends.base.base import BaseDatabaseWrapper se = schema_editor() se = schema_editor() NameError: name 'schema_editor' is not defined se = BaseDatabaseWrapper.schema_editor() TypeError: schema_editor() missing 1 required positional argument: 'self' se = BaseDatabaseWrapper.schema_editor(self) NameError: name 'self' is not defined bdw = BaseDatabaseWrapper() TypeError: __init__() missing 1 required positional argument: 'settings_dict' from BaseDatabaseWrapper import schema_editor ModuleNotFoundError: No module named 'BaseDatabaseWrapper' ...even though it let me import it.... settings_dict = { ...: 'ENGINE': 'django.db.backends.sqlite3', ...: 'NAME': 'db.sqlite3', ...: } bdw = BaseDatabaseWrapper(settings_dict) TypeError: 'NoneType' object is not callable And after all that, I quit and came here. Help? Thanks. -
How do I post on a django model when it has another model (manytomany ) inside nested serializers, I want at the same time to create both
My models are: Period ClassStudentSubject Period has a manytomany relationship with ClassStudentSubject When I POST a period I don't want to choose which existing ClassStudentSubject object I use, I want to create a new one together with the period. ClassStudentSubject - I created this model for the sake of structuring some data of period into an object -
Get exact date format in excel from Python Datetime field
I have some question how can I get exact format date in excel.I need create excel cheat from some data(in my models.py "date_result_stamp" it's DateTime field) in Django project and I don't know how I can pass to excel exact date not str or another type of data result["date_result_stamp"] = datetime.strftime(result["date_result_stamp"], "%Y-%m-%d") but it's str format I need get in excel date format. Can you help me -
Save two instances on same model in django
In my case, it a treasury managing app, the task is i want to transfer an amount x from treasury A to treasury B, from bank to cashier or from paypal acc to my bank, i m adding two instances to same table (treasuryitem) but with different details (treasury). in the code bellow, i got two instances but the field treasury doesn t save as i choose, it save same, for ex treasury A in both instances. Also, i would like to fill only first form and treasury of second form, and the other fields of second form have to save automatically (name=name, date=date, debit=credit, credit=debit). Anyone can help pls. thanks in advance MODEL : class Treasury(models.Model): name = models.CharField(max_length=256) class TreasuryItem(models.Model): treasury = models.ForeignKey('Treasury', on_delete=models.CASCADE) date = models.DateField(default=timezone.now) name = models.CharField(max_length=256) debit = models.DecimalField(max_digits=20, decimal_places=2, null=True, blank=True) credit = models.DecimalField(max_digits=20, decimal_places=2, null=True, blank=True) FORM : class TreasuryItem1Form(ModelForm): class Meta: model = TreasuryItem fields = "__all__" class TreasuryItem2Form(ModelForm): class Meta: model = TreasuryItem fields = "__all__" VIEW: def TreasuryItem_Create(request, pk): treasurys = Treasury.objects.all() treasury = treasurys.get(id=pk) form1 = TreasuryItem1Form() form2 = TreasuryItem2Form() if request.method == 'POST': form1 = TreasuryItem1Form(request.POST) form2 = TreasuryItem2Form(request.POST) if form1.is_valid() and form2.is_valid(): form1.save() form2.save() return redirect('treasury_profile', … -
ReactJS Api Fetch Request to Django Backend returns "strict-origin-when-cross-origin" error
I tried to make a API call to Django Backend made with djangorestframework and simplejwt from ReactJS and it returns an error. error: "strict-origin-when-cross-origin" I set the cors-headers and It still doesen't working.But when I send the request from postman it works. Here's the fetch request code function handleSubmit(e) { e.preventDefault() const email = emailRef.current.value const password = emailRef.current.value if (!email || !password) return const res = fetch('http://localhost:8000/api/token', { method: "POST", headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json' }, body: JSON.stringify( { username: email, password } ) }) if (res.status !== 200) navigate('/login') } -
Problems with updating a Django form with information from another model
I'm basically building functionality to update a form with values from one table in my models.py, the form will populate the initial values with that table (leads) and upon submitting the information, the form will populate another model (leads) These is my models.py class Leads(models.Model): project_id = models.BigAutoField(primary_key=True, serialize=False) created_at = models.DateTimeField(auto_now_add=True) expected_revenue = MoneyField(decimal_places=2,max_digits=14, default_currency='USD') expected_licenses = models.IntegerField(blank=True) country = CountryField(blank_label='(select_country)') status = models.CharField(choices=[('Open', 'Open'), ('Closed', 'Closed'), ('Canceled', 'Canceled')], max_length=10) estimated_closing_date = models.DateField(blank=True) services = models.CharField(choices=[('Illumination Studies', 'Illumination Studies'), ('Training', 'Training'),('Survey Design Consultancy', 'Survey Design Consultancy'), ('Software License', 'Software License'), ('Software Development','Software Development')], max_length=40) agent = models.ForeignKey(Profile, default='agent',on_delete=models.CASCADE) company = models.ForeignKey(Company,on_delete=models.CASCADE) point_of_contact = models.ForeignKey(Client, default='agent',on_delete=models.CASCADE) updated_at = models.DateTimeField(auto_now=True) class Deal(models.Model): project_id = models.ForeignKey(Leads, on_delete=models.CASCADE, default='id') agent = models.ForeignKey(Profile, on_delete=models.CASCADE, default="agent") service = models.ForeignKey(Leads, on_delete=models.CASCADE, related_name='service') closing_date = models.DateField(auto_now_add=True) client = models.ForeignKey(Client, on_delete=models.CASCADE,default='client') licenses = models.ForeignKey(Leads,on_delete=models.CASCADE, related_name='license') revenue = MoneyField(max_digits=14, decimal_places=2, default_currency='USD') comments = models.TextField(blank=True,null=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) Forms.py class NewDealForm(forms.ModelForm): class Meta: model = Deal fields = ['project_id','agent','client','company','service', 'licenses','revenue','comments'] @login_required def close_lead(request): if request.method == 'POST': deal_form = NewDealForm(request.POST) print(deal_form) if deal_form.is_valid(): deal_form.save() messages.success(request, 'You have successfully updated the status from open to Close') id = request.GET.get('project_id', '') obj = Leads.objects.get(project_id=id) obj.status = "Closed" obj.save(update_fields=['status']) return HttpResponseRedirect(reverse('dashboard')) else: … -
Implementing OAUTH2 with custom user model
I am trying to use custom user model for implementing OAUTH2 and I am having an issue with convert token API. my custom model returns a JWT token and it is defined in settings.py as - AUTH_USER_MODEL = 'user.User' here is name of custom backend- DRFSO2_PROPRIETARY_BACKEND_NAME = "MyAPP" I am not sure if the above step is correct because I just gave it a random name. now I am confused what should I do in- AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) -
How to set variable in python django template from a function call?
I have the following library which returns a dict: {% load path_parts %} I can successfully call the method and print the value: {% path_parts request.get_full_path %} I would like to assign the dict to a variable, but I cannot: {% with paths=path_parts request.get_full_path %} How can I assign a result of a function call to a variable? -
'str' object has no attribute 'user' generated for unknown reason from Django View
I have a view built around the following code: views.py: def create_instance(request): form = InstanceMF() form2 = TextBox() if request.method == 'POST': form = InstanceMF(request.POST) form2 = TextBox(request.POST) if form.is_valid() and form2.is_valid(): content = form2.cleaned_data['content'] form = form.save(commit=False) form.author = request.user scores_dict = analyze(content) When I try to submit data in this view however, I get the error message from the title based on the last line where I attempt to call the analyze function, which is the following: def analyze(content): content = content.translate(remove_punctuation) word_list = content.lower().split() columns = Model1._meta.fields for word in word_list: model = Model1.objects.all() if word in model.filter(word__icontains=word): column = model for key, value in dictionary.items(): selected_columns = columns[value[0]:value[1]:2] if column in selected_columns: instance = dictionary2.get(key) if 'yes' in key: final_score[instance] += 1 elif 'no' in key: final_score[instance] -= 1 return final_score My guess here is that the database query somehow messes up the data structure needed to save InstanceMF in such a way that the current "user" is no longer accessible. How do I correct this? -
Is it possible to refresh an included Django template without refreshing the whole page?
I'm struggling with an issue similar to this one. I've got a Django template that includes a whole bunch of smaller templates with for-loops to render various aspects of my page. I'm wondering what the best way is to go about updating individual little templates to render them in the master template without having to do a whole page refresh. Does Django for example support some kind of React-like virtual dom to rerender only individual sub-templates? I understand that templates are being computed on the server and the generated HTML is then sent to the client for rendering so perhaps it's not possible to render templates in-place? The post above mentions passing data to the server with AJAX to refresh a particular template, but before I start revamping my page, I was wondering if that would work for rendering multiple templates at a time, and if so, if someone could point me to an example where this is explained in some detail; I've been looking, but couldn't find any. Thanks! -
Calling Python function from JS [duplicate]
I have a python django project. And I am trying to call a python function from JS. To start I’ve a html button that runs a JS function. It works fine: <input id="clickMe" type="button" value="clickme" onclick="show();" /> Currently I have this JS function just showing an alert. Like so. function show_eb_variable_table() { alert("Hello! I am an alert box!!"); } What I want to do is to instead of showing this alert I want to call and run a python function from my “plot.py” file in the project. The function I want to call is as so: def printing_something (request): print('hi') return render(request, 'index2.html', {}) Is there a way I can connect the JS to call the Python function? -
Django form validation only validating partially before submit/post
I have a customer registration form within a bootstrap modal, for this reason I would like to do some basic validation before posting. At the moment if you leave a field blank, if the string is too long or if there isn't a @ in the email then an alert appears, which is perfect. But, mismatching passwords, invalid email addresses like example@example submit. Surely that should fail the ValidateEmail regex? The validation failures are picked up fine in views after submission but getting back to the modal is the problem so I'd like them caught by the same pre-submission validation that picks up a blank fields. Or failing that, is it feasible to do an Ajax request on View and refresh the form asynchronously? Getting the form into json wouldn't be fun. Or should I just give up on django and use jquery validation? Forms: class CreateRegistrationForm(UserCreationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for f in self.fields: self.fields[f].widget.attrs['class'] = 'form-control' class Meta: model = User fields = ["email", "password1", "password2", "first_name", "last_name"] Models: class User(AbstractBaseUser, PermissionsMixin): class Types(models.TextChoices): CUSTOMER = "CUSTOMER", "Customer" STAFF = "STAFF", "Staff" base_type = Types.CUSTOMER type = models.CharField( _("Type"), max_length=50, choices=Types.choices, default=base_type ) user_name = models.CharField(max_length=150) … -
Add a template folder selection for a django package
I am relatively new to django and am looking for help on custom package templates management. At work, we are using a home-made custom django package that we add to installed apps in our main projects. This package has tools and utilities, as well as the base templates that we derive from in main projects. What's changing? We need to update our frontend and are changing libraries, which has an impact on the templates in this custom package. With a view to avoid multiplying the custom package branches and versions (we already have a couple for different versions of django), and given that the templates in our existing applications will not all be updated at once, we wish to make it so that the main project will use either the old templates or the new version of templates (variable selection or default). What I aim for (if possible): adding a folder level in the custom package templates folder that the project will look in adding a variable (in the project's settings.py file for example) to indicate which template folder the main project needs to look for in the package not having to modify the old templates folder in the package, … -
django documentation user permission ambiguity on object level permission
I am getting my feet wet with django user permission and I am trying to: Create specific permissions for different models I have. Assign to some permissions to some users for only some instances of a specific model. So basically, user_i might have permission_a and permission_b on project_one but only permission_a on project_two. Looking at the documentation, I got that I can define a custom permission on a model by adding the following Meta to the class: class JobProject(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) .... class Meta: permissions = [ ("permission_a", "This is perm a"), ("permission_b", "This is perm b"), ] However, now I am not sure I understand how can I add permission_a to user_a only for a specific instance project_a of the JobProject class. Django documentation is indeed ambiguous on the matter. On one hand it states that I can use the method has_perm(perm, obj=None) to check if a user has a specific perm on a specific obj. On the other hand, there is no hint on how I can specify which specific object I want to add a permission for when I run user_a.user_permissions.add(permission_a) Any idea? I saw that django-guardian could be a valuable alternative but I … -
How to make many to one field reference in Django 3.2?
I'm working on a simple project in Django which is a To Do applictaion. Lately I have add to this project a login/register form, but despite that every user has their own account with their own credentials they access to the same data. I tried to use the models.ForeignKey(User, on_delete=models.CASACADE) but it shows me this error: django.core.exceptions.FieldError: Unsupported lookup 'user' for CharField or join on the field not permitted. To understand it better will show the full code: models.py from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE # Create your models here. class todo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.content class User(models.Model): name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self): return self.name views.py from django.http.response import HttpResponse from django.shortcuts import render, redirect from django.utils import timezone from django.db.models import Count from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.contrib import messages from .models import * from .models import __str__ from .forms import CreateUserForm # Create your views here. @login_required(login_url='login/') def home(request): user = request.user count_item = todo.objects.count() all_items = todo.objects.filter(content__user=user).order_by("created") context = {'all_items': all_items, 'count_item':count_item} … -
sudo supervisorctl status: gumi gunicorn ERROR (spawn error)
$ sudo supervisorctl status guni:gunicorn FATAL Exited too quickly (process log may have details) Process log details in short: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: all the packages are installed with their latest versions bit still I am getting these above errors after running sudo supervisorctl status output gumi:gunicorn: ERROR (spawn error) Any idea what I am missing? -
An if-statement based on src HTML
I have big html document with various images with href and src. I want to make an if statement based on the output of the src. <img class="img-fluid d-block w-100" src="/static/assets/img/{{ LANGUAGE_CODE }}/actionFlow({% if form.status.value|slugify == '1'%}taak-toegewezen{% else %}{{form.status.value|slugify}}{%endif%}).png" id="workflowVisual"> Example outputs can be: "/static/assets/img/en/actionFlow(taak-toegewezen).png" "/static/assets/img/en/actionFlow(firststep).png" Now, I want to create an if statement like so: {% if src== "/static/assets/img/en/actionFlow(taak-toegewezen).png"}{{instance.reviewer2}} {% else src== "/static/assets/img/en/actionFlow(firststep).png"}{{instance.reviewer1}}{%endif%} How do I do this in HTML? Best, Rob -
Using a ListCharField as a filter field
I am trying to implement an API which you would filter objects using a ListCharField called categories. I want an object to be filtered if any of the values in its categories field matches with the category being searched. With my implementation, objects are being matched only if all the values in the categories match. Example: Consider an object A with categories='fun','party' and B with categories='fun' Then http://127.0.0.1:8000/theme/?categories=fun does not match with A but with B only. Model: class Themes(models.Model): id = models.CharField(max_length=64, unique=True, default=gen_uuid4_th name = models.CharField(max_length=128) description = models.CharField(max_length=512) categories = ListCharField(base_field=models.CharField(max_length=32), size=5, max_length=(6*33), null=True) View: class ThemesView(viewsets.ModelViewSet): serializer_class = AgendaTemplateSerializer permission_classes = (IsMemberUser,) filter_backends = (filters.DjangoFilterBackend,) filterset_fields = ('categories',) def get_permissions(self): ... def get_queryset(self): return Themes.objects.filter(Q(team__isnull=True) | Q(team=self.request.mp.team.teamid), is_archived=False) \ .order_by('-created_at')