Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot change column 'id': used in a foreign key constraint of table error on Django
Im trying to create models taking a MySQL database as reference using Django, but when I try to migrate it throws me the next error: Cannot change column 'id': used in a foreign key constraint 'fk_post' of table 'demoniosmv.images'" My models looks like this: from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Images(models.Model): #id = models.IntegerField(primary_key=True) fk_post = models.ForeignKey('Post', related_name="images", blank=True, null=True, on_delete = models.CASCADE) img_url = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = True class Post(models.Model): #id = models.IntegerField(primary_key=True) author = models.ForeignKey(User, related_name="posts", on_delete = models.CASCADE) title = models.CharField(max_length=200, blank=True, null=True) text = models.TextField(blank=True, null=True) created_date = models.DateTimeField(default = timezone.now) class Meta: managed = True And the SQL script from which I'm creating the database is this: -- MySQL Script generated by MySQL Workbench -- Sun Jul 21 14:14:44 2019 -- Model: New Model Version: 1.0 -- MySQL Workbench Forward Engineering SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'; -- ----------------------------------------------------- -- Schema demoniosmv -- ----------------------------------------------------- -- ----------------------------------------------------- -- Schema demoniosmv -- ----------------------------------------------------- CREATE SCHEMA IF NOT EXISTS `demoniosmv` DEFAULT CHARACTER SET utf8 ; USE `demoniosmv` ; -- ----------------------------------------------------- -- Table `demoniosmv`.`post` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `demoniosmv`.`post` ( `id` INT … -
Calling script from Django on a webserver
I made a website and I deployed it with Nginx and Gunicorn on an Ubuntu server (18.04). In my site I call with subprocess some python scripts that are in my project folder. If I start them on terminal they work as well, but with subprocess they don't work. This problem also belongs to commands on terminal. @staff_member_required() def get_all_process(request): process = subprocess.Popen(["ps a"], shell=True, executable='/bin/bash', stdout=subprocess.PIPE) # /bin/bash -c output = process.stdout.readline().decode("utf-8") out = (process.communicate()[0]).decode("utf-8") return HttpResponse('{}, {}'.format(output, out)) @staff_member_required() def start_script(request): process = subprocess.Popen(["nohup /home/user/project/source/test.py >/dev/null 2>&1 &"], shell=True, executable='/bin/bash', stdout=subprocess.PIPE) # /bin/bash -c output = process.stdout.readline().decode("utf-8") out = (process.communicate()[0]).decode("utf-8") pid = process.pid + 1 return HttpResponse('{}, {}'.format(output, out)) How can I solve? -
How do I pass url path argument to view success url, in url patterns?
I want to pass the <int:pk> of my view_submission path to the success_url. Can you please help? I can't seem to find a way to do this here, without changing the code in my views file, which I'd really not like to do because I want to keep these all in the urls file. urlpatterns = [ path('', login_required(SubmissionsList.as_view()), name='all_submissions'), path('create', login_required(SubmissionCreate.as_view( success_url=reverse_lazy('all_submissions'))), name='create_submission'), path('view/<int:pk>', login_required(SubmissionDetail.as_view()), name='view_submission'), path('edit/<int:pk>', login_required(SubmissionUpdate.as_view( success_url=reverse_lazy('view_submission', kwargs={'pk': pk}))), name='edit_submission'), path('delete/<int:pk>', login_required(SubmissionDelete.as_view( success_url=reverse_lazy('all_submissions'))), name='delete_submission'), ] Thanks! -
django-simple-history Sum of columns for each historical snapshot
I've been trying to get the sum of one colum in my database. I know how to do it but when it comes to using django-simple-history and get the value for each snapshot (24 hours), I can't. It just returns the value for all snapshots together. How would I construct the correct ORM to get the individual value of each snapshot, so that I can use it inside my template to create a time graph with a for loop, that grabs each single snapshot in the db and the Node_Cores sum for that snapshot? Example of what i'm looking for: 17/07/19 - Sum = 190302 18/07/19 - Sum = 190583 19/07/19 - Sum = 190703 Views.py def networkOverview(request): GolemDatadb2 = GolemData.history.aggregate(Sum('Node_Cores')) print(GolemDatadb2) return render(request, 'golemstats/networkOverview.html', { 'GolemData':GolemDatadb2, }) Template: <script> var timeFormat = 'DD-MM-YYYY'; var config2 = { type: 'line', data: { datasets: [{ label: "Lorem", data: [{%for h in GolemData %} { x: "{{ h.history_date|date:" d / m / Y " }}", y: {{ h.Node_Cores}} }, {% endfor %}], fill: false, borderColor: 'red' }, ] }, options: { responsive: true, title: { display: false, text: "Core count by day" }, legend: { display: false }, scales: { xAxes: [{ … -
Is there a way to use an active Bootstrap element as an input to a Django form?
I want to use a Bootstrap list group as seen here as a choice selection tool in a form. One of the list items in the said Bootstrap list can have an active attribute at a time. I was hoping to map that active attribute to a choice in a Django forms.ChoiceField, thus making the list into a radio button of sorts. -
Django App not compatible with buildpack: App not compatible with buildpack: https://.../python.tgz
I want to deploy my django application on Heroku. But it seems impossible. after git push heroku master it says: Counting objects: 99, done. Delta compression using up to 4 threads. Compressing objects: 100% (97/97), done. Writing objects: 100% (99/99), 2.51 MiB | 98.00 KiB/s, done. Total 99 (delta 22), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to mammadovs. remote: To https://git.heroku.com/mammadovs.git Although, I didn't forget declaring heroku buildpacks:set heroku/python -
How to change data in database by clicking a button in HTML with Django
I have a mini project with Django. I have just a model with a counter total : class Reponse(models.Model): total = models.IntegerField() I have this view: def questions(request): _reponse = get_object_or_404(Reponse, id= 1) return render(request, 'vautmieux/test.html', {'reponse': _reponse}) And my HTML test display the variable total: <p id="block1"> {{reponse.total}} </p> My question is : I would like when I click on a button in the HTML, the variable total increases by 1. How can I do that ? With a form POST or GET ? May be there is a better method ? -
Why I'm receiving this an error TemplateDoesNotExist?
I'm receiveng this an error and I can't figure out why: TemplateDoesNotExist at /products/ products/product_list.html My code: #from django.views import ListView from django.views.generic import ListView from django.shortcuts import render # Create your views here. from .models import Product class ProductListView(ListView): queryset = Product.objects.all() tempalate_name = "products/list.html" def get_context_data(self, *args, **kwargs): context = super(ProductListView, self).get_context_data(*args, **kwargs) print(context) return def product_list_view(request): queryset = Product.objects.all() context = { 'qs': queryset } return render(request, "products/list.html", context) As you can see, I have nowhere mentioned a path: products/product_list.html, I'm using products/list.html. How can I troubleshoot this issue? -
How to change QS structure in Django?
Currently, my QS is like this: Great Expectations Bookstore 1 $8.99 Great Expectations Bookstore 2 $12.99 Great Expectations Bookstore 3 $6.99 Tales from the Crypt Bookstore 1 $5.99 The Sisterhood of the Traveling Pants Bookstore 3 $8.99 Oprah: The Icon Bookstore 2 $6.99 Oprah: The Icon Bookstore 3 $9.99 I'd like to create a QS or just a dictionary that I could pass to my view that looks like this: Great Expectations, 3, {price1: $6.99, price2: $8.99, price3: $12.99} Tales from the Crypt, 1, {price1: $5.99} The Sisterhood of the.., 1, {price1: $6.99} Oprah: The Icon, 2, {price1: $6.99, price2: $9.99} Basically I don't care about the bookstore that it's sold at and want to compress the QS into just book titles with a dictionary or tuple of prices. It would be preferable if I could order those prices from min to max in the dictionary. -
Django Tests Against a Read Only Database
I'm looking for some best-practice advice on how to go about writing tests in this specific scenario I have. I've got a Django API that runs against a postgres database (which I have control over on my server) as well as a remote read-only MySQL database. The read-only db is provided by an external service, and they do provide a pretty liberal API for writing data to their database (so we overwrite our .save method to write to the API, rather than using the database directly), but this is all production data, so not something I want to mess with for tests. Do people have thoughts on how to organize this project so that it sets up a similar MySQL database, or just continuously mocks every write (in a way that writing API endpoint integration tests are still do-able). Happy to provide more details if needed. -
Is there any way i can render template and at the same time use django restful framework together
Is there any way i can render template and at the same time use django restful framework because i want to render template and give restful api at the same time in django using function views -
Why doesn't the first ModelFormSet pick up the id from request.POST?
I'm trying to add multiple of a ModelForm using the ModelFormSetFactory. Upon submission the first of the set returns an error saying "(Hidden field id) This field is required." even though the hidden id field is in the form. For any further forms in this set, this error does not occur and the id can be found in the cleaned_data. The view for this form (in views.py): class NewRecipeView(generic.TemplateView): def get(self, request, *args, **kwargs): ingredient_data = { 'ingredient-TOTAL_FORMS': '0', 'ingredient-INITIAL_FORMS': '1', } context = {"new_page": "active", "form": RecipeForm(), "formset_ingredient": RecIngFormSet(ingredient_data, prefix="ingredient"), } return render(request, 'recipes/new_recipe.html', context) def post(self, request): form = RecipeForm(request.POST) formset_ingredient = RecIngFormSet(request.POST, prefix="ingredient") print(request.POST) for fs in formset_ingredient: print(fs) print(fs.cleaned_data) if form.is_valid() and formset_ingredient.is_valid(): new_rec = form.save(commit=False) new_rec.created_at = timezone.now() new_rec.save() for fs in formset_ingredient: new_rec_ing = fs.save(commit=False) new_rec_ing.recipe = new_rec new_rec_ing.save() return HttpResponseRedirect(reverse('recipes:recipe', args=(new_rec.id,))) else: print('handle invalid forms here') And the actual form in forms.py: class RecipeIngredientForm(forms.ModelForm): class Meta: model = RecipeIngredient fields = ['quantity', 'unit', 'ingredient'] recIngFormSet = modelformset_factory(RecipeIngredient, RecipeIngredientForm) In the HTML I am building the form from {{ formset_ingredient.empty_form }} with javascript and making sure that I follow the rules set in {{ formset_ingredient.management_form }}. I think this bit is fine as the … -
Slices vs queryset in django
It all started with me trying to apply slices to a queryset to limit it. As I understand the documentation it is supposed to limit the results to 10 entries: def get_queryset(self, *args, **kwargs): qs = Message.objects.all() qs = qs.filter(Target_id=self.dialog)[:10] # here the limit qs = qs.annotate(sender_id=Max('Sender__id')) return qs But really in template the request returns me all the records, but applies the annotation only to the first 10. I do not know why. I thought the whole reason was annotate. Then I remove the last line (with annotate). However I got in the template all the records instead of 10. That is same result as if I didn't make the slice. In my template I'm not doing anything unusual: the iteration over the my queryset: {% for message in messages %} {{message}} {% endfor %} This is weird: if I take len(qs) in my view, I get 10! But in template I get 300! It doesn't fit in my head. I tried also to apply slice in the template instead of my view: {% for message in messages|slice:":10" %} But nothing has changed. I have got all messages in my template instead of 10. How could this be? PS: … -
How to Extend The User Model with field of another class in django?
i want make an extend of the User Model with field from another class (structure in models.py in immob app) in django ,i will show you my project -
what mean the error local variable 'instance' referenced before assignment
i am trying to get values from the views.py function into the html template but the system crash and display this error : local variable 'instance' referenced before assignment views.py def update(request,pk): #deny anonymouse user to enter the detail page if not request.user.is_authenticated: return redirect("login") else: if request.method == "POST": instance = get_object_or_404(suspect,pk=pk) print(suspect) context = { "title":instance.suspect_name, "instance":instance, } return render(request,'blog/update.html',context) update.html {{instance.id}} its just a test because what i want is to be able to update form based on the id so i am trying to get the id of the object. i will appreciate any help -
Threading.py in python while running server for django project
This is the error message shown up while running server for django project in pycharm,I didn`t find what kind of error is this.. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Ashish Attri\AppData\Local\Programs\Python\Python35\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\Ashish Attri\AppData\Local\Programs\Python\Python35\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) My Threading.py file is provided below: Please help me out of this.... THIS IS THE STARTING OF A CODE: import sys as _sys import _thread from time import monotonic as _time from traceback import format_exc as _format_exc from _weakrefset import WeakSet from itertools import islice as _islice, count as _count try: from _collections import deque as _deque except ImportError: from collections import deque as _deque AND THIS IS THE ERROR PART OF A CODE: def _bootstrap_inner(self): try: self._set_ident() self._set_tstate_lock() self._started.set() with _active_limbo_lock: _active[self._ident] = self del _limbo[self] if _trace_hook: _sys.settrace(_trace_hook) if _profile_hook: _sys.setprofile(_profile_hook) try: self.run() except SystemExit: pass except: -
Passing csv data from views to template
I've been stuck on this problem for some time now. It's pretty simple, and I bet there's a simple solution for this. I'm able to read the csv file pretty easily, and just to test if everything is working, I print the data from the csv file on the cmd line. The prooblem is that I'd like to, instead of printing it out, send everything to the template (book/r.html) so I can graph it later (using chart.js). # views.py def rtest(request): url = staticfiles_storage.path('dat.csv') with open(url, 'r') as csv_file: csv_reader = csv.reader(csv_file) for line in csv_reader: print(f'value: {line[3]} & year:{line[4]}') return render(request, 'book/r.html') Each line has the following format: ['59', 'US', 'United States', '3007.12344537862', '1960'] And I'm only interested in the last two values. I believe I need to use a dictionary as context to send this data through the view function, but I have no idea how I'd that. If I can do something like {{ context.value }} and {{ context.year }} on my r.html would be awesome, but my final goal is to graph these values (value y-axis, year x-axis). Any help is appreciated, thank you! -
How to automate object adding in the django model?
I have the model for a team object. I want to add objects in this models by parsing. So, I have parsing code in the views.py. How can I do adding of that data in the model in the views.py. Should I use queryset or something like that? As I know there is approach to add objects using Django shell. But is it possible to add objects automatically? While the project is deployed on a hosting it is not possible to use Django shell. I tried to use manual adding using lists and dictionaries as the variable during template rendering. from django.shortcuts import render from django.views.generic import TemplateView from bs4 import BeautifulSoup from urllib.request import urlopen def homePage(request): tn = [] ti = [] for team in teamList: tn.append({'name': team}) for img in imgList: tn.append({'img': img}) teamDict = { 'team': tn, 'matchLink': linkSrc, 'img': tn, } return render(request, 'home.html', teamDict) # Parser try: html = urlopen("//some url//") except: print("Connection problems") teamList = [] imgList = [] bsObj = BeautifulSoup(html, "lxml") futMatches = bsObj.find("div", {"class": "esport-match-future-list"}) for link in futMatches.find_all("div", {"class": "esport-match-single"}): linkTag = link.find("a", {"class": "team-vs-team"}) if "tbd" not in linkTag.attrs["href"]: teamDiv = linkTag.find_all("div", {"class": "team"}) for item in teamDiv: … -
Django: SELECT JsonField AS new_name?
I have a table, in which some attributes are columns, and some are implemented as a postgres JsonField. For the columns, I can write eg Product.objects.values(brand=F('brand_name')) for implement a SELECT brand_name AS brand query. I need to do something similar for a JsonField, eg Product.objects.values(color=F('jsonproperties__color')) However, the F expressions do not work correctly with JsonFields, and there doesn't seem to be a fix coming anytime soon. How could I work around this? -
Sharing database definitions (models.py) across two separate django projects
Say you want to share some model definitions across two separate django projects, living in two different workspaces. How would you go about this? May models.py be "linked" as done in java from one project to the other? May the models.py live in a separate "libarary"? or does that requires use of pip?! Am I forced to put the two project in the same workspace? Copy the definition over once it changes ... Is there a best practice around this? -
How to interpret/render template tags as HTML from Django database
I'm trying to add posts with images from Django admin site, but the safe/autoescape-off filter cannot interpret Django's template tags. My input and page look like: "copy image address" gives http://127.0.0.1:8000/%7B%%20static%20'post/image.jpg'%20%%7D My view inherits from a generic ListView. My base.html and post_list.html: <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <div style="color: red;"> <a href="{% url 'admin:index' %}">admin</a> {% block contents %} {% endblock %} </div> </body> </html> {% extends 'post/base.html' %} {% block contents %} {% for post in object_list %} {% autoescape off %}{{ post.text }}{% endautoescape %} {{ post.text|safe }} {% endfor %} {% endblock %} -
Ipd matching query does not exist in Django
I am trying to get objects from ForeignKey using QS but I can't seem to find a problem models.py : class Patient(models.Model): name = models.CharField(max_length=200); phone = models.CharField(max_length=20); address = models.TextField(); Patient_id = models.AutoField(primary_key=True); Gender= models.CharField(choices=GENDER,max_length=10) consultant = models.CharField(choices=CONSULTANT,max_length=20) def __str__(self): return self.name class Ipd(models.Model): reason_admission = models.CharField(max_length=200, blank=False) presenting_complaints = models.CharField(max_length=200,) ipd_id = models.AutoField(primary_key=True) rooms = models.ForeignKey(Rooms,on_delete=models.CASCADE, blank=False) date_of_admission = models.DateField(("Date"), default=datetime.date.today) patient = models.ForeignKey(Patient,on_delete=models.CASCADE,blank=False,default = " ") def __str__(self): return self.patient.name views.py: @login_required def ipd (request,patient_id): formtwo = IpdForm() qs = Ipd.objects.get(patient=patient_id) if request.method=="POST": formtwo = IpdForm(request.POST) if formtwo.is_valid() : instance = formtwo.save(commit=False) instance.save else: return HttpResponse(formtwo.errors) else: formtwo = IpdForm() return render(request, 'newipd.html', {'a':qs,'form2':formtwo}) html : Name : {{a.name}} Phone : {{ a.phone }} Address : {{ a.address }} Gender : {{ a.Gender }} -
how can i make a functional feedback view in Django?
i have a view where users can provide feedback by filling a form which will send emails.The idea is that the app also sends emails for confirming emails and resetting passwords and stuff. forms.py subjects = ( (1,'Bug/error reporting'), (2,'Enhancement suggestion'), (3,'Support and help'), (4,'General feedback') ) class ContactForm(forms.Form): name = forms.CharField(max_length=180) email = forms.EmailField(required=True) subject = forms.ChoiceField(choices=subjects,required=True) message = forms.CharField(widget=forms.Textarea(attrs={"rows":9, "cols":20})) views.py def emailView(request): user = request.user initial_data = { 'name' : user.first_name, 'email' : user.email, } if request.method == 'GET': form = ContactForm(initial=initial_data) return render(request, "email.html", {'form': form}) else: form = ContactForm(request.POST,initial=initial_data) if form.is_valid(): name = form.cleaned_data['name'] subject = form.cleaned_data['subject'] from_email = form.cleaned_data['email'] message = form.cleaned_data['message'] message_f = name + 'has the following complaint \n' + message try: send_mail(subject, message_f, from_email, ['admin@example.com'],fail_silently=True) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "email.html", {'form': form}) but i don't thinks this is functional as it returns error for invalid username and password from the dummy data i provided the settings.py with. I think that the problem is that i have to use other function for sending mails with other email backends. -
is there is a solution for urls issues
I am building a web app using django and I get an error, I couldn't figure out what is the problem behind it. I have three models( Category, SubCategory, Article) in my url I want something like that (localhost:8000/categories/Id_category/Id_subcategory) the url (localhost:8000/categories/Id_category) worked perfectly but (localhost:8000/categories/Id_category/Id_subcategory) didn't work I get this error enter image description here So here is my code that I tried to make it: #views.py def categorie(request): Catégorie_list=Catégorie.objects.all() context = { 'Catégorie_list':Catégorie_list, } return render(request,'articles/Category.html',context) def souscategorie(request,categoryID): SousCatégorie_list=SousCatégorie.objects.order_by('désignation').filter(Catégorie_identifiant_id=categoryID) name_category=Catégorie.objects.get(id=categoryID) articles=Article.objects.select_related('Sous_Catégorie__Catégorie_identifiant').filter(Sous_Catégorie__Catégorie_identifiant_id=categoryID) context = { 'SousCatégorie_list':SousCatégorie_list, 'name_category': name_category, 'articles':articles } return render(request,'articles/SubCategory.html',context) def articl(request,categoryID,articleID): return render(request,'articles/article.html') #articles/urls.py urlpatterns=[ path('',views.categorie, name='Category'), path('<int:categoryID>/',views.souscategorie, name='SubCategory'), path('<int:categoryID>/<int:articleID>/',views.articl, name='article'), path('search',views.search, name='search'), ] #my template <div class="row"> {% if articles %} {% for article in articles %} <div class="col-lg-4 col-md-6 mb-4"> <div class="card h-100"> <a href="#"><img class="card-img-top" src="{{ article.photo_main.url }}" alt=""></a> <div class="card-body"> <h4 class="card-title"> <a href="{% url 'article' name_category.id article.id %}">{{ article.désignation }}</a> </h4> <h5>{{ article.Sous_Catégorie }}</h5> <p class="card-text">{{ article.Description }}</p> </div> <div class="card-footer"> <h6 class="text-muted">Ajouter au panier</h6> </div> </div> </div> {% endfor %} {% else %} <a class="list-group-item"> Aucune sous catégorie disponible</a> {% endif %} </div> -
Object does not exist error: User has no profile
I am trying to create two forms to update the user profile, but I keep getting the error: django.contrib.auth.models.User.profile.RelatedObjectDoesNotExist: User has no profile. I do not know where I am going wrong! My code is as follows: My profile.html {% extends "apotofgold/base.html" %} {% load crispy_forms_tags %} {% load avatar_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{% avatar user %}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Profile Info</legend> {{ u_form|crispy }} {{ p_form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Update</button> </form> </div> {% endblock content %} My forms.py from django import forms from django.contrib.auth.forms import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegistrationForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username','email','password1','password2'] class UserUpdateForm(forms.ModelForm): class Meta: model = User fields = ['username','email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] My models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __sr__ (self): return f'{self.user.uMy mpodsername} Profile' My signals.py from djamgo.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import …