Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to get websockets tests to pass in Django Channels
Given a Django Channels consumer that looks like the following: class NotificationConsumer(JsonWebsocketConsumer): def connect(self): user = self.scope["user"] async_to_sync(self.channel_layer.group_add)("hello", "hello") self.accept() async_to_sync(self.channel_layer.group_send)( "hello", {"type": "chat.message", "content": "hello"} ) def receive_json(self, content, **kwargs): print(content) async_to_sync(self.channel_layer.group_send)( "hello", {"type": "chat.message", "content": "hello"} ) print("Here we are") def chat_message(self, event): self.send_json(content=event["content"]) def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)("hello", "hello") and a test that looks like the following: @pytest.mark.asyncio class TestWebsockets: async def test_receives_data(self, settings): communicator = WebsocketCommunicator( application=application, path="/ws/notifications/" ) connected, _ = await communicator.connect() assert connected await communicator.send_json_to({"type": "notify", "data": "who knows"}) response = await communicator.receive_json_from() await communicator.disconnect() I am always getting a TimeoutError when I run the test. What do I need to do differently? If you'd like to see a full repo example, check out https://github.com/phildini/websockets-test -
Keep Record of Anonymous user Django
I want to keep record of Anonymous user action on my wishlistwebsite. and want to keep sync with django server. what will be best way to do that ? till Now I came across way using localstorage of browser but its not effective in some cases like keeping record of guest user wishlist's etc . -
Django API to get or post ERP API [closed]
I have access to ERP API and also want to give my clients access to it but not directly, but by another API. I want to restrict what They can POST and GET, but ERP API couldn't do it so need to create my own like some connector or something. I want to use Django for it. How can I do it the right way? -
Django REST Framework: Is it possible to implement after the complete development of a website?
I am a newbie and currently developing a Django website, I want to know whether I should implement REST framework now for each app or should I do it after completing the whole website? Which is the easiest or the most proffered way and is it easy to implement? -
Do we need to have different virtualenv for different project in django
I have installed django and have set up virtualenv with the name let be 'xyz' and working on project A. Can I work on project B using that 'xyz' virtualenv or should I go for another virtualenv suppose to be 'pqr'? -
How can i customize the label of model form?
I want to set a class or id (to make it special) to label of model form. My forms.py : from django import forms from .models import Note class NoteForm(forms.ModelForm): class Meta: model = Note fields = ['title', 'content'] widgets = { 'title': forms.TextInput(attrs={'class': 'form-input', 'placeholder':'Your note...'}), 'content': forms.Textarea(attrs={'class': 'form-input', 'placeholder':'Your note...'}), } Here i can set class fields by using widgets as you see. But when i enter the page, form labels look bad. Please check the image below. enter image description here My modals.py : class Note(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name="notes") title = models.CharField(max_length=40, verbose_name="Title") content = models.TextField(verbose_name="Content") hour = models.TimeField(verbose_name="Hour", auto_now_add=True) date = models.DateField(verbose_name="Date", auto_now_add=True) def __str__(self): return self.title And html file : {% block content %} <div class="container notes-app"> <h1 class="text-center text-light py-5" style="font-weight: lighter;margin-top: 100px;">Create Note :</h1> <form action=""> {{ form }} </form> </div> {% endblock %} So basically, i want to modify label tags that {{form}} creates. I searched but I could not find a solution. :( -
What is the cleanest way for validation on dynamic forms in Django?
I have been working on a project for an online clothes, shoes, accessories store for a while. I have a form with category, subcategory, size field etc. If the selected category is either "clothes" or "shoes" the size field is required. But if the category choice is "accessories" the size field is hidden and it's not required, because in my case accessories don't have sizes. Also my category choices are not hard coded, they are stored in the database. So while I was doing the validation, in my form's clean method I hard coded an if statement which fires an error when the user's category choice is different from "accessories" and when the size field is blank. But I think that this is not very clean, because the if statement is kinda hard coded. And my question is: Is it there any cleaner solution to do this task? class ItemCreateForm(forms.ModelForm): class Meta: model = Item fields = ['category', 'subcategory', 'brand', 'brand_collection', 'price', 'price_negotiable', 'size', 'gender', 'condition', 'description'] def clean(self): cleaned_data = super().clean() category = cleaned_data.get("category") size = cleaned_data.get("size") if str(category) != 'accessories' and not size: print(category) print(size) self.add_error('size', 'Това поле е задължително!') return cleaned_data -
Django 3 InvalidTemplateEngineError
I am trying to load the detail page html template but appears to throw a error. Which I am trying to debug still new to django but most of the time can sort of figure it out. But at a total loss on this. Something to do with template engine either in setting.py or the template view or url. I think its something in the settings. I did some searches with no luck. There no errors in debug console in virtual studio. Just when i go the the url from the html templates. Any feed back or tips on how to read the error better would be appreciated. I assume I am supposed to configure the basic_app/school_detail.html in the template section of the settings.py. This is where I am stuck. raise InvalidTemplateEngineError( django.template.utils.InvalidTemplateEngineError: Could not find config for 'basic_app/school_detail.html' in settings.TEMPLATES This is the error that gets raised. InvalidTemplateEngineError at /basic_app/1/ Could not find config for 'basic_app/school_detail.html' in settings.TEMPLATES Request Method: GET Request URL: http://127.0.0.1:8000/basic_app/1/ Django Version: 3.0.4 Exception Type: InvalidTemplateEngineError Exception Value: Could not find config for 'basic_app/school_detail.html' in settings.TEMPLATES Exception Location: C:\Users\taylo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\utils.py in getitem, line 71 Python Executable: C:\Users\taylo\AppData\Local\Programs\Python\Python38-32\python.exe Python Version: 3.8.2 Python Path: ['C:\Users\taylo\django\Advanced_Django_CBV\advcbv', 'C:\Python\Python37\Lib', 'C:\Python\Python37\DLLs', 'C:\Python\Python37\Lib\lib-tk', … -
django-admin display the name field of a foreign key instead of foreign key id
In my django-admin it is displaying the foreign-key id value instead of the name value of the foreign key. How can I display the actual name value. I tried the str method for my foreignkey model, but doesn't change anything. -
Convert Date model field with filter query
i'm baffled by this one and no amount of google has come up with an answer. I'm running this query against my database: pedigrees = Pedigree.objects.filter(account=attached_service, status='alive').values('reg_no', 'parent_father__reg_no', 'parent_mother__reg_no', 'sex', 'breed__breed_name', 'dob', 'status') I'm using values to limit the amount of data that comes back. As you can see one of the columns i need is the dob. however the return i'm getting in the field is {'dob': datetime.date(2019, 9, 24)}, which isn't ideal. I'd like to change it's value to "YYYY-mm-dd". I've tried using the DATE_FORMAT setting in settings.py and i've tried lots of other methods suggested on here but nothing has worked. Model item looks like this... dob = models.DateField(blank=True, null=True, verbose_name='date of birth', help_text="Date formats: 1984/09/31, 84/09/31, 31/09/1984, 31/09/84, 1984-09-31, 84-09-31, 31-09-1984, 31-09-84") The data that's being extracted is being sent to an API, i've also built the API so i could change it's format at the other end but i'd rather not. -
Counting problem in django blog: using django ajax
I created a like button for my django blog using ajax but I'm getting an error that its not counting properly, at first its 0 like in a post when i hit like it works 1 like appeared with unlike button but when i hit unlike and like again it gives 2 likes and sometimes when i unlike it show -1 like i think its jQuery problem I'm not an expert in jQuery jQuery $(document).ready(function() { function updateText(btn, newCount, verb) { btn.text(newCount + " " + verb) } $(".like-btn").click(function(e) { e.preventDefault() var this_ = $(this) var likeUrl = this_.attr("data-href") var likeCount = parseInt(this_.attr("data-likes")) |0 var addLike = likeCount + 1 var removeLike = likeCount - 1 if (likeUrl){ $.ajax({ url: likeUrl, method: "GET", data: {}, success: function(data){ console.log(data) var newLikes; if (data.liked){ updateText(this_, addLike, "Unlike") } else { updateText(this_, removeLike, "Like") // remove one like } }, error: function(error){ console.log(error) console.log("error") } }) } }) }) post.html {% if user not in post.likes.all %} <p><a class='like-btn' data-href='{{ object.get_api_like_url }}' data-likes='{{ object.likes.all.count }}' href='{{ object.get_like_url }}'> {{ object.likes.all.count }} Like</a></p> {% else %} <p><a class='like-btn' data-href='{{ object.get_api_like_url }}' data-likes='{{ object.likes.all.count }}' href='{{ object.get_like_url }}'> {{ object.likes.all.count }} Unlike</a></p> {% endif %} … -
Django query database and adding users to specific group of objects
I a trying to query my Blog model such that it will return the number of likes for a blog post with the title = example and name = something class Post(models.Model): title = models.CharField(max_length=20) name = models.CharField(max_length=100) content = models.CharField(max_length=100) likes = models.ManyToManyField(User, blank=True, related_name='likes') right now I am trying to get the count of likes in my model with this method: def average_voting(self): likes = Post.objects.filter(title=self.title,name=self.name).likes.count() return likes and for adding a user I am using: Post.objects.filter(title="example",name="something").likes.add(User) but my lines are not working I cannot figure out what I'm doing wrong. -
How to create a Barcode code using python and store the png file in s3 without saving in local
import barcode from barcode.writer import ImageWriter from io import StringIO # python3; python2: BytesIO import boto3 import pandas as pd def generate_asst(request): df=pd.DataFrame list_of_images = [] for i in range(10): number = 'xxx43256' number = number + str(i) print(number) EAN = barcode.get_barcode_class('Code39') ean = EAN(number, writer=ImageWriter()) fullname = str(i) + 'barcodhhe' filename = ean.save(fullname) filename = ean.save(fo) with open(filename, 'rb') as f: contents = f.read() fo.close() s3 = boto3.resource('s3') s3_obj = s3.Object(bucket_name='bucket-name', key=fullname).put(Body=contents) s3_client = boto3.client('s3') response = s3_client.generate_presigned_url('get_object', Params={'Bucket': 'bucket-name', 'Key': fullname},ExpiresIn=300 ) list_of_images.append({"imagepath":response}) print(response) df=pd.DataFrame(list_of_images) df=json.loads(df.to_json(orient='records')) print(df) # return fullname return JsonResponse(df,safe=False) -
Heroku + Django + Redis Cloud: Connect call failed
I have a django project on heroku. I add Redis Cloud to make my Channels Layers. When I visit the page with my WebSocket I don't see the response and I have this errors in Heroku LOG: Exception inside application: [Errno 111] Connect call failed ('127.0.0.1', 6379) raise OSError(err, 'Connect call failed %s' % (address,)) ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 6379) ERROR Task exception was never retrieved DEBUG WebSocket closed for ['10.32.185.71', 22959] ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 6379) DEBUG Parsed Redis URI ('localhost', 6379) DEBUG Creating tcp connection to ('localhost', 6379) DEBUG WebSocket ['10.38.200.97', 14816] open and established 10.38.200.97:14816 - - [04/May/2020:15:34:35] "WSCONNECT /ws/channel/" - - DEBUG WebSocket ['10.38.200.97', 14816] accepted by application DEBUG Parsed Redis URI ('localhost', 6379) DEBUG Creating tcp connection to ('localhost', 6379) DEBUG Parsed Redis URI ('localhost', 6379) DEBUG Creating tcp connection to ('localhost', 6379) DEBUG WebSocket incoming frame on ['10.38.200.97', 14816] ERROR Exception inside application: [Errno 111] Connect call failed ('127.0.0.1', 6379) My CACHES configuration (from https://devcenter.heroku.com/articles/rediscloud#configuring-redis-on-django): redis_url = urlparse.urlparse(os.environ.get('REDISCLOUD_URL')) CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': '%s:%s' % (redis_url.hostname, redis_url.port), 'OPTIONS': { 'PASSWORD': redis_url.password, 'DB': 0, } } } And my CHANNEL_LAYERS: CHANNEL_LAYERS = { "default": { 'BACKEND': … -
A Django powered backend with PostgreSQL or Firebase backend
I’m a backend developer and I love using Django and PostgreSQL for backends on a Linux server. But I’ve been learning flutter and I’m convenient with it and was reading about firebase real time. I just want to know if firebase offers more functionality than building my own backend. I prefer to build my own backend but I have been reading that firebase offers real time which Postgres doesn’t, I don’t really understand this and doesn’t it really count? Thank you. -
JSON serializable Problem in Django When Try to Use Session
I try to add a cart process in my ecommerce prject which is built with Python Django Framework. But when i try to check data the visitor is authenticated or not and try to return data from model manager I face a json serializable problem. In Bellow i give you the sample code, Here is my view file: from django.shortcuts import render from .models import Cart from django.core import serializers # Create your views here. def cart_create(user=None): cart_obj = Cart.objects.create(user=None) print('New Cart Created') return cart_obj def cart_home(request): cart_id = request.session.get("cart_id", None) qs = Cart.objects.filter(id=cart_id) if qs.count() == 1: print("Cart Id exists") cart_obj = qs.first() if request.user.is_authenticated and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: #cart_obj = cart_create() cart_obj = Cart.objects.new(user=request.user) request.session['cart_id'] = cart_obj return render(request, "carts/home.html") Here Is my Model File: from django.db import models from django.conf import settings from products.models import Product from django.core.serializers import serialize User = settings.AUTH_USER_MODEL # Create your models here. class CartManager(models.Manager): def new(self, user=None): print(user) user_obj = None if user is not None: if user.is_authenticated: user_obj = user return self.model.objects.create(user=user) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) products = models.ManyToManyField(Product, blank=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) … -
django download file not found
I'm using Python 3.6 and django 2.2 to develop a webserver. I want to have a webpage displaying a download link for a file I generated based on user input. In my setting.py I have: MEDIA_ROOT = os.path.join.(BASE_DIR,'media') MEDIA_URL='/media/' In my views.py I have query.outputfile.name = os.path.join('submission',query_id,'output_file.txt') to associate the filefield object to the file that I created: path/to/project/media/submission/[query_id]/output_file.txt And when I include print(query.outputfile.url) I got: media/submission/[query_id]/output_file.txt In my html template I have <a href={{ query.outputfile.url }} download> Download output file here </a> On the webpage the file link points to [local ip]/media/submission/[query_id]/output_file.txt But when I click on the link chrome says "Failed - No file" and on the cmd line I got Not Found: /media/submission/[query_id]/output_file.txt I found related questions like this one but do not understand what's wrong with my code. My questions are: The .url seems to be relative to my MEDIA_ROOT, but why it cannot find my file? Does the cmd line error point to the absolute path /media/... ? I tried to make that path and file but still got the same error. What should I do to generate the download link? Thanks -
Is there a way of a inserting blank datetimefield from another table?
class Customer(models.Model): last_purchase = models.DateTimeField(blank=True, null=True) I have a blank DateTimeField, which will continuously update itself with the last modified DateTimeField in the corresponding table. class Order(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) How will this look on views? -
no such table: main.auth_user__old (OperationalError)
Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/main/tutorial/add/ Django Version: 2.1.4 Python Version: 3.8.2 Traceback: File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/db/backends/utils.py" in _execute 85. return self.cursor.execute(sql, params) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py" in execute 296. return Database.Cursor.execute(self, query, params) The above exception (no such table: main.auth_user__old) was the direct cause of the following exception: File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/contrib/admin/options.py" in wrapper 604. return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/contrib/admin/sites.py" in inner 223. return view(request, *args, **kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/contrib/admin/options.py" in add_view 1637. return self.changeform_view(request, None, form_url, extra_context) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/contrib/admin/options.py" in changeform_view 1525. return self._changeform_view(request, object_id, form_url, extra_context) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/contrib/admin/options.py" in _changeform_view 1568. self.log_addition(request, new_object, change_message) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/contrib/admin/options.py" in log_addition 804. return LogEntry.objects.log_action( File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/contrib/admin/models.py" in log_action 29. return self.model.objects.create( File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/db/models/query.py" in create 413. obj.save(force_insert=True, using=self.db) File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/db/models/base.py" in save 717. self.save_base(using=using, force_insert=force_insert, File "/home/webdev/Desktop/my_django_app/venv/lib/python3.8/site-packages/django/db/models/base.py" in save_base 748. updated = … -
How can I display images in Django after uploading?
I'm making a small blog. And I will be creating a cover image uploading system. But after uploading, I'm unable to retrieve the image. Do you have any solutions? Here's my model.py: class Post(models.Model): id = models.AutoField author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content_images = models.ImageField(default="media/noimg-l.jpg") and here's form.py: class Createcontent(forms.ModelForm): class Meta: model = Post fields = ( "title", "content", "slug", "content_images", "status", ) file = forms.FileField() widgets = { "content": SummernoteWidget(), } and this is the HTML I'm using: <div class="row"> <form method="POST" enctype="multipart/form-data" class="post-form">{% csrf_token %} {{ form|crispy }} <button type="submit" class="save btn btn-default">Save</button> </form> </div> and my setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') X_FRAME_OPTIONS = 'SAMEORIGIN' SUMMERNOTE_THEME = 'bs4' # Show summernote with Bootstrap4 -
Django... Why template page doesn't show results of the query in the view function
Sorry I am new to django and I made mistake or bunch of mistakes somewhere and I don't see what is wrong... Django also doesn't let me know where is the mistake... If somebody pinpoint me to the answer or let me know what is wrong that would be totally awesome... Thank you I have 2 models: one is the Director (pk = director_name) and one is the Worker (pk = worker_name)... Means family names, unique... They are many to many connection for the database. One worker can be under 2 supervisors... So, another model is Connection (fk = director_connect, fk = worker_connect, pk = (director_connect, worker_connect))... By the way, in postgresql the database model as I just described, but when I run "inspectdb" in cmd... it gives me: worker_connect = models.OneToOneField(...)// I made this connection by the alphabet, but somehow for Django, instead of ForeignKey it is OneToOneField? Can I just change it to models.ForeignKey(...)? And then apply changes? director_connect = models.ForeignKey(...) // as expected... def __str__(self): return f'{self.worker_connect}' def get_absolute_url(self): return reverse('director-detail', args=[str(self.director_connect)]) class Meta: managed=False db_table 'Connection' unique_together = (('director_connect', 'worker_connect')) ...So, the idea is to be able to find which worker under whose supervision, and whom … -
Is there a way to crop an image using only css? [duplicate]
I am currently working on a django project which is a youtube clone.I scrape the image of the thumbnails of the videos.When I do so, I faced a problem in fixing the image in the card(from materializecss).The image has empty black space on top and bottom.This is URL of a sample image:https://i.ytimg.com/vi/bt4-FwVe1Fk/hqdefault.jpg Now i want to crop the image so that, the empty black space doesn't show up.Is there a way to do it with only CSS?Any help would be appreciated. Thank You in advance. -
How to post multiple objects in Django Rest API from HTML form where multiple input filed id are same
Here You Can See My form where user Can give input and my goal is to take all the data user-provided and post it through API Firstly I want to see you my HTML code : <div class="content" id="skills"> <form action="#" method="post" class="job-post-form ajax" id="skill_create"> <div class="form-group row"> <label class="col-sm-3 col-form-label">Type Skills</label> <div class="col-sm-9"> <div class="input-group"> <div class="input-group-prepend"> <div class="input-group-text">01</div> </div> <select class="form-control" data-text="name" id="skill_name_id" data-value="id" data-placeholder="Skills" data-src="/api/skill_list"> </select> <input type="number" id="rating" class="form-control" placeholder="Rating"> <label class="form-control" >Verified By SkillCheck</label> <input type="checkbox" id="verified_by_skillcheck" style="margin-top:16px;" name="Skillcheck" value="X"> </div> </div> </div> <div class="form-group row"> <div class="offset-sm-3 col-sm-9"> <div class="input-group"> <div class="input-group-prepend"> <div class="input-group-text" >02</div> </div> <!-- <input type="text" class="form-control" >--> <select class="form-control" id="skill_name_id" data-text="name" data-value="id" data-placeholder="Skills" data-src="/api/skill_list"> </select> <input type="number" id="rating" class="form-control" placeholder="Rating"> <label class="form-control">Verified By SkillCheck</label> <input type="checkbox" id="verified_by_skillcheck" style="margin-top:16px;" name="Skillcheck" value="X"> </div> </div> </div> And now I will show you my script code : function skillGet(){ var skill_id = $("#skill_name_id").val(); var skill_rating = $("#rating").val(); var isVerified = $('input[name="Skillcheck"]:checked').val(); var path = window.location.pathname.split('/'); var id = path[path.length-2]; if (!isVerified){ isVerified = "False"; } else{ isVerified = "True"; } var data = { "professional_id" : id, "skill_name_id": skill_id, "rating": skill_rating, "verified_by_skillcheck": isVerified } skillCreateUrl = "/api/professional/professional_skill/"; if(Object.keys(data).length>1){ post(skillCreateUrl, JSON.stringify(data)); } } By this … -
How to get intermediary models instances related to a specific model in a Django symmetrical m2m relation?
Since Django 3.0, setting symmetrical=True for recursive m2m relationships using a through model is supported. [docs] For exemple, with the following models, where Town objects are symmetricaly linked together through Roads objects : class Town(models.Model): neighboors = models.ManyToManyField('self', through='Road', symetrical=True) class Road(models.Model): from_town = models.ForeignKey('Town', models.CASCADE, related_name='road_from') to_town = models.ForeignKey('Town', models.CASCADE, related_name='road_to') How to get all Road instances related to a specific town? As the doc explains, related_name of the two fk in the Road models have to be different, meaning a single reverse acessor like town.related_road will not work. Of course, I can set two different related_name and join the results of two queries, but that does not seems very Pythonic to me: class Town(models.Model): ... @property def roads(self): return self.road_to + self.road_from Is there any other way I can achieve this ? -
Why does Django create a new instance instead of update?
I want to modify some of my 'Location' object with an UpdateView. class LocationUpdateView(UpdateView): #form_class = LocationForm model = LocationTemplate fields = ['address','district','grid_x','grid_y'] #template_name = 'locationTemplate_update_form' def get_success_url(self): return reverse('location_detail', kwargs={'pk': self.object.pk}) def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): self.object = self.get_object() for loc in Location.objects.all(): if self.object.location_name == loc.location_name: setattr(loc,'address',(form.cleaned_data['address'])) setattr(loc,'district',(form.cleaned_data['district'])) setattr(loc,'grid_x',(form.cleaned_data['grid_x'])) setattr(loc,'grid_y',(form.cleaned_data['grid_y'])) loc.save() return self.form_valid(form) else: return self.form_invalid(form) However, instead of updating the objects, the above loop creates a new object with the update information(except the location_name is None). I was expecting setattr() to modify the attributes of that specific loc instead of creating new instances. models.py class LocationTemplate(models.Model): location_name = models.CharField(max_length=50, null=True, blank=True) address = models.CharField(max_length=300, null=True, blank=True) district = models.CharField(max_length=300, null=True, blank=True) grid_x = models.IntegerField(null=True, blank=True) grid_y = models.IntegerField(null=True, blank=True) def __str__(self): return self.location_name + ", Address: " + self.address + ", District: " + self.district + ", Coordinates: (" + str(self.grid_x) + ", " + str(self.grid_y) + ")" forms.py class LocationForm(forms.ModelForm): class Meta: model = LocationTemplate #exclude = ('patient',) fields=['location_name', 'address','district', 'grid_x','grid_y']