Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django use AWS sand mail, "SESAddressNotVerifiedError: 400 Email address is not verified."
I use django and AWS to send mail. I have move my account out of sandbox. Your account has also been moved out of the sandbox I use "boto" and "django-ses". My setting.py is EMAIL_BACKEND = 'django_ses.SESBackend' AWS_ACCESS_KEY_ID = '************************' AWS_SECRET_ACCESS_KEY = '****************************************' AWS_SES_REGION_NAME = 'us-west-2' AWS_SES_REGION_ENDPOINT = 'email.us-west-2.amazonaws.com' And view.py is from django.core.mail import EmailMessage from django.core.mail import send_mail Megti = '*********' Megco = '*********' send_mail( Megti, Megco, 'XXXX@XXXXXX.com', [aproduct.commail], fail_silently=False) I get error: SESAddressNotVerifiedError at /success/success SESAddressNotVerifiedError: 400 Email address is not verified. <ErrorResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/"> <Error> <Type>Sender</Type> <Code>MessageRejected</Code> <Message>Email address is not verified. The following identities failed the check in region US-WEST-2: XXXX@XXXXXX.com</Message> </Error> <RequestId>3cdc4a07-6523-11e7-b493-1d79005a6fdc</RequestId> </ErrorResponse> Could someone help me? -
I cant query a unique User info to show up on their profile
Here are my Views and My models.I am trying to make a profile page in django. I have tried many tutorials and reading the documentation but I have yet to be able to pull all the user's post to a their profile #views.py class UserView(generic.ListView): model = Post template_name = 'post/user_page.html' context_object_name = 'all_post' def get_queryset(self): return Post.author.all() #Models.py class Post(models.Model): creator = models.CharField(max_length=250) post_name = models.CharField(max_length=250) category = models.CharField(max_length=250) post_photo = models.FileField() author = models.ForeignKey(User, blank=True, null=True, related_name ='user_post') category = models.ManyToManyField(Category) def get_absolute_url(self): return reverse('post:detail', kwargs={'pk': self.pk}) def __str__(self): return self.creator + ' - ' + self.post_name -
unable to run django project in other system
I have a Django project copied from a system. I have copied it to my system and I have put it in Apache www directory. Now When I run command $python mamange.py runserver it is giving error Import Error: NO module named jet can anyone please identify bug. Thanks in advance -
django how to get sum of decimal in view?
I'm using django to make website. I want to get total pay by members_pay one line of views.py members_pay = members.aggregate(Sum('payment_amount')).get('payment_amount__sum',0.00) I tried, total = int(0) total += total+ memebers_pay But, it occurs error 'unsupported operand type(s) for +=: 'decimal.Decimal' and 'NoneType'. payment_amount is demicalfield, so mayve total is NoneType. How I get total sum of members_pay ?? -
template does not exist error in django
part_stock_form.html {{ update_form }} part_detail.html <div> <form id="update_form" action="" method="post"> {% csrf_token %} <div id="my_form"> {% if update_form %} {{ update_form }} {% else %} {% include 'part_stock_form.html' %} {% endif %} </div> <input type="submit" id="btn_stock_update" style="display: none;"> </form> </div> $(function () { $('.edit_btn').on('click',pop_up); function pop_up() { var update_url = url to update stock; $('#update_form').attr('action',update_url); $("#my_form").load(update_url,function () { $("#btn_stock_update").show(); }); }); </script> UpdateView class stock_update_view(UpdateView): model = part_stock fields = ['part_id','entry_date','supplier','amount','remaining'] success_url = reverse_lazy('parts:part_list') template_name = 'part_stock_form.html' def get_context_data(self, **kwargs): context = super(stock_update_view, self).get_context_data(**kwargs) context['update_form'] = context.get('form') return context def form_invalid(self, form): print("form is invalid") return render(self.request, 'part_details.html', {'update_form': form}) when the form is valid it works fine but when the form is invalid, an error is obtained -
Django + MySQL - Admin Site - Add User Error
We're trying to have a custom User model and behaviors, but then we noticed that even the default Django installation has issues when adding a new User via the Django Admin. The issue happens even in other Django versions (e.g. Django 1.8, Django 1.10, etc). Surprisingly, the issue does not happen when using SQLite or PostgreSQL databases. Also, adding user via $./manage.py createuser and programmatically will work. Editing existing uses like the created admin superuser user will work. CRUD mechanisms for Group also work, hence only the Add User view is affected. Possible point of failures include the Django core (any version), MySQL binary (bundled in XAMPP for Mac, tried various versions also), or the Python-MySQL connector (version 1.2.5). Related issue here, using Django 1.10 w/ MySQL also. Steps to replicate: Install the latest Django version: $ pip install django Install the Python-MySQL driver: $ pip install MySQL-python Create a new project: $ django-admin.py startproject sandbox Create a new database in MySQL and set the db config in settings.py Migrate the Django apps' models: $ ./manage.py migrate Create an admin superuser: $ ./manage.py createsuperuser Run the Django's bundled server: ./manage.py runserver Go to http://127.0.0.1:8000/admin/login, and login w/ the admin superuser … -
How do I use requests_cache with django?
I am currently using requests to receive json data from third party API services and would like to cache the data to limit the number of call requests. If my requests code are inside methods in views.py, where do I put the install_cache code below? When should this line be called? requests_cache.install_cache('demo_cache') -
OperationalError in Django app: models.py
There's an OperationalError in my models.py code. Can anyone pinpoint the problem? I have tried deleting the cache, along with previous migrations and doing them over - doesn't help the issue. from django.db import models # Create your models here. class Topic(models.Model): """A post within a blog.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of a model.""" return self.text class Post(models.Model): """Class for Blog Post entries.""" topic = models.ForeignKey(Topic) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'posts' def __str__(self): """Return a string representation of the model.""" return self.text[:50] + "..." It gives me the following errors, if this helps: OperationalError at /admin/blogs/post/ no such table: blogs_post -
Django ORM alternatives
Is there a good feature-wise alternative to the django ORM? Specifically the migrations and the error handling. I am developing an application which is not for the web, so django is overkill. I am using sqlalchemy at the current time but dislike (or havent found the right groove) some of its behaviors. For example the required rollback after an insert with a pk collision. The migration packages also look too work intensive. Am I making something wrong? I really want to like it but fail to understand the minimalism at some points. Some code, maybe it helps: Base = declarative_base() class Apartment(Base): __tablename__ = 'apartment' id = Column('id', primary_key=True) # address street= Column('street', String(128)) house_number = Column('housenumber', String(32)) zip = Column('zip', String(16)) city = Column('city', String(64)) country = Column('country', String(64)) def save(self): try: session.add(self) session.commit() except IntegrityError: session.rollback() @staticmethod def objects(): return session.query(Apartment) conn_string = 'postgres://....' engine = create_engine(conn_string) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() -
'WSGIRequest' object has no attribute 'user_agent'
I am using a package called django-tracking-analyzer. if request.user_agent.is_mobile: This line is causing the problem. I have noticed that in the documentation it is asking for a HttpRequest object and this is a wsgi object. I am not able to understand what is causing the issue. Please help me out. -
How do I use Django-Postman and integrate it into my app?
So I just started learning Django last week and am trying to make a web app that allows users to message each other. I decided to use Django-Postman. I do not have a firm grasp on Django packages and how to install them. I think I've installed Django-Postman and included it in my app. I've gotten as far as including postman urls and can see the 'No messages' text when I enter http://127.0.0.1:8000/messages . The documentation seems very vague and I think I need something to walk me through step-by-step. My question is, how do I integrate the rest of the Postman files into my site? Should I copy and paste each template as needed? What is the folder structure within my entire app? Is there a website or Github file I can view as a sample? Thanks!! -
QuerySet select_related not working when overriding get_queryset methd on generic ListView
When overriding the get_queryset method on a generic ListView, the select_related() method, does not have any effect on the queryset, making n+1 sql calls on template loop: models.py: class Bulding(models.Model): name = models.Charfield(max_length=100) ... class Property(models.Model): building = models.ForeignKey(Building) ... views.py class PropertyListView(LoginRequiredMixin, PHViewMixin, ListView): model = Property def get_queryset(self): return super().get_queryset().filter(ph=self.kwargs['some_kw']).select_related('building') property_list.html: ... {% for p in object_list %} <tr> <td>{{ p.building }}</td><td><a href="{{ p.get_absolute_url }}">{{ p.name }}</a></td>>...</td> </tr> {% endfor %} ... Any help is appreciated. Eric -
Django rest swagger failed to load content over https
I'm using django rest swagger for showing my APIs. It works locally but on production which was served over https, I can't make an API call, since swagger makes use of the http protocol instead of https. Mixed Content: The page at 'https://foo.net/api/v1/#!/assets/assets_list' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://foo.net/api/v1/assets/'. This request has been blocked; the content must be served over HTTPS.f.end @ swagger-ui.min.js:8 swagger-ui.min.js:8 XMLHttpRequest cannot load http://foo.net/api/v1/assets/. Failed to start loading. So how to tell swagger to make use of https instead of http on production? -
Why isn't urls.py generated with django-admin startapp mysite?
But instead has to be created by the user. project | +-- settings.py +-- mysite | +-- views.py +-- apps.py +-- models.py +-- * user created urls.py file * -
how to query M2M with related_name
I have two really similar models with M2M field, somehow I tried to query one of them which works perfectly but when I try the same code with the other one, it gives me errors. The only difference I can find is the related_name I found a workaround but I am still curious how can I get this to work if I met the same problem next time. (I only wrote the M2M field I have, and each model only has one M2M field, even though come to think of it, what can be done if there are more than one M2M, but this is out of this question) this is the working model I have class Team(View): members = models.ManyToManyField(User, blank=True) this is the view with the above model, (skipping the class, the def post and so on) user = User.objects.filter(id=111).first() all_members = user.Team_set.filter() # this would return all below is the model that is giving me problems class Room(View): participants = models.ManyToManyField(User, blank=True, related_name='participants') this is the view with the above model user = User.objects.filter(id=111).first() all_p = user.room_set.filter() # this then gives me error of 'User' object has no attribute 'room_set' Thanks in advance for any help -
Docker + Django + Angular + Heroku + Postgresql - Process exited with status 127, error code=H10 desc=“App crashed”
I am trying to deploy on Heroku my project in Docker with Angular 4 frontend, Django backend and postgresql database. At this moment my files look as shown below. I am note sure if this is done properly? I pushed it using heroku container:push web --app myproject but it doesn't work (Logs). I noticed that in logs there is Process exited with status 127. I have found here 127 Return code from $? that Value 127 is returned by /bin/sh when the given command is not found within your PATH system variable and it is not a built-in shell command. In other words, the system doesn't understand your command, because it doesn't know where to find the binary you're trying to call. Besides, when I was trying different commands I very often were getting error like /bin/sh: 1 not found what I described in this post. Maybe it is a root of the problem? Or eventually there is a problem with ports like in this case? Any other ideas? It seems to me that I was trying everything. I have no idea what is wrong. Logs: 2017-07-08T13:19:48.882112+00:00 heroku[web.1]: Process exited with status 0 2017-07-08T13:20:40.336825+00:00 heroku[run.9745]: Awaiting client 2017-07-08T13:20:40.395900+00:00 heroku[run.9745]: Starting … -
Django block not showing up
So, originally I was using {% include}, and that was working fine, then I wanted to try out {% block}, and its not showing the nav.html content anymore. I've been trying to figure this out for about 15 minutes now, and it looks like its the same as I've seen everyone else do it. This is my code, what am i doing wrong? <html> <body> It is now {{ current_date }} {% block content %} {% endblock %} </body> </html> this block of code being the current_datetime file. {% extends 'current_datetime.html' %} {% block content %} <h1>this is a test</h1> {% endblock %} and this block of code being nav.html. I'm 100% sure that I'm naming the extends file correctly since I copied the name from the views file. -
Fetch data from form and display in template
I'm trying to modify posts app from a django tutorial- https://github.com/codingforentrepreneurs/Advancing-the-Blog/tree/master/src/posts I'm creating a new field 'userc' in a forms.py: userc = forms.ModelChoiceField(queryset=User.objects.filter(is_staff=True)) I've tried various methods but I'm unable to display the selected user in the template. What should I add in views.py? -
django collectstatic with django-storages recopying all files
I am using django.contrib.staticfiles along with django-storages for deploying my static files to Amazon S3. The django version that I am using is 1.10.4 and django-storages version is 1.5.2. Now when I run collectstatic, it re-copies all files from local system to S3 even when there is no change in the files locally. Looking at the collectstatic management command code I can see: In method delete_file: # The full path of the target file if self.local: full_path = self.storage.path(prefixed_path) else: full_path = None # Skip the file if the source file is younger # Avoid sub-second precision (see #14665, #19540) if (target_last_modified.replace(microsecond=0) >= source_last_modified.replace(microsecond=0) and full_path and not (self.symlink ^ os.path.islink(full_path))): if prefixed_path not in self.unmodified_files: self.unmodified_files.append(prefixed_path) self.log("Skipping '%s' (not modified)" % path) return False On debugging I saw that even though the target_last_modified >= source_last_modified but full_path is None which is why the check fails and it ends up deleting the file on remote. I am not sure what am I doing wrong or if I have missed some setting because of which it is re-uploading the files. Interestingly if I remove the extra check in the code above and just check like: if (target_last_modified.replace(microsecond=0) >= source_last_modified.replace(microsecond=0)): it works … -
Usage of unique_for_date
I'm trying to use unique_for_date option to prevent creating multiple posts with the same slug for the same date. But it doesn't seem to work at all: I still can create posts with the same slug from the shell and admin dashboard. The same goes for ModelForm. My models.py: class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ('suspended', 'Suspended'), ) title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique_for_date='created') status = models.CharField(max_length=15, choices=STATUS_CHOICES, default='draft') content = models.TextField(max_length=200000, blank=True) # dates created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) publish = models.DateTimeField(default=timezone.now) I've found some kind of a workaround for problem by changing auto_now_add=True to default=timezone.now but it only shows error while creating object via django admin - still no errors while creating objects from shell or form. -
Django doesn't match CreateView if the route begins with 'post/'
I've written a small blog website in django. I'm using generic views and everyting works. EXCEPT CreatePostView which is a generic CreateView: class CreatePostView(LoginRequiredMixin, generic.CreateView): model = Post login_url = '/login/' redirect_field_name = 'blog_app/post_detail.html' form_class = PostForm def form_valid(self, form): self.object = form.save(commit=False) self.object.author = self.request.user self.object.save() return super().form_valid(form) I'm routing it via blog.urls to blog_app.urls # Project urls url(r'^blog/', include('blog_app.urls'), name='blog'), # App urls url(r'^post/new/$', views.CreatePostView.as_view(), name='post_new'), but when I go to /blog/post/new/ I'll get Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/post/new/ Raised by: blog_app.views.PostDetailView However this will work: url(r'^new/post/$', views.CreatePostView.as_view(), name='post_new'), Now if I go to http://127.0.0.1:8000/blog/new/post/ I see my form. No matter what I write after the slash if the first part is 'post/' it will 404 me. At least that's what I believe I have observed. It works the opposite direction too: url(r'^somesuperlongroute/add/$', views.CreatePostView.as_view(), name='post_new'), This works, but that's how it is supposed to be. What's so specific about having 'post' in the first part of the route? I have 5 other routes beginning with 'post/' which work, actually maybe I'll just include this file here: from django.conf.urls import url, include from . import views app_name = 'blog_app' urlpatterns = [ url(r'^$', views.PostListView.as_view(), … -
django_filters (Associative table, reverse foreign key)
I am using django_filters to create filters. My models in models.py: class Person(models.Model): Name = models.CharField("Name", max_length = 50) class School(models.Model): Name = models.CharField("School Name", db_column='Name', max_length=50) class Person_School(models.Model): PersonID = models.ForeignKey(Person, models.DO_NOTHING, db_column='PersonID') SchoolID = models.ForeignKey(School, models.DO_NOTHING, db_column='SchoolID') The 'Person_School' is an associative table that links 'Person' and 'School'. I want to create a drop down list in front end that contains university names, people's names can be filtered by university names. I only know basic function of django_filters, but have no idea when there is an associative table. How should I code in filters.py using django_filters? Thanks -
Django-tinymce default settings
I am trying to turn my textfields in admin site into rich text editor but i can't do it by reading documents so could you please write minimum configuration code for me? -
Django, edit content 15 min after posting by using Built-in templates
I'm working on a comment funktion in django. It should be possible for the user to edit the comment until 15 min after he posted the comment. The editing of the comment works fine, but I don't know how I can handle it with the 15 min. My idea was it to use a Bullit-in template, so that the editing button just appear if the post is not older then 15 min. Kind of this: {% if comment.publication_date - now() <= 15 min %} <button type="">Edit comment</button> {%endif%} Is there any way to implement it like that or do I have to do it on a different way? Thanks a lot! Cheers -
Pytz - timezone activated yet getting wrong time. Am I missing something?
On my main page I get the following view definition triggered def initializeTimeZone(request): tzone = request.GET.get("tzone") # returns 'America/Los_Angeles' user_time_zone = request.session.get('user_time_zone', None) try: if user_time_zone is None: request.session['user_time_zone'] = tzone timezone.activate(pytz.timezone(tzone)) #--->is this correct ? return HttpResponse("OK") except Exception as ex: print >> sys.stderr, str(ex) Now when I do something like this later on time = datetime.datetime.now().strftime(settings.DATE_TIME_OBJECT_FORMATTING) I get the wrong date '2017-07-09 19:01:33' Any suggestions on what I might be doing wrong.