Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
smtplib.SMTPServerDisconnected after sending multiple mails in Django
I have a blog post objects. After blog post created I have a signal to dispatch emails. And I want to send emails to multiple subscribers. I am using google mail as a mail server. I put in my settings file some attributes for using mail: EMAIL_HOST = settings['EMAIL']['HOST'] EMAIL_PORT = settings['EMAIL']['PORT'] EMAIL_HOST_USER = settings['EMAIL']['USER'] EMAIL_HOST_PASSWORD = settings['EMAIL']['PASSWORD'] EMAIL_USE_TLS = True And function to dispatch mails. Function is a celery task. @shared_task def email_dispatch(heading, text): recipients = TheUser.objects.filter(subscription=True) for recipient in recipients: try: html_content = render_to_string('mails/email_dispatch.html', {'text': text}) text_content = strip_tags(html_content) subject = '{}'.format(heading) email = EmailMultiAlternatives(subject, text_content, to=[recipient.id_user.email]) email.attach_alternative(html_content, 'text/html') email.send() logger.info('Successful processed "{}", sent to: "{}"'.format(count_processed, recipient.id_user.username)) except NoReverseMatch: logger.info('Unexpected username: "{}"'.format(recipient.id_user.username)) logger.info('Email dispatching has been finished.') At a first glance, all work okay. When celery task starts executing it dispatches correctly. But after approximately sent ~80 emails I receive smtplib.SMTPServerDisconnected: Connection unexpectedly closed Unfortunately, I didn't found any info about Google Mail restrictions in that case. Maybe I am setting something wrong from Django side or using an incorrect function for this case. Thank you for any help. -
Django REST Framework - pass related field in POST data
I'm using Django 2.0 and Django REST Framework I have a model to store contact's address like class ContactAddress(models.Model): contact = models.ForeignKey(Contact, on_delete=models.CASCADE) city = models.CharField(max_length=250) postal = models.CharField(max_length=6) state = models.ForeignKey(State, on_delete=models.PROTECT, blank=True) I have two more models to store state and country class Country(models.Model): name = models.CharField(max_length=100, unique=True, verbose_name='Country Name') class State(models.Model): country = models.ForeignKey(Country, on_delete=models.PROTECT) name = models.CharField(max_length=100, verbose_name='State Name') I want to pass state field with POST data while creating a new address record app/serializers.py class ContactAddressSerializer(serializers.ModelSerializer): class Meta: model = ContactAddress depth = 2 fields = ( 'id', 'city', 'postal', 'state' ) def create(self, validated_data): print(validated_data) and my POST data [ { "city": "City Name", "postal": "110011", "state": "Bihar" } ] But there is no state data in validated data. Printing validate_data return def create(self, validated_data): print(validated_data) {'city': 'City Name', 'postal': '110011', 'contact': <Contact: contact_object>} How can I pass POST data for related field? -
Push has been rejected in heroku django
check this [1]: https://i.stack.imgur.com/Z2fvM.png please check this image -
Django - serving an Angular app
I'm trying to integrate Angular and Django and I am encountering a problem when I point to the index.html in the angular folder. My url pattern in djangoapp.urls.py is: urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^.*/$', TemplateView.as_view(template_name="index.html")), ] Which successfully opens the index.html template in my angular app. However, the angular app isn't able to reach the app.component.html and deliver content. I just get a blank page (index.html, which displays nothing atm) when i visit 127.0.0.1:8000/anything. If I cd into angular app directory and ng serve --open and visit 127.0.0.1:4200 I get the regular front page you would get with app.component.html in the mix (The angular welcome page). The templates are the standard ng new templates, index.html: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>AngularWebapp</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> </head> <body> <app-root></app-root> </body> </html> app.component.html: <!--The content below is only a placeholder and can be replaced.--> <div style="text-align:center"> <h1> Welcome to {{ title }}! </h1> <img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg=="> </div> <h2>Here are some links to help you start: </h2> <ul> <li> <h2><a target="_blank" rel="noopener" href="https://angular.io/tutorial">Tour of Heroes</a></h2> </li> <li> <h2><a target="_blank" rel="noopener" href="https://github.com/angular/angular-cli/wiki">CLI Documentation</a></h2> </li> <li> <h2><a target="_blank" rel="noopener" href="https://blog.angular.io/">Angular blog</a></h2> </li> </ul> How … -
Key Error in a class based DetailView
I've had this problem a few times before but I've always been able to work it out. This time I cant. Its just returning: "Key error at streams/sport_slug 'pk' " The error at at line 34 in the Views, which I have highlighted below: Views.py: class StreamSport(ListView): template_name = "stream/stream-index.html" context_object_name = 'stream_list' def get_queryset(self): self.sport = get_object_or_404(Sport, sport_slug=self.kwargs['sport_slug']) *self.pk = Video.objects.filter(pk=self.kwargs['pk'])* return Video.objects.filter(sport=self.sport, pk=self.pk) URLs.py: app_name = 'streams' urlpatterns = [ path('', StreamIndex.as_view(), name='stream-index'), path('<slug:sport_slug>/', StreamSport.as_view(), name='stream-sport'), path('<slug:sport_slug>/<int:pk>/', StreamDetail.as_view(), name='detail'), stream-index.html: <a href="{% url 'streams:detail' video.sport.sport_slug video.pk %}" -
How to create nesting models in django
Level has many questions, each question has one level. And the tree goes no from there + Level - Question + Level - Question + Level - Question + Level - Question + Level - Question + Level - Question + Level - Question + Level - Question + Level -
IntegrityError: music_song.album_id may not be NULL
I'm Django beginner and facing this error "music_song.album_id may not be NULL" and i was trying to solve this error but unfortunately can't solve it. i put almost all my code here so please Django Experts review the code and let me tell from where i did a mistake? Views.py def model_form_upload(request, pk): all_song = Song.objects.all() print'\n-------------------------------------------------------' if request.method == 'POST': print request.FILES form = SongForm(request.POST, request.FILES) if form.is_valid(): songName = request.FILES['audio_file'] #getting song name fs = FileSystemStorage() #allocate memory uploaded_file_url = fs.url(songName) #getting url of uploaded file form.save() #song saved return render(request, 'music/model_form_upload.html', {'uploaded_file_url': uploaded_file_url, 'form': form}) else: form = SongForm() return render(request, 'music/model_form_upload.html', {'form': form, 'all_song': all_song}) forms.py class SongForm(forms.ModelForm): class Meta: model = Song fields = ('song_title', 'audio_file') models.py from django.db import models from django.core.urlresolvers import reverse from .validators import validate_file_extension class Album(models.Model): artist = models.CharField(max_length=100) album_title = models.CharField(max_length=100) genre = models.CharField(max_length=100) album_logo = models.FileField() def get_absolute_url(self): return reverse('music:upload', kwargs={'pk': self.pk}) def __str__(self): return self.artist class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) song_title = models.CharField(max_length=250, blank=True) audio_file = models.FileField(validators=[validate_file_extension], max_length=500) uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.song_title urls.py url(r'^(?P<pk>[0-9]+)/upload/$', views.model_form_upload, name='upload') model_form_upload.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> {% if uploaded_file_url %} … -
Django: How can i use a dynamic id in loops?
I am trying to build a calendar that - for the moment - shows the number of the clicked button in an popup-window (modal). This is working for button#1 but every other button Shows number 1 as well. Example: Click on Button #5: Modal shows: "Clicked Button: 5" (at the moment it shows: "Clicked Button: 1") Does anybody have an idea? Extract of the .html file: (The tags are closed correctly in the document!) <body> <div id='wrapper'> <div class="daybox"> <ul> {% for i in "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" %} <p>count={{forloop.counter}} <button id="count" class="btn btn-primary btn-lg">{{forloop.counter}} </button> </ul> </div> </div> ..... <div class="form-group"> <h1>Test for ID</h1> <h2>Clicked button: {{forloop.counter}}</h2> </div><!---form group---> ... <script> $(document).ready(function(){ $("#count").on('click',function(){ $("#modal").modal({show:true}); });//SHOw MODAL $("#close").on('click',function(){ $('#modal').modal('hide'); }); }); </script> {% endfor %} -
Creating views for a Django application to return object data as JSON & JSONP
I'm trying to create views for my django application to utilize models I've created beforehand. The models are the continents/countries of the world and the views are meant to return stringified data of them, depending on what has been called. The views are either called to return JSON/JSONP -formatted data, and either data related to a single country or data related to a continent. I'm trying to create the view for a single country first, but I'm not entirely sure if what I'm doing is exactly correct. def country_json(request, continent_code, country_code): country = Country(code = country_code) country.save() var obj = { area: country.area, population: country.population, capital: country.capital, json: function() { return JSON.stringify(this); } } return HttpResponse(obj, content_type="application/json") I have to figure out a way to check whether I have to return as JSON/JSONP, but I think it should be somewhat simple by viewing the request (check if the request has callback?), but I'm not entirely sure if what I've got here now works even for what I want to achieve at this stage. The model for a country looks like class Country(models.Model): name = models.CharField(max_length=60, default='', unique=True) code = models.CharField(max_length=3, default='', unique=True) capital = models.CharField(max_length=60, default='') population = models.PositiveIntegerField(default=0) area … -
exporting datetime to excel in django using xlwt
I am exporting data to excel(.xls) in django using xlwt module but datetime is exporting in this 43239.6389467593 format. I dont know what is this format and how to change it to datetime in excel sheet -
Using 'with' template tag in combination with 'if' template tag
In Django templates we can use with: {% with total=business.employees.count %} {{ total }} employee{{ total|pluralize }} {% endwith %} Can we use with in combination with if I tried: {% with a={%if product.url %}product.url{%else%}default{%endif %} %} but I get an error: Could not parse the remainder: '{%if' from '{%if' -
Django: Moving 'oscar' site-package
I am starting my own Django-Oscar project, and am wondering about the possibility of changing the location of the 'oscar'-directory (containing all apps, a models.py etc), moving it from the default on-installation site-packages directory within my virtual environment - into my project root directory. Would it be possible to simply copy the 'oscar'-directory, and paste it into a new location, assuming I also change the locations of the 'INSTALLED_APPS', and make sure that my project-structure is the same (i.e. not changing things like the directory-name 'oscar' so that imports etc break)? If so, would that mean that I could delete it all together from site-packages (DRY-solution)? This would mimic the sandbox-installation, and would be a set up I'd feel more comfortable with as a beginner who needs visible overhead. Thank you! -
NoReverMatch error that looks for something non-existant
I am working with an unfamiliar code base and added in something that broke the rest of the pages I was working with, and I have no clue how. It seems to be looking for something I wrote, but I commented out any reference to what I wrote and it is still giving me this error: NoReverseMatch at /exercise/onboardintro/2e0a85f0-751b-4246-a024-ab0a95ef978a/ Reverse for 'client_submit' with arguments '('2e0a85f0-751b-4246-a024-ab0a95ef978a',)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I understand why that error happens, but the pages that this error happens on have no connection to "client_submit", which is something I wrote. I completely undid and commented out anything that had to do with "client_submit" yet the error still persists. How is that even possible? -
ImportError: No module named "webisite_dj"
I am getting an below error while running manage.py run server. Directory: C:\Users\home\Desktop\website_dj>ls 557 manage.py PS C:\Users\home\Desktop\website_dj> python manage.py runserver ImportError: No module named 'website_dj' -
Django model ForeignKey backwards referencing and AttributeError when trying to use ManyToManyField
So I'm trying to build models for a database that reads an .xml file with a given data format, and I'm having trouble at setting backwards compatibility. My models are from django.db import models class Continent(models.Model): name = models.CharField(max_length=60, default='', unique=True) code = models.CharField(max_length=3, default='') countries = models.ManyToManyField( 'Continent', through='Country', ) class Country(models.Model): name = models.CharField(max_length=60, default='', unique=True) code = models.CharField(max_length=3, default='', unique=True) capital = models.CharField(max_length=60, default='') population = models.PositiveIntegerField(default=0) area = models.PositiveIntegerField(default=0) continent = models.ForeignKey(Continent, default='', related_name='related_name') and as you can see, I'm a bit clueless when it comes to related_name. Anyhow, running a test that has parsed through this data gives me the error AttributeError: 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache' but I'm not sure how I should approach to eliminate it. The test tries to run fi = europe.countries.get(code="fi") and raises an exception if it can't find anything for it (the data holds every continent and country), so the backwards referencing is not functional as of yet. -
How to get the object of self children from a parent-child relationship model
I am making an application like Twitter's clone with Django and DRF, among which the following models are available. Reply is a model that defines the parent-child relationship of Post. class Post(models.Model): tweet = models.CharField(max_length=140, blank=False) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) created_at = models.DateTimeField(auto_now_add=True) @property def children(self): reply_obj = Reply.objects.filter(parent=self) children = [] for obj in reply_obj: children.append(obj) return children class Reply(models.Model): parent = models.ForeignKey( Post, related_name='parent_post', on_delete=models.CASCADE ) child = models.ForeignKey( Post, related_name='child_post', on_delete=models.CASCADE ) created_at = models.DateTimeField(auto_now_add=True) I'd like to get a list of Post object that become children of that Post with property children. However, if you write Post.objects.get (id = 1) .children in View, for example, you can use<django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager. <Locals> .RelatedManager object at 0x10d0395c0> Is returned, and I can not get the expected result. How can I get good results? -
In django queryset filter, how to check if at least one key in json field is non empty?
class Library(models.model): book = JSONField(default=[], blank=True, null=True) possible structure of 'book' is {'title':'' ,'no_of_pages': '', 'author_name': '', 'color': '', edition: ''} I am trying to write a django query that returns only records where book has at least one non empty key ( i.e either title or no_of_pages or author_name or color or edition has some value) one possible solution to this is something like: Author.objects.filter( Q(book__title__is_null=False) | Q(book__no_of_pages__is_null=False) | Q(book__author_name__is_null=False) | Q(book__color__is_null=False) | Q(book__edition__is_null=False) ) is there any better way to do this ? As there may be case where book can have some additional keys in future like publisher or availabilty How can I perform this filter without having to mention the specific keys of the field ( just check at least one key with some value) ? or any shorter method to write this query with all the keys mentioned ? -
ForeignKey dateField result none
here my model and views models.py class ClosingDate(models.Model): ... name = models.CharField(max_length=255) date_from = models.DateField() class Salary(models.Model): ... closingdate = models.ForeignKey(ClosingDate, related_name='closingdate') desc = models.TextField(blank=True, null=True) Views.py class CreateView(CreateView): fields = ('employee', 'closingdate') model = models.Salary def form_valid(self, form): self.object = form.save(commit=False) self.object.desc = str(self.object.closingdate.date_from) self.object.save() return super(ModelFormMixin, self).form_valid(form) iam trying to get datefield and post it into str, i do with str(self.object.closingdate.date_from) but result none. but when i try take the name str(self.object.closingdate.name) its working as well. whats wrong with my code?... what should i do?... thank you! -
django rest framework APIView returns json with scape caracters
I have an APIView that constructs a json based on several model objects, but the resulting jason has a backslash before every doble quote, and some other scaped codes. This is my APIView: class RoundtripCompositionAPIView(APIView): def get(self, request, pk, format=None): try: roundtrip = models.Roundtrip.objects.get(id=pk) except: return Response({}) try: tours = models.RoundtripTour.objects.filter(roundtrip=roundtrip) except: tours = None try: hotels = models.RoundtripHotel.objects.filter(roundtrip=roundtrip) except: hotels = None try: services = models.RoundtripService.objects.filter(roundtrip=roundtrip) except: services = None roundtrip_composition = { 'roundtrip': core_serializers.serialize('json', [roundtrip]), 'tours': core_serializers.serialize('json', tours), 'hotels': core_serializers.serialize('json', hotels), 'services': core_serializers.serialize('json', services) } return Response(roundtrip_composition) And this is the result I get: { "roundtrip": "[{\"model\": \"ReservationsManagerApp.roundtrip\", \"pk\": 1, \"fields\": {\"name\": \"Intelectual\", \"code\": \"iii\", \"duration\": 10, \"description\": \"Todas las formas de sublimaci\\u00f3n intelectual: arte, ciencia y tecnolog\\u00eda.\"}}]", "tours": "[{\"model\": \"ReservationsManagerApp.roundtriptour\", \"pk\": 1, \"fields\": {\"roundtrip\": 1, \"tour\": 1, \"day\": 1}}]", "hotels": "[]", "services": "[]" } I would like to know to get a clean json. I also get the name of the model in the resulting json and I would like it to content only user data. Thanks for your help -
The QuerySet value for an exact lookup must be limited to one result using slicing-Django
I'm building a news website.While I tried to get the list of relative news which have the same tags.The error said:The QuerySet value for an exact lookup must be limited to one result using slicing-Django. I have two models News and Tag,Tag is a many to many foreign key of News. News model: class News(models.Model): tag = models.ManyToManyField(Tag, blank=True, verbose_name='tag') Tag model: class Tag(models.Model): name = models.CharField(max_length=40) View: def newsDetailView(request, news_pk): news = get_object_or_404(News, id=news_pk) tags = news.tag.annotate(news_count=Count('news')) relative_news = News.objects.filter(tag=tags) return render(request, "news_detail.html", { 'news': news, 'tags': tags, 'relative_news': relative_news }) Any friend can help?Thank you so much! -
How to search in cassandra case-insensitive?
I am learning cassandra with Python and specially with Django 2 using cqlengine. I am trying to search in database where I search for string that starts with the search parameter but I want to make it case insensitive. So if I have following data ------------------------------- | PKID | String | ------------------------------- | 1234 | FOObar | | 4321 | FoOBar | | 5665 | IreALLy | | 5995 | DontknoW | | 8765 | WHatTOdo | | 4327 | foobaR | ------------------------------- So if I want to search for string that starts with foo, I should get all three records. I searched for the solution and I found one comment on stackoverflow that everything is byte in cassandra and so it is not possible but I also found something that says I need to write custom function to do it. For Django I am using django-cassandra-engine to create model. It is an implementation of cqlengine for django. So when I create my model, is there anything that I need to add in it? My test model is class TestModel(DjangoCassandraModel): key_id = columns.UUID(primary_key=True, default=uuid.uuid4) string = columns.Text() I looked for it in cqlengine docs but couldn't find anything helpful. So … -
Error while running attempting to start a new project on Django using 'django-admin startproject website'
Basic Information: I am completely new to Django, and have been attempting to follow their documentation. When I attempt to run the code shown here, it comes up with an error: django-admin startproject website Error message: django-admin is not recognized as an internal or external command, operable program or batch file. (https://gyazo.com/5159e172f1d0235b49db4fb4a73469cc) System Information: Python version: 3.6.3, Computer Operating System: Windows 10, Django version: 2.0.5 -
Disply the list of users with total posts
How can I display the list of users with the count of total number of posts made by them in a separate HTML page ? models.py class Post(models.Model): author = models.ForeignKey(User.request, on_delete = models.CASCADE) title = models.CharField(max_length=100) text = models.TextField() slug = models.SlugField(unique=True, blank=True, default=uuid.uuid1) created_date = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(User, related_name='post_likes', blank = True) def get_like_url(self): return reverse("posts:like-toggle", kwargs={"slug": self.slug}) def get_api_like_url(self): return reverse("posts:like-api-toggle", kwargs={"slug": self.slug}) def get_absolute_url(self): return reverse("post_detail",kwargs={'pk':self.pk}) def __str__(self): return self.title def count_posts_of(user): return Post.objects.filter(author=user).count() -
Upload image and show it on template - Django 2.0
I have this code on my template: {% extends "base.html" %} {% block content %} <div style="padding:40px;margin:40px;border:1px solid #ccc"> <h1>picture</h1> <form action="" method="post" enctype="multipart/form-data"> <!--{% url 'imageupload' %}--> {% csrf_token %} {{form}} <input type="submit" value="Upload" /> </form> {% for img in images %} {{forloop.counter}}.<a href="{{ img.pic.url }}">{{ img.pic.name }}</a> ({{img.upload_date}})<hr /> {% endfor %} </div> {% endblock content %} Although I have doubts with the form action but anyways. The problem is that when I click on submit button, it takes me to a blank page, no pop-up to actually upload the image, nothing. Is there some example I should follow to accomplish this? Also, this is just a proof test, but I'd like to know if a model and/or form is actually needed for it to work? -
Issues with path() in urls.py in django 2.0.5
I am trying to do the following thing in urls.py but Django 2.0.5 doesn't seem to support url(). Instead of it, I used path() but still, its throwing invalid syntax error. Can someone give a clearer picture of path() as it seems to be not supporting regex. Providing the code here: from django.contrib import admin from django.urls import path from .views import home_page urlpatterns = [ path('$', home_page) path('admin/', admin.site.urls), ]