Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i wanna have two ways to add imag to my site one through url and other through my pc storage
so i wanna have two different options to upload an image to the website one through src="{{ product.image_url }} so i can display the image through a url i provide and the other option i wanna keep is to add an image through pc storage like from desktop. I have already setup the displaying of image through url but now i want to to add a way were if i cant find the image url i can just upload an image through my pc. Here is all the code admin.py from django.contrib import admin from .models import Product, Offer class OfferAdmin(admin.ModelAdmin): list_display = ('code', 'discount') class ProductAdmin(admin.ModelAdmin): list_display = ('name', 'price', 'stock') admin.site.register(Product, ProductAdmin) admin.site.register(Offer, OfferAdmin) apps.py from django.apps import AppConfig class ProductsConfig(AppConfig): name = 'products' models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2083) class Offer(models.Model): code = models.CharField(max_length=10) description = models.CharField(max_length=255) discount = models.FloatField() urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index), path('new', views.new) ] views.py from django.http import HttpResponse from django.shortcuts import render from .models import Product def index(request): products = Product.objects.all() return render(request, 'index.html', {'products': products}) def new(request): return HttpResponse('New … -
How can i store a python list into my mongodb from my views.py
My problem may be really simple cause im new to django.. I have a model and a form that work as expected. I type in my template, a project_name and a subnet address and i store them in the database. What if i want to store in that model a python list too? The list i want to save is being generated in my views.py function after the user submits the project name and the subnet. What changes must i do in order to achieve that? Code below: forms.py class LanModelForm(forms.ModelForm): helper = FormHelper() # helper.form_show_labels = False class Meta: model = UserProject fields = ['project_name', 'subnet', ] models.py class UserProject(models.Model): project_name = models.CharField(max_length=15) subnet = models.CharField(max_length=30) def __str__(self): return self.project_name views.py . . . elif request.POST.get('Arp'): print('ARP-PING code accessed') # _target = request.session['target'] _target = request.session.get('subnet') ans, _ = srp(Ether(dst='ff:ff:ff:ff:ff:ff') / ARP(pdst=_target), timeout=3, verbose=0) clients = [] for sent, received in ans: clients.append({'IP': received[1].psrc, 'MAC': received[1].hwsrc}) print('AVAILABLE CLIENTS IN THE NETWORK:') for client in clients: print('{} {}'.format(client['IP'], client['MAC'])) context = { 'error_message': 'Nothing found,try another subnet!', 'subnet': _target, 'arp_clients': clients, } return render(request, 'projectRelated/passive_scanning.html', context) -
Not using user = models.OneToOneField(User,on_delete=models.CASCADE)
I am creating the registration,login, logout which requires only email and password. When I use user = models.OneToOneField(User,on_delete=models.CASCADE) it gives me an error because it requires username too. How can I take only email and password from User and save it to user? -
Can't find the template - Django
In my Django project I have two apps, called data_app and user_app. The data_app works perfectly, but user_app not. When I write in my browser http://127.0.0.1:8000/login/ appears the following error, django.template.exceptions.TemplateDoesNotExist: /login.html Probably I'm forgetting something, but I don't know what. Then, I show the different parts and my structure, views.py from django.shortcuts import render # Create your views here. from django.shortcuts import redirect from django.contrib.auth.models import User, auth from django.contrib import messages def login(request): if request.method == 'POST': username = request.POST['uname'] password = request.POST['pass'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request,user) return redirect('/data_app/data-bbdd/') else: return redirect('login') else: print('Hello2') return render(request, '/login.html') def logout(request): auth.logout(request) return redirect('login') urls.py (user_app) from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('login/', views.login, name='login'), path('logout/', views.logout, name='logout') ] urls.py ("general" app) from django.contrib import admin from django.urls import path, re_path, include urlpatterns = [ path('admin/', admin.site.urls), re_path('', include('applications.data_app.urls')), re_path('', include('applications.user_app.urls')) ] Estructure I suppose I'm forgetting some path, but I can't see were. Note The print('Hello2') from views.py is working, the the problem is in return render(request, '/login.html'). Thank you very much! -
Validation erorr raise for the form that validates its value from another model
I am trying to raise validation error for the entry field in the forms.py My models.py class StudBackground(models.Model): stud_name=models.CharField(max_length=200) class Student(models.Model): name=models.CharField(max_length=200) My forms.py class StudentForm(forms.ModelForm): name = forms.CharField(max_length=150, label='',widget= forms.TextInput) class Meta: model = Student fields = ['name',] where i tried to apply clean method : def clean_student(self,*args,**kwargs): name=self.cleaned_data.get("name") if not studBackground.stud_name in name: raise forms.ValidationError ( "It is a not valid student") else: return name My form takes name from the form entry field and then requests from DB whether name in DB based on my StudBackground model. I tried to incorporate stud_name from the StudBackground model to the form but it does not work it raises following error when i try to type student name that is not in DB: Profiles matching query does not exist however it supposed to return near the name field "It is a not valid student" How to make it work? What is the wrong with the code. I am learning Django and would appreciate your help and any thought on that. -
No module named 'urllib2' rapportive - Python 3.8.2
I am looking for the files but did not found any urllib2 ModuleNot How can I solve it? I am too beginner in python I am just looking at this extension for my working purposes can anyone please help. here is the post from where I collected this extension https://github.com/andrealmieda/rapportive Thanks in advance -
How to apply __contains to formatted date with django ORM?
I want to implement a database search and I need to filter queryset by date that contains search request. The problem is that users will see formatted date (like dd.mm.yyyy) and will expect search to see it the same way, but default __contains consider date in yyyy-mm-dd format. How can I apply filter to DateField before using __contains? I need a way using django orm because otherwise it will be too long (not using sql). I tried to set DATE_FORMAT = 'd.m.Y' to satisfying format but it has no effect (even setting USE_L10N = False) Also thought about creating custom lookup but not sure how to implement it -
How could the form display data that it takes from database? (similar to google sheets cells concept)
I'm developing notes taking app and want to create the following: I have: class Ticket(models.Model): ticket_num = models.IntegerField(default=0) post = models.CharField(max_length=000) date = models.DateTimeField(auto_now=True) when I do the view like this: def get(self, request): form = TicketsForm(initial={'post':Ticket.post}) my form displays < django.db.models.query_utils.DeferredAttribute object at 0x10e0a92b0 > I think I'm almost there but something goes wrong here %) It should work exactly like google sheets but the only difference might be that the submitting will be made by button. if you could help to make it exactly like google sheets that'd be awesome! -
ajax response is sending data but not getting any response
i am sending a data via ajax on POST method , the problem is that it sends data but it don't recieves it and it also dont renders html page. views.py def checkoutnow(request): my_dict = {} name_dict = {} final_dict = {} record=0 total_price = 0 if request.method == 'POST': print(type(request.POST)) m = request.POST print("length",len(m)) for k,v in m.items(): print(k,"and ", v) my_dict.update({k: v}) key = my_dict.pop("csrfmiddlewaretoken") #print(my_dict) print(key) for p in range(int(len(my_dict)/5)): name = m[f'object[{p}][name]'] qty = m[f'object[{p}][qty]'] name_dict.update({name: qty}) #print("zz",name_dict) for n, q in name_dict.items(): print(n , q) if newarrival.objects.filter(product_name__contains=n): db = newarrival.objects.filter(product_name__contains=n) print("price",db[0].price * int(q)) price = db[0].price * int(q) print("na", price) elif womentrouser.objects.filter(product_name__contains=n): db = womentrouser.objects.filter(product_name__contains=n) print("price", db[0].price) price = db[0].price * int(q) print("wt",price) elif womenshirt.objects.filter(product_name__contains=n): db = womenshirt.objects.filter(product_name__contains=n) print("price", db[0].price) price = db[0].price * int(q) print("ws",price) elif mentrouser.objects.filter(product_name__contains=n): db = mentrouser.objects.filter(product_name__contains=n) print("price", db[0].price) price = db[0].price * int(q) print("mt",price) elif menshirt.objects.filter(product_name__contains=n): db = menshirt.objects.filter(product_name__contains=n) print("price", db[0].price) price = db[0].price * int(q) print("ms",price) elif equipment.objects.filter(product_name__contains=n): db = equipment.objects.filter(product_name__contains=n) print("price", db[0].price) price = db[0].price * int(q) print("eq",price) else: print("didnt match") d = {record: [n, q, price]} record = record + 1 final_dict.update(d) print(final_dict) print(final_dict[1][2]) print(len(final_dict)) for j in range(int(len(final_dict))): print("this is j",j) total_price += final_dict[j][2] print(total_price) return … -
'function' object has no attribute 'objects' Django, help me
I'm designing a Django app and experiencing an error message: AttributeError at / 'function' object has no attribute 'objects' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.10 Exception Type: AttributeError Exception Value: 'function' object has no attribute 'objects' This is my views.py that generates the message: from django.shortcuts import render from post.models import posts def index(request): featured = Post.objects.filter(featured=True) context = { 'object_list': featured } return render(request, 'index.html', context) def blog(request): return render(request, 'blog.html', {}) def Post(request): return render(request, 'post.html', {})` and this is my model.py from django.db import models from django.contrib.auth import get_user_model user = get_user_model() class author(models.Model): user = models.OneToOneField(user, on_delete=models.CASCADE) profile_picture = models.ImageField class category(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title class posts(models.Model): title = models.CharField(max_length=100) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) comment_count = models.IntegerField(default=0) author = models.ForeignKey(author, on_delete=models.CASCADE) thumbnail = models.ImageField() categories = models.ManyToManyField(category) featured = models.BooleanField() def __str__(self): return self.title Thanks for any help. -
Is there a way to make foreign key from an attribute to another from other class in django?
class Assignatura(models.Model): """docstring for Assignatura""" nom = models.CharField(max_length = 40) codi = models.IntegerField() any_academic = models.CharField(max_length = 7) class Matricula(models.Model): """docstring for Matricula""" nia_alumne = models.ForeignKey(Alumne, null = False, on_delete=models.CASCADE, verbose_name = 'Nom alumfne') codi_assignatura = models.ForeignKey(Assignatura, null = False, on_delete=models.CASCADE) any_academic = models.CharField(max_length = 7) image = models.ImageField(upload_to="matriculas", null=True) i Want that codi_assignatura gets only codi from Assignatura -
Reverse for 'post' with keyword arguments '{'pk': 8}' not found. 1 pattern(s) tried: ['Loader/post/$'] "DANGO"
urls.py app_name = 'Loader' urlpatterns = [ path('post_detail/', views.Loader_post_view.as_view(), name="post_detail"), path('post/', views.post.as_view(), name="post"), path('my_job/', views.Loader_post_list.as_view(), name="my_job"), path('delete/<int:pk>', views.Loader_post_delete.as_view(), name="Delete"), path('update/<int:pk>', views.Loader_post_update.as_view(template_name="post_detail.html"), name="Update") ] this is my models.py class Loader_post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Loader") pick_up_station = models.CharField(max_length=150) destination_station = models.CharField(max_length=150) sender_name = models.CharField(max_length=150) phone_number = PhoneNumberField(null=False, blank=False, unique=True) receiver_name = models.CharField(max_length=150) sending_item = models.CharField(max_length=150) #image_of_load = models.ImageField(default='',upload_to='static/img') weight = models.CharField(max_length=150) metric_unit = models.CharField(max_length=30, default='') quantity = models.PositiveIntegerField() pick_up_time = models.DateField() drop_time = models.DateField() paid_by = models.CharField(max_length=150) created_at = models.DateTimeField(auto_now=True) published_date = models.DateField(blank=True, null=True) def __str__(self): return self.user.username def get_absolute_url(self): return reverse("Loader:post", kwargs={'pk': self.pk}) this if my views.py class Loader_post_view(CreateView,LoginRequiredMixin): form_class = forms.Loader_post_form model = Loader_post template_name = "post_detail.html" def form_valid(self, form): print(form.cleaned_data) self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) this is my post form in html <form method="POST"> {% csrf_token %} <div class="container"> <div class="form-row"> <div class="col">{% render_field form.pick_up_station class="form-control" placeholder="Enter pick_up_station"%}</div> <div class="col">{% render_field form.destination_station class="form-control" placeholder="Enter destination_station"%}</div> </div> <div class="form-row"> <div class="col">{% render_field form.sender_name class="form-control" placeholder="Enter sender_name"%}</div> <div class="col">{% render_field form.phone_number class="form-control" placeholder="Enter phone_number"%}</div> </div> <div class="form-row"> <div class="col">{% render_field form.receiver_name class="form-control" placeholder="Enter receiver name"%}</div> <div class="col">{% render_field form.sending_item class="form-control" placeholder="Enter sending_item"%}</div> </div> <div class="form-row"> <div class="col">{% render_field form.weight class="form-control" placeholder="Enter weight"%}</div> <div class="col">{% render_field form.metric_unit … -
Django/Python: Adding incrementing numbers to bulk of usernames
I am creating a game where I have a player list, and when a game is created a list of players (users) is generated. The function below creates a player with random usernames, for example "Player_0tt". I wish to instead of having random ascii_lowercase + digits, to increment each user by 1. So the first user is called Player_1, Player_2..etc. I will be adding the game ID to the username to make each game users unique but for now I am trying to get the 1, 2, 3...behind my usernames. Should I make a new function that increments, or is there a smarter way to do this? Create random username def generate_username(length=3, chars=ascii_lowercase + digits, split=7, delimiter='_'): username = 'Player' + ''.join([choice(chars) for i in range(length)]) if split: username = delimiter.join([username[start:start + split] for start in range(0, len(username), split)]) try: User.objects.get(username=username) return generate_random_username(length=length, chars=chars, split=split, delimiter=delimiter) except User.DoesNotExist: return username -
Django: Creating model managers does not work
Please help me ... I understand that the problem is very simple ... but I'm stuck! I Creating model managers class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Post(models.Model): ................... objects = models.Manager() published = PublishedManager() and this is what I get in the terminal >>> Post.objects.filter(publish__year=2020, author__username='sasa') <QuerySet [<Post: try>, <Post: 3 article>]> >>> Post.published.filter(publish__year=2020, author__username='sasa') <QuerySet []> >>> Post.object.filter... works correctly, but Post.published.filter returns an empty object This is not right? Where am I mistaken? -
Start docker image with python3.6.8 and django3.0.4 got pkg_resources.DistributionNotFound: The 'supervisor==3.0' distribution was not found
I upgraded from python 2.7 to python3.6.8 and django1x to django3.0.4. When I start the docker image, this is what shown on the docker logs: I tried install supervisor3.0 but it said supervisor is not supported in python 3x. Please help me if I can solve this problem or another version of 3x python could help? -
How to configure django-tenant-schemas to exclude port in request?
I am developing a django project that implements multi tenancy using django-tenant-schemas. I have the following records in my Client models: 1) Public schema with domain_url "huncho.com" and schema name "public" 2) tenant schema with domain_url "tenant1.huncho.com" and schema name "tenant1" 3) tenant schema with domain_url "tenant2.huncho.com" and schema name "tenant2" when I access the public schema using url: huncho.com:8000, it accepts the url and shows content from public schema. However, when i try to access tenant schema using tenant1.huncho.com:8000, it raises a 404 error saying "No tenant found for "tenant1.huncho.com:8000". I have tenant1.huncho.com in my hosts file. 127.0.0.1 huncho.com 127.0.0.1 tenant1.huncho.com 127.0.0.1 tenant2.huncho.com ... Earlier in this project, i had set domain_url of public schema as huncho ie single word. tenant urls were tenant1.huncho, tenant2.huncho and so on, with schema nams tenant1, tenant2. my hosts file had this: 127.0.0.1 huncho 127.0.0.1 tenant1.huncho 127.0.0.1 tenant2.huncho ... This was working perfectly and it did not cause any trouble to seperate the schemas. All data was seperately stored and managed, according to host and schema, as it should be. In short, when I am setting the hostname to huncho.com instead of huncho, it includes the port number also while checking for schemas. … -
Sending real time data to a webpage in Django
I'm creating a Django project and i found myself at a dead end when looking for a solution to retrieve data and display it on a page in real time. My app is a trading analytics webapp, so i need to show those trades in real time on a HTML page whenever a user opens the page. So i have an external Python app which retrieves the trades and updates them on a database and then my Django app, which should retrieve them again and put them in real time on the html page, whenever a user opens it. Now, the first thing that came to my mind is Django Channels; the problem with using it, though, is that i would be flooding my database with requests and i would end up crashing it, since it should handel 1+ requests per second for every user. Then i thought of using RabbitMQ and Celery, but the problem is that i don't know, in that case, how the data would be sent to my frontend/html page. I know this question will probably get downvoted for being too broad, so i'm trying to make it as specific as possible; is there a service/solution … -
Hide divs and display div when button clicked
I am a total newbie of Jquery and JavaScript. I am using this code as reference: https://jsfiddle.net/6uzU6/2/ What I am trying to do is similar as the link above, which is to display a div after a corresponding button is clicked while others divs are hidden. I was trying to modify the code to use div instead of unordered list. The problem I am having right now is when I use Brave Browser to open the page, the divs are not hiding and no changes are made after clicking the button. While using Chrome, the page will be blank, nothing is shown. tutorialIndex.html {% extends "morse_logs/base.html" %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'morse_logs/css/style.css' %}"> <link href="{% static 'morse_logs/js/jquery-ui/jquery-ui.min.css' %}" rel="stylesheet"> <link href="{% static 'morse_logs/js/jquery-ui/jquery-ui.structure.min.css' %}" rel="stylesheet"> <link href="{% static 'morse_logs/js/jquery-ui/jquery-ui.theme.min.css' %}" rel="stylesheet"> <div class="container"> <h1>Tutorial</h1> </div> <div id="menu"> <button class="justClick" href="#">A</button> <button class="justClick" href="#">B</button> <button class="justClick" href="#">C</button> <button class="justClick" href="#">D</button> </div> <div class="content"> </div> <div class="content1"> <h1>A</h1> <img src="{% static 'morse_logs/img/A.png' %}" alt="A" style="width:128px;height:128px;"> </div> <div class="content2"> <h1>B</h1> </div> <div class="content3"> <h1>C</h1> </div> <div class="content4"> <h1>D</h1> </div> <script src="{% static 'morse_logs/js/jquery-3.4.1.min.js' %}"></script> <script src="{% static 'morse_logs/js/jquery-ui/jquery-ui.js' %}"></script> <script src="{% static 'morse_logs/js/app.js' %}"></script> {% … -
How can I give foreign key to two models (so as to represent the activity logs)
The problem is, I have to give foreign key reference to two different models so as to record the activity logs of the user I have model named Activity Log to record the activities done by the user class ActivityLog(models.Model): target = models.ForeignKey(Build, on_delete=models.CASCADE, null=True, blank=True) # Target, (Optional) The object to which the activity was performed. user = models.ForeignKey(User, on_delete=models.CASCADE) # Actor The object that performed the activity. action_object = models.ForeignKey(Team, on_delete=models.CASCADE, null=True, blank=True) # Action Object. (Optional) The object linked to the action itself. content = models.TextField() # Content of the activity timestamp = models.DateTimeField() I need to give the target field with foreign key refering to two different models. Is it possible to use generic relations? -
Login Records of each Admin Panel User to be available
I am working upon a Django app and wants to trace the login records based on timestamp, IP address and city identification through IP. How do I do it? -
How can I make a an html form from a image of a scanned form using pyhon 3.x APIs?
I want to get the output as digital/HTML form from a scanned image or pdf form I've got to know that I've to first read all the textual data from the image using OCR and further Django would be used. I'm not so familiar with Django though so I don't know what type of output should I get to pass to Django so that it'd give me an HTML form as an output. Following is the code for reading text from an image, that's working import numpy as np import requests import io import json img = cv2.imread("C:\\Users\\Asus\\Desktop\\ocr\\screenshot.jpg") height, width, _ = img.shape # Cutting image """roi = img[0: height, 400: width]""" roi = img # Ocr url_api = "https://api.ocr.space/parse/image" _, compressedimage = cv2.imencode(".jpg", roi, [1, 90]) file_bytes = io.BytesIO(compressedimage) result = requests.post(url_api, files = {"screenshot.jpg": file_bytes}, data = {"apikey": "helloworld", "language": "eng"}) result = result.content.decode() result = json.loads(result) parsed_results = result.get("ParsedResults")[0] text_detected = parsed_results.get("ParsedText") print(text_detected) cv2.imshow("roi", roi) cv2.imshow("Img", img) cv2.waitKey(0) cv2.destroyAllWindows() But what shall be done next? I would be grateful if anyone can enlighten me on how to proceed through this whole thing. Thanking in advance -
Django: ConnectionResetError: [Errno 54] Connection reset by peer
Anytime when the program calls for either favicon.ico or any admin css files, I'm getting the ConnectionResetError: [Errno 54] Connection reset by peer I'm using Django==3.0.4 Python 3.6.1 For any of the below calls "GET /favicon.ico HTTP/1.1" 404 2104 "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 "GET /static/admin/css/changelists.css HTTP/1.1" 200 4096 "GET /static/admin/css/dashboard.css HTTP/1.1" 200 412 "GET /static/admin/css/widgets.css HTTP/1.1" 200 4096 I'm getting Traceback error like Exception happened during processing of request from ('127.0.0.1', 60974) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 639 , in process_request_thread self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 361 , in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 696 , in __init__ self.handle() File "/Users/sunilhn/Documents/programming/Envs/proenv/lib/python3.6/site-packages/django/core/s ervers/basehttp.py", line 174, in handle self.handle_one_request() File "/Users/sunilhn/Documents/programming/Envs/proenv/lib/python3.6/site-packages/django/core/s ervers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py", line 586, in r eadinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer The program runs fine in the frontend without any issues. But this error in console is bugging me. -
Session key is None in django?
guys, I have been trying to use cookie sessions to save user's data,I have used session successfully in my previous applications but this time it's not working properly I know that in order to get the value of the session key the session has to modified or saved. So what I used to do before is make a mixin and used to call that on the view I needed the session key, The case for me here was to grab the session key and the save link that with a model instance but the session key is None or if I change my code to what I have wrote at the bottom it creates a new session key at every request Here's the mixin I used in my previous applications and it worked fine class SessionMixin: def get_session(self,request,*args,**kwargs): session = self.request.session if not session.get('has_session'): session["has_session"] = True return self.__class__.get(self,request,*args,**kwargs) class MyView(SessionMixin,generic.View): def get(self,request,*args,**kwargs): super().get(self,request,*args,**kwargs) print(self.request.session.session_key,"Gives me none") # rest of the code goes here My setting for session cookies SESSION_COOKIE_AGE = 604800 SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies" Here's what I tried too but it just created a session key on every single request. class SessionMixin: def get(self,request,*args,**kwargs): session = self.request.session if not … -
How to get sum of values inside django loop
inside my loop i am getting the values in a variable i want to get sum of these values .code is given value for index in range(len(json_objects)): getsum = 0 sum = json_objects[index]['fields']['bill'] getsum += float(sum) print(getsum) but i am getting only values except sum can any one please help me related tihs ?? > json_objects[index]['fields']['bill'] i am getting values like 100 > and 200 in a loop i want the sum 300 in getsum variable -
Django Patterns: One-To-One Field, Auto Create
Is there a good way, or a common pattern to automatically create one-to-one fields that do not yet exist? Conceptually, I want my OneToOneField to work like a get_or_create call. For example: class Foo(models.Model): user = models.OneToOneField(User, related_name="foo", unique=True) class User(models.Model): ... @property def foo(self): """ This is what I want to achieve conceptually. """ foo, created = Foo.objects.get_or_create(...) return foo ... user.foo() # if none, will create.