Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UI for Machine Learning results in Python
I have been working in a project for last 3 months, I have done my analysis over a number of financial datasets such as stock market predictions, I used a number of feature selection techniques and a bunch of algorithms as well. I use Jupyter environment for Python for my analysis and to display my results such as prediction charts, I go for Ipython Dashboard. But,this is not what actually I want. I can run those all things, but now I want to make all my work compiled within a tool that an individual from financial background can use my tool to analyze the datasets. I want to make all my feature engineering and algorithms available in that tool. Broadly Speaking. The following are my requirements. User open the tool. Select the dataset. (The dataset will always be in the same format as the requirement of our model) User selects the training and testing dates User chooses the feature selection techniques and extracts the features. User choose the particular algorithm. User also able to choose the parameters of that particular algo. Results are displayed in UI manner. Test Results are saved. Finally, the user is happy. ;-) See, I have … -
Get related cousin model in a template
I'm struggling finding docs or examples how to get data from a cousin related model. So if the models look like this: class Part(models.Model): name = models.CharField(max_length=550) class Quantity(models.Model): quantity = models.DecimalField(max_digits=10, decimal_places=2) part = models.ForeignKey('Part', related_name='quantity_part') stockarea = models.ForeignKey('StockArea', related_name='quantity_stockarea') class Stock(models.Model): name = models.CharField(max_length=550) class StockArea(models.Model): area = models.CharField(max_length=550) stock = models.ManyToManyField(Stock, related_name='stockarea_stock') def __str__(self): return self.area And in the view I get the part like this: def details(request, part_id): part = get_object_or_404(Part, pk=part_id) context = { 'part': part, } return render(request, 'part/details.html', context) Finally template trying to display the data: {% for a in part.quantity_part.all %} {{ a.quantity }} pcs Find part in area: {{ a.stockarea }} in stock: {{ part.stockarea.stock.name }} {% endfor %} You see how I try to get the name of the stock. I can't figure out how to be able to get hold of the name of the stock. I have a path there from the part. Part have a related_name to the Quantity model called quantity_park. And in the model Quantity I have a relation to model StockArea. And from there I have a relation to model Stock. Guidance is much appreciated =) Maybe I'm totally doing this backwards. Maybe I'm … -
How to get the username from django.contrib.auth (Django built-in login system)?
I am very new to Python and Django, and am looking at a code that uses the Django built-in login system (django.contrib.auth.login). After the user has logged in, I would like to redirect the user to an appropriate URL based on the users privilege. For example, some usernames have admin privileges, while some are just regular users. However, after the "login" button is clicked, the user is always redirected to the same URL. In order to redirect the user differently, I would have to check the username, and check what privileges that user has. However, I can not find any way to fetch the username from django.contrib.auth.login. It is as if the username just disappears after it has been authenticated. Does anyone know how to solve this problem? Thank you! -
add oscar feature to djnago app in google cloud platform
I would like to use Oscar in my Django app at google cloud platform. in the configuration in app.yaml file I have a 'skip_files' tag: - ^env/.*$ But, the oscar installation is in \env\Lib\site-packages\oscar directory. therefore I get the error: "ImportError: No module named oscar.defaults". When I erase this tag I get the error: "ERROR: (gcloud.app.deploy) Error Response:[400] This deployment has too many files." Tried to include as library but this library is not supporeted. Therefore thought maybe to use a regular expression to skip all files not including "oscar" in it, (referencing Regular expression to match a line that doesn't contain a word?). But it doesnt work for me. Please someone can tell me how to solve this? maybe I wrote the regex incorrectly? (This is after I chose working with oscar at my website, but maybe better choosing another platform?) Thank you. -
Detect if model has been added as foreign key to some other model
Say I have some model instance A1 and existing models B1 and B2 have A1 as a foreign key field fk. Is there a way for the model instance A1 to know that another newly created model instance B3 has assigned it as it fk field (without having to set some kind of counter every time a model B uses A1 as its fk and tracking the counter changes)? Ultimately, I'd like behavior similar to how users are notified of new answer or comment (say model B instance) when other users post to their questions (say model A instance). Any advice on doing this efficiently would be appreciated. Thanks :) -
Set Django REST Frmework JWT in cookies
I am using djangorestframework-jwt to authenticate users. I have overridden the builtin JSONWebTokenAPIView to return user details in the response as well. And I am also setting the token in cookies in my view. def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): user = serializer.object.get('user') or request.user token = serializer.object.get('token') response_data = { 'access_token': token, 'user': UserInfoSerializer(user).data } response = Response(response_data, status=status.HTTP_200_OK) if api_settings.JWT_AUTH_COOKIE: expiration = (datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA) response.set_cookie(api_settings.JWT_AUTH_COOKIE, response.data['access_token'], expires=expiration, httponly=True) return response return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) It works fine on Django server. I can see the token in cookies when I verify the api using REST browseable api view. But my frontend (React) app is running on localhost:3000 and when i hit this api from my frontend server I receive the success response but token is not being set in the cookies. Do I need to set the cookie domain as well? -
Django: Query Database
Here's my model, class Question(models.Model): ... timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) How can I filter out the Questions asked in last 14 hours? Thank You :) -
Django authentication LDAP and token management locally
I am trying to use LDAP to authenticate my users. In addition, I would like to manage the tokens. I am assuming I can't do that using ldap (correct me if I am wrong), so I am trying to find an alternative using Django. Currently, I am creating a dummy mirror user on my system with a default 'abcd1234' password. Once the ldap authenticates the user, my code uses the Django auth module to authenticate the mirror user locally and give him a token that is managed in my app with a timeout. I am sure there must be a better way, my management is double. -
Django, apidoc js What to add in a PUT method?
I have read the apidoc.js documentation and i have a dilemma. I don't exactly know the difference between @apiParam and @apiSucces, the documentation doesn't explain properly what they really do. For example i have a get and a put with these parameters in the get: I am using apidoc in django and this is my view: class LocationView(APIView): """ @api {get} /locations/:id/ Location id - details @apiName GetLocation @apiGroup Locations @apiParam {integer} [id] Location id. @apiParam {string} [name] Location name. @apiParam {object} [company] Company name. @apiParam {string} [website] Location website. @apiSuccess {object[]} results List with location details """ serializer_class = LocationSerializer permission_classes = (IsAuthenticatedOrReadOnly,) def get_object(self, pk): try: return Location.objects.get(pk=pk) except Location.DoesNotExist: raise Http404 def get(self, request, pk): serializer = LocationSerializer(self.get_object(pk)) return Response(serializer.data) def put(self, request, pk): location = self.get_object(pk) serializer = LocationSerializer(location, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk): location = self.get_object(pk) location.save() return Response(status=status.HTTP_204_NO_CONTENT) I want to create the put apidoc. What do i have to write in it for modifying? Do i have to write every parameter again? or use apiSuccess? An example would be great. -
Globally getting context in Wagtail site
I am working on a Wagtail project consisting of a few semi-static pages (homepage, about, etc.) and a blog. In the homepage, I wanted to list the latest blog entries, which I could do adding the following code to the HomePage model: def blog_posts(self): # Get list of live blog pages that are descendants of this page posts = BlogPost.objects.live().order_by('-date_published')[:4] return posts def get_context(self, request): context = super(HomePage, self).get_context(request) context['posts'] = self.blog_posts() return context However, I would also like to add the last 3 entries in the footer, which is a common element of all the pages in the site. I'm not sure of what is the best way to do this — surely I could add similar code to all the models, but maybe there's a way to extend the Page class as a whole or somehow add "global" context? What is the best approach to do this? -
Fixture not loading in Django
Settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) FIXTURE_DIRS = ( os.path.join(BASE_DIR, '/deals/fixtures/'), ) test_deals.py: import unittest from deals.models import Retailer import django.test class TestRetailer(django.test.TestCase): def setUp(self): fixtures = ['deals_test_data.json'] self.bestbuy = Retailer(Retailer.objects.get(pk=1)) def test_name(self): self.assertEqual(self.bestbuy.name, 'Best Buy US') Project structure: project - deals - fixtures - test_deals_data.jason - tests - test_deals.py Error: Traceback (most recent call last): File "/home/danny/PycharmProjects/askarby/deals/tests/test_deals.py", line 10, in setUp self.bestbuy = Retailer(Retailer.objects.get(pk=1)) File "/home/danny/.virtualenvs/AskArby/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/danny/.virtualenvs/AskArby/lib/python3.5/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name deals.models.DoesNotExist: Retailer matching query does not exist. Destroying test database for alias 'default'... Process finished with exit code 1 I've tried not using FIXTURES_DIR but instead using fixtures=['../deals_test_data.jason']. I've tried removing the slashes at the front and back of the string in my FIXTURES_DIR. No joy. How can I make my fixtures load? -
How to develop web Unix terminal using Python3 [on hold]
i am developing free online python tutorial. can somebody assist me what are the library i can use to develop web Unix console using python & django. -
Spyne - change name of part in wsdl message "wsdl:part"
in my case, in order to keep conformance with some existing SOAP client "name" of "part" in "message" element of WSDL needs to be "parameters" like here <wsdl:message name="Notify"> <wsdl:part name="parameters" element="tns:Notify"/> </wsdl:message> <wsdl:message name="NotifyResponse"> <wsdl:part name="parameters" element="tns:NotifyResponse"/> </wsdl:message> Currently I don't see any way of doing that in Spyne. I went through documentation, source code and it seems that WSDL generator always takes the same value for "name" of "part" as for "name" of whole "message" (spyne/interface/wsdl/wsdl11.py) def add_messages_for_methods(self, service, root, messages): for method in service.public_methods.values(): self._add_message_for_object(root, messages, method.in_message, method.in_message.get_element_name()) (...) def _add_message_for_object(self, root, messages, obj, message_name): (...) message = SubElement(root, WSDL11("message")) message.set('name', message_name) (...) for obj in objs: part = SubElement(message, WSDL11("part")) part.set('name', obj.get_element_name()) part.set('element', obj.get_element_name_ns(self.interface)) So basically "name" for "message" message_name is method.in_message.get_element_name() and that's the same case for "name" in "part" as obj.get_element_name() -> method.in_message.get_element_name() However, in Python I've never done anything larger then 3 lines of code and it took my a while to understand all of this (Swift/Objc programmer here) I might be missing something and maybe there's some nice easy method to do that ? As a quick and poor hack/workaround I've just changed part.set('name', obj.get_element_name()) into part.set('name', 'parameters') and in my case … -
How make a get request with an atribute from another class in Django?
Basically i want to make a get method that when filled with a ID from a Person, list all the addresses of that person in json format. Already tried many other methods but none came close from django.db import models from django.core.validators import RegexValidator # Create your models here. class Address(models.Model): zipcode = models.CharField(max_length=8) state = models.CharField(max_length=100) city = models.CharField(max_length=100) street = models.CharField(max_length=100) number = models.IntegerField() person_id = models.ForeignKey('Person', on_delete=models.CASCADE, related_name="addresses") class Person(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() -
Homepage in Django isn't working
I'm currently trying to create a homepage for Django, but when I test it, it just shows me a blank page with nothing on it. This is what I have so far. First is my URL page from mysite: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'',include('firstapp.urls')), ] and my url page from firstapp: from django.conf.urls import url from firstapp.views import HomePage urlpatterns = [ url(r'^$', HomePage.as_view(), name='home'), ] this is my views page: from django.shortcuts import render from django.views.generic import TemplateView class HomePage(TemplateView): template_name = 'home/home.html' def home(request): return render(request, self.template_name) this is the base.html which extends to home.html {% load staticfiles %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Home</title> <link rel='stylesheet' href='{% static "css/base.css" %}'/> </head> <html> <p>{{ variable }}</p> <script src= '{% static "js/base.js" %}'></script> </body> </html> And finally home.html itself. {% extends 'base.html' %} {% block body %} <div class="container"> <p>Testing Home</p> </div> {% endblock %} Now if it works, I should be seeing "Testing Home"...but...I see nothing. I just get an empty white page. Any idea why this is happening? -
Django SMTPServerDisconnected error on password reset (but works elsewhere)
I'm trying to set up self-serve password resets on a django setup. I have configured it to use the in-built password reset system, and have tested everything on my dev machine, and works fine. However, in production (i.e. actually sending emails), when I try to get a password reset email, it throws an SMTPServerDisconnected error: [22/Sep/2017 15:04:59] ERROR [django.request:256] Internal Server Error: /password_reset/ Traceback (most recent call last): File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/utils/decorators.py", line 145, in inner return func(*args, **kwargs) File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/utils/decorators.py", line 110, in _wrapped_view response = view_func(request, *args, **kwargs) File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/contrib/auth/views.py", line 182, in password_reset form.save(**opts) File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/contrib/auth/forms.py", line 256, in save html_email_template_name=html_email_template_name) File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/contrib/auth/forms.py", line 213, in send_mail email_message.send() File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/core/mail/message.py", line 303, in send return self.get_connection(fail_silently).send_messages([self]) File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 107, in send_messages sent = self._send(message) File "/srv/virtualenvs/sis_esv/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 123, in _send self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n')) File "/usr/lib/python2.7/smtplib.py", line 735, in sendmail self.rset() File "/usr/lib/python2.7/smtplib.py", line 469, in rset return self.docmd("rset") File "/usr/lib/python2.7/smtplib.py", line 394, in docmd return self.getreply() File "/usr/lib/python2.7/smtplib.py", line 368, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") SMTPServerDisconnected: Connection unexpectedly closed I'm using G-Suite (Google) as the SMTP relay; the settings I'm using are: EMAIL_HOST = 'smtp-relay.gmail.com' EMAIL_PORT … -
best way to send files to GCS with Django
what is the best way to send files to Google cloud storage with django. this moment I'm getting the file with a post method file = request.FILES['image'] but when I try to send to GCS from google.cloud import storage client = storage.Client(projectName) bucket = client.get_bucket(bucketName) blob = bucket.blob(fileName) blob.upload_from_filename(file) I get this erros InMemoryUploadedFile so I have to save the file in a temp and after that send to GCS, but it is slow. -
TemplateDoesNotExist at / What is wrong?
I got an error,TemplateDoesNotExist at / app/index.html or index.html . app(child app) is in testapp(parent app),and app has index.html・urls.py・views.py .urls.py of app is from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] views.py of app is from django.shortcuts import render def index(request): return render(request, 'app/index.html') urls.py of testapp is from django.conf.urls import include, url from django.contrib import admin from app.views import index urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', index, name='index'), ] render's argument of views.py in app was changed into 'index.html',but same error happens.What is wrong?(the way to write directory?) How should I fix this? -
Best Practices for retrieving Django Model Fields that may be "None"
I have a Django model that looks something like this : class Candidate(models.Model): first_name = models.CharField(max_length=30, blank=True, null=True) middle_name = models.CharField(max_length=30, blank=True, null=True) last_name = models.CharField(max_length=30, blank=True, null=True) current_job = models.ForeignKey( Job, on_delete=models.SET_NULL, blank=True, null=True, default=None, ) I get an instance of "Candidate", and try to save some of the values into a dictionary candidate = Candidate.objects.get(first_name = "John") data['first_name'] = candidate.first_name data['last_name'] = candidate.last_name data['company_name'] = candidate.current_job.company This works fine when all values and foreign-keys are properly populated. However, when any of the values of the fields are None, especially important regarding the ForeignKey relationships, I'll hit an AttributeError, something like : 'NoneType' object has no attribute 'company' I want to properly handle the "None" case for any Field in the Model. I've found these two work-arounds for it right now, but neither seem satisfactory to me. A) I can put a try-except around EACH and EVERY field (which doesn't seem correct as my models get to ~20 fields) try: data['first_name'] = candidate.first_name data['last_name'] = candidate.last_name except: pass try: data['company_name'] = candidate.current_job.company B) I can convert the instance to a dict like this and use a .get() since that never raises an Exception. candidate_dict = candidate.__dict__ data['first_name'] = candidate_dict.get('first_name') … -
django Markdown problems
Django:1.11.5 Python:3.5.2 Markdown 2.6.9 Code picture Code picture Django Version: 1.11.5 Exception Type: AttributeError Exception Value: 'DeferredAttribute' object has no attribute 'strip' Exception Location: /usr/local/lib/python3.5/dist-packages/markdown/init.py in convert, line 355 Python Executable: /usr/bin/python3 Python Version: 3.5.2 Python Path: ['/data/mysite', '/usr/local/bin', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-i386-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages'] Do not know where there is a problem. Remove Post.content = markdown.markdown (Post.content), show normal! -
Django 1.9 form not valid
I try to make simple form: class ContactUsForm(forms.Form): name = forms.CharField(label=(u'Name')) phone = forms.CharField(label=(u'Phone')) email = forms.CharField(label=(u'E-mail')) here is html of this form: <form action="/contact_us/" method="POST"> {% csrf_token %} {{contact_us.errors}} {{contact_us}} <input type="submit" class="button" value="Submit"> </form> And here is the view of action: def contact_us(request): if request.POST: form = ContactUsForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] phone = form.cleaned_data['phone'] mail = form.cleaned_data['email'] return HttpResponseRedirect('/thanks/') else: return HttpResponse(form.errors) else: form = ContactUsForm() return HttpResponseRedirect('/') I don't know why, but my form always not valid. Can you help me with it? Thanks a lot. -
how to update another field on admin django
models.py Good night friends, I would like to know if there is a possibility that every time I register a new move, the django administrator checks what is a 'hydrographic region' and adds the value that is entering with the 'balance_box'. class Movement(models.Model): TYPE_MOVE = ( ('1', 'Receita'), ('2', 'Despesa'), ) regiao_hidrografica = models.ForeignKey(RegiaoHidrografica, verbose_name="Região Hidrografica", null=False) origem = models.ForeignKey(Origem, verbose_name="Origem", null=False) finalidade_recurso = models.ForeignKey(FinalidadeRecursos, verbose_name="Finalidade de Recursos", null=True) descricao = models.TextField("Descrição", null=True) valor = MoneyField(max_digits=10, decimal_places=2, default_currency='BRL') data_refencia = MonthField("Data de Referencia", help_text="Informe mês e ano") # data_refencia = models.DateField("Data de Referencia", null=True, blank=True, default=None) tipo_movimento = models.CharField(max_length=1, default=1, choices=TYPE_MOVE) def __str__(self): return self.descricao def update_total_valor(self): total = 0 self.movimento_set: total += mov.valor self.saldo_caixa = total self.save() class RegiaoHidrografica(models.Model): name = models.CharField("Nome", max_length=100, null=False) sigla = models.CharField("Sigla", max_length=10, null=True) taxa_inea = models.IntegerField(default=10, null=True) taxa_trans = models.IntegerField(default=0, null=True) saldo_caixa = MoneyField('Saldo em caixa estimado', max_digits=10, decimal_places=2, null=True, default=0, default_currency='BRL') saldo_cc = MoneyField('Saldo em conta estimado', max_digits=10, decimal_places=2, null=True, default=0, default_currency='BRL') def __str__(self): return self.name I tried something like this, create this method in the 'class MovimentoAdmin(admin.ModelAdmin)', but it did not work. admin.py def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) for instance in instances: instance.save() formset.save_m2m() instance.RegiaoHidrografica.update_total_valor() Would anyone … -
TypeError: 'NoneType' object is not subscriptable followed by AttributeError: 'NoneType' object has no attribute 'split'
Using django. I have the following model: class Postagem(models.Model): id = models.AutoField(primary_key=True, editable=False) descricao = models.CharField(max_length=50) area = models.ForeignKey('core.Area', null=True) user = models.ForeignKey('User') categoria = models.CharField(max_length=50, null=True) post = models.FileField(upload_to='posts/', null=True) thumbnail = models.FileField(upload_to='posts/', null=True) def __str__(self): return self.descricao The Following form: class PostForm(forms.ModelForm): categoria = forms.ChoiceField(choices=[("Video","Vídeo"),("Audio","Aúdio"),("Imagem","Imagem"),("Musica","Música")], required=True) thumbnail = forms.FileField(required=False) class Meta: model = Postagem fields = ['descricao', 'area', 'user', 'post'] View: def profileView(request): context = getUserContext(request) if request.method == 'POST': exception=None userDict = {} userDict["user"] = context["user"].id if "categoria" in request.POST: newPost = request.POST.copy() newPost.update(userDict) form = PostForm(newPost,request.FILES) print("postform POST: ",newPost, " File ",request.FILES) if form.is_valid(): print("valid") try: form.save() print("saved") return HttpResponseRedirect(reverse_lazy('accounts:profile')) except IntegrityError as e: print("Integrity Error") exception=e else: print("PostForm error") print(form.errors) form.non_field_errors=form.errors if exception is not None: form.non_field_errors.update(exception) context['form']=form posts = Postagem.objects.get_queryset().order_by('id') paginator = Paginator(posts, 12) page = request.GET.get('page') context["areas"] = Area.objects.all() try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. posts = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. posts = paginator.page(paginator.num_pages) context["posts"]=posts return render( request, 'accounts/profile.html', context ) And at last the template: {% for post in posts %} {% if forloop.counter0|divisibleby:4 or forloop.counter0 == 0 %} … -
I am not sure my django app and LDAP work properly
Please help. I am not sure how my django app can work with LDAP server. I am attached here my project configuration for your references Thanks for all, Joe Nguyen [DC][1] [Login page][2] [configuration 1][3] [configuration 2][4] -
where clean garbage?? In TearDown or function's end?
Here is the story: when I request one view, the view will create some resource, now we need to clean it to let them not affect next test. (ps: garbage is something like directory or network device) class SomeViewTest(TestCase): def setUp(self): self.init_sth() def tearDown(self): self.clean_init_sth() # is there to clean the garbage?? def test_view(self): self.client.post(url, data={}) # here generate the garbage self.assertTrue() # is there to clean the garbage?? I think if put clean in tearDown, the clean will execute, even the view failed, it let me more convenient that not need to clean garbage manual.(for example, rm -rf /garbage_directory), but now setUp and tearDown is not equivalent create and destroy.