Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to do field validation in django-import-export
Following is my model: class Product(models.Model): product_title = models.CharField(max_length=100, null=False, verbose_name='Product title') product_description = models.TextField(max_length=250, verbose_name='Product description') product_qty = models.IntegerField(verbose_name='Quantity') product_mrp = models.FloatField(verbose_name='Maximum retail price') product_offer_price = models.FloatField(verbose_name='Selling price') I wanted to have a validation for product_offer_price field before save for which I had posted a QUESTION and it was answered with the working solution. Validation needed is: if product_offer_price > product_mrp: raise ValidationError Now the solution to above question works perfectly for the admin forms. But, I have implemented django-import-export, in which I am importing Product Data in bulk in admin, and I need similar validation during bulk import. How to achieve this? -
Django admin ModelForm, save calculated relateds
I'm facing a problem with django admin in overwritter ModelForm's save() method. models.py class Reservation(models.Model): status = models.PositiveSmallIntegerField(choices=STATUS, default=0) creation_date = models.DateTimeField(auto_now_add=True) date_start = models.DateField() date_end = models.DateField() service = models.ForeignKey(Service, on_delete=models.CASCADE) class ReservationItem(models.Model): quantity = models.IntegerField() unit_price = models.DecimalField(max_digits=10, decimal_places=2) unit_tax = models.DecimalField(max_digits=10, decimal_places=2) row_total = models.DecimalField(max_digits=10, decimal_places=2) row_total_incl_tax = models.DecimalField(max_digits=10, decimal_places=2) reservation = models.ForeignKey(Reservation, on_delete=models.CASCADE, related_name='items') resource = models.ForeignKey(Resource, on_delete=models.CASCADE) The reservation items are derived from the service, by an availability query, so it've written a custom ModelFrom for the admin admin.py class ReservationModelForm(forms.ModelForm): def clean(self): if 'service' in self.cleaned_data: self._check_availability() return self.cleaned_data def _check_availability(self): '''do some stuff an get items ad an array of ReservationItems instances created like this: ReservationItem( resource=avail_resource, quantity=resource_type.quantity, unit_price=resource.unit_price, unit_tax=resource.unit_price*resource.tax.percentage, row_total=resource.unit_price*resource_type.quantity, row_total_incl_tax=... )''' self.cleaned_data['items'] = items #then the save method def save(self, commit=True): reservation = super(ReservationModelForm, self).save(commit=commit) if not self.instance.id: service = self.cleaned_data.get('service') .... reservation.items.set(self.cleaned_data['items'], bulk=False) return reservation class ReservationAdmin(admin.ModelAdmin): form = ReservationModelForm Now all I get is an error: save() prohibited to prevent data loss due to unsaved related object 'reservation'. But I can't save reservation first, because I need an atomic save, how can I solve? -
Dynamically making queries
I am trying to find best way for dynamically making queries. Front-end of the project will send json to back-end for getting query of objects by parameters query like a: Model.objects.filter(**query) I can set json format on my wish. In this moment json: # first case {'type': 'channel_type', 'or': {'param1': {'__gte': 10}, 'param2': {'': 12}}} # second case {'type': {'in': ['channel1', 'channel2']}, 'and': {'p1': {'__lte': 12}, 'p2': {'!=': 1}}} And that will be equal in sql (select x from y - will be static, code only generate 'where' condition): # first case WHERE table.type = channel_type AND (table.param1 >= 10 OR table.param2 = 12 # second case WHERE table.type IN [channel1, channel2] AND (table.p1 <= 12 AND table.p2 <> 1) I already did that: query_params_dict = {'>': '__gt', '<': '__lt', '>=': '__gte', '<=': '__lte', '==': ''} def parse_segmentation_query(query): type = {'type': query.pop('type')} if isinstance(query['type'], str) else {'type__in': query.pop('type')['in']} query = recursive_parsing_query(query) query.update(type) return query Func "recursive_parsing_query" not ready, so not shown. But I want recursively pop params from dict and make {'param1__gte': 2} dict which will passed in **kwards for objects.filter. Trouble is getting "non-equal" condition => It breaks simple-writed "Model.objects.filter(**query), because there we need "exclude". I'm wondering: are this … -
How do I use the django template tag in the css tag?
I tried to use the forloop.last template tag <div class="panel-body"> {% for card in cardlist.card_set.all %} {% if forloop.last %} <div class="well" style="margin-bottom: 0px;">{{ card.title }}</div> {% else %} <div class="well" style="margin-bottom: 20px;">{{ card.title }}</div> {% endif %} {% endfor %} </div> How do I refactor the above source like the source below? In the refactored source, "margin-bottom: {{margin-bottom}} px;" Error in "{{margin-bottom}}". <div class="panel-body"> {% for card in cardlist.card_set.all %} {% if forloop.last %} margin-bottom = 0 {% else %} margin-bottom = 20 {% endif %} <div class="well" style="margin-bottom: {{ }}px;">{{ card.title }}</div> {% endfor %} </div> -
Django with extend database
I am developing project with database postgres. Today I tried do transfer to the server, database was transfered too and I changed my settings.py for it But after that I see strange errors in console Exception ignored in: <generator object SQLCompiler.setup_query.<locals>.<genexpr> at 0x10718ca98> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 35, in <genexpr> if all(self.query.alias_refcount[a] == 0 for a in self.query.tables): SystemError: error return without exception set Exception ignored in: <generator object Loader.get_template_sources at 0x10718c258> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/template/loaders/filesystem.py", line 54, in get_template_sources loader=self, SystemError: error return without exception set Exception ignored in: <generator object Apps.is_installed.<locals>.<genexpr> at 0x1071266d0> ... ... ... "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 264, in get_finders yield get_finder(finder_path) SystemError: error return without exception set So What is it? -
django on nginx + uwsgi / static files don't show
So I want to run django on nginx with uwsgi. I installed everything, changed the ALLOWED_HOSTS and STATIC_ROOT in the settings.py and ran "collectstatic". With the terminal I can see that the admin-static-files were put exactly where I wanted them to be put. Yet I don't see the static files when I go to domainxy.de/admin . After my the installation I did this: sudo mkdir -p /etc/uwsgi/sites sudo nano /etc/uwsgi/sites/mysite.ini with ####mysite.ini#### [uwsgi] project = mysite uid = root base = /%(uid) chdir = %(base)/%(project) module = %(project).wsgi:application master = true processes = 5 socket = /run/uwsgi/%(project).sock chown-socket = %(uid):www-data chmod-socket = 660 vacuum = true and sudo nano /etc/systemd/system/uwsgi.service with ###uwsgi.service#### [Unit] Description=uWSGI Emperor service [Service] ExecStartPre=/bin/bash -c 'mkdir -p /run/uwsgi; chown root:www-data /run/uwsgi' ExecStart=/usr/local/bin/uwsgi --emperor /etc/uwsgi/sites Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target and sudo nano /etc/nginx/sites-available/mysite.conf with ####mysite.conf#### server { listen 80; server_name domainxy.de www.domainxy.de xx.xxx.xxx.xxx; location = /favicon.ico { access_log off; log_not_found off; } location /static { root /root/mysite/; } location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/mysite.sock; } } and sudo ln -s /etc/nginx/sites-available/mysite.conf /etc/nginx/sites-enabled sudo systemctl restart nginx sudo systemctl start uwsgi sudo ufw allow 'Nginx Full' Where did I make the mistake? I did change … -
Is there an easy way of finding all relations (ForeignKey/ManyToManyField/OneToOneField) to the model?
Given I have a File model I'd like to know which instances of this model aren't used in any other models in my DB so I can safely delete them. The sample models look like this: class File(models.Model): origin = models.FileField() class Doc(models.Model): files = models.ManyToManyField(File) class Company(models.Model): logo = models.ForeignKey(File) class FileInfo(models.Model): file = models.OneToOneField(File) Also, the solution should be dynamic so that it will work without modifications in cases when new links to the File models are added. I tried looping over model._meta.fields, checking field.rel.to but failed to produce a working version. -
Django can't login after save
I have TokenAuthentification on my django rest server. After registration logging in work perfectly, but when I call update with old fields, I can't login anymore. What am I doing wrong? update code: class ClientSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username') first_name = serializers.CharField(source='user.first_name') last_name = serializers.CharField(source='user.last_name') email = serializers.CharField(source='user.email') password = serializers.CharField(source='user.password') profile_photo = serializers.ImageField(source='details_sample.profile_photo', required=False) class Meta: model = Client fields = ('id', 'username', 'first_name', 'last_name', 'email', 'password', 'profile_photo', 'phone') def update(self, instance, validated_data): if validated_data.get('user') is not None: instance.user.set_password(validated_data['user'].get('password', instance.user.password)) instance.username = validated_data['user'].get('username', instance.user.password) instance.first_name = validated_data['user'].get('first_name', instance.user.password) instance.last_name = validated_data['user'].get('last_name', instance.user.password) instance.user.save() instance.phone = validated_data.get('phone', instance.phone) instance.save() return instance login url: url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), -
Django blog, send an email to administrator when users submit a form
Background I am building a blog about my research group. There is a join_us page where users are able to fill a application form to apply for the research program. The basic function works well but I want to notify my mentor when someone submits the application. Problem The official document of Django about the sending_email is a bit ambiguous and I still do not figure out how to add the value of the form into the email content. Code views.py def application_action(request): last_name = request.POST.get('last_name', 'LAST_NAME') first_name = request.POST.get('first_name', 'FIRST_NAME') email_address = request.POST.get('email_address', 'EMAIL_ADDRESS') program_type = request.POST.get('program_type', 'PROGRAM_TYPE') personal_statement = request.POST.get('personal_statement', 'PERSONAL_STATEMENT') resume = request.FILES.get('resume') models.Application.objects.create(last_name=last_name, first_name=first_name, program_type=program_type, email_address=email_address, personal_statement=personal_statement, resume=resume) send_mail( 'An new application', 'Dear professor, you received an new application. Please check it out in the administration console', 'from@example.com', ['to@example.com'], fail_silently=False, ) application = models.Application.objects.all() return render(request, 'research_spacecoupe/join_us.html', {'application': application}) settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = False EMAIL_HOST = 'smtp.126.com' EMAIL_PORT = 25 EMAIL_HOST_USER = 'demo@126.com' EMAIL_HOST_PASSWORD = 'demo' DEFAULT_FROM_EMAIL = 'demo <demo@126.com>' models.py class Application(models.Model): program_choice = (('硕士项目', '硕士'), ('博士项目', '博士'), ('博士后项目', '博士后')) first_name = models.CharField(max_length=30, default="名") last_name = models.CharField(max_length=30, default="姓") email_address = models.CharField(max_length=30, null=True) program_type = models.CharField(max_length=10, choices=program_choice) personal_statement = models.TextField(null=True) application_time = models.DateTimeField(auto_now=1) resume … -
NoReverseMatch at -- coming from a template tag
I was doing a small walk-through project from an online django course. It's a simple design. Site has users. Users can create zines (groups). Users can write text posts in the various zines. I have two 'zines' (groups). MUFON and EastCoast. I have three posts in MUFON and I have no posts in EastCoast. The drilldown for the the no-post http://127.0.0.1:8000/zines/posts/in/east-coast-94-lovers/ works fine. It says, "no posts yet". But when I go to the drilldown for group with three posts, http://127.0.0.1:8000/zines/posts/in/mufon/ I get a failure: Request URL: http://127.0.0.1:8000/zines/posts/in/mufon/ Django Version: 1.11.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'for_user' with keyword arguments '{'username': ''}' not found. 1 pattern(s) tried: ['posts/by/(?P<username>[-\\w]+)/$'] I don't know what the problem is. Ideas I had: 1) the URL dispatching isn't working (it cannot find the template to render) 2) There is some syntactical error in the template. I think the relevant template is coming from _post.html. <span class="username"><a href="{% url 'posts:for_user' username=post.user.username %}">@{{ post.user.username }}</a></span> Although this matches the sample code, it's throwing an error. There error message is odd, why does it say the keyword argument I'm passing is {'username': ''} ? It's actually supposed to be {'username': post.user.username} So that made me wonder … -
Django model pre_save Validation in Admin
Following is my model: class Product(models.Model): product_title = models.CharField(max_length=100, null=False, verbose_name='Product title') product_description = models.TextField(max_length=250, verbose_name='Product description') product_qty = models.IntegerField(verbose_name='Quantity') product_mrp = models.FloatField(verbose_name='Maximum retail price') product_offer_price = models.FloatField(verbose_name='Selling price') def validate_produce_offer_price(sender, instance, **kwargs): if instance.product_offer_price > instance.product_mrp: from django.core.exceptions import ValidationError raise ValidationError('Product offer price cannot be greater than Product MRP.') pre_save.connect(validate_produce_offer_price, sender=Product) I am trying to validate the product_offer_price before the model is saved. The Validation error is being raised successfully, but the on an exception page created by the debugger. How to show the error on the form in the admin itself like other errors raised by the admin form? -
override django auth contrib validator and widget templates
I would like to adapt the built-in django authentication system to my needs. More specifically I would like to: 1) Adapt the username validator in django/contrib/auth/validators.py to allow for spaces in usernames like so: @deconstructible class ASCIIUsernameValidator(validators.RegexValidator): #Added "\s" in this regex: regex = r'^[\w\s.@+-]+$' message = _( 'Enter a valid username. This value may contain only English letters, ' 'numbers, and @/./+/-/_ characters.' ) flags = re.ASCII 2) I would like to change the aut/widgets/read_only_password_hash.html which is now: <div{% include 'django/forms/widgets/attrs.html' %}> {% for entry in summary %} <strong>{{ entry.label }}</strong>{% if entry.value %}: {{ entry.value }}{% endif %} {% endfor %} </div> to basically an empty file, because I do not want to display all the entries (hash, salt, algorithm, ...) which are not important to the user. All of this works fine if I change the source code in my Django installation in my vritualenv on my dev machine. However, this seems way to hackish to deploy on the staging/production server. I did some research but couldn't find any clue on where/how to override these two specific files. For the read_only_password_hash.html, creating a file like PROJROOT/templates/auth/widgets/read_only_password_hash.html has no effect. Thanks for pointing me in the right direction! -
submit form as superuser vs regular user
In my django app I have a Myuser(User) class. It inherits the User class. When a new user is created the Myuser table is poplulated. Here's the rest of the code: models.py class Someclass(models.Model): objectid = models.IntegerField() objecttype = models.CharField(max_length=200) created = models.DateTimeField(default=timezone.now) modified = models.DateTimeField(auto_now=True) class Someotherclass(Someclass): status = models.IntegerField(default=0,) name = models.CharField(max_length=200) created = models.DateTimeField(default=timezone.now) modified = models.DateTimeField(auto_now=True) user = models.ForeignKey(User) forms.py class SomeotherclassForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") self.user = kwargs.pop('user') self.app = kwargs.pop('app') self.table = kwargs.pop('table') self.mytype = kwargs.pop('mytype') initial = kwargs.get('initial', {}) super(SomeotherclassForm, self).__init__(*args, **kwargs) create.py class DataCreate(CreateView): @method_decorator(login_required) def dispatch(self, *args, **kwargs): #some code here not relevant at all def get_form_kwargs(self): kwargs = super(DataCreate, self).get_form_kwargs() objectid = self.request.GET.get('objectid',None) objecttype = self.request.GET.get('objecttype',None) kwargs.update({'mytype': objecttype}) kwargs.update({'request': self.request}) kwargs.update({'user': self.request.user}) kwargs.update({'app': self.app}) kwargs.update({'table': self.kwargs['table'].lower()}) return kwargs def form_valid(self, form): obj = form.save(commit=False) group = '' if not self.request.user.is_superuser: group = MyUser.objects.get(user_ptr_id=self.request.user.pk) else: groups = self.request.user.groups.all() if self.kwargs['table'] == 'Myprotocol': obj = form.save(commit=False) table = eval(self.request.GET.get('objecttype',None).title()).objects.get(pk=int(self.request.GET.get('objectid',None))) obj.objectid = table.pk obj.objecttype = table.__class__.__name__.lower() obj.user_id = self.request.user.pk obj.save() else: obj = form.save() if self.request.POST.get('is_popup'): check = int(self.kwargs['is_list']) if self.kwargs['table'] == 'Someclass': popup = 1 a = checkPopup2(obj,check,popup,obj.pk) else: a = checkPopup(obj,check) return a else: return super(DataCreate, self).form_valid(form) When … -
Emptying a table and filling with fixtures
I'm working on a big project (tons of migrations already exist, etc...) and I'm at a point in which I must empty an entire table and then fill it again with ~10 elements. What is the Django approach to this situation? Fixtures? RunPython? -
Django Views how is working - iterating over arguments
I try to understand how Django as_view works. We have the following code that goes over key,value of a dictionary: for key, value in six.iteritems(kwargs): setattr(self, key, value) in six.iteritems is defined as: def iteritems(d, **kw): return iter(d.items(**kw)) form Python 2 to python 3 using iter. the function iteritems has 2 arguments, in as_view are just two. I take the code from Django(as_view,dispatch) to a separate project to see how it works. If instead of using the function I introduce the call inside the loop I have an error, because off course the dictionary doesn't exist(there is no d): for key, value in iter(items(kwargs): setattr(self, key, value) Why when I use the function d appears by itself, even if is not passed ? (there is no d in the code) -
Sum of a column with group by in django
I need some help with this sql query that I am trying to run with django orm model. SELECT SUM(CAPITAL) AS PRODUCT_CAPITAL, PRODUCT FROM CAPITAL_SHEET WHERE CLIENT_ID = 'X1234' GROUP BY PRODUCT I did this CapitalSheet.objects.filter(client_id="X1234").values("product").annotate(Sum("capital")) This is what I am getting as a result in json: [ { "product": "product1" }, { "product": "product2" } ] I was expecting this as output : [ { "product": "product1", "capital": 1234.00 }, { "product": "product2", "capital": 1234.00 } ] What am i doing wrong here ? -
How to upload a file in a folder from django admin using form.FileField
I am trying to upload a file in a local directory called uploads. The directory structure is Folder A Folder B Folder C settings.py urls.py <app_name1> Folder Static manage.py uploads accounts/forms.py-- class CouplingUploadForm(forms.ModelForm): def validate_file_extension(value): import os from django.core.exceptions import ValidationError ext = os.path.splitext(value.name)[1] valid_extensions = ['.xml'] if not ext.lower() in valid_extensions: raise ValidationError(u'Only files with ".xml" extension are supported, ' 'received: "%s" file.' % ext) coupling_file = forms.FileField(label='XML File Upload:', required=True, validators=[validate_file_extension]) class Meta: model = models.Coupling exclude = ['coupling_name', 'module_name'] I don't have model.FileField so won't be able to use upload_to accounts/admin.py class couplingAdmin(admin.ModelAdmin): list_display = ('coupling_name','module_name') form = CouplingUploadForm def post(request): if request.method == 'POST': print('I am here') I am trying to upload the file under post but I think this is not trigerring at all. Is there any way so that I can upload a file in that uploads folder. Any help/suggestion/link is highly appreciated. Thanks in advance. -
What all front-end frameworks can be used with Django?
I've recently just begun learning Django. My friend once told me that he used Materialize with Django and that it wasn't a good fit. So what all front-end frameworks can I use with Django (like Bootstrap) to create responsive web applications? -
Django how can I specify a different authentication method per view
Pretty much what the title says. I'm using Django 1.11 and I've been asked to set CAS as authentication method to some of views, and keep the rest behind Django model auth or leave them without authentication. I'm trying to integrate django_cas_ng to redirect to a CAS server for authentication, but I can't figure out how to distinguish the auth method among view functions. Django supports multiple auth backends, or even completely customized ones, but I wonder if I can specify a separate auth method by name for each view (for example with a view decorator). Django allows explicitly specifying different databases and caches, but is there a way (or an app) to enable the same for authentication backends? -
SystemError: Parent module '' not loaded, cannot perform relative import
I'm trying to make documentation file using pydoc. I'm using command: python /usr/bin/pydoc -w views and I'm getting this error: problem in views - SystemError: Parent module '' not loaded, cannot perform relative import In views.py I have: from .models import my_model from .serializers import my_serializer from .forms import my_form When I replaced above to: from my_app.models import my_model from my_app.serializers import my_serializer from my_app.forms import my_form I've got another error: problem in views - ImportError: No module named 'my_app' Is there any way to fix that ? -
Model validation: can I access ValidationError code?
I have two directly related questions. Django documentation recommends raising ValidationError with a code: # Good ValidationError(_('Invalid value'), code='invalid') # Bad ValidationError(_('Invalid value')) How can I access this code in tests? All my attempts to use as_data, as_json, or simply .code on the caught exception fail. Unfortunately, the suggestions I see all relate to form validation. My test validates the models. It is almost the same question as asked before (I don't use forms). The related question: the same documentation page linked above gives a few examples of how to raise ValidationError, and while "Raising ValidationError" section recommends using the code, "Using validation in practice" never mentions it again, and the examples there don't use code. I wonder if that's an indication of this feature being stale. -
What is the logic behind Django's field validation?
When a form's field is being cleaned, that is done using two functions that in turn call other functions: clean() (method on a Field subclass) is responsible for running to_python(), validate(), and run_validators() clean_<fieldname>() runs on the Form subclass, not the Field subclass, and is not given a value (it has to look it up) but has to return the cleaned value. What's the logic behind this? There are three places to run validation-logic: validate(), the methods registered as validators that are run by run_validators, and clean_<fieldname>(), is that really useful? The official documentation on this is here: https://docs.djangoproject.com/en/1.11/ref/validators/ -
Python Requests headers giving wrong size of content-length [duplicate]
This question already has an answer here: How does Python compare string and int? 2 answers I am working on a Python Django project in which I need to get the size of the file from the URL entered by the user. Here I have created a test function in a separate file for testing. import requests def upload_file(request): check = requests.head(request) if check.status_code != 200: print "The URL is invalid or the file does not exist!" return False else: if check.headers.get("content-length") > 4*1024*1024*1024*1024: print "File size exceeds limit!" return False elif check.headers.get("content-type") == "text/html": print "The link is an html file" return False else: print "All is well" return True print upload_file('http://speed.hetzner.de/100MB.bin') OUTPUT: File size exceeds limit! False I am using this test file: Test file 100MB Since 100MB is less than 4*1024*1024*1024*1024, the function should return True. I have tried increasing the 4*1024*1024 value and got same result. Is it a bug? If not Please guide me where I'm wrong. -
Django incremental tests
I'm working on an app that has lots of test cases, which takes a lot of time to get executed, sometimes upto 1 hr. My aim to make sure that I execute only those test cases or test modules that affected by the changes made. I know there exists a python package for similar work but I want something for Django. Also to mention, I've been using Django 1.9 along with Discover Test runner to execute my test cases. Thanks in advance! -
from .models import User SystemError: Parent module '' not loaded, cannot perform relative import
I got an error,from .models import User SystemError: Parent module '' not loaded, cannot perform relative import . I wanna parse excel and put data in model(User).User model in models.py is class User(models.Model): user_id = models.CharField(max_length=200) name_id = models.CharField(max_length=200) age = models.CharField(max_length=200) man = models.BooleanField() The last code of man = models.BooleanField() means man or woman,if ’●’ in excel,it means the user is man and true wanna be put in man variable. Now views.py is #coding:utf-8 from django.shortcuts import render import xlrd from .models import User book = xlrd.open_workbook('../data/data.xlsx') sheet = book.sheet_by_index(1) for row_index in range(sheet.nrows): row = sheet.row(row_index) print(row) for row in rows: is_man = row[4] != "" user = User(user_id=row[1], name_id=row[2], age=row[3], man=is_man) user.save() I removed the import and used my IDE to import it,but now error happens from app.models import User ImportError: No module named 'app' .However,models.py & views.py are in app(it is child app) folder,so I really cannot understand why No module named 'app' error happens. How can I fix this?