Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django save data once in a day to file after first script run
I'm a newbie in django. I'm providing some parsed content on a page from data, which was loaded from another web source via api. So, I'm wondering if there a way to load data one time in a day and then save it to a file, so my program will parse that data from a file for the rest of that day, not via api service? Where should I look for? -
How to stop calling dehydrate()
class Resource_1(ModelResource): def dehydrate(): some code class Resource_2(ModelResource): abc = ToOneField('Respurce_1') I have a resource which is referred by another resource by ToOneField, I didn't give full=true. then also dehydrate() method is getting called. but i dont want to call dehydrate() method. Somehow I don't want to call dehydrate method, I wrote a dehydrate method in that resource where I'm referring it by ToOneField, but then it is calling both of the dehydrate. -
How we can login by using email or phone number in django
This in my backends.py page but I don't think its working because I pass both email or phone number but its not login by phone number. from .models import UserModel from django.db.models import Q import logging class MyAuthBackend(object): def authenticate(self, email_or_phone_number=None, password=None): try: user = UserModel.objects.get(Q(email=email_or_phone_number) | Q(phone_number=email_or_phone_number)) if user.check_password(password): return user else: return None except UserModel.DoesNotExist: logging.getLogger("error_logger").error("user with login %s does not exists" % login) return None except Exception as e: logging.getLogger("error_logger").error(repr(e)) return None def get_user(self, user_id): try: user = UserModel.objects.get(sys_id=user_id) if user.is_active: return user return None except UserModel.DoesNotExist: logging.getLogger("error_logger").error("user with %(user_id)d not found") return None -
Django ImageField is not working with TemplateView
I am new to django. I am creating a simple webpage which has images and title of the images. I am practicing template view. I upload an image and title using django admin as a superuser and trying to show uploaded image and title in webpage, but image and title isn't showing in place of image alt name 'image' is showing. python3 django version 2.1.1 Here is my code. Thanks models.py from django.db import models class English_model(models.Model): img = models.ImageField(upload_to = 'media/', ) title = models.CharField(max_length=20) def __str__(self): return self.title views.py from django.contrib.auth.decorators import login_required from .models import English_model from django.views.generic.base import TemplateView, TemplateResponseMixin, ContextMixin class English(LoginRequiredMixin, TemplateView): model = English_model template_name = 'English/english.html' def get_context_data(self, *args,**kwargs): context = super(English, self).get_context_data(*args, **kwargs) context['English_model'] = English_model.objects.all() return context english.html <!doctype html> {% extends 'Base/basedemo.html' %} {% load static %} {% block content %} <div class="row"> <h1>TESTING TESING TESTING TESING TESTING TESING TESTING TESING TESTING TESING</h1> <div class="row"> <div class="col-md-3"> <img src="{{English_model.img}}" alt="image">{{English_model.title}} </div> </div> <div class="row"> <div class="col-md-3"> <img src="{{English_model.img}}" alt="image">{{English_model.title}} </div> </div> <div class="row"> <div class="col-md-3"> <img src="{{English_model.img}}" alt="image">{{English_model.title}} </div> </div> </div> {% endblock %} app urls.py from django.urls import path from PlayTrailer.views import English urlpatterns = [ path('english/', English.as_view(), … -
How decide which Database (SQLite OR MySQL,PostgreSQL) we will use in Django Project [on hold]
Hey everyone i know i asked a silly question but i'm new to Django i m trying to learn Django from last 2 months by making small projects , I searched alot different things. I already made a polls app in Django using Django ,I also made a book store app using Store app, and like this i made other projects too. But i noticed in every project we mainly use SQLite and there is always a line "we can also use more scalable database like MySQL,PostgreSQL etc.." ,I also searched alot for the reason why we use sqlite more in Django ,I also seached how to we decide which type databse is right for the Database.Before Starting Django and in present too i m working in PHP and in php we use mysqli. So Please anyone can help me in this to understand how we will decide the Database according too project. -
Hide invalid methods in Django Rest Framework Documentation View
If a set of methods, e.g. for creation, deletion, and update are only available for admin users, I want to be able to hide the method in the documentation view, but I have found no way to do so. Is this possible? class MyDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = MyObject.objects.all() authentication_classes = (SessionAuthentication, BasicAuthentication, TokenAuthentication) permission_classes = (permissions.IsAdminUser,) serializer_class = MySerializer -
Django business rules, how to compute variables from an API endpoint
I would just lke to ask this question. This is about django business rules ,Anyone had a vast knowledge regarding djnago business rules ? sources : https://github.com/venmo/business-rules : https://github.com/venmo/business-rules : https://pypi.org/project/django-business-rules/ Based on how django business rule works , they have what we call as variables that represents values on our system for example . Values are computed direct from the database , for example that " return self.product.current_inventory " , What i wanted to know is it possible that we can compute variables which is from an api endpoint for data from json object response where in ill be using http request and then based on the result then thats where i will use something to compute . Badly need your ideas guys. Thank You. And i think this would also help those people who are finding a good business rule engine. Thanks , if you dont fully understand how django business rule works i have provided links. lass ProductVariables(BaseVariables): def __init__(self, product): self.product = product @numeric_rule_variable def current_inventory(self): return self.product.current_inventory @numeric_rule_variable(label='Days until expiration') def expiration_days(self): last_order = self.product.orders[-1] expiration_days = (last_order.expiration_date - datetime.date.today()).days return expiration_days @string_rule_variable() def current_month(self): return timezone.now().strftime('%B') -
django session security popup on every page load
I have installed django-session-security 2.6.1 on Django 1.9 to log out inactive users after two hours. I have the following in my settings: INSTALLED_APPS = ( ... 'session_security', ... ] MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'intro.middleware.director.SiteDirector', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'session_security.middleware.SessionSecurityMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'reversion.middleware.RevisionMiddleware', 'intro.middleware.persistfilter.FilterPersistMiddleware', 'content.middleware.content.ContentMiddleware', 'intro.middleware.booking.BookingMiddleware', 'common.middleware.accounts.PasswordChangeMiddleware' ) # session security SESSION_SECURITY_WARN_AFTER = 6900 SESSION_SECURITY_EXPIRE_AFTER = 7200 SESSION_EXPIRE_AT_BROWSER_CLOSE = True ... and in base.html in the <head> <script src="{% static "suit/js/jquery-1.8.3.min.js" %}"></script> {% include 'session_security/all.html' %} For every page load on the site if 10 seconds or more go by, the following popup occurs when navigating to another page on the same domain This is not just on Firefox, but on Chrome. Searching for other people with similar issues does not yield helpful results, but indicates that the issue is caused by a javascript onbeforeunload command: I have another project Django 1.6.1 and django-session-security 2.2.4. The only difference I can see is that in Django 1.9, I have to have SESSION_EXPIRE_AT_BROWSER_CLOSE = True or django crashes on any page reload, where is in Django 1.6.1, this is not set at all. Could it be some issue with my version of jquery? Any solutions would be appreciated. -
redis cache configuration for environ
settings.py CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': env.str("REDIS_URI"), 'OPTIONS': { 'DB': 1, 'SOCKET_TIMEOUT': 5, 'SOCKET_CONNECT_TIMEOUT': 5, 'CONNECTION_POOL_CLASS': 'redis.BlockingConnectionPool', 'CONNECTION_POOL_CLASS_KWARGS': { 'max_connections': 50, 'timeout': 20}, 'PICKLE_VERSION': -1, }, }, } I'm moving the above configruation to django-environ env REDIS_URL=rediscache://127.0.0.1:6379/1client_class=redis_cache.RedisCache&default_timeout=360 How can I add the connection pool to the REDIS_URL. -
unindended session timeout Django
I need help to know the cause of unexpected session timeout on Django web app deployed on AWS. I've been googling for a couple of days and still couldn't solve it. Could you please give me any idea for this. Target Set session timeout as 30 minutes(not reloaded for 30 minutes leads to auto logout) Current Situation Currently, session_id shown on google chrome seems correct. However auto logout is unexpectedly excecuted before that time. Nearly between 2 to 3 minutes after the last request time. enter image description here In settings.py, all the environ variable related to session is defined like # Application definition INSTALLED_APPS = [ 'recommend', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', # default sessions app is included 'django.contrib.messages', 'django.contrib.staticfiles', 'django_ses', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'recommend.middlewares.disable_csrf.DisableCSRF', 'recommend.middlewares.session_manage.SessionManageMiddleware', # Sessions manage middleware named session_manage.py is also included. ] SESSION_TIMEOUT_MINUTE = 30 session_manage.py process_request() is executed every time request is given, but it doesn't seem to work correctly. DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S' SESSTION_TIMEOUT = settings.SESSION_TIMEOUT_MINUTE * 60 class SessionManageMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): self.process_request(request) response = self.get_response(request) return response def process_request(self, request): if not request.user.is_authenticated(): return if 'last_touch' not in … -
Channels websocket AsyncJsonWebsocketConsumer disconnect not reached
I have the following consumer: class ChatConsumer(AsyncJsonWebsocketConsumer): pusher = None async def connect(self): print(self.scope) ip = self.scope['client'][0] print(ip) self.pusher = await self.get_pusher(ip) print(self.pusher) await self.accept() async def disconnect(self, event): print("closed connection") print("Close code = ", event) await self.close() raise StopConsumer async def receive_json(self, content): #print(content) if 'categoryfunctionname' in content: await cellvoltage(self.pusher, content) else: print("ERROR: Wrong data packets send") print(content) @database_sync_to_async def get_pusher(self, ip): p = Pusher.objects.get(auto_id=1) try: p = Pusher.objects.get(ip=ip) except ObjectDoesNotExist: print("no pusher found") finally: return p Connecting, receiving and even getting stuff async from the database works perfectly. Only disconnecting does not work as expected. The following Terminal Log explains what's going on: 2018-09-19 07:09:56,653 - INFO - server - HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2018-09-19 07:09:56,653 - INFO - server - Configuring endpoint tcp:port=1111:interface=192.168.1.111 2018-09-19 07:09:56,653 - INFO - server - Listening on TCP address 192.168.1.111:1111 [2018/09/19 07:11:25] HTTP GET / 302 [0.02, 10.171.253.112:35236] [2018/09/19 07:11:25] HTTP GET /login/?next=/ 200 [0.05, 10.111.253.112:35236] {'type': 'websocket', 'path': '/ws/chat/RP1/', 'headers': [(b'upgrade', b'websocket'), (b'connection', b'Upgrade'), (b'host', b'10.111.111.112:1111'), (b'origin', b'http://10.111.253.112:1111'), (b'sec-websocket-key', b'vKFAnqaRMm84AGUCxbAm3g=='), (b'sec-websocket-version', b'13')], 'query_string': b'', 'client': ['10.111.253.112', 35238], 'server': ['192.168.1.111', 1111], 'subprotocols': [], 'cookies': {}, 'session': <django.utils.functional.LazyObject object at 0x7fe4a8d1ba20>, 'user': <django.utils.functional.LazyObject object at 0x7fe4a8d1b9e8>, … -
Django form not rendering input fields in template
When creating a form bounded to a model in django, it does not render at all. I have the following model: class Recipe(models.Model): title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) url = models.TextField(validators=[URLValidator()], blank = True) photo = models.ImageField(upload_to='photos', blank = True) def publish(self): self.created_date = timezone.now() self.save() def __str__(self): return self.title The form: class RecipeForm(forms.ModelForm): class Meta: model = Recipe fields = ['title', 'text'] The view: def recipe_new(request): form = RecipeForm() return render(request, 'recipe_edit.html', {'form:': form}) The template: {% extends 'base.html' %} {% block content %} <h1>New recipe</h1> <form method="post" class="recipe-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock %} But only the title "New recipe" and "Save" button is rendered. If I try to print the form variable in my terminal, it prints out correctly. However, the response to the request always comes without the input fields (whether I use form.as_p or just form). Am I passing the form to the template incorrectly or is the form itself wrong? -
Advance queryset in django ModelAdmin. AttributeError: 'dict' object has no attribute '_meta'
I writing an app that have one Model User, with different roles. So assign role I added field in User model "user_type". below is my User model. class User(models.Model): name = models.CharField(max_length=30) password = models.CharField(max_length=250) gender = models.CharField(max_length=10) user_type = models.CharField(max_length=10, choices=USER_TYPE_CHOICE) It's working fine. I am able to do operation from Django admin site. And now I want to display a count of the user in Django admin. To do so I tried to customize django ModelAdmin class. Below is the Code. class UserCount(User): class Meta: proxy = True class UserCountAdmin(admin.ModelAdmin): list_display = ("user_type", "count") def get_queryset(self, request): return User.objects.all().values("user_type").annotate(count=Count("user_type")) admin.register(User) admin.register(UserCount, UserCountAdmin) And I get error AttributeError: 'dict' object has no attribute '_meta' I also check error on internet, i found the same thing in django issue but it was closed with invalid status. https://code.djangoproject.com/ticket/24387 -
Django : Avoid session database query when serving media in dev
In developpment environnement, when serving media (user-uploaded files) django perform a database query to fetch "django session". I understand this default behavior, but in our case we need to speed a little up this part and we want to avoid theses useless db queries. (We do it in production, because media files are served directly by the web server) How to configure django to not perform database query for session when serving media files ? -
(Django/Python) How to limit onetoonefield's choices?
I'm using a poorman's method to provide translated content. For this I've added translation fields for each language in the model. These field's are onetoone field's since for each content there can be only one translation per language. How could I limit the choices of these fields in the admin? The point is to provide content (model instances) with lang attribute set to ceartain language i.e. en for translations_en field. Django documentation doesn't state onetoonefield at https://docs.djangoproject.com/en/2.0/ref/contrib/admin/ -
Django: General query accesible from all views
I am a bit confused concerning a general query. I have a model with a class Customer information and a class with Comment related to these customers. I want to add in my base.html template an Info tag where I can see the last created comments. So it should be visible in all templates/views. lastCom = Comment.objects.order_by('-id').last() The problem is that I want to define the query once and not for each view separetely. Do you have a hint how define a query only on one place and to access it in each template and not to define the query in each view? What to choose Model Managers, ListViews etc. -
Django, custom error pages redirects to 500 instead of 404
I have production server which has these settings: DEBUG = False ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'my.ip.address', 'example.com'] Then in my main urls.py file I have added this: from django.conf.urls import url, include, handler404, handler500 handler500 = 'main.views.error_500' handler404 = 'main.views.error_404' My main.views has these: def error_404(request): return render(request, 'main/errors/404.html', status=404) def error_500(request): return render(request, 'main/errors/500.html', status=500) When I deploy my production server and try to open page that does not exists, it should redirect to my error_404 view. However, it redirects to my error_500 view. Why this is happening? -
Capturing file upload progress in JS (no Ajax) with Django Back End
Can someone let me know, if there is any native way of capturing value of that little upload progress text normally displayed in the bottom-left corner of my Chrome browser (see image below) with JS? I wanted to enrich my Django file upload app, by showing these upload %s on the submit button after it is clicked, but am at a loss about how to do it. I have already tried the Ajax way, but I ended up having the same file being saved twice in the destination folder, and have no idea why Django is doing that. -
Restrict Users to visit personal action logs
I have block and its subset of article in Model class Block(models.Model): STATUS = ( (1, 'normal'), (0, 'deleted'), ) name = models.CharField("block name", max_length=100) desc = models.CharField("block description", max_length=100) admin = models.CharField("block admin", max_length=100) status = models.IntegerField(choices=STATUS) class Article(models.Model): STATUS = ( (1, 'normal'), (0, 'deleted'), ) tags = models.ManyToManyField(Tag, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) block = models.ForeignKey(Block, on_delete=models.CASCADE) title = models.CharField(max_length=100) I'd like to restrict the users to visit Block actions which records my daily logging. In [40]: [b.name for b in Block.objects.all()] Out[40]: ['Concepts', 'Reading', 'Coding', 'Action'] I accomplish such a task with condition check: def article_detail(request, pk): article = get_object_or_404(Article, pk=pk) # sections and current_section if article.block.name == "Action" and request.user.username not in administors: raise Http404("You are not authorized to read Section Action,I prefert to communicate on the topic action in persion.") Nonetheless, it seems definitely informal as a solution. How could I get it done by a Django's builtin decorators or such on? -
Amazon S3 with Django can't load the all the static file folders
I'm using Amazon S3 to be my static and media files storage.My Django project is running in digitalocean ubuntu 16.04. After running python manage.py collectstatic I found the css and js did not work.And then I found that the css and js hadn't been upload in the S3. there is only 'static' folder in S3. in this static folder there is not my project static files but the admin xadmin and another plug's static files Above is the folder under static in S3. When I check the url of the js it looks like this: <link rel="stylesheet" href="https://myproject.s3.amazonaws.com/css/main.css?Signature=imJphDmnb4U%2BWOWHjE0Iagk2tow%3D&amp;AWSAccessKeyId=AKIAI4LFEI2ASSMOYRTQ&amp;Expires=1537337559"> <link rel="icon" href="https://myproject.s3.amazonaws.com/images/logo-blue.png?Signature=ACidpeC946mBazTtHx0McVIk6rM%3D&amp;AWSAccessKeyId=AKIAI4LFEI2ASSMOYRTQ&amp;Expires=1537337559"> But in my project the main.css is under static folder,the images is under media folder. Here is the main part of my settings.py: import os import sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(BASE_DIR, 'apps')) sys.path.insert(0, os.path.join(BASE_DIR, 'extra_apps')) ROOT_URLCONF = 'myproject.urls' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') AWS_ACCESS_KEY_ID = 'myproject' AWS_SECRET_ACCESS_KEY = 'myproject' AWS_STORAGE_BUCKET_NAME = 'myproject' AWS_S3_FILE_OVERWRITE = False AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME # the sub-directories of media and static files STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION = 'media' # a custom storage file, so we can easily put static and media in one … -
How to show dot thousand separator instead of comma in Python and Django
I have something as follows: { 'takeover': { 'vat_margin': vat_margin, 'purchase_price': "{0:,.2f}".format(quote.offerPrice), 'purchase_price_excl': "{0:.2f}".format(Decimal(quote.offerPrice) / Decimal(vat_value)), }, 'mileage': 12500 } Where takeover dictionary is something as follows: {'vat_margin': True, 'purchase_price_excl': '10330.58', 'purchase_price': '12,500.00'} I pass it to Django template. The problem is that I want dot as thousand separator, but it shows me comma instead. That is only for values in takeover dics, mileage is shown with dot as separator. The code in Django template is as follows: {% load humanize %} {% load i18n %} {% load l10n %} .... <div>{{ car.mileage|intcomma }} {% trans "km" %}</div> ///////// 12.500 <div>{% trans "Overname" %}: € <b>{{ car.takeover.purchase_price|intcomma }}</b></div> ///////// 12,500.00 ... Any idea how to solve it? -
XML Parsing Error: no root element found (django+AJAX)
I'm trying to send a POST request using formdata. But this error comes out in FF and status code 400. XML Parsing Error: no root element found Location: http://127.0.0.1:8000/ajax/set_user_profile/. On the server logs, the request to the function does not even reach. I have another POST request that works without problems, but this one does not work. Also i'm checked html with w3c validator. all its ok. JS function set_user_profile(e){ e.preventDefault(); let csrf_token = document.getElementById("profile-menu-csrf").value; let form = document.getElementById("profile-form"); let formData = new FormData(form); let xhr = new XMLHttpRequest(); xhr.open('POST', '/ajax/set_user_profile/', true); xhr.setRequestHeader('Content-Type', 'multipart/form-data') xhr.setRequestHeader('X-CSRFToken', csrf_token); xhr.onreadystatechange = function(){ if(xhr.readyState === 4 ){ if (xhr.status === 200){ console.log('ok'); } else{ console.error(xhr.status); } } }; xhr.send(formData); } HTML form like this <form id="profile-form"> <input name="csrfmiddlewaretoken" value="${csrf_token}" type="hidden" id="profile-menu-csrf"> <input type="text"/> <textarea></textarea> <input type="text"/> <input type="text"/> <input type="text"/> <input type="submit"/> </form> URL conf urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/$', generic.RedirectView.as_view(url='/accounts/login', permanent=False), name='login'), url(r'^register/$', views.registration, name='registration'), url(r'^webchat/$', views.home, name="home"), url(r'^ajax/add_chat/$', ajax.add_chat, name='add_chat'), url(r'^ajax/update_chats/$', ajax.update_chats, name='update_chats'), url(r'^ajax/load_messages/$', ajax.load_messages, name='load_messages'), url(r'^ajax/who_online/$', ajax.who_online, name="who_online"), url(r'^ajax/get_user_profile/$', ajax.get_user_profile, name="get_user_profile"), url(r'^ajax/set_user_profile/$', ajax.set_user_profile, name='set_user_profile'), ] Django view just for testing def set_user_profile(request): data = {} data['ok'] = 'ok' return JsonResponse(data) -
Django - One CBV to handle multiple scenarios
I am having trouble to understand how to use a single CBV to handle (at least) 2 different scenarios. Here's what I am trying to do: I have a ListView to display a list of objects. From there, I generate a link to navigate to a DetailView to display the details of an object. From there, I generate a link to a different view to render a related report. I'd like to use the following URL's: 1. /myapp/list.html/ 2. /myapp/detail.html/<<uuid>>/ 3. /myapp/detail.html/<<uuid>>/?<layout> Scenario 2 and 3 I am thinking to use a single CBV but I don't understand how to differentiate the scenarios. Can you advise what my urls.py and my views.py need to look like? Thanks! -
Django: Redirect to user details after clicking on user
I have two models: class UserProfile(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) designation=models.CharField(max_length=100) def __str__(self): return str(self.user) class UserScores(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) ImpactAction=models.ForeignKey(ImpactMatrix,on_delete=models.CASCADE) role=models.ForeignKey(ImpactRoles, on_delete=models.CASCADE) score=models.IntegerField(null=True, blank=True) fiscalYear=models.DateField(blank=True) def __str__(self): return str(self.user)+" : "+str(self.ImpactAction)+" : "+str(self.role) When a user clicks on the name in user profile, show the scores of the particular user. Example: aava Teacher If a user click on aava then the results in the UserScores Model should be filtered and show only scores related to aava aava LDI Functional 15 -
How create object with create object from another model and make relationship
I need create objects with creating object of another model and make relationship one-to-one unique after save object in django admin. How i can do that?