Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django multiple databases django.db.utils.OperationalError: no such table: django_content_type
I'm trying to store my celery tasks tables in tasks database witch has nothing related with any other tables but i keep getting this error. sqlite3.OperationalError: no such table: django_content_type i'd rather to not having extra tables which i don't use in celery tasks like users or my other models so i made two abstract models for my databases: class TaskModel(models.Model): class Meta: abstract = True _db = 'tasks' class CeleryTasks(TaskModel): ... class DefaultModel(models.Model): class Meta: abstract = True _db = 'default' class MyDefaultDatabaseModel(DefaultModel): ... and my database router looks like : class DatabaseRouter: tasks_models = ['CeleryTasks'] def db_for_read(self, model, **hints): """ reading model based on params """ if not hasattr(model, 'Meta'): return None return getattr(model.Meta, '_db', None) def db_for_write(self, model, **hints): """ writing model based on params """ if not hasattr(model, 'Meta'): return None return getattr(model.Meta, '_db', None) def allow_relation(self, obj1, obj2, **hints): if hasattr(obj1._meta, '_db') and hasattr(obj2._meta, '_db'): return obj1._meta._db == obj2._meta._db return None def allow_migrate(self, db, app_label, model_name=None, **hints): print( f'allow migration database router invoked with args db={db},app_label={app_label},model_name={model_name},hints={hints}') if db == 'tasks': if model_name in self.tasks_models: print('returning True') return True print('returning False') return False print('returning None') return None and my full error logs may help: allow migration … -
Django is not styling the page although the static files are being fetched with 200 response code
Django is displaying a 200 response code for every static file that has been asked for yet the page isn't styled.Some of the static files requested and the response code Can anyone tell what the problem is here? The page isn't looking like it's supposed to be -
Django - how to force user to select a certain amount of options in a checbox modelform?
I'm making a simple survey built around a modelform: models.py class Fruits(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200, default='') text = models.TextField(default='') banana = models.BooleanField(default=False) grape = models.BooleanField(default=False) apple = models.BooleanField(default=False) mango = models.BooleanField(default=False) forms.py class FruitPicker(ModelForm): class Meta: model = Fruits fields = [ 'title', 'text', 'banana', 'grape', 'apple', 'mango' ] widgets = { 'text': forms.Textarea(attrs={"style": "height:10em;" "width:60em;"}), 'banana': forms.CheckboxInput(attrs={"style": "margin-left:350px;"}), 'grape': forms.CheckboxInput(attrs={"style": "margin-left:350px;"}), 'apple': forms.CheckboxInput(attrs={"style": "margin-left:350px;"}), 'mango': forms.CheckboxInput(attrs={"style": "margin-left:350px;"}) } Now let's say I want to make sure the user has to select a minimum amount of 2 fruits, but a maximum amount of 3. How would I go about doing this? -
Unable to fetch the matched data in the search filter in Django
I wanted to apply a search filter in the Django which will show the matched table row in the HTML. I have saved the data which comes from the API endpoint in the database and have created few fields based on which it will filter the API data in the table. It rather than searching the matched value but its adding another column with searched value. For instance: If I search "vendorname" as Pepsi it should reflect the table row which containing Pepsi rather than it creating another column with the value as Pepsi. I don't know where I'm going wrong. I have lot of columns from the API and 6filter just I have added few only here. Thanks in Advance I have created two database here one for filter another for API data: models.py: //filter class Userbase(models.Model): Vendor_Name = models.CharField(max_length=255, null=True) Region = MultiSelectField(choices=CHOICES) Area = MultiSelectField(choices=AREACHOICES) //api data class invoiceapi(models.Model): Vendor_Name = models.CharField(max_length=155, null=True) area = models.CharField(max_length=155, null=True) country = models.CharField(max_length=155, null=True) views.py: def homeview(request): userb = Userbase.objects.all() table_data= requests.get('http://127.0.0.1:1500/api/').json() if request.method == 'POST': userb = Userbase() userb.Area = request.POST.getlist('Area') userb.country = request.POST.getlist('country') userb.Vendor_Name = request.POST.get('Vendor_Name') userb.save() # api data saving in db for new_data in table_data: data … -
Django Rest Framework: using the create method of a ModelViewSet to create another model instance
I'm using Django Rest Framework and drf-nested-routers and I have three models: Projects, Users and Contributors. Contributor is a way to link Projects and Contributors and contains two fields, user_id and project_id. I have a nested User ModelViewSet that returns all the users in a given project. For my assignment, using the post method on projects//users/ must create a new Contributor (not User). My theory was that I want to get only the chosen User's id as a request, then post will fetch the relevant User and create the Contributor object. However, create() and perform_create() both immediately throw an error when I try to override them: create() crashes because it gets a project_pk argument I never added and perform_create() wants a complete User form to serialize (and try to create). I have tried to customize serializer so the 'post' request on my ModelViewSet would use a custom FetchUser serializer, but then I get a TypeError: 'NoneType' object is not callable. I've searched high and low, but I haven't found anyone with the same problem. Is it even feasible to override these methods in this way? -
How can I get list of rooms user joined via another model
I have 3 models: User, Room, Join. I'm trying to get a list of room user has joined but I don't know how. # models.py class User(models.Model): full_name = models.CharField(max_length=40) class Room(models.Model): room_name = models.CharField(max_length=40) create_by = models.ForeignKey(User, on_delete=models.CASCADE) class Join(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) I tried using related_name and related_query_name but unfortunately I don't know how these things work. If my question is duplicated, please provide me some keywords, thank you in advance. -
How to get nested json export using django-import-export?
I'm using django-import-export and I want to do exports to json in which relations are nested. So let's say I use the example from the docs (Book/Author/Category) and I want to do an export of all books, including it's authors and categories. I would expect the export to include the authors and categories as objects so that it looks something like this: [ { "name": "Hitchhikers guide to the galaxy", "Author": {"name": "Douglas Adams"} "categories": [{"name": "Science fiction"}, {"name": "classics"}] "imported": true }, { "name": "Don Quixote", "Author": {"name": "Miguel de Cervantes"}, "categories": [{"name": "Idiots"}] "imported": true } ] I'm looking through the documentation but I can't find how I could achieve that. Could anybody give me a tip on how to achieve that? -
How to get distinct record from database querey in django?
I have following record in messages table and I want to get all the receiver where the sender is 15 and all the sender where the reciever is 15. so I used the querey return Messages.objects.filter(Q(sender=15) | Q(receiver=15)).distinct() but it returns duplicates results also as following. How can I get only the distinct/unique records.for example {sender: 15, receiver: 11} should never repeats -
Dependent/Chained Dropdown List with Django not see the 'gruppo_single' in self.data
I have a problem with a select that filters the other. I did all the filtering correctly from the frontend point of view but in the backend I can not save the data. This is the error: select a valid choise. That choice is not one of the available choices. I think the problem is in the fact of the form as it does not find 'group_single' that I pass through post in my views. view esercizi_instance.gruppo_single = get_object_or_404(DatiGruppi, gruppi_scheda = scheda.id, dati_gruppo = gruppoName) form if 'gruppo_single' in self.data: models.py class Gruppi(models.Model): nome_gruppo = models.CharField(max_length=100) class Esercizi(models.Model): nome_esercizio = models.CharField(max_length=100) gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'gruppo' ) class Schede(models.Model): nome_scheda = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente = models.ForeignKey( User, on_delete = models.CASCADE, related_name = 'utente' ) class DatiGruppi(models.Model): giorni_settimana_scelta = [ ("LUNEDI","Lunedì"), ("MARTEDI","Martedì"), ("MERCOLEDI","Mercoledì"), ("GIOVEDI","Giovedì"), ("VENERDI","Venerdì"), ("SABATO","Sabato"), ("DOMENICA","Domenica") ] giorni_settimana = MultiSelectField( choices = giorni_settimana_scelta, default = '-' ) dati_gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'dati_gruppo' ) gruppi_scheda = models.ForeignKey( Schede, on_delete = models.CASCADE, related_name = 'gruppi_scheda' ) class DatiEsercizi(models.Model): serie = models.IntegerField() ripetizione = models.IntegerField() peso = models.DecimalField( max_digits = 4, decimal_places = 1, blank = True, null … -
What is "Type Error: can't pickle weakref objects"
I am trying to pickle.dump() an object with a model property that stores a Keras and TensorFlow model. admin.py def build(self, request, queryset): count = 0 for p in queryset: if build_id(p.project_management.id): count += 1 else: messages.warning(request, f"Could not build model for {p}") messages.success( request, f"Successfully built models for {count} projects") build.short_description = "Build models for selected Projects" build.py def build_id(project_id): # get directory path to store models in path = fetch_model_path(project_id, True) # train model model, scaler_in, scaler_out = train_project_models(project_id) # ensure model was trained if model is None: return False # store models store_model(f'{path}/model.pkl', model) store_model(f'{path}/scaler_in.pkl', scaler_in) store_model(f'{path}/scaler_out.pkl', scaler_out) # clear current loaded model from memory keras_clear() return True utils.py # dump model to path def store_model(path, model): with open(path, 'wb') as f: model_file = File(f) pickle.dump(model, model_file) when I Build my model then I found this error. I am using the python Django project. When I Build model this show an internal server error too as shown in picture -
ModelForm fills foreign key field as a number
I have model from which I created a ModelForm: models.py: class City(models.Model): name = models.CharField(max_length=50) def __str__(self): return f'{self.name}' class Profile(models.Profile): name = models.CharField(max_length=50) user = models.OneToOneField(User, on_delete=models.CASCADE, unique=False) location = models.ForeignKey('City', on_delete=models.SET_NULL, blank=True, null=True) forms.py from django import forms from .models import Profile, City class LocationField(forms.CharField): def clean(self, value): try: city = City.objects.get(name=value) except ObjectDoesNotExist: city = City.objects.create(name=value) return city class ProfileForm(forms.ModelForm): location = LocationField() class Meta: model = Profile exclude = ['user'] views.py def profile_update_view(request): template_name = 'profiles/update.html' user = request.user profile = Profile.objects.get(user__id=user.id) if request.method == 'GET': form = ProfileForm(instance=profile) else: form = ProfileForm(request.POST, instance=profile) if form.is_valid(): obj = form.save(commit=False) obj.user = user obj.save() return redirect('profile_view') context = {'form': form} return render(request, template_name, context=context) When I'm saving form, I'm satisfied how it's working, but when I load form again to update in, it fills LocationField() as an City pk integer, but I want it to load name instead. Is there a way to do this? -
Fill forms.MultipleChoiceField with list instead model
Well, I've started with django and I want to extract the categories of a wordpress blog and expose them in a multiple selector. Here is what i do: Forms.py from django import forms from django.conf import settings from wordpress_xmlrpc import Client from wordpress_xmlrpc.methods import taxonomies def categoryList(): wp = Client(settings.WP_URL, settings.WP_USER, settings.WP_PASSWORD) categories = wp.call(taxonomies.GetTerms('category')) return categories class WPCategoriesForm(forms.Form): wpCategories = forms.MultipleChoiceField(label="Select your category",choices=categoryList(), widget=forms.Select(attrs={'class':'form-control selectpicker show-tick'})) views.py def get_categories(request): ''' Bring categories from wordpress ''' context ={} context['WPform']= WPCategoriesForm() return render(request, 'page_1.html', context) But i'm a little lost with templates, Here is what i coded: Page_1.html <div class="col-md-6"> <form class="form-inline" method="POST"> <select name="wpCategories" class="form-control page-section selectpicker show-tick" id="WpCategories"> <option value="" selected>Select Wordpress category</option> {{ form.wpCategories }} </select> </form> </div> Sorry but i'm pretty new with django and i don't know why de multiple choice is not filled, can you help me? -
I get this Error AttributeError at /listings/5689-resot-relly-market, 'Profile' object has no attribute 'favourite' please any help would be apprciate
I'm working a add to favourite function in django and i keep getting this error when i hit the save button, everything looks fine from here that why i can't really tell where the error is coming from and i'm stuck with this project now. It kinda urgent please any help would be really appreciated and honoured. Models.py from basefunc.models import Accomodation class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) usertitle = models.CharField(max_length=1000, null=True, blank=True) city = models.CharField(max_length=1000, null=True, blank=True) state = models.CharField(max_length=1000, null=True, blank=True) address = models.CharField(max_length=10000, null=True, blank=True) about = models.TextField(max_length=10000, null=True, blank=True) about = models.TextField(max_length=10000, null=True, blank=True) facebook = models.URLField(max_length=10000, null=True, blank=True) twitter = models.URLField(max_length=10000, null=True, blank=True) instagram = models.URLField(max_length=10000, null=True, blank=True) other = models.URLField(max_length=10000, null=True, blank=True) phone = models.IntegerField(null=True, blank=True) zipcode = models.IntegerField(null=True, blank=True) image = models.ImageField(default='default.jpg', upload_to="profile_pic") favorite = models.ManyToManyField(Accomodation, related_name='profile') views.py from userauth.models import Profile def AccomodationDetails(request, accomodation_slug): accomodations = get_object_or_404(Accomodation, slug=accomodation_slug) accomodations_list = Accomodation.objects.filter(status="publish").order_by("-publication_date") images = Images.objects.all() categories = Category.objects.all() features = Features.objects.all() amenities = Amenities.objects.all() advanced_features = Advanced_Features.objects.all() user = request.user.id profile = Profile.objects.get(user__id=user) if request.method == "POST": if profile.favourite.filter(slug=accomodation_slug).exists(): profile.favorite.remove(accomodations) else: profile.favorite.add(accomodations) context = { 'accomodations': accomodations, 'accomodations_list': accomodations_list, 'categories': categories, 'features': features, 'advanced_features': advanced_features, 'amenities': amenities, 'images': images, } return render(request, … -
how to query from multiple models in django
I am trying to understand the most efficient way to query the data needed from multiple tables in Django. class City(): name = models.CharlField() class Address(): line1 = models.CharlField() ... city_id = models.ForeignKey(City ... related_name="city_address") class Student() name = models.CharlField() gender = models.CharlField() # a student can only have one address address_id = models.OneToOneField(Address ... related_name="address_student") How can I optimize the query below to get the city this student belongs to? student = User.objects.filter(name="John").first() # assuming its a unique name address_id = student.address_id address = Address.objects.filter(id=address).first() city_id = address.city_id City.objects.get(id=city_id) Thank you in advance. -
Server Error 500 when Debug = False in django
I've keep getting Server Error (500) when I let the DEBUG = False I cant find the solution -
How to validate a field with uppercase with django serializers
I am programming an API and I have noticed the following error when debugging. The following code does not validate the Status field class DocumentSalesforceSerializer(serializers.Serializer): AccountId = serializers.CharField(required=True) ContactId = serializers.CharField(required=True) Status = serializers.CharField(required=True) StartDate = serializers.CharField(required=True) EndDate = serializers.CharField(required=True, allow_blank=True) Subject = serializers.CharField(required=True) def validate_status(self, Status): if Status not in ("New", "In Progress", "On Hold", "Completed", "Closed", "Cannot Complete", "Canceled"): raise serializers.ValidationError("Invalid Status") return Status But, when I change the word "Status" to "status" like this: class DocumentSalesforceSerializer(serializers.Serializer): AccountId = serializers.CharField(required=True) ContactId = serializers.CharField(required=True) status = serializers.CharField(required=True) StartDate = serializers.CharField(required=True) EndDate = serializers.CharField(required=True, allow_blank=True) Subject = serializers.CharField(required=True) def validate_status(self, status): if status not in ("New", "In Progress", "On Hold", "Completed", "Closed", "Cannot Complete", "Canceled"): raise serializers.ValidationError("Invalid Status") return status Everything is working perfectly fine. Can anyone tell me why is it working like that and how can I do to validate the "Status" uppercase field? Thanks -
Django charts.js of database column?
I have a model database in this format sno Date Premium Count Time Date_time Close None Oct. 13, 2021 None 2 2:22 p.m. 38735 None Oct. 13, 2021 None 2 2:23 p.m. 38727 None Oct. 13, 2021 None 2 2:24 p.m. 38739 None Oct. 13, 2021 None 2 2:25 p.m. 38750 None Oct. 13, 2021 None 2 2:26 p.m. 38730 None Oct. 13, 2021 None 2 2:27 p.m. 38723 I want to make a simple bar chart of 'Close' column in the database. I have tried using some manual random values in chart.js code which I have done successfully, but how do I take the database field 'Close' , converting it into a list and plot a chart from it? -
Assign user to a single group LDAP Django Netbox
I have a single group in Netbox admin page. I am trying to assign users to that specific group when the user logs in for the first time. I managed to assign the user to the group I wanted by using: AUTH_LDAP_MIRROR_GROUPS = "true" This also created all other groups which user belongs to and I want to avoid that. Is there a way to mirror only a single group, or should I approach this without mirroring? My current idea is to use: AUTH_LDAP_MIRROR_GROUPS_EXCEPT = [listOfAllOtherUsersGroupsExceptTheSpecificOne] I was not able to find how to get the list of users groups and then return list without a specific group. -
Custom button classes in django crispy forms
The technical issue of styling buttons in django crispy forms. I would like to apply my own class, without using the primary button class. class MyForm(Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fields("field_1"), Fields("field_2"), Submit('submit', u'On', css_class='own-css-class'), ) Basically, I solved this by adding self.helper.form_tag = False and inserting the button code directly into the html template. In addition, I deleted the submit button from the layout. class MyForm(Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fields("field_1"), Fields("field_2"), ) self.helper.form_tag = False Is this solution correct and will it be compatible in the long term? -
How to read an dictionary object from Django form?
I have 2 models in Django, one is the Todo model, another is the Team model, the Todo model has a foreign key from Team, but the team is return its value as a dictionary, so my question is how can I get value from the dictionary in Todo.form. The dictionary is a must-have for another app, so I wonder is it possible to return a dictionary and a self.name together? Now I can only see text like 'team object(1)' on the list, it would be great if anyone happen to know what can I do about this, cheers. models.py ''' class Team(models.Model): name = models.CharField(max_length=20) employeeID = models.CharField(max_length=20) email = models.CharField(max_length=50) position = models.CharField(max_length=50) password = models.CharField(max_length=20) projects = models.ForeignKey(Project, on_delete=models.CASCADE) def toDict(self): return{'id':self.id, 'employeeID':self.employeeID, 'name':self.name, 'email':self.email, 'position':self.position, 'password':self.password} class Todo(models.Model): status_option = ( ('to_do', 'to_do'), ('in_progress', 'in_progress'), ('done', 'done'), ) status = models.CharField(max_length=20, choices=status_option, default='to_do') # todo_list's content team = models.ForeignKey('Team', on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=20) create_date = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField(default=datetime.datetime.now) due_date = models.DateTimeField(default=datetime.datetime.now) priority_level = models.IntegerField(default=1) project_code = models.CharField(max_length=20) details = models.TextField() def __str__(self): return self.details[:20]+"..." # return self.team['team'].queryset def update_status(self): if self.status == 'to_do': self.status = 'in_progress' elif self.status == 'in_progress': self.status … -
How to show the user the posts (or movies) in this case they have liked?
I have a user profile page where I want to show the user the movies they have liked. Here is the part of model which contains the like field as an ManyToManyField. class moviefiles(models.Model): name = models.CharField(max_length=50) duration = models.CharField(max_length=20) . . . liked = models.ManyToManyField(User, related_name='movie_like') rt = models.IntegerField(default=1) Here is the def in view for liking or unliking: def movieLike(request, slug): user = request.user if user.is_authenticated: post = get_object_or_404(moviefiles, slug=request.POST.get('post_id')) liked = False if post.liked.filter(id=request.user.id).exists(): post.liked.remove(request.user) liked = False return HttpResponseRedirect(reverse('movie-about', args=[str(slug)])) else: post.liked.add(request.user) liked = True return HttpResponseRedirect(reverse('movie-about', args=[str(slug)])) else: return redirect('/user/signup') I am using MongoDB as the database and django made two tables in it on running makemigrations, one is the home_moviefiles and another is home_moviefiles_liked which is storing the liked data and the data of liking or unliking is getting saved correctly. I'm trying to retrieve the the movies which a user has liked but I am unable to proceed from here. -
Display information about linked models fields in the django admin
These are my models: class Partner(models.Model): name = models.CharField(max_length=200, verbose_name="Organisation name") class ResearchActivity(models.Model): title = models.CharField(max_length=200) partner = models.ManyToManyField(ActivityPartner, blank=True) I'd like, in the Django administration forms, to have a field in my Partner edit form representing the ResearchActivity linked to that Partner. Can this be achieved by adding a field to my Partner model (say, naming it linked_partner) and then edit my admin.py like so: @admin.register(ActivityPartner) class ActivityPartnerAdmin(admin.ModelAdmin): search_fields = ['academic',] autocomplete_fields = ['partnership_type', 'relationship_type', 'academic_links'] def get_changeform_initial_data(self, request): return {'live_contract': ResearchActivity.objects.all().filter(linked_partner__id=request.ResearchActivity.partner.id)} ? -
Django: How can I change the design of a foreign key when using forms.py?
This is my patient model and forms: class Patient(models.Model): def __str__(self): return f"{self.first_name} {self.last_name}" doctor = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) sex = models.CharField(max_length=20) phone = models.IntegerField() birth_date = models.DateField() class PatientForm(forms.ModelForm): BIRTH_YEAR_CHOICES = [] for years in range(1900,2021): BIRTH_YEAR_CHOICES.append(str(years)) sex_choice = [('1', 'Homme'), ('2', 'Femme')] sex = forms.ChoiceField(widget=forms.Select(attrs={'class':'form-control'}), choices=sex_choice) doctor = forms.ModelChoiceField(widget=forms.Select(attrs={'class': 'form-control'}),queryset=Patient.objects.all()) first_name = forms.CharField(widget= forms.TextInput(attrs={'class':'form-control'})) last_name = forms.CharField(widget= forms.TextInput(attrs={'class':'form-control'})) phone = forms.CharField(widget= forms.TextInput(attrs={'class':'form-control'})) birth_date = forms.DateField(widget=forms.SelectDateWidget(years=BIRTH_YEAR_CHOICES,attrs={'class': 'form-control'})) class Meta: model = Patient fields = '__all__' def __init__(self, *args, **kwargs): super(PatientForm, self).__init__(*args, **kwargs) self.fields['birth_date'].input_formats = ('%Y-%m-%d') And this register.html: <form method="POST">{% csrf_token %} <div class="input-group"> <span class="input-group-text">Prénom:</span> {{form.first_name}} </div> <div class="input-group"> <span class="input-group-text">Nom:</span> {{form.last_name}} </div> <div class="input-group"> <span class="input-group-text">Sex</span> {{form.sex}} </div> <div class="input-group"> <span class="input-group-text">Telephone</span> {{form.phone}} </div> <div class="input-group"> <span class="input-group-text">Date de naissance</span> {{form.birth_date}} </div> <div class="input-group"> <span class="input-group-text">Docteur</span> <select name="doctor_choice"> {% for doctor in doctors %} <option value="{{doctor.pk}}">{{doctor.first_name}} {{doctor.last_name}}</option> {% endfor %} </select> </div> The attrs={'class':'form-control'} is working at all the fields except the doctor field which is a ForeignKey in Patient model. So when I search about it I found that they use doctor = forms.ModelChoiceField but still dosen't work and 'class':'form-control' isn't working yet -
How can I test a function that takes record as a parameter?
I need to write a test for a function post_log_filter(record) in the file my_logging.py #my_logging.py import os import sys import traceback log_format = '[%(levelname)s] %(asctime)s %(context)s %(pathname)s:%(lineno)d: %(message)s' log_time_format = '%Y-%m-%dT%H:%M:%S%z' def post_log_filter(record): # filter out undesirable logs logs_to_omit = [ {'filename': 'basehttp.py', 'funcName': 'log_message'}, # annoying logging any response to sys.stderr (even if status is 200) {'filename': 'options.py', 'funcName': 'construct_change_message'}, # logging `Key not found` if a checkbox was unchecked and isn't present in POST data ] if any([bool(record.__dict__.viewitems() >= r.viewitems()) for r in logs_to_omit]): return False return True The test that I have written is: test_my_logging.py from my_logging import * import collections import mock from mock import patch import logging LOGGER = logging.getLogger(__name__) log_format = '[%(levelname)s] %(asctime)s %(context)s %(pathname)s:%(lineno)d: %(message)s' log_time_format = '%Y-%m-%dT%H:%M:%S%z' class TestMyLogging(TestCase): def test_post_log_filter(self): self.assertEqual(True, post_log_filter(logging.LogRecord(None, None, None, None, msg=None, args=None, exc_info=None, func=None))) def test_post_log_filter_false(self): record = logging.Formatter([ {'filename': 'basehttp.py', 'funcName': 'log_message'}, # annoying logging any response to sys.stderr (even if status is 200) {'filename': 'options.py', 'funcName': 'construct_change_message'}, # logging `Key not found` if a checkbox was unchecked and isn't present in POST data ]) self.assertEqual(False, post_log_filter(record)) I am testing it for two cases. For True: No matter what I pass for post_log_filter(), I get … -
Which field is this Django field and how to use it?
This can be found in Django Admin, under Groups table. Picture: https://imgur.com/a/Of9ZASM As I see, it is a <select> html tag with the multiple option (<select multiple>). How can we achieve it in custom tables, and how can we handle them? I looked up the django documentation, but it's not that documented (if I found the right one).