Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django array field error
I have imported the following header file from django.contrib.postgres.fields import ArrayField Used the following in the model question_array = ArrayField(models.IntegerField, blank=True,) i get the following error Traceback (most recent call last) File "C:\Program Files (x86)\Python\Python35-32\lib\site-packages\django-1.10.4-py3.5.egg\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files (x86)\Python\Python35-32\lib\site-packages\django-1.10.4-py3.5.egg\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Program Files (x86)\Python\Python35-32\lib\site-packages\django-1.10.4-py3.5.egg\django\apps\config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files (x86)\Python\Python35-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "C:\Users\DELL\Desktop\cstrom\comp\models.py", line 24, in <module> class User(models.Model): File "C:\Program Files (x86)\Python\Python35-32\lib\site-packages\django-1.10.4-py3.5.egg\django\db\models\base.py", line 157, in __new__ new_class.add_to_class(obj_name, obj) File "C:\Program Files (x86)\Python\Python35-32\lib\site-packages\django-1.10.4-py3.5.egg\django\db\models\base.py", line 316, in add_to_class value.contribute_to_class(cls, name) File "C:\Program Files (x86)\Python\Python35-32\lib\site-packages\django-1.10.4-py3.5.egg\django\db\models\fields\__init__.py", line 689, in contribute_to_class self.set_attributes_from_name(name) File "C:\Program Files (x86)\Python\Python35-32\lib\site-packages\django-1.10.4-py3.5.egg\django\contrib\postgres\fields\array.py", line 75, in set_attributes_from_name self.base_field.set_attributes_from_name(name) TypeError: set_attributes_from_name() missing 1 required positional argument: 'name' please help me resolve this error. I am beginner in Django -
return 'None' from APNs in python using pyapns
In the starting,Notifications(Safari) was sending with response 'None' but now notifications are not sending and response is same in both case-- my payload format- payload = Payload(alert={ "title": "Test", "body": "Test message", "action": "View" }, sound="default", badge=1,url_arg={"name":"https://www.google.com",},) My Complete View(Code):- rom apns import APNs, Frame, Payload apns = APNs(use_sandbox=False, cert_file='cert.pem', key_file='key.pem',enhanced=True) print "11" # Send a notification payload = Payload({ "aps": { "alert": { "title": "Flight A998 Now Boarding", "body": "Boarding has begun for Flight A998.", "action":"View" }, "url-args": ["boarding", "clicked"] } }) # alert={ # "title": "Test", # "body": "Test message", # "action": "View" # }, sound="default", badge=1,url_arg={"name":"https://www.google.com",},) token_hex = 'FA47BC7C526AFE0A31A30B2EFE1A2AD1DB5A9935B16C9A81B706FDA7619B1B55' print '123345' frame = Frame() identifier = 1 expiry = time.time()+3600 priority = 10 saf_sub=['FA47BC7C526AFE0A31A30B2EFE1A2AD1DB5A9935B16C9A81B706FDA7619B1B55','FA47BC7C526AFE0A31A30B2EFE1A2AD1DB5A9935B16C9A81B706FDA7619B1B55'] for i in saf_sub: if i != '': try: frame.add_item(str(i), payload, identifier, expiry, priority) except: pass try: # print 'output',output output =apns.gateway_server.send_notification_multiple(frame) print 'output',output return Response({"status":output}) except: pass why come none(code=255) from apns?? Any suggestion??? -
Django ImageField can not change image file correctly
I use ImageField to store user's avatar, here is my model: class User(AbstractUser): mugshot = models.ImageField(upload_to=user_mugshot_path) def save(self, *args, **kwargs): if not self.mugshot: avatar = Avatar(rows=10, columns=10) image_byte_array = avatar.get_image(string=self.username, width=480, height=480, pad=10) self.mugshot.save('default_mugshot.png', ContentFile(image_byte_array), save=False) super().save(*args, **kwargs) When user sign up, this would create a default mugshot for him/her. The expected behavior is when user update their own mugshot, the default mugshot would be deleted. So I write the form and view like this: class MugshotForm(forms.ModelForm): class Meta: model = User fields = ('mugshot',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class MugshotChangeView(LoginRequiredMixin, UpdateView): form_class = MugshotForm template_name = 'users/mugshot_change.html' success_url = '/users/profile' def form_valid(self, form): if form.has_changed(): self.object.mugshot.delete(save=False) return super().form_valid(form) # TODO: Can't update mugshot correctly def get_object(self, queryset=None): return self.request.user But the real behavior is when updating the mugshot, the old mugshot would be deleted but the new one doesn't associated to model. It always create a new default mugshot for user. What's wrong in codes? Thank you for you help! -
Properly make a BETWEEN clause in DjangoORM
Im having problem querying the desired result in my database using DjangoORM. Here is my model. class HeatWatchList(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='watchlist_users', on_delete=models.CASCADE) heat = models.OneToOneField(Heat, related_name='heat_watch_list', on_delete=models.CASCADE) next_date_from = models.DateTimeField() next_date_to = models.DateTimeField() I would like to get all record where today's date is BETWEEN next_date_from and next_date_to fields. And i can easily do this in raw sql: SELECT * FROM farm_management_db.heat_heatwatchlist WHERE DATE('2017-01-23') BETWEEN DATE(next_date_from) AND DATE(next_date_to); This is what i tried so far but i ain't getting any records: HeatWatchList.objects.filter( next_date_from__date__gte=datetime.now().date(), next_date_to__date__lte=datetime.now().date() ) -
Userprofile does not exist user has no profile
For a wallet app I have created a profile for every user of the django.contrib.auth.models User model. when a user create an account their profile is created and saved. But when i try to add money i get an error called Userprofile does not exist user has no profile. So i checked the database and their the Userprofile with the correct user exists. I am really confused as to why this is happening. //add_money view def add_money(request): if request.user: if request.user.has_perm('add_money'): if request.POST and request.POST.get('amount'): username = request.user.username add_amount = request.POST.get('amount') wallet = Wallet.objects.get(pk=request.user.userprofile.wallet_id_id) wallet.add_money(add_amount) wallet.save() now = datetime.now() trans = Transaction(from_name=username, wallet_id=wallet, date=now, amount=add_amount) trans.save() return render(request, 'user_profile.html', {'user': request.user,'userprofile': request.user.userprofile, 'wallet': wallet}) else: return render(request, 'add_money.html') else: return render(request, 'access_denied.html') else: return HttpResponseRedirect('/login/?next={}'.format('/add_money/')) //create_user view def create_user(request): form = UserReg(request.POST or None) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) wallet = Wallet(username=request.POST['username'], amount=0) wallet.save() user.save() userprofile = Userprofile(user=user, wallet_id=wallet) userprofile.save() user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return render(request, 'user_profile.html', {'user': user, 'wallet': wallet}) context = { "form": form, } return render(request, 'create_user.html',context) //Userprofile model class Userprofile(models.Model): user = models.OneToOneField(User, unique=True, primary_key=True) wallet_id = models.ForeignKey(Wallet, on_delete=models.CASCADE) date_ob … -
Polling celery task and return on display
I am new to celery. I was following this example https://github.com/mikeumus/django-celery-example Views.py def results(request): documents = Document.objects.all() if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data['name'] print 'data', data newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() #send it to celery documents = Document.objects.all() return render_to_response( 'results.html', {'documents' : documents}, context_instance=RequestContext(request)) The user would upload a file which would be processed by an engine. In the meantime, i would want the results page to show all jobs that are already completed. I thought of using celery and modifying the tasks.py to process the files. After its completed, the file will be shown as a url for users to download it. I cannot think of a way to poll this tasks asynchronously to achieve this part. I know this might not be a good question but thanks for the answers in advance. thanks. -
2 OneToOneFiled defined for two tables. One got deleted but not other
I have defined two OneToOneFileds in my model as below: class StudentCrossMap(models.Model): rfId = models.OneToOneField(StudentDailyTrans) studentId = models.OneToOneField(StudentMaster) When I apply delete on the model above giving rfId, the entry related to it in StudentDailyTrans gets deleted, BUT the one in StudentMasterdid not gets removed. Ideally, if I am deleting the object from StudentCrossMap it should not be deleting the entries from mapped tables as those tables are not dependent on StudentCrossMap table. Please advise if I am doing something wrong. -
Unable to save differenent date format in django
I am working on a form and have a date field. I want to save different date format for date field instead django used. I am getting "01-jan-2016" date and want to save as it is in my database.when i am trying to save this same format is raise an error [u"'07-Dec-2016' value has an invalid date format. It must be in YYYY-MM-DD format."]. I know this type of question asked already but they do not solve my problem. views.py post_date = request.POST['date'] lead_obj = CustomerLeads.objects.create(posting_date = post_date) my models.py class Leads(models.Model): customer_name = models.CharField(max_length=50,null=True, blank=True) title = models.CharField(max_length=100, null=True, blank=True) posting_date = models.DateField() -
How do I configure the sqlite3 module to work with Django 1.10?
So the issue is that apparently Django uses the sqlite3 that is included with python, I have sqlite3 on my computer and it works fine on its own. I have tried many things to fix this and have not found a solution yet. Please let me know how I can fix this issue so that I can use Django on my computer. :~$ python Python 3.5.2 (default, Nov 6 2016, 14:10:16) [GCC 6.2.0 20161005] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.5/sqlite3/__init__.py", line 23, in <module> from sqlite3.dbapi2 import * File "/usr/local/lib/python3.5/sqlite3/dbapi2.py", line 27, in <module> from _sqlite3 import * ImportError: No module named '_sqlite3' >>> exit() -
Building Attribute Based Recommendation using Solr
I need to match user attributes with solr fields and calculate a cumulative score and retrieve documents based on that custom score. After reading docs I found couple of ways of doing this task 1) Building Function query using Python and then retrieving its response Example: if state == "Uttar Pradesh" then customscore=40 statescore:{!func}map(strdist(def(state_exact,""),"Uttar Pradesh",edit),1,1,40,0) customscore=SUM($statescore,....(sum of all attribute score)) sort=product(customscore*score) 2) Creating my custom function in java and using it.Example customscore=customscorefunction(state_exact,...other attributes)&sort=product(customscore*score) Is there any other efficient way of doing this? Which is correct way of doing this (from above two ways)? To be specific I have around 10-15 filters and assume that these filters won't change frequently.Also my application is using python and django as framework? -
Generate and download a pdf from html in django
Below code is executing but no pdf is opening/downloading in the browser. your help is very grateful to me. Thanks in advance! I want onclick a button a pdf will open/download.Onclick the button i called the url. my url : url(r'^hotel_sales_report/downloadpdf/$', views.HotelSalesReport.as_view()), my view : from wkhtmltopdf.views import PDFTemplateResponse from django.http import HttpResponse class HotelSalesReport(View): def get(self, request): try: import ipdb; ipdb.set_trace() template='reports/hotel_sales_report.html' context= {'title': 'Hello World!'} response = PDFTemplateResponse(request=request, template=template, filename="hotel_sales_report.pdf", context= context, show_content_in_browser=True, cmd_options={ 'encoding': 'utf8','quiet': True }, ) assert(response.status_code == 200) return response except Exception as e: import traceback; traceback.print_exc(); print "This Is Error ---================>>>>",e -
custom tags random load fail at TemplateSyntaxError 'custom_tags' is not a valid tag library: Template library custom_tags not found, tried
I have Django 1.8 project w/ python 2.7 and has one page load fail randomly on some custom tags. TemplateSyntaxError as 'custom_tags' is not a valid tag library: Template library custom_tags not found, tried. I have the templatetags folder under app folder and also init.py inside it. Also the app is in the INSTALLED_APPS and have reviewed several topics and have tried several method but it still random happen. When the issue happen, if refresh again, this issue will gone. but sometime later, it happen again. -
Using Haystack for autocomplete returns unrelated models when searching common words.
For example a search for 'is', 'if', or 'on' returns all the models in the index. How can I turn off this behaviour? I couldn't find any relevant pages in the docs but I might be missing something. Any help is appreciated. -
Loading JS in Django
I am very new in Django, I want to create a navtab using bootstrap and I have already created an static file, I actually could read the CSS file, but the JS interaction is not working. This is my code <!DOCTYPE html> <html lang="en"> <head> {% load staticfiles %} <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <meta charset="utf-8"> <title>Quant Consulting</title> </head> <body> <div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> Dropdown <span class="caret"></span> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li role="separator" class="divider"></li> <li><a href="#">Separated link</a></li> </ul> </div> <script src="{% static 'js/bootstrap.min.js' %}"></script> </body> </html> The problem is that I cannot see any interaction on the development server, anybody knows why? Thanks in advance for all your help. -
error 403 forbidden on server request via ajax
I'm working on a site the keeps track of a to-do list and pulls it from a server. There are two sample ajax calls bellow, the tasks on works fine, how add does not. Add gives me a 403 forbidden error and doesn't execute the code. i was looking at 403 Forbidden error when making an ajax Post request in Django framework and i read the link posted by @yohn, but i'm not understanding how to implement this and fix my issue var tasker = (function() { return { tasks : function( ownerId, cb ) { $.ajax({ url: "http://138.49.184.143:3000/tasker/api/"+ownerId+"?key=f725ebbc9c", type: 'GET', success: function(task) { if(task){ var list = [] for(var a=0; a<task.length; a++){ var newTask = { onwerId: task[a].ownderId, desc: task[a].desc, due: new Date(task[a].due), color: task[a].color, complete: task[a].complete, id: task[a].id }; list.push(newTask); } cb(list , null); } else{ cb(null, 'error retreiving your tasks');} }, error: function( xhr, status, errorThrown ) { alert( "Sorry, there was a problem! " + errorThrown ); }, }); }, add : function( ownerId, task, cb ) { $.ajax({ url: "http://138.49.184.143:3000/tasker/api/"+ownerId+"?key=f725ebbc9c", type: 'POST', success: function(task) { var d = new Date(task.due); if(task){ var newTask = { onwerId: task.ownderId, desc: task.desc, due: d, color: task.color, complete: task.complete, … -
postgresql django not sending password
I am getting the error OperationalError: fe_sendauth: no password supplied on my production server but I cannot see why... settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dbname', 'USER': 'dbuser', 'PASSWORD': PROD_DB_PASSWORD, 'HOST': 'localhost', 'PORT': '5432', } } pg_hba.conf: host dbname dbuser localhost md5 If I do psql -d dbname -U dbuser -h localhost and then enter the password at the prompt I can see that it works so IDK why django is not sending the password and IDK where to look from here. -
How to collect Django static files with the same name?
Three of my Django apps have static files with the same name app1/static/css/mycss.css, app2/static/css/mycss.css, app3/static/css/mycss.css. How do I collect them all to STATIC_ROOT since default behavior of DJango is to collect only the first one encountered among the same named static file? -
django-summernote Help Adding Code Mirror
I visited http://summernote.org/examples/#codemirror-as-codeview, but I still can't get codemirror to work. I'm getting 200 responses from all the codemirror css and javascript, but I still get blank when I press code view. Here's my SUMMER_NOTE config. SUMMERNOTE_CONFIG = { 'toolbar': [ ['cmds', ['undo', 'redo', 'clear']], ['style', ['style']], ['font', ['bold', 'italic', 'underline', 'strikethrough']], ['font2', ['superscript', 'subscript']], ['color', ['color']], ['para', ['ul','ol']], ['layout', ['hr', 'table']], ['insert', ['link', 'picture']], ['misc', ['codeview']], ], 'width': '100%', 'css': ( '//cdnjs.cloudflare.com/ajax/libs/codemirror/3.20.0/codemirror.css', '//cdnjs.cloudflare.com/ajax/libs/codemirror/3.20.0/theme/monokai.css', ), 'js': ( '//cdnjs.cloudflare.com/ajax/libs/codemirror/3.20.0/codemirror.js', '//cdnjs.cloudflare.com/ajax/libs/codemirror/3.20.0/mode/xml/xml.js', '//cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/formatting.js', ), 'codemirror': { 'theme': 'monokai', } } Is this the right way to configure? -
Django 1.10 claims template does not exist, but it clearly does
But if I copy and paste that location into firefox, the template is there... views.py: def artists(request): artists = Artist.objects.all() template = loader.get_template('artists/index.html') context = {'artists': artists,} return HttpResponse(template.render(context, request)) index.html: {% extends "site_base.html" %} {% load i18n %} {% block head_title %}pinax-project-account{% endblock %} {% block body_class %}home{% endblock %} {% block body_base %} <section class="jumbotron"> <div class="container"> {% include "_messages.html" %} <h1>{% blocktrans %}Welcome to<br>pinax-project-account{% endblocktrans %}</h1> <p> {% blocktrans %} In addition to what is provided by the "zero" project, this project provides thorough integration with django-user-accounts, adding comprehensive account management functionality. It is a foundation suitable for most sites that have user accounts. {% endblocktrans %} </p> {% if not user.is_authenticated %} {% url "account_login" as login_url %} {% url "account_signup" as signup_url %} <p>{% blocktrans %}You can <a href="{{ login_url }}" class="btn btn-default">Log In</a> or <a href="{{ signup_url }}" class="btn btn-primary">Sign Up</a> to try out the site.{% endblocktrans %}</p> {% endif %} </div> </section> <section> <div class="container"> <h2 class="text-center">{% blocktrans %}What is Pinax?{% endblocktrans %}</h2> <p class="lead"> {% blocktrans %} <b>Pinax</b> is an open-source platform based on Django and intended to provide a starting point for websites. It takes care of the things that many … -
can't connect mysql local server while deploy to aws
I am trying to deploy django rest app to AWS Elastic Beanstalk. I followed this tutorial and I configure DATABASES in setting.py like following if 'RDS_DB_NAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'DB_NAME', 'USER': 'USER_NAME', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '3306', } } and I add following code to .ebextensions directory, option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "myApp.settings" "PYTHONPATH": "./src" "ALLOWED_HOSTS": ".elasticbeanstalk.com" "aws:elasticbeanstalk:container:python": WSGIPath: [WSGI_PATH] NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "www/static/" container_commands: 01_migrate: command: "source /opt/python/run/venv/bin/activate && python campusBackend/manage.py migrate --noinput" leader_only: true However, when I try to deploy, it gives me the error django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)"). container_command 01_migrate in .ebextensions/02_python.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. I really stucked at this point and I have no idea how to solve this. -
Django For Not Displaying in Template
I am trying to create an "edit profile" page/form and have followed the SimpleIsBetterThanComplex tutorial on how to extend the user model by way of the OneToOne Link. However, when i try to display the user profile form to allow the user to update their profile, the form doesn't display at all except for the Submit button... Any ideas where i might have gone wrong here? models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.utils import timezone class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #account types is_userA = models.BooleanField('User A', default=True) is_userB = models.BooleanField('User B', default=False) is_superuser = models.BooleanField('SuperUser', default=False) #other fields here avatar = models.ImageField('avatar', upload_to='static/media/images/avatars/', null=True, blank=True) phone = models.CharField('phone number', max_length=20, blank=True, default='') address = models.CharField('address', max_length=100, default='', blank=True) city = models.CharField('city', max_length=100, default='', blank=True) state = models.CharField('state', max_length=2, default='', blank=True) country = models.CharField('country', max_length=100, default='', blank=True) date_joined = models.DateTimeField(default=timezone.now) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ('first_name', 'last_name', 'email') views.py @login_required @transaction.atomic def update_profile(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) if … -
django form widget number input
I have the below code in my forms.py I am trying to get widget on phone to put up an error if the input is not numbers but it does not work. Everything else works. Any reason why the type=number is not pulling up an error on the form? class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile exclude = ('user',) widgets = { 'first_name': forms.TextInput(attrs={'maxlength':100, 'required': True}), 'last_name': forms.TextInput(attrs={'maxlength': 100, 'required': True}), 'phone': forms.NumberInput(attrs={'minlength': 10, 'maxlength': 15, 'required': True, 'type': 'number',}), 'date_of_birth': forms.DateInput(attrs={'minlength': 10, 'maxlength': 10, 'required': True}), 'country': CountrySelectWidget(attrs={'country': 'CountrySelectWidget'}), } -
Django admin inline prefetch foreign relation of foreign relation
I'm running into the fairly common issue that the django admin inline does a whole bunch of unnecessary queries to populate the dropdown. There are 4 models - when I view the user, I would like to see UserClientRoles associated with that user, displayed with the ClientRole name and the Client. When I just use the role name, it queries once for each UserClientRole (if there 3 assignments, it queries 3 times). If I include the client name, it queries every client name once for every UserClientRole. I've tried the solution outlined here (Django admin inline: select_related), but no dice. It doesn't modify the behavior. I've also tried overriding the get_queryset method on the UserAdmin class to no effect. Nothing I've tried reduces the number of queries. I've deleted some model details for conciseness. Here's the models: class User(models.Model): id = models.AutoField(primary_key=True) email = models.CharField(unique=True, max_length=200) class Client(models.Model): id = models.AutoField(primary_key=True) client_name = models.CharField(unique=True, max_length=200) client_identifier = models.CharField(unique=True, max_length=200) class ClientRole(models.Model): client_role_id = models.AutoField(primary_key=True) role_name = models.CharField(unique=True, max_length=200) client = models.ForeignKey(Client) def __unicode__(self): return self.role_name + self.client_id.client_name class UserClientRole(models.Model): user_client_role_id = models.AutoField(primary_key=True) client_role = models.ForeignKey(ClientRole) user = models.ForeignKey(User) And here are the admin models: class UserClientRoleFormset(forms.BaseInlineFormSet): def __init__(self, *args, **kwargs): … -
No S3 media files in Heroku-deployed django project
I am trying to serve the static and media files in my Django project (hosted on Heroku) from Amazon S3. Static files are now serving properly both locally and deployed, but media files are only working locally. I can verify that files are being added and served properly from my bucket when served by localhost, but neither saving nor loading works in production. When I try to serve a media image (which I manually added to the bucket), I get a 403 access denied error: <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>7430A21BE321C26B</RequestId> <HostId> h/c1VQF57wrLJ7JdHXuJ8LCrQdZL9PfQZN4G38Ihg8UYCxSt0znbxWfiTSDxz0dCooQoqgW9tpw= </HostId> </Error> When I attempt to save a file (through the Wagtail image upload), I get the rather generic Internal Server Error - 500. I'm at a loss as to what the problem is. The fact that I can get static but not media files is part of what's so confusing (and makes me think it's not just a permissions error). Here are the things that I think might be relevant to the problem. My bucket policy: { "Version": "2008-10-17", "Statement": [ { "Sid": "PublicReadForGetBucketObjects", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::owen-tribune/*" }, { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::494147019987:user/jtebert" }, "Action": "s3:*", "Resource": … -
Django log user in using class based view
I am trying to log a user in, however, my view does not seem to work. The page is rendered and the form is displayed and everything. But when I enter a valid user name and password it just refreshes the page. I think it is the way I am implementing my view method. I do not think login(request, user_obj) is being accessed, and if so, so is request.user.is_authenticated(). from .models import Usermie from django.shortcuts import render from django.views.generic import View from .forms import SignUpForm, LoginForm from django.contrib.auth.models import User from django.http import HttpResponseRedirect from django.views.generic.base import TemplateView from django.contrib.auth import authenticate, login, logout class UserLoginRegistration(View): form_class = LoginForm # Use initial to declare the initial value of form fields at runtime. # For example, you might want to fill in a username field with # the username of the current session. initial = {'key': 'value'} template_name = 'usermie/usertest.html' # template form will be rendered on success_url = '/usermie/home/' # template for successfully submitted form def get(self, request, *args, **kwargs): form_login = self.form_class(initial=self.initial) return render(request, self.template_name, {'form_login': form_login}) # method for posting form def post(self, request, *args, **kwargs): # Accessing form with post data form_login = self.form_class(request.POST) # Checking if …