Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Interstitial Page / Intermediare Page before external Link - Django
I'm developing a price compare shopping website and i'm trying to figured out how can I achieve the following behavior: I have a Product Model and each product has-many Offers. Each offer has the company name and a external link to the product checkout page. I'd like when people click on the external link to the checkout actually reachs another page, let's say "http://mywebsite.com/redirect.html" which contains the following: You'll be redirected to the checkout page in 5 seconds. After the 5 seconds redirect them to the checkout page. How can I achieve that? Anybody has some reference to recommends me? -
Django channels Error when starting the server
I have my channels placed in the top of INSTALLED_APPS. When I ty to start the server I get following error: File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 224, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 36, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\channels\management\commands\runserver.py", line 10, in <module> from channels import __version__ ImportError: cannot import name '__version__' from 'channels' (C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\channels\__init__.py)``` -
django path using wsgi apache loses first parameter
I have a Django set up to handle requests for http://myserver/bayeux/online as follows: in the apache http.conf file: this line WSGIScriptAlias /bayeux /home/peter/path_to_wsgi In the top-level urls.py file: if I have this line urlpatterns = [ path('bayeux', _call_to_view)] The pattern will not match. This is because the first path element "bayeux" is used to direct to the urls.py structure, and so is not visible to the path calls inside urls.py. So instead, I have to have this line in urls.py: urlpatterns = [ path('online', _call_to_view)] The problem with this is that I have other folders I want to send calls to django. For http://myserver/anotherbook/online, the urls.py file ONLY sees the 'online' part of the path. There is no way to have different handlers for /bayeux and /anotherbook. Both will be handled by the same _call_to_view function. Of course, I can examine the whole url within call_to_view, but that is ugly. An alternative would be to have EVERY call on the server routed to django by having this in my httpd.conf: WSGIScriptAlias / /home/peter/path_to_wsgi With this set up I could have the lines urlpatterns = [ path('bayeux', _call_to_view)] urlpatterns = [ path('anotherbook', _call_to_different_view)] But this has a dire side-effect. It means … -
Django Inheritance gives import errors
I have one class (DeckDeviceUtil) with an abstract function (get_active_deckdevices) who needs to be inherited by 2 classes (Deck and Device). The structure is as follows: A.py from models import Deck class DeckDeviceUtil: @property @abstractmethod def deckdevice(self): pass def get_active_deckdevices(self): #somecode class Device(models.Model, DeckDeviceUtil): #somecode B.py from backend.devices.models import DeckDeviceUtil class Deck(models.Model, DeckDeviceUtil): #somecode I get following error: from backend.house.models import Deck ImportError: cannot import name 'Deck' probably because the 2 python files/classes need each other. When I try to do the imports inside the classes there are other errors when import DeckDeviceUtil inside Deck : class Deck(models.Model, DeckDeviceUtil): NameError: name 'DeckDeviceUtil' is not defined when import Deck inside Device: from backend.house.models import Deck ImportError: cannot import name 'Deck' Important: Device needs to import Deck What's the best way to solve this? -
How to handle POST form data with Django (refresh avoided)?
I'm trying to save the form's data in a database using Django. Refreshing after click on submit button is avoided using: scripts.py var form = document.getElementById("mail_form_id"); function handleForm(event) { event.preventDefault(); } form.addEventListener('submit', handleForm); function send_mailform(){ console.log("cal") var http = new XMLHttpRequest(); http.open("POST", "", true); http.setRequestHeader("Content-type","application/x-www-form-urlencoded"); var params = "search=" + document.getElementById('mail_input').value; http.send(params); http.onload = function() { alert(http.responseText); } } document.getElementById("mail_send_btn").addEventListener('click', send_mailform, false); views.py #Mail check if request.POST: Marketingform = Marketingforms(request.POST) print("sdf") if Marketingform.is_valid(): receiver_mail = Marketingform.cleaned_data['receiver_mail'] p = mail_receiver(receiver_mail=receiver_mail) p.save() print("correct") route_n_valid = False template ='index.html' views.py class mailForm(forms.ModelForm): class Meta: model = mail_receiver fields =[ 'receiver_mail', ] widgets = { 'receiver_mail': forms.EmailInput(attrs={ 'id':'mail_input', 'name':'mail_input'}), } How can I receive the value of params in the django views.py? -
Celery not connecting to Redis
I'm working in a Django project and i'm trying to integrate celery into my project but my app doesn't seem to be able to connect to my redis-server that I'm running locally. This is what it shows me when I run celery -A project worker. ---- **** ----- --- * *** * -- Linux-4.15.0-58-generic-x86_64-with-Ubuntu-18.04-bionic 2020-03-18 19:06:29 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: proyecto_is2:0x7f7c98351518 - ** ---------- .> transport: redis://h:**@ec2-34-202-114-79.compute-1.amazonaws.com:17729// - ** ---------- .> results: redis://127.0.0.1:6379/0 - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [2020-03-18 19:31:24,595: ERROR/MainProcess] consumer: Cannot connect to redis://h:**@ec2-34-202-114-79.compute-1.amazonaws.com:17729//: Error 110 connecting to ec2-34-202-114-79.compute-1.amazonaws.com:17729. Connection timed out.. I noticed that the url in transport is not my localhost and I don't know where that got set up. I'm using celery 4.3.0, redis 3.2.1. In my celery.py I have import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proyecto_is2.settings.dev_settings') app = Celery('proyecto_is2') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() In my settings i have ... other configs CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' -
How can i render objects in html through django templating via primary key?
i have a problem in searching articles on my home page. the problem is that when i enter a query in a search bar , the error "Reverse for 'blog_detail/' not found. 'blog_detail/' is not a valid view function or pattern name." appears. code homepage from where i search a query <form method="get" action={% url 'search' %} class=""> <!-- <form method="get" action="{% url 'search' %} class="">--> <input type="text" name="search" class="form-control bg-dark text-white" placeholder="Search Articles" aria-label="Recipient's username" aria-describedby="basic-addon2"> <div class="input-group-append bg-dark"> <button class="btn btn-outline-primary bg-danger text-white" type="submit" >Search </button> </div> </form> search.html The action of the form sends query to this page <div class="row"> {% for item in post %} <div class="card my-3 text-white bg-dark mb-3" style="width: 18rem;"> <img src="/media/{{item.thumbnail}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{item.title}}</h5> <p class="card-text">{{item.intro}}</p> <a href="{% url 'blog_detail/' id=item.post_id %}" class="btn btn-primary">read more...</a> </div> </div> {% if forloop.counter|divisibleby:5 %} </div> {% endif %} {% endfor %} </div> this (href="{% url 'blog_detail/' id=item.post_id %}") is giving an error saying (NoReverseMatch at /search/) in the urls.py the route for blog_detail is : path("blog_detail/<int:id>", views.blog_detail, name = "blog"), and for search route is : path("search/", views.search, name="search"), in the models the primary key is set as post_id : post_id = … -
Django: Unable to configure handler 'logging.handlers.SysLogHandler'
Receiving this error when running Django app. "ValueError: Unable to configure handler 'logging.handlers.SysLogHandler'" On Windows 10, I think I gave the folder dev/log full access for my user. Log handlers: #Loggly settings LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'django': { 'format':'django: %(message)s', }, }, 'handlers': { 'logging.handlers.SysLogHandler': { 'level': 'DEBUG', 'class': 'logging.handlers.SysLogHandler', 'facility': 'local7', 'formatter': 'django', 'address' : '/dev/log', }, }, 'loggers': { 'loggly_logs':{ 'handlers': ['logging.handlers.SysLogHandler'], 'propagate': True, 'format':'django: %(message)s', 'level': 'DEBUG', }, } } -
Django import messes up Celery
I have a django project with the following Django project structure: project/ ... some_app/ __init__.py some_module_where_i_import_some_utils.py server/ __init__.py settings/ __init__.py common.py dev.py ... celery.py ... utils/ __init__.py some_utils.py manage.py ... When using utils I import them the following way: from project.utils.some_utils import whatever And it works well. However when I run celery worker using DJANGO_SETTINGS_MODULE=server.settings.dev celery -A server worker --beat -l info autodiscover_tasks fails with the following error ModuleNotFoundError: No module named 'project'. Here are contents of server/celery.py: import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings.prod") app = Celery("server") app.config_from_object("django.conf:settings", namespace="CELERY") # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print("Request: {0!r}".format(self.request)) Here is server/__init__.py: from .celery import app as celery_app __all__ = ("celery_app",) -
Django - user profile picture not being displayed in the browser
In my project, I have a DetailView, so a user can view their profile. On here, I want to display their profile picture. However when I open the browser and go to the detail page, no profile picture is displayed. My code is displayed below. views.py: class DetailProfile(generic.DetailView): model = User # Template that a users profile picture should be displayed in template_name = 'detail_profile.html' detail_profile.html: <img width="200px" src="{{ user.profilePic.url }}" alt=""> Error returned by the browser: GET http://localhost:8000/media/static/default-profile.png 404 (Not Found) urls.py (for the users apps): urlpatterns = [ path('signup/', views.signup, name='signup'), path('login/', views.login, name='login'), path('resetone/', views.resetone, name='resetone'), path('resetwo/', views.resetwo, name='resetwo'), path('viewprofile/<int:pk>', views.DetailProfile.as_view(), name='detail_profile'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) SETTINGS.PY: STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'proj2/static/') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Currently, all the users have the file default-profile.png assigned to their profile pic, however later I am going to implement the ability for users to change their profile pic. default-profile.png is stored in the static folder(Check my settings.py code above). Does anybody know why this file isn't being displayed in the browser and why I am getting returned the error displayed above? Thank you. -
I am using django with mongodb, I need to export databases from the website
I was looking for how to do that but I just want a button that lets me download a csv and the same that lets me import a scv (or alike) and just sets the current database to that one. Is there a short way around for that? -
How exactly to use `current_app` and `urlconf` arguments of the `reverse()` function in Django
I had to use the reverse() function in my project and saw usage of the reverse() in other projects, but i have never used current_app and urlconf arguments. As i read in docs: The current_app argument allows you to provide a hint to the resolver indicating the application to which the currently executing view belongs. This current_app argument is used as a hint to resolve application namespaces into URLs on specific application instances, according to the namespaced URL resolution strategy. The urlconf argument is the URLconf module containing the URL patterns to use for reversing. By default, the root URLconf for the current thread is used. And i never saw examples of their usage. Could you give me some tips or maybe a little usage example, please, to understand how should i use them properly? -
How to use update_or_create when updating values in Django database from CSV files
Problem summary: I don't understand the syntax for objects.update_or_create in Django. CSV files have the field names in first row: # data.csv field1, field2, 12, 14, 35, 56, I have a model for my postgresql database in models.py: from django.db import models # example model, real one has 100 fields of different types class MyModel(models.Model): field1 = models.IntegerField(blank=True, null=True) field2 = models.IntegerField(blank=True, null=True) Now I want to create/update the database when new data comes in in form of CSV files: import csv with open('./datafiles/data.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: update, created = MyModel.objects.update_or_create( defaults={???}, ??? ) update.save() What goes into the question mark marked places? -
Unable to run Django code on localhost, using pythonanywhere's bash console
I installed Django and started a project. The moment I made the project, I ran python manage.py runserver on pythonanywhere's bash console. It gave the output Starting development server at http://127.0.0.1:8000/ However when I opened the URL, it showed me "This site can't be reached" (venv) 18:31 ~/django_sample $ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. March 18, 2020 - 18:35:54 Django version 3.0.4, using settings 'django_sample.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Error: That port is already in use. (venv) 18:35 ~/django_sample $ -
Where and how put my business logic in django
A friend recommended that I read the book two scoops Django and I was amazed at the recommendations he makes for a robust and well-designed Django project. This reading created a doubt in me and it is where I put the business logic, I give an example. Suppose I have two models: models.py class Sparks(models.Model): flavor = models.CharField(max_length=100) quantity = models.IntegerField(default=0) class Frozen(models.Model): flavor = models.CharField(max_length=100) has_cone = models.BooleanField() quantity_sparks = models.IntegerField(default=0) Let's suppose that every time I add a frozen, if it has sparks, I have to subtract it from the Sparks model and check that there is an available quantity. In the book they recommend putting this logic in models.py or forms.py. Where and how should I put this? -
How to initialize Django forms where fieldtype is variable
I have a json object like this: { "Enzyme": { "order": 1, "required": "no", "help": "enzyme", "dataType": "CharField" }, "Date": { "order": 2, "required": "yes", "help": "date", "dataType": "DateField" } } And now I want to initialize a form something like this: class MyForm(forms.Form): def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) for key,values in jsonObj.items(): self.fields[key] = forms.values["dataType"] I am not sure how can I do this, as taking this datatype from my json input. What should I write after forms. to initialize forms? Right now it's throwing an error module 'django.forms' has no attribute 'values' -
switching from one app to another app in django
I am here C:/Users/MaitRi/Desktop/PROJECT/MyProject/HappyHomes/templates/reg.html and want to move at C:/Users/MaitRi/Desktop/PROJECT/MyProject/HappyHomesAdmin/templates/home.html Can anyone please help me with this. HappyHomes and HappyHomesAdmin are my two different app in django. I want to move from first app to second app. How to give path of moving to different app in views.py file in django. -
How to validate child serializer that requires data from parent in django rest framework nested serializer?
I am using DRF Writable Nested to create writable nested serializer. I need to validate 'ItemDetail' but it requires 'product_id' which is present in the parent serializer i.e. 'InvoiceItem'. Models class InvoiceItem(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="invoice_items" ) class ItemDetail(models.Model): invoice_item = models.ForeignKey( InvoiceItem, on_delete=models.CASCADE, related_name="item_details" ) size = models.ForeignKey( Size, on_delete=models.CASCADE, related_name="item_details" ) quantity = models.PositiveIntegerField() Serializers class InvoiceItemSerializer(WritableNestedModelSerializer): product = ProductMiniSerializer(read_only=True) product_id = serializers.IntegerField(write_only=True) item_details = ItemDetailSerializer(many=True) class Meta: model = InvoiceItem fields = [ "id", "product_id", "product", "item_details", ] class ItemDetailSerializer(serializers.ModelSerializer): class Meta: model = ItemDetail fields = [ "id", "size", "quantity", ] def validate(self, data): return item_detail_validate(self, data) Validator def item_detail_validate(self, data): # How to get product_id here so I can use it in a query return data -
How to get the human readable name when saving a ModelMultipleChoiceField in Local Storage in a Django Form
I have this model: class TourCreator(models.Model): preferred_location = models.ManyToManyField('tours.TourDetailPage', blank=True) For which I use a form: from django_select2.forms import Select2MultipleWidget class TourCreatorForm(ModelForm): class Meta: model = TourCreator fields = '__all__' widgets = { 'preferred_location': Select2MultipleWidget, } I am using Django Select2 to render a nice Select2MultipleWidget. When going through a form wizard I am saving the form input to Local Storage with JavaScript. The problem is, it is saving the PK's of the ManyToMany relationship, I want it to save the string name of the model. See the screenshot as example: How can I make sure that the string name of the ManyToMany relationship gets stored instead of the PK? -
Python Django signals 'int' object has no attribute 'save'
I creating badminton sport app in Django where you can create matches, etc.. What I am trying to do now is update matches_played from my models.py via signals. Here is my signals.py: class Player(models.Model): ... matches_played = models.IntegerField(default=0, blank=True, null=True) ... class Match(models.Model): player_home = models.ForeignKey(Player, null=True, on_delete= models.SET_NULL, related_name='player_home') player_away = models.ForeignKey(Player, null=True, on_delete= models.SET_NULL, related_name='player_away') player_home_sets = models.IntegerField(default=0, blank=True, null=True) player_away_sets = models.IntegerField(default=0, blank=True, null=True) Here is my signals.py: def add_match_count(sender, instance,**kwargs): home_player_sets = instance.player_home_sets away_player_sets = instance.player_away_sets if home_player_sets > 0 or away_player_sets > 0: instance.player_home.matches_played += 1 instance.player_away.matches_played += 1 instance.player_home.matches_played.save() If I edit any match I receive error: 'int' object has no attribute 'instance'. Any idea how to fix it? -
Is it possible to run celery tasks inside of the django runserver when testing?
I have a django project with several Celery tasks. Also, I have several tests (using django TestCase) and I'm mocking the celery tasks. I don't want to run celery for the tests. I have searched a lot on the internet, but no luck. So I want to ask: would there be any way not to mock these functions and have the task code executed inside the django runserver? More info (I can't update them right now): python 2.7 django 1.11 celery 4.3 Thank you so much for your help! :) -
Django Logging Config By Apps
Django application uses logger but was not configured and I used this in settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': LOGGING_FILE_PATH, 'formatter': 'verbose' }, }, 'loggers': { 'django': { 'handlers':['file'], 'propagate': True, 'level':'DEBUG', }, 'MYAPP': { 'handlers': ['file'], 'level': 'DEBUG', }, } } Which I think realized Everything was being included. Including django.db.backends which shows all of the SQL queries being made. Which is useful but can be cumbersome to comb through when debugging. How can I configure Django to filter out these loggings into specific files to make it easier to debug. There are management commands that are executed on cronjobs, I would like designate specific log files for them. -
how to solve 500 internal server error mod_wsgi apache "importerror: No Module named 'django'
I have been trying to solve this error but I am not been able to solve, totally frustrated because I have tried every single answer on these related question , any help would be appreciated. My configuration of VPS server Ubuntu 18.04 django 2.2.5 apache 2.4.49 python 3.6(virtualenv) libapache2-mod-wsgi-py3 My folder structure is: /var/www/dataforze/prediction_project/venv (virtualenv folder) bin include lib /var/www/dataforze/prediction_project |- manage.py static prediction_project |__init__.py |settings.py |urls.py |wsgi.py 000-default.conf file code <VirtualHost *:80> <Directory /var/www/dataforze/prediction_project/prediction_project> Require all granted </Directory> <Directory /var/www/dataforze/prediction_project/prediction_project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess prediction_project python-path=/var/www/dataforze/prediction_project python-home=/var/www/dataforze/prediction_project/venv WSGIProcessGroup prediction_project WSGIScriptAlias / /var/www/dataforze/prediction_project/prediction_project/wsgi.py ErrorLog ${APACHE_LOG_DIR}/mysite_error.log LogLevel warn </VirtualHost> my wsgi.py file code import os from django.core.wsgi import get_wsgi_application sys.path.append('/var/www/dataforze/prediction_project/prediction_project') # add the virtualenv site-packages path to the sys.path sys.path.append('/var/www/dataforze/prediction_project/venv/lib/site-packages') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'prediction_project.settings') application = get_wsgi_application() My server logs [Wed Mar 18 17:29:01.003624 2020] [wsgi:error] [pid 82169:tid 140431942575872] mod_wsgi (pid=82169): Target WSGI script '/var/www/dataforze/prediction_project/prediction_project/wsgi.py' cannot be loaded as Python module. [Wed Mar 18 17:29:01.003722 2020] [wsgi:error] [pid 82169:tid 140431942575872] mod_wsgi (pid=82169): Exception occurred processing WSGI script '/var/www/dataforze/prediction_project/prediction_project/wsgi.py'. [Wed Mar 18 17:29:01.003823 2020] [wsgi:error] [pid 82169:tid 140431942575872] Traceback (most recent call last): [Wed Mar 18 17:29:01.003844 2020] [wsgi:error] [pid 82169:tid 140431942575872] File "/var/www/dataforze/prediction_project/prediction_project/wsgi.py", line 12, in <module> [Wed Mar … -
Django read_frame on filterset returns 'property' object has no attribute '_iterable_class'
I'm trying to create and xlsx file from a filterset queryset (HostServiceFilterSet.qs) using this view: def exportHostServices(request): qs_hostServices = HostServiceFilterSet.qs df = read_frame(qs_hostServices) # my "Excel" file, which is an in-memory output file (buffer) # for the new workbook excel_file = IO() # pylint shows a false positive error here, # so the alert is suppressed with the comment after the code xlwriter = pd.ExcelWriter(excel_file, engine='xlsxwriter') # pylint: disable=abstract-class-instantiated df.to_excel(xlwriter, 'Host Services') xlwriter.save() xlwriter.close() # rewind the buffer excel_file.seek(0) # set the mime type so that the browser knows what to do with the file response = HttpResponse(excel_file.read(),\ content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') # set the file name in the Content-Disposition header response['Content-Disposition'] = 'attachment; filename=Anagrafica-Servizi.xlsx' return response The view works correctly when used with the model's queryset HostService.objects.all() and the xlsx file is correctly generated. The filterset that i'm trying to convert to xlsx is declared as follows: import django_filters from django import forms from .models import HostService class HostServiceFilterSet(django_filters.FilterSet): hostname_input = django_filters.CharFilter(widget=forms.\ TextInput(attrs={'placeholder':'Hostname', 'type': 'search', 'class': 'form-control'}), field_name='hostname', lookup_expr='icontains', label="",) ip_input = django_filters.CharFilter(widget=forms.\ TextInput(attrs={'placeholder':'Ip Address', 'type': 'search', 'class': 'form-control'}), field_name='ip', lookup_expr='icontains', label="",) servicename_input = django_filters.CharFilter(widget=forms.\ TextInput(attrs={'placeholder':'Service Name', 'type': 'search', 'class': 'form-control'}), field_name='servicename', lookup_expr='icontains', label="",) port_input = django_filters.CharFilter(widget=forms.\ TextInput(attrs={'placeholder':'Port Number', 'type': 'search', 'class': … -
Django ImportError: cannot import name 'views'
The command python3 manage.py makemigrations projectxap keeps returning the import error. ImportError: cannot import name 'views' from 'projectxproject'. I have tried different variation of importing the views e.g from projectxapp import views , import views and from projectxapp.views import * but i keep getting the same error. Here is my folder structure and code.