Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
*** TypeError: get_value_by_attribute() missing 1 required positional argument: 'attribute'
I am using Django oscar and trying to get product attributes key and values using product.attr.get_value_by_attribute(). And I am getting above errors and I have tried to pass attribute and it still giving me an error. My testing debugger code is as follows: (Pdb) child_product <Product: Good Day 100 gm> (Pdb) child_product.__dict__ {'_state': <django.db.models.base.ModelState object at 0x7fa088e1c438>, 'id': 13, 'structure': 'child', 'upc': '', 'parent_id': 12, 'title': 'Good Day 100 gm', 'slug': 'good-day-100-gm', 'description': '', 'product_class_id': None, 'rating': None, 'date_created': datetime.datetime(2019, 6, 22, 15, 30, 24, 273252, tzinfo=<UTC>), 'date_updated': datetime.datetime(2019, 6, 22, 15, 30, 24, 273270, tzinfo=<UTC>), 'is_discountable': True, 'attr': <oscar.apps.catalogue.product_attributes.ProductAttributesContainer object at 0x7fa088e1c470>} (Pdb) child_product.attr <oscar.apps.catalogue.product_attributes.ProductAttributesContainer object at 0x7fa088e1c470> (Pdb) child_product.attr.__dict__ {'product': <Product: Good Day 100 gm>, 'initialised': False} (Pdb) child_product.attr.__dict__ {'product': <Product: Good Day 100 gm>, 'initialised': False} (Pdb) child_product.attr.get_values() <QuerySet [<ProductAttributeValue: Brand: Britania>, <ProductAttributeValue: Variant Name: 100 gm x 12>]> (Pdb) child_product.attr.get_all_attributes() <QuerySet [<ProductAttribute: Brand>, <ProductAttribute: GST Rate>, <ProductAttribute: HSN Code>, <ProductAttribute: Liquid Content>, <ProductAttribute: Parent Company>, <ProductAttribute: Promo SKU>, <ProductAttribute: Selling Lot Size>, <ProductAttribute: Sub Brand>, <ProductAttribute: Tags>, <ProductAttribute: Variant Name>, <ProductAttribute: Weight>, <ProductAttribute: Weight Unit>]> (Pdb) child_product.attr.get_value_by_attribute() *** TypeError: get_value_by_attribute() missing 1 required positional argument: 'attribute' (Pdb) child_product.attr.get_value_by_attribute(attribute="Brand") *** ValueError: invalid literal for int() with base … -
When and how does DRF calculate the queryset?
I have a ModelViewSet that looks like: class UserRegistrationView(viewsets.ModelViewSet): """ UserRegistrationView A view to handle the User registration process """ permission_classes = ( permissions.AllowAny, ) serializer_class = accounts_serializers.UserRegistrationSerializer And, I have a serializer that looks like: class UserRegistrationSerializer(core_serializers.BaseModelSerializer): mobile_number = serializers.CharField(required=True, min_length=10, max_length=10) password = serializers.CharField(required=True, min_length=6, max_length=20) class Meta: model = accounts_models.User fields = ( 'mobile_number', 'password', ) I was studying the Django REST Framework code base to ascertain how the queryset used by the serializer is calculated by the view. I realized that happens within the get_queryset method within the view. But, I'm unable to understand how that happens. Basically, get_queryset looks like: queryset = self.queryset if isinstance(queryset, QuerySet): # Ensure queryset is re-evaluated on each request. queryset = queryset.all() return queryset Now, what I find difficult to understand is that when is self.queryset set and where in the drf code base does that happen? Also, how does the view come to know of the model I'm trying to use before calculating the queryset? Am I missing something here? Thanks for the help in advance! -
How to automatically use my custom PasswordResetSerializer? (Django - DRF)
I want to use my custom PasswordResetSerializer to send the email automatically after the user reaches the limits of login attempts This serializer works fine in my frontend via API call Here is my code: authentication.py class ExampleAuthentication(authentication.BaseAuthentication): def authenticate(self, request): username = request.data.get('email', None) # get the username request header password = request.data.get('password', None) """ After all validations and login attempts """ if user.fails_authentication(): #Use here my custom PasswordResetSerializer serializers.py class PasswordResetSerializer(serializers.Serializer): email = serializers.EmailField() password_reset_form_class = PasswordResetForm def validate_email(self, value): self.reset_form = self.password_reset_form_class(data=self.initial_data) if not self.reset_form.is_valid(): raise serializers.ValidationError(_('Error')) ###### FILTER YOUR USER MODEL ###### if not User.objects.filter(email=value).exists(): raise serializers.ValidationError(_('Invalid e-mail address')) return value def save(self): request = self.context.get('request') user = User.objects.get(email=request.data.get('email')) token = Token.objects.get(user=user.id) uid = urlsafe_base64_encode(force_bytes(user.id)).decode() template = 'example_message.html' context = {'usertoken': token, 'reactdomain': 'localhost:3000', 'userid': uid} opts = { 'use_https': request.is_secure(), 'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'), ###### USE YOUR TEXT FILE ###### 'email_template_name': template, 'extra_email_context': context, 'html_email_template_name': template, 'request': request, } self.reset_form.save(**opts) -
Inlineformset Factory to pass the foreign Key and set it automatically from another model
i am trying to link the Team with the startup name as my model below using inlineformse factory: i want the assigning of foreign key to be autoset to startup name each time a new application is initiated. my codes are below for both models.py and views.py appreciate help. '''''' Models.py: from django.db import models class Startup (models.Model): startup_name=models.CharField('Startup Name', max_length = 100) def __str__(self): return self.startup_name class Team (models.Model): startup=models.ForeignKey(Startup, on_delete = models.CASCADE ) name=models.CharField('Name', max_length = 100) position=models.CharField('Position', max_length = 100) def __str__(self): return self.startup Views.py: def StartupName (request): form = modelform_factory ( Startup , fields = ('startup_name',) ) if request.method == 'POST': formset = form (request.POST) if formset.is_valid ( ) : formset.save ( ) return redirect ( 'str_team' ) else : formset = form() return render ( request , 'application/str_name.html' , { 'formset' : formset } ) def Teams (request, startup_id) : startup = Startup.objects.get(pk=startup_id) team = inlineformset_factory(Startup, Team , fields = ('name' , 'position') ) if request.method == "POST" : formset = team (request.POST, instance = startup ) if formset.is_valid ( ) : formset.save () return redirect ( 'str_dashboard' ) else : formset = team (instance = startup) return render ( request , 'application/str_team.html' , { … -
how to define a pk for models in django-tables 2 ? isn't it an automated?
I've used django-table2 to render a patients list entered by users however I'm getting a value error for unknown reason to me: Failed lookup for key [Patient] in , when resolving the accessor Patient.pk here's my tables.py class PatientTable(tables.Table): FirstName = tables.Column(linkify=("PatientDetailView", {"pk": tables.A("Patient.pk")})) LastName = tables.Column(linkify=("PatientDetailView", {"pk": tables.A("Patient.pk")})) Telephone_no = tables.Column(linkify=("PatientDetailView", {"pk": tables.A("Patient.pk")})) class Meta: model = Patient # attrs = {'class': 'table table-striped table-hover'} exclude = ("user", "Notes", "Address") template_name = 'django_tables2/bootstrap4.html' and here's my view function in the views.py def Patients_list(request): table = PatientTable(Patient.objects.filter(user=request.user)) return render(request, 'accounts/patients_list.html',{ 'table' : table }) -
How i can serealized data to json with drf serealizer
I have data model like: from django.db import models class Student(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() def __str__(self): return self.first_name + ' ' + self.last_name class Course(models.Model): name = models.CharField(max_length=255) description = models.TextField() start_date = models.DateField(null=True) end_date = models.DateField(null=True) def __str__(self): return self.name class CourseParticipant(models.Model): course = models.ForeignKey(Course, related_name='courses', on_delete=None) student = models.ForeignKey(Student, related_name='students', on_delete=None) completed = models.BooleanField(null=True, default=False) def __str__(self): return self.course I have some serealizer: class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ('name', 'end_date', 'start_date') I need make some method which will be return date in json like: { "courses": [ { "name": "Math", "end_date": "2019-06-26", "start_date": "2019-06-26", "participant_students_count: 10 } ] } How I can get "participant_students_count" and return it data in json with other fields. Thanks for help! -
Make JWT (Jason Web Token) Last Longer or Other Alternatives For Flutter App
I have a django backend that user the Django Rest Framework. I have Django Rest APIs set up, that are specific for every user. I then also use Jason Web Tokens to be able to authenticate Users via my mobile Flutter Frontend. I then use the token I get on login in every request which works great! My problem is when the token runs out the user has to login again for this all to work. Is there any way I could make the Jason Web Tokens to last longer then the standard time of like 5 minutes??? Token Code in Django: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES' : ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_AUTHENTICATION_CLASSES' : ('rest_framework_simplejwt.authentication.JWTAuthentication',), } Different URLS (also the get-token url): urlpatterns = [ path('admin/', admin.site.urls), path('project/', include('project.urls')), path('studyplan/', include('studyplan.urls')), path('get-token/', TokenObtainPairView.as_view()), path('refresh-token/', TokenRefreshView.as_view()) ] -
I don't work comments and forms are not displayed
I'm trying to make comments on the site, but when I start the server, I do not see the forms. I create a simple blog in which a person can post likes and comment, but the problem is that when i add a comment form, they simply do not appear. P.S And excuse me for my English I am from another country and I don’t know English very well post.html main template {% extends "ShapeHtml/wrapper.html" %} {% block content %} <div class="panel panel-default"> <div class="panel-heading"> <h1 class=" text-info">{{object.title}}</h1> </div> <div class="panel-body"> <p> {{object.post|safe|linebreaks}} </p> <h3 align="right" class=" text-info"> Опубликованно: {{articles.date|date:"d-m-Y в H:i"}}</h3> </div> <h4>Comments</h4> <form action="{% url '' %}" method="post"> {% csrf_token %} {% if CommentModel %} {% for CommentModel in comments %} {{ CommentModel.WhoAreYou }} <br> {% endfor %} {% endif %} {{ form }} <input type="submit" value="Submit"> </form> {% endblock %} views.py from .forms import CommentForm class ArticlesList(ListView): model = Articles template_name = 'news/posts.html' class ArticleDetail(DetailView): model = Articles template_name = 'news/post.html' def GetComments(request): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(request.path_info) else: form = CommentForm() comments = CommentModel.objects.all() return render(request, 'news/post.html', {'form': form, 'comments': comments}) urls.py urlpatterns=[ path('', ArticlesList.as_view(), name='articles_list'), path('<int:pk>/', ArticleDetail.as_view(), name='article_detail'), … -
how to set/get language for 2 different templates ( if lang a > templ2te1 elif lang b > template2
in my views i have the following, i have 2 different templates for each lang maybe i just have some kind of thinking problem when hiting site with lang en in browser i get de not defined since it is an if statement i seem not to be able where the problem is and the other way around with browser lang de LANGUAGES = translation.get_language() . . . if LANGUAGES == de: return render(....) elif LANGUAGES == en: return render(....) else: return HttpResponseNotFound NameError: name 'de' is not defined -
Django Template - Foreign Key Order by
In a Django template, how can I specify the order when I loop over all the objects founds in a reverse lookup such as in: {% for item in object.other_set.all %} <p>item.text</p> {% endfor %} Let's say I'd like this to be ordered by item.creation_date then by item.text? -
problems with Python Django NSException
I am working on a project using Django and Python and I am trying to plot a simple graph using matplotlib and I keep getting the error "uncaught exception of type NSException", python also crashed after that. I am using mac if that helps. I have already tried using the most simple graphs but still the problem persists. This is my code in the views.py file def get_svg(request): t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2 * np.pi * t) fig, ax = plt.subplots() ax.plot(t, s) ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='Sample') ax.grid() response = HttpResponse(content_type = 'image/png') canvas = FigureCanvasAgg(fig) canvas.print_png(response) return response print("hello") This is the error message I get: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'NSWindow drag regions should only be invalidated on the Main Thread!' terminating with uncaught exception of type NSException -
When using my Custom Filter in Django Filters I do not have a 'Submit' button
As the title says I made my own custom filter class, and when I clock on 'Filters' on Django-Rest page I get the search bars, but not 'Submit' button: Example of what I mean Here's my views.py def get_views(): ret_views = {} # loops through all the models in the program and sets up the view for it for model in apps.get_models(): if model._meta.app_label in settings.API_BLACKLIST: continue # creates the view for the api for the specific model class GenericView(viewsets.ModelViewSet): # permission_classes = (permissions.IsAuthenticatedOrReadOnly,) # if you're not logged in you can only read parser_classes = (MultiPartParser, JSONParser, FormParser) serializer_class = create_serializer(model) queryset = model.objects.all() # IMPORTANT: ONLY WORKS WHEN MODELS ARE PROPERLY ROUTED filter_backends = (DjangoFilterBackend,) filter_class = create_filter(model) # changes the name of the class so it will be displayed in the api properly GenericView.__name__ = model.__name__ + "View" ret_views[model.__name__] = GenericView return ret_view Here's my filters.py # edit the standard filter so it does a more general search instead of an exact search class CustomFilterSet(FilterSet): @classmethod def get_fields(cls): fields = super().get_fields() for name, lookups in fields.items(): lookups[:] = ['icontains'] return fields # creates a custom filter with which ever model is passed into it def create_filter(desired_model): class … -
How to edit django-allauth templates?
I have already tried to move files to PROJECT_ROOT/TEMPLATES/ a project and write to apps.py template dirs -
How to format html content before save in Django/Wagtail?
I'm using Wagtail as a headless CMS, and I created a block to insert code, but by saving it it saved exactly the html tags I typed, and rendering this on the front end is rendered as html content. For example, if I enter: <h1>Hello<h1/> he'll save just that way. I need a representation of this, but without actually being a valid html, since this will be rendered as html on the front end, inside pre and code tags. I know there are some htmls that represent things like "<" and ">". But I do not know how to solve this. There are also things I need to convert when saving, such as a new line inserted in the code, it should be saved as "" And the spaces are also being saved as white space, and when rendering html, all spaces are "converted" to one, so I also need a representation for those spaces. -
Django M2M filed validation for defined types
I have got a situation where i have couple of type choices for model in Django. i am willing to validate while making curd operations on M2M field? here is an example of Django model: class Employee(models.Model): TYPE_CHOICES = ( (1, 'OWNER'), (2, 'STAFF') ) name = models.CharField(max_length=30, blank=True) type = models.SmallIntegerField(choices=TYPE_CHOICES, default=2) staffs = models.ManyToManyField('self', symmetrical=False) def __str__(self): return f'{self.id}: {self.name}: {self.type}' def clean(self): """How to validate if adding staff is of type `STAFF`?""" """would like to check type of child object here?""" pass How can i validate all staff objects when i am adding staffs for a owner object? staff = Employee.objects.create(name='emp1') owner = Employee.objects.create(name='emp1', type=1) owner.staff.add(staff) -
I'm geting a name error where it can't find my model
I'm making a view to show a list of patients entered by a user. so i used django-tables module to render the table. in tables.py class PatientTable(tables.Table): FirstName = tables.Column(linkify=("PatientDetailView", {"pk": tables.A("Patient.pk")})) LastName = tables.Column(linkify=("PatientDetailView", {"pk": tables.A("Patient.pk")})) Telephone_no = tables.Column(linkify=("PatientDetailView", {"pk": tables.A("Patient.pk")})) class Meta: model = Patient # attrs = {'class': 'table table-striped table-hover'} exclude = ("doctor", "Notes", "Address") template_name = 'django_tables2/bootstrap4.html' # this is the view def Patients_list(request): table = PatientTable(Patient.objects.filter(doctor=request.user)) return render(request, 'accounts/patients_list.html',{ 'table' : table }) but when i reach to my url it returns Name error and i can't really see why. Is there a better method for doing that and delivering a table view of the patients of the doctor only and it's well stylized ? 'name 'Patient' is not defined' -
Django - How do I properly send a list from template to AJAX to view?
I'm trying to make an AJAX get request to the server whenever a user clicks a button. My problem is that I'm trying to return a list of dictionaries to the view. JQuery sees the object as a string, so technically I guess it's already in a JSON format. When I send it to the view the view sees it as a Querydict and when I try to index it, it only returns singular characters of the string. When I try to call json.loads(cameras) in views.py, it throws an error saying: json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 3 (char 2) I know this is probably an issue with how I'm handling the variable on the front end side, but I'm not sure how to fix this issue. Should I initially pass the variable from the view to the template differently? views.py def trigger_sirens(request): # Retrieve the list of dictionaries cameras = request.GET.get('cameras') print(type(cameras)) # ==> <class 'str'> print(cameras) # ==> [{'name': 'camera1', 'site': 'city'}, {'name': 'camera2', 'site': 'city'}] print(cameras[0]) # ==> [ # Manipulate data return JsonResponse({'success': True}, status = 200) # This is just a placeholder for now siren_search.html <!-- A button to trigger … -
django.core.exceptions.ValidationError value must be a decimal number
So, I have two different django models, I want to fill one field in one model (that is configured as CharField) with some string, based on a condition, what string is in an other model. I wrote a simple method for that: method screenshot In next method of a class I'm trying to call this method inside of a creating and saving a model instance:model creating and saving When I run this via django management command, I'm receiving this error:error screenshot Both fields (first I'm taking from another model in a method on a first screenshot, second I'm trying to save in a DB) configured as CharField:first field second field I had tried to reset migrations and to drop and create a DB (PostgreSQL 11.4), that hadn't helped. my 0001_initial.py migration And my \d+ tablename result from a psql table information I had found some similar question here, but nothing had helped, I had tried: reset migrations, cast a string as a Decimal built-in instance I don't have so much expirience in django and I could make a silly mistake, but I spent troubleshooting around 12 hours already, so I decided to write a question here. -
Django Tutorial app, part 2. Why is missing - add field Question to Choice after makemigrations command?
I'm following the tutorial 2.2 Writing your first Django app, part 2. I created the models Question and Choice in the polls/models.py file like the tutorial. from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) I activated the poll app in the mysite/settings.py file. INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Then i run the command makemigrations but in the output is missing "- Add field question to choice". $ python manage.py makemigrations polls Migrations for 'polls': polls/migrations/0001_initial.py - Create model Question - Create model Choice I'm using the following versions: /mysite$ pip freeze Django==2.2.2 pkg-resources==0.0.0 pytz==2019.1 sqlparse==0.3.0 /mysite$ python --version Python 3.7.3 I deleted all the project and start again without success. -
Django 1.8 Conditional expression returns empty queryset
I have two models that are something like this: class Foo(models.Model): # fields... class Bar(models.Model): foo = models.ForeignKey(Foo) is_done = models.BooleanField() # more fields.... I would like to annotate Foo with a count of all the associated Bar objects for which is_done is true. Unfortunately, I am trapped in Django 1.8, so Count('bar', filter='bar__is_done) is not an option for me. So instead, I used a conditional aggregation: Foo.objects.all().annotate( # other fields... done=Count(Case( When(bar__is_done=True, then=1), output_field=IntegerField() )) ) Unfortunately, this returns an empty queryset. Removing the conditional returns a queryset as normal, but the last annotation in particular seems to break the query. What's wrong? -
directory problem when starting apache for django (wsgi)
after having created a small local web application with django, I want to be able to access it remotely by hosting it with apache and nginx and gunicorn. However I have an error on the directory entered in /etc/apache2/apache2.conf I get the following error when starting apache: "Job for apache2.service failed because the control process exited with error code" Recording after in detail, I saw this error: "apache2: Syntax error on line 235 of /etc/apache2/apache2.conf : Expected </Directory\xc2\xa0/home/pi/Desktop/ecole> but saw </Directory>" My additions in the apache2 conf files: WSGIScriptAlias / /home/pi/Desktop/ecole/école/école/wsgi.py WSGIPythonPath /home/pi/Desktop/ school/ <Directory /home/pi/Desktop/school> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> I don't understand the problem, thank you for coming back. -
Searching in Foreign Key Fields in Django Haystack
I want to search from a Foreign Key field in Django. I am using ElasticSearch as a backend search engine. It's working perfect for local fields that is , non foreign key fields Many sites said to create a prepare_<> function , but even after that I couldn't figure out why its not working. Here is my code. search_indexes.py class UploadFileIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True, indexed=True) #OtherFields Types = indexes.CharField(model_attr="Types") def get_model(self): return UploadFileModel def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().Objects.all().select_related('Types') def prepare_Types(self, obj): #Even after doing this its not working return '' if not obj.Types else obj.Types.Name views.py class search(SearchView): form_class = UploadFileSearch template_name = 'search/search.html' queryset = SearchQuerySet().filter() form.py class UploadFileSearch(SearchForm): q = forms.CharField(required=False, label=('Search'), widget=forms.TextInput(attrs={'type': 'search'})) def __init__(self, *args, **kwargs): data = dict(kwargs.get("data", [])) self.q = data.get('q', []) super(UploadFileSearch, self).__init__(*args, **kwargs) def search(self): if not self.is_valid(): return self.no_query_found() if not self.cleaned_data.get('q'): return self.no_query_found() sqs = self.searchqueryset.filter(SQ(Type__exact=self.q)) if self.load_all: sqs = sqs.load_all() return sqs models.py class TypeModel(models.Model): Name = models.CharField(default="", max_length=5, null=False) Objects = models.Manager() def __str__(self): return self.Name class UploadFileModel(models.Model): #Other fields Types = models.ForeignKey(TypeModel, on_delete=models.CASCADE,related_name="Types") model_text.txt #other objects... {{ object.Types}} I expect the output for searching pdf to … -
How to secure post/put/patch payload with in Django views?
I've been using django serializers for a while now, And it seems like any time I send a payload using put/post/patch, serializers.is_valid() only checks if the payload data attributes types are correct, required ones are present and does not check if there are surplus data in the payload not defined in models.py Let's say that I have models.py : class Task(models.Model): title = models.CharField(max_length=100, default='default_task_name') description = models.CharField(max_length=1000, blank=True, default='') complete = models.BooleanField(default=False) canceled = models.BooleanField(default=False) date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('id', 'date') In my serializers.py i have the following : from rest_framework import serializers from .models import Task class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = '__all__' In my views.pyI have the following : class TaskDetails(APIView): def get_object(self, pk): try: return Task.objects.get(pk=pk) except Task.DoesNotExist: raise Http404 def put(self, request, pk): data = JSONParser().parse(request) serializer = TaskSerializer(self.get_object(pk), data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=HTTP_201_CREATED) return Response(serializer.errors, status=HTTP_422_UNPROCESSABLE_ENTITY) using cURL : curl -X PUT -H "Content-Type: application/json" -d '{"title":"task_1", "description":"learning rest", "task_force":"undefined "}' "my_api_uri" I except 'errors': {'task_force': ['undefined attribute task_force', 'status_code': '422'} What is a work around here to make that check with the serializer ? -
Trying to create a general search using django filters for all the fields in a given model
So I am creating a custom filter for my model and I want all the fields in that filter not use 'exact' but 'contains', but I don't want to manually add all the fields. I am trying to do something like this: from django_filters import FilterSet from polls.models import Question, Choice from django_filters import rest_framework class ChoiceFilter(FilterSet): for field in Choice._meta.get_fields(): field = rest_framework.CharFilter(lookup_expr='icontains') #question = rest_framework.CharFilter(lookup_expr='icontains') #this works want to generalize this class Meta: model = Choice fields = '__all__' So the second line works, but my for loop doesn't and my filter uses 'exact' instead of 'contains' -
Getting a relay not permitted error with Exim4
I am currently getting the following error: 2019-06-28 14:45:41 no host name found for IP address 192.168.X.X 2019-06-28 14:45:41 H=(cabc5b9f0d80) [192.168.X.X] F=<noreply@X.X.X.X> rejected RCPT <example@exmple.com>: relay not permitted My update-exim4.conf.conf looks as follows: dc_eximconfig_configtype='smarthost' dc_other_hostnames='example.com; localhost.localdomain; localhost' dc_local_interfaces='127.0.0.1 ; ::1' dc_readhost='example.com' dc_relay_domains='*' dc_minimaldns='false' dc_relay_nets='smtpserver.url' dc_smarthost='example.com' CFILEMODE='644' dc_use_split_config='false' dc_hide_mailname='' dc_mailname_in_oh='true' dc_localdelivery='mail_spool' When I run echo "Subject: sendmail test" | sendmail -v example@exmple.com, I receive the email which leads me to believe the config is fine, HOWEVER, when I attempt to send the email via my django app that is hosted on the same server I get the above error. My app conf looks as follows: EMAIL_HOST = "example.com" EMAIL_PORT = 25 EMAIL_NAME = "exmaple" EMAIL_ALIAS = "noreply@X.X.X.X" EMAIL_HOST_USER = "" EMAIL_HOST_PASSWORD = "" EMAIL_USE_TLS = False EMAIL_BATCH_SIZE = 50 EMAIL_BATCH_PAUSE = 300 The error in the app's logs is as follows: Task scheduler.tasks.workflow_send_email[740b2e55-896e-4a75-9e19-4fa5562783e2] raised unexpected: SMTPRecipientsRefused({'example@example.com': (550, b'relay not permitted')},) ... smtplib.SMTPRecipientsRefused: {'example@example.com': (550, b'relay not permitted')}