Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django parent template has to act as a child template to itself
I'm just beginning to use Django's template extending feature, and I've hit a bit of a problem. So I have here two html templates, one is the main section page, the other is a specific 'post' page Main Section Page {% if latest_post_list %} {% for post in latest_post_list %} <a href = "{% url 'blog:detail' post.id %}"><h1>{{post.title}}</h1></a> <h2>{{post.author}}</h2> <h2>{{post.pub_date}}</h2> <p>{{post.body}}</p> {% if post.video_set.all.exists %} <h3>Videos</h3> {% endif %} {% for video in post.video_set.all %} <a href = "{{video.url}}"><h4>Here is a video</h4></a> {% endfor %} {% if post.link_set.all.exists %} <h3>Links</h3> {% endif %} {% for link in post.link_set.all %} <a href = "{{link.url}}">{{link.name}}</a> {% endfor %} {% endfor %} {% else %} <p>no recent posts made</p> {% endif %} Post Page <h1>{{post}}</h1> <h2>{{post.author}}</h2> <h2>{{post.pub_date}}</h2> <p>{{post.body}}</p> {% if post.video_set.all.exists %} <h3>Videos</h3> {% endif %} {% for video in post.video_set.all %} <a href = "{{video.url}}"><h4>Here is a video</h4></a> {% endfor %} {% if post.link_set.all.exists %} <h3>Links</h3> {% endif %} {% for link in post.link_set.all %} <a href = "{{link.url}}">{{link.name}}</a> {% endfor %} Now what I'm trying to do is have the following code (which is the same for both pages) get extended: {% if post.video_set.all.exists %} <h3>Videos</h3> {% endif %} {% for … -
error: template does't exist
hi i am trying make work my login in django but when i intance the login view from django in urls.py and passed my template i have this error : TemplateDoesNotExist at /login/ Using engine django: django.template.loaders.filesystem.Loader: C:\Users\sdand\Documents\envganagro\templates\login.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\sdand\Documents\envganagro\lib\site-packages\django\contrib\admin\templates\login.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\sdand\Documents\envganagro\lib\site-packages\django\contrib\auth\templates\login.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\sdand\Documents\envganagro\ganagroapp\templates\login.html (Source does not exist) but how you can see in this image: the template exist in ganagroapp/templates/ganagroapp my ganagro/urls.py is this : from django.conf.urls import include,url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'',include('ganagroapp.urls')), ] my ganagroapp/urls.py is this : from django.conf.urls import include, url from . import views from django.contrib.auth.views import login app_name = 'ganagroapp' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^product/(?P<pk>[0-9]+)/$', views.product_detail, name='product_detail'), url(r'^category/(?P<pk>[0-9]+)/$', views.product_category, name='product_category'), url(r'^product/new/$', views.new_product, name='new_product'), url(r'^login/$',login,{'template_name':'login.html'}, name='login'), ] -
Django expiration date membership
I'm working on a django (Version 1.11) project that require "One-year membership". It is, a user - membership that will stay no longer that one year active and after that it will be no valid or can be renewed. (im using postgres). I have a model called membership with many to many relationship with user model , this table contains the activation date of the membership. How can i achieve this? -
How to change src with Jquery in django templates
I'm using a code to change the text content of a paragraph tag, When an object is updated, as I'm using websockets I don't need to update the page to see the changes. But instead of that, now I want to change the src of an image. I'm trying this way but it's not working. Of course, There are topics like this, But none works. {% for object in numbers %} <img class="js-{{ object.id }}" src="{% static "imagens/ativado.png" %}" width="100px" height="100px"> {% endfor %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script> $(document).ready(function() { socket = new WebSocket("ws://" + window.location.host); socket.onmessage = function(e) { var data = JSON.parse(e.data); for (var object in data) { $(".js-" + object).src("{% static "imagens/desativado.png" %}"); } } }); </script> -
Mezzanine Fab All Error During Deployment
I've been trying to follow Mezzanine's Deployment Documentation, however whenever I run fab all I encounter the following error: Fatal error: sudo() received nonzero return code 1 while executing! Requested: psql -c "CREATE USER Learnmez WITH ENCRYPTED PASSWORD '*****';" Executed: sudo -S -p 'sudo password:' -u "postgres" /bin/bash -l -c "psql -c \"CREATE USER Learnmez WITH ENCRYPTED PASSWORD '*****';\"" Aborting. Disconnecting from *****... done. I think the error has to do with the PostgreSQL database that I'm using for deployment, but I am not entirely sure. Does anyone have any insight? Thanks for your time -
filter query django clause having min
This is my database id | room_id | date | qty | rate ---------------------------------------- 1 | 1 | 2017-01-01 | 0 | 500 2 | 1 | 0217-01-02 | 3 | 500 3 | 2 | 2017-01-01 | 3 | 500 4 | 2 | 0217-01-02 | 3 | 500 i am working with django, and this is my query def sel_rooms(request, id_hotel, check_in, check_out): paso = "SELECT ROOM & RATES" hotel = Hotel.objects.get(id_hotel=id_hotel) rooms = Room.objects.filter(hotel=hotel) check_in = datetime.datetime.strptime(check_in, '%Y-%m-%d').date() check_out = datetime.datetime.strptime(check_out, '%Y-%m-%d').date() - timedelta(days=1) stock = Stock.objects.filter(hotel=hotel, date__range=(check_in, check_out)) for room in rooms: avail = stock.annotate(min_q=Min('qty')).filter(min_q__gte=1).order_by('room') I cant make that query only bring me the room that has qty > 0 the two days. the query only should return the two rows that correspond with room_id 2. -
How to overcome the website not able direct view issue after i using iframe function?
I have a website that I created by Django python and now I want to insert this website that I create by Django into another web portal(another programing language) by using function and I notice that I not able to direct view my website, the following picture is the output of my website and I need to click the link Open this content in a new window to open a new tab now only I can view my website, anyone have any idea to overcome this security issue? -
How to write a view test for django's app?
I've recently entered the test field, and it seems to be tricky, so if you can help me understand how to make a view test for this function, I'd be thankful. def Deactivate(request,Username): islogged, current_UserID = USER.IsLogged(request) if USER.IsAutherized(request, 'Player'): if USER.CurrentUser(request, Username): user = USER.ShowUser(Username) statusID = user.StatusID result = PLAYER.ChangeStatus(Username,StatusID=statusID) if result: Feedback = "Deactivated!" AlertType = "alert-success" USER.Logout(request) return render(request, 'org_view/index.html', {'ModalFeedBack': Feedback, 'signin': True, 'AlertType': AlertType}) else: # 404 view dosen't have feedback Feedback = "Error!" return render(request, 'org_view/404.html', {'ModalFeedBack': Feedback}) else: Feedback = "Error you are not authorized!" return render(request, 'org_view/404.html', {'Feedback': Feedback}) else: Feedback = "Error you are not the authorized user!" return render(request, 'org_view/404.html', {'Feedback': Feedback}) -
Docker + Django + virtualenv + Heroku deployment
I would like to use Docker with my existing Django project in virtualenv and MySQL database. It seems to my that my solution is not optimal (BTW it is not working). My app is not finished, but I wonder if it is possible to deploy it on Heroku and working with it without publishing? I will be grateful if you could show me the best solution. To wit this is my docker-compose.yml: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" db: image: mysql environment: - MYSQL_ALLOW_EMPTY_PASSWORD=yes - MYSQL_USER=root - MYSQL_DATABASE=pri Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'pri', 'USER': 'root', 'HOST': 'db', } } Structure of my files looks in this way: DockerContainerDirectory: - docker-compose.yml - Dockerfile - requirements.txt - ProjectDirectory In ProjectDirectory I have virtualenv and Project: - bin - include - lib - pip-selfcheck.json - Project In Project I have git repository, back-end and front-end written in Angular2: - backendFolder - frontendFolder backendFolder: -backendProject -backendProject: - my project with `manage.py` etc. -
pysolr.SolrError: Solr responded with an error (HTTP 400): [Reason: ERROR: Error adding field msg=For input string
I am getting this error when I run python manage.py rebuild_index WARNING: This will irreparably remove EVERYTHING from your search index in connection 'default'. Your choices after this are to restore from backups or rebuild via the `rebuild_index` command. Are you sure you wish to continue? [y/N] y Removing all documents from your index because you said so. All documents removed. Indexing 1 lodging offers Failed to add documents to Solr: Solr responded with an error (HTTP 400): [Reason: ERROR: [doc=hosts.lodgingoffer.35] Error adding field 'ad_title'='Apartamento multifamiliar' msg=For input string: "Apartamento multifamiliar"] Traceback (most recent call last): File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/haystack/backends/solr_backend.py", line 73, in update self.conn.add(docs, commit=commit, boost=index.get_field_weights()) File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/pysolr.py", line 891, in add overwrite=overwrite, handler=handler) File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/pysolr.py", line 478, in _update return self._send_request('post', path, message, {'Content-type': 'text/xml; charset=utf-8'}) File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/pysolr.py", line 393, in _send_request raise SolrError(error_message % (resp.status_code, solr_message)) pysolr.SolrError: Solr responded with an error (HTTP 400): [Reason: ERROR: [doc=hosts.lodgingoffer.35] Error adding field 'ad_title'='Apartamento multifamiliar' msg=For input string: "Apartamento multifamiliar"] (ihost) bgarcial@elpug ‹ testing ●● › : ~/workspace/ihost_project [0] % I am using solr-6.6.0 and my ModelIndex fields generated by Haystack in my schema.xml are: <field name="ad_title" type="text_en" indexed="true" stored="true" multiValued="false" /> <field name="text" type="text_en" indexed="true" stored="true" multiValued="false" /> Just in case … -
Django get() returned more than one
i have this error, how can i fix this? get() returned more than one Event -- it returned 2! Can you guys tell me what that means and maybe tell me in advance how to avoid this error ? **MODEL** class Event (models.Model): name = models.CharField(max_length=100) date = models.DateField(default='') dicript = models.CharField(max_length=50, default='Описание отсутствует') category = models.ForeignKey(Category,on_delete=models.CASCADE) adress = models.TextField(max_length=300) user = models.ForeignKey(User,related_name="creator",null=True) subs = models.ManyToManyField(User, related_name='subs',blank=True) @classmethod def make_sub(cls, this_user, sub_event): event, created = cls.objects.get_or_create( user=this_user ) sub_event.subs.add(this_user) ***VIEWS** def cards_detail (request,pk=None): # if pk: event_detail = Event.objects.get(pk=pk) subs = event_detail.subs.count() # else: # return CardsView() args = {'event_detail':event_detail,'subs':subs} return render(request,'events/cards_detail.html',args) class CardsView (TemplateView):` template_name = 'events/cards.html' def get (self,request): events = Event.objects.all() return render(request,self.template_name,{'events':events }) def subs_to_event (request,pk=None): event = Event.objects.filter(pk=pk) Event.make_sub(request.user,event) return redirect('events:cards') -
local variable 'user' referenced before assignment issue
so i currently have my likes app which deals with friend requests, and it works fine however my notification dont seem to be working. Whenever some likes someone else regardless of weather they are liked by that user or not it only sends the second of the two notify.send. I presume its an issue with the line "user = get_object_or_404(User, username=user.username)", however i dont know how to get round it. Here is my code: def like_user(request, id): pending_like = get_object_or_404(User, id=id) user_like, created = UserLike.objects.get_or_create(user=request.user) user = get_object_or_404(User, username=user.username) liked_user, like_user_created = UserLike.objects.get_or_create(user=user) if pending_like in user_like.liked_users.all(): user_like.liked_users.remove(pending_like) elif request.user in liked_user.liked_users.all(): user_like.liked_users.add(pending_like) notify.send(request.user, #action=request.user.profile, target=request.user.profile, recipient=pending_like, verb='sent you a friend request view'), else: user_like.liked_users.add(pending_like) notify.send(request.user, #action=request.user.profile, target=request.user.profile, recipient=pending_like, verb='accepted your friend request view') return redirect("profile", username=pending_like.username) Here is an example of where the line " if request.user in liked_user.liked_users.all():" works fine i presume because the line " user = get_object_or_404(User, username=username)" has username in it. @login_required def profile_view(request, username): user = get_object_or_404(User, username=username) liked_user, like_user_created = UserLike.objects.get_or_create(user=user) do_they_like = False if request.user in liked_user.liked_users.all(): do_they_like = True However in my first bit of code I'm trying to use user.username instead of username=username but i get the error "local variable … -
Django request.FILES is empty when saving canvas image
I am creating a webapp where the an image is shown to the user and the user can draw on the image (basically the image is in a canvas). Now once the user is done drawing, the user will press the save button and the image needs to be saved in static folder (not locally). Since I am using Django to accomplish this; my request.FILES is always empty whenever I call the route. My question is how can I save the canvas on which the user drew to a folder in the project and not locally. index.html <div id="uploaderForm"> <form enctype="multipart/form-data" action="{% url 'addImg' %}" method="post"> <input type="hidden" for="image_data" id="image_data" name="image_data" /> </form> <div class="uploaderItem" id="uploaderSubmit"> <a href="#" onclick="addImage();">Add to the gallery</a> </div> </div> script.js function addImage() { console.log("In add image"); var image_data = canvas.toDataURL(); console.log("Image data:", image_data); $('#image_data').val(image_data); $('#uploaderForm > form').submit() } views.py def add(request): print request.FILES #print request.POST['image_data'] return HttpResponse("You're looking at question") -
AssertionError: False != True in django's form test
I'm testing my app's forms, and I've successfully tested two apps, but then I got an error when trying to test a form in a third app, I don't know what's the difference or what I did wrong, here is the error: AssertionError: False != True class EditGameForm_Test(TestCase): def test_EditGameForm_Test_valid(self): GameStatus.objects.create(GameStatusID=1, GameStatusTitle='Active') sID = GameStatus.objects.get(pk=1).pk form_data = {'GameName': 'Checkers', 'GameDescription': 'checkers game', 'GameCover': r'UsersImages/checkers_picture.png', 'GameStatusID ': sID, 'GameURL': 'Checkers'} form = EditGame(data=form_data) self.assertEquals(form.is_valid(), True) class EditGame(forms.ModelForm): class Meta: model = models.Game exclude = ('updated', 'created') def __init__(self, *args, **kwargs): super(EditGame, self).__init__(*args, **kwargs) self.fields['GameName'].widget = forms.TextInput( attrs={ 'class': 'form-control', 'name': 'GameName', } ) self.fields['GameName'].required = True self.fields['GameDescription'].widget = forms.Textarea( attrs={ 'id': 'Description', 'rows': '10', 'class': 'form-control', 'name': 'GameDescription', } ) self.fields['GameDescription'].required = True self.fields['GameCover'].widget = forms.FileInput( attrs={ 'id': 'input-6', 'name': 'GameCover', } ) self.fields['GameCover'].required = False self.fields['GameStatusID'].widget = forms.HiddenInput( attrs={ 'class': 'form-control', 'name': 'GameStatusID', } ) self.fields['GameURL'].widget = forms.HiddenInput( attrs={ 'class': 'form-control', 'name': 'GameURL', } ) -
How to change model class name without losing data?
How do you change the model class name in Django without losing data? Does anybody knows? Thank you very much to all for the help in advance. -
Django call_command
I have a little problem with call_command in Django. This is my Kronos decorator: @kronos.register('*/{} * * * *'.format(config.CRON_MIN)) In admin.py I have a function which returns new config.CRON_MIN value and runs call_command to reload cron jobs: @receiver(config_updated) def constance_updated(sender, key, old_value, new_value, **kwargs): call_command('installtasks') print(key, old_value, new_value) In my terminal window I see: 1 tasks removed, 1 installed. CRON_MIN 3 4 but when I check it by typing: crontab -l I see cron job with old value of CRON_MIN. When I run installtasks command manually it works as It should (python manage.py installtask). It properly changes interval in kronos cron job. Where I make a mistake? -
Django Admin - choices working for one Integer model, but not another
I'm making a tea catalog in Django, and I'm having a bit of an issue with the models. I want some things in the database to have choices for 1-5, for certain ratings. For example, for the tea type, I want a caffine level of 1-5. I do this with the following code: one_to_five_choices = zip(range(1,5+1), range(1,5+1)) ... class TeaType(models.Model): name = models.CharField(max_length=20, primary_key=True) steeping_temperature = models.PositiveSmallIntegerField() steeping_time_minutes = models.PositiveSmallIntegerField() caffeine_level = models.PositiveSmallIntegerField(choices=one_to_five_choices) directions = models.TextField() def __str__(self): return self.name And it works perfectly! However, I seemingly have the same code for ratings, and it does not show this box for the choices. class Rating(models.Model): rating = models.PositiveSmallIntegerField(choices=one_to_five_choices) tea = models.ForeignKey(Tea) user = models.ForeignKey(User) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return "{} star rating for {} by {}".format(self.rating, self.tea, self.user.get_username()) class Meta: unique_together = (("user", "tea"),) And here is the picture: Any idea why this is happening? -
Using django bulk_create with M2M relations
I have a bunch of object in a response object, which I save into the database. Doing it object by object is very slow since that essentially means if its 30k objects, its gonna make 30k commits to the database afaik. Example 1: for obj in response['RESULTS']: _city = City.objects.create( id=obj['id'], name=obj['name'], shortname=['shortname'], location=['location'], region=['region'] ) _events = Event.objects.get(pk=obj['Event']) _events.city_set.add(_city) My new approach to implement bulk_create() is something like this: Example 2: bulk_list = [] for obj in response['RESULTS']: bulk_list.append( City( id=obj['id'], name=obj['name'], shortname=['shortname'], location=['location'], region=['region'] ) ) bulk_save = City.objects.bulk_create(bulk_list) While this is alot faster than my previous attempt it has a problem, now I dont know how to add my M2M relationships. Questions I have looked around on stackoverflow and have found some examples but I dont understand them completely.. it seems like most answers talks about bulk_create the M2M relations aswell via a through model, and im not sure thats what I am looking for. How can I add those M2M relations? Please break it down so I can understand, I want to learn :-) Any help or pointers are highly appreciated. Thank you. Other information I run: postgresql django==1.11 Related posts Django setting many_to_many object while … -
Django Admin - Sorting Table by Average of related Ratings model
I'm designing a tea website, with two related models. class Tea(models.Model): ... def avg_rating(self): return self.rating_set.aggregate(Avg('rating'))['rating__avg'] one_to_five_choices = zip( range(1,5+1), range(1,5+1) ) class Rating(models.Model): rating = models.PositiveSmallIntegerField(choices=one_to_five_choices) tea = models.ForeignKey(Tea) user = models.ForeignKey(User) ... class Meta: unique_together = (("user", "tea"),) And then in the admin, I have one of the list_display fields avg_rating, which is the function that gets the average of all the ratings for a particular tea. @admin.register(Tea) class TeaAdmin(admin.ModelAdmin): list_display = ('name', 'type', 'brand', 'avg_rating') The problem with this is that it does not allow sorting. Is there a better way to do this that allows for sorting? Also - is this the best way to do ratings in general? I couldn't think of a better one. -
Update Django database after drag & drop through javascript
I want to do a kanban table(project management) but I have no ideea how to save the modification in database after I drop a task(from todo to in progress for example). This is how my model looks class Task(models.Model): TODO = 1 INPROGRESS = 2 DONE = 3 STATUS_TYPES = ( (TODO, 'To do'), (INPROGRESS, 'In progress'), (DONE, 'Done'), ) taskid = models.AutoField(primary_key=True,default = increment_booking_number) projectcode = models.ForeignKey('Project', models.DO_NOTHING, db_column='projectid') taskname = models.CharField(max_length=100) taskdescription = models.TextField(max_length=500, blank=True, null=True) task_status = models.PositiveSmallIntegerField(choices = STATUS_TYPES, blank=True, null=True) here is my javascript for drag and drop: https://paste.fedoraproject.org/paste/pAcECud8nRItO5nJefYF0w Any help please? This is how the table should look -
local variable 'user' referenced before assignment error
I keep getting the error "local variable 'user' referenced before assignment". I'm trying to replicate the user = line of code in this function: def profile_view(request, username): user = get_object_or_404(User, username=username) withing this function, as you can see on on the bottom line: def like_user(request, id): pending_like = get_object_or_404(User, id=id) user_like, created = UserLike.objects.get_or_create(user=request.user) user = get_object_or_404(User, username=user.username) however as im not passing through username into the function, so I'm trying to use user.username but i get the error "local variable 'user' referenced before assignment". What is the best way round this? am i do it completely wrong? should i try and pass in username, because when i do i get the error "like_user() takes exactly 3 arguments (2 given)". Sorry quite new to django, any help would be massively appreciated! Thanks -
Django: Can't query a foreign field
I'm still a novice so any help is gladly appreciated. Running Django 1.10 I'm trying to retrieve all the profiles that are assigned a particular manager but my query set always comes up empty. Model.py Blockquote class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=30, blank=False) email = models.EmailField( blank=True, help_text='Optional',) receive_email_notifications = models.BooleanField(default=False) manager = models.ForeignKey(User, unique=False, blank=True, related_name='+', null=True) def get_full_name(self): """ Returns the first_name plus the last_name, with a space in between. """ full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def publish(self): return self.save def __str__(self): return str(self.user) View.py Blockquote def instrument_list(request): # pulls all instruments from instrument model instruments = Instrument.objects.all().order_by('instrument_name') test = Profile.objects.filter(manager='jenn') print(test) # pulls all checklists from checklist model checklists = Checklist.objects.all().order_by('created_date') # takes instruments, pushes them to template with variable 'instruments' return render(request, 'blog/instrument_list.html', {'instruments': instruments, 'checklists': checklists}) I've also tried filtering a single profile entry (with a non-foreign key attribute) and printing how managers are saved in the database and the output looked like this Blockquote <User: jenn> However, even when I try filtering with that output, my query sets come up empty Blockquote test = Profile.objects.filter(manager='<User: jenn>') I think I need to adjust my … -
Setting the Python Django app on godaddy vps
Hello all correct me if this is not a good platform to ask the such server management questions. I have a VPS on godaddy on which i want to deploy my django site. There are bundle of problem which i am facing and i want solution the community or some suggestions. First of all i want to tell you that i have read the question and searched on this topic but all the articles were about 2 to 4 years, when godaddy did not support the python. Problem 1: I have VPS based upon CentOS, so first problem is there is python 2.6.6 and my app is on 2.7 so does it really matters? i tried to upgrade without breaking the yum but it did not upgrade the python and give error at pip install. Problem 2: I tried to deploy/host a simple welcome html page on but did not happened successfully. I used httpd along with apache for this simple site. I want some solution and i really banging my head for django app to be deployed on this server. Sorry to say but godaddy technical support is not enough in any article. -
Why does Django save pictures twice?
I am trying to overwrite the save function. What I want is to resize the original photos to a default size (800 * 534) and then to generate a thumbnails for this picture. However, I found the photos were stored twice. For example, I add a photo named sample.jpg at first time. There are three photos in my directions. One is in ../Media/photos/ and the others are in ../Media/. When I save this picture again, there are four photos. Two are in ../Media/photos/, and the others are in ../Media/. I am really confused why Django stores the picture twice. What I want is only two pictures in ../Media/photos. Here are my codes. The class Photo: class Photo(models.Model): title = models.CharField(max_length=250) slug = models.SlugField(max_length=250) summary = models.TextField(blank=True) created_date = models.DateField(auto_now_add=True) modified_date = models.DateField(auto_now=True) image = models.ImageField(upload_to='photo/') album = models.ForeignKey(Album, on_delete=models.CASCADE) is_cover_photo = models.BooleanField(default=False) The save function I wrote in class Photo def save(self): if not self.pk: filename = self.image if filename: print(filename) img = Image.open(filename) # save the default size photo default_size = (800, 534) img.thumbnail(default_size, Image.ANTIALIAS) img.save(self.get_img_filename(filename)) # save thumbnail photo cover_size = (342, 229) img.thumbnail(cover_size, Image.ANTIALIAS) img.save(self.get_img_thumb_filename(filename)) super(Photo, self).save() And the other two functions: def get_img_filename(self, img): return img.path … -
Get ManyToMany objects
I'm building a simple application to learn Django. Basicly a portfolio can have multiple companies in it. I want to display the companies of a certain portfolio of the logged in user. Models.py class UserPortfolio(models.Model): name = models.CharField(max_length=128, default='X') user = models.ForeignKey(User) #Company = models.ManyToManyField(Company) def __str__(self): return self.name class Company(models.Model): name = models.CharField(max_length=128, default='X') slug = models.SlugField(max_length=6, default='X', unique=True) def get_absolute_url(self): return reverse('news:detail',kwargs={'pk': self.pk}) def __str__(self): return self.slug class PortfolioCompany(models.Model): UserPortfolio = models.ForeignKey(UserPortfolio) Company = models.ManyToManyField(Company) views.py portfolio = UserPortfolio.objects.filter(user=self.request.user) myPortfolioRel = PortfolioCompany.objects.filter(UserPortfolio=portfolio) But now it only displays the ID of the portfolioCompany. How can I display the Companies inside the UserPortfolio?