Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to install mysqlclient on Ubuntu LTS 16.04 LTS on Python3.6
I installed and created a virtual environment on my Linux Ubuntu LTS 16.04 server. MySQL database is successfully installed and the database server is working. While trying to migrate django I get error that mysqlclient is not installed. When I try to install mysqlclient using the below command, pip install mysqlclient I am getting the below error, Collecting mysqlclient Using cached mysqlclient-1.3.12.tar.gz Building wheels for collected packages: mysqlclient Running setup.py bdist_wheel for mysqlclient ... error Complete output from command /home/ubuntu/django_project/bin/python3.6 -u -c "import setuptools, tokenize;file='/tmp/pip-build-m44_w0__/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" bdist_wheel -d /tmp/tmprdsdub84pip-wheel- --python-tag cp36: running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.6 copying mysql_exceptions.py -> build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/init.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.6/MySQLdb creating build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/init.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants running build_ext building 'mysql' extension creating build/temp.linux-x86_64-3.6 x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -Dversion_info=(1,3,12,'final',0) -D__version=1.3.12 -I/usr/include/mysql -I/home/ubuntu/django_project/include -I/usr/include/python3.6m -c _mysql.c -o build/temp.linux-x86_64-3.6/_mysql.o … -
django rest api for autosuggest search
i am relatively new in django rest framework(DRF).i want to create a auto suggest api to create a list of objects, do i need to do anything more for auto sugestion or just create a create api and rest of the job will be done in front end, FYI, i am using react native for my front end. This is my model.py, class Item(models.Model): item_id = models.IntegerField(null=True, blank=True) item_name = models.CharField(max_length=100, null=True, blank=True) quantity = models.CharField(max_length=5, null=True, blank=True) unit = models.CharField(max_length=50, null=True, blank=True) and serializers.py class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__' and the api view class ItemList(APIView): """ List all item, or create a new item. """ permission_classes = [permissions.IsAuthenticated] def get(self, request, format=None): bazarerlist = Item.objects.all() serializer = ItemSerializer(bazarerlist, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = ItemSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and urls.py from django.conf.urls import url from . import views urlpatterns = [ # api endpoints url(r'^items/$', views.ItemList.as_view()), ] now what should i do more if i want o add a auto suggest while creating list item ? -
Start developer server in django
After update code I have problem with runserver. Could You help me? After typing python manage.py runserver I have following exception. Unhandled exception in thread started by <function check_errors. <locals>.wrapper at 0xb615d89c> Traceback (most recent call last): File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/amich/virtualenvs/problemondo/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/home/amich/virtualenvs/problemondo/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'url_tools' Thank You -
Is there a simple way to handle SECRET_KEY update for encrypted fields?
Let's begin with two assumptions: Some of database fields like third party access tokens are encrypted using e.g. Fernet and SECRET_KEY as encryption key. SECRET_KEY needs to be changed, because of security problem. What would be the best thing to do in such situation? I assume that I should change the SECRET_KEY immediately after I've fixed the security hole, however if I do that I'll essentially lose access to all of the encrypted data. What I have came up with is to first do a migration, which would temporarily replace encrypted fields with simple charfields/textfields + data migration to unencrypt stored values. Then change the SECRET_KEY. Finally bring the encrypted fields back, again with a data migration to encrypt stored values. It seems like a great hassle though, is there a better/simpler/faster way to handle such situation? -
Django/rest: return user's data plus one more json in one response
I'm using django rest-framework in python 3.5. When User.objects.filter(uid = data['id']).exists() I want to combine user's data and {"isnew":"TRUE"} in one json string and return it as response. User's data have this structure: I have the following view function. class UserRegister(CreateAPIView): permission_classes = () serializer_class = RegisterUserSerializer def post(self, request): serializer = RegisterUserSerializer(data=request.data) # Check format and unique constraint if not serializer.is_valid(): return Response(serializer.errors, \ status=status.HTTP_400_BAD_REQUEST) data = serializer.data if User.objects.filter(uid = data['id']).exists(): user = User.objects.get(uid = data['id']) json_resp = { "user":JsonResponse(user), "isnew":"TRUE"} return Response(json_resp, status=status.HTTP_200_OK) else: u = User.objects.create(uid=data['id'], firstname=data['firstname'], yearofbirth=data['yearofbirth'], \ lastname=data['lastname'], othernames=data['othernames']) u.save() return Response(serializer.data, status=status.HTTP_201_CREATED) Then I get the error TypeError: <User: User object> is not JSON serializable. The ideal response must be something like: { user: { "user_id": "844822", "firstname": "zinonas", "yearofbirth": 1984, "lastname": "", "othernames": "" }, isnew: "false" } -
error while migrating models.py
i have created models for a blog application this my models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class post(models.Model): STATUS_CHOICE=( ('draft','DRAFT'), ('published','Published'), ) title=models.CharField(max_length=250) slug=models.SlugField(max_length = 250,unique_for_date='publish') author=models.ForeignKey(User,related_name='blog_posts') body=models.TextField() publish=models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices = 'STATUS_CHOICES', default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.title and when i tried to migrate models iam getting an error as ERRORS: myblog.post.status: (fields.E004) 'choices' must be an iterable (e.g., a list or tuple). and my here is my admin.py file from django.contrib import admin from .models import post # Register your models here. admin.site.register(post) please can anyone help me solve this issue thanks in advance guys -
django NOT NULL constrait failed: BekanSite_project.owner_id
I have this problem::: IntegrityError at /addproject/ NOT NULL constraint failed: BekanSite_project.owner_id. I do not know how I can fix this problem. This is my model :: from django.db import models from django import forms from django.contrib.auth.models import User from django.core.validators import URLValidator class Project(models.Model): project_name = models.CharField(verbose_name='Имя проекта',max_length=200, default='') project_cost = models.IntegerField(verbose_name='Сумма инвестиции',default='') investor = models.IntegerField(verbose_name='Долья инвестерa',default='') email = models.EmailField(verbose_name='Почта',max_length=50, default='')..other fields owner = models.ForeignKey(User) def __str__(self): return self.owner VIEWS.py @login_required def addproject(request): if request.POST: form = ProjectForm(request.POST, request.FILES) if form.is_valid(): form.owner = request.user addproject = form.save()"<<<<where it fails" addproject.save() return HttpResponseRedirect(reverse('accounts:profile')) else: form = ProjectForm() return render(request, 'BekanSite/addproject.html', {'form':form,'username':auth.get_user(request).username}) FORMS.py from django.db import models from django import forms from .models import Project from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from PIL import Image class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ['project_name','project_cost',...(other fields),] I think it is somehow related to FreignKey. Please help. Thanks beforehand. -
How can I serialize a single Django object to geojson?
I'm trying to serialize a single Django object to geojson format. I was able to do this if multiple objects is given: test = Test.objects.all() test_json = serialize('geojson' , test, fields=('test_type', 'wkb_geometry')) test_geojson = json.loads(test_json) test_geojson.pop('crs', None) test_geojson = json.dumps(test_geojson) To make the serializer accept the single object I modify it to: test_json = serialize('geojson' , [test], fields=('test_type', 'wkb_geometry')) However, the error now would be Test is not iterable in my Django template leaflet map. How can I turn one object to geojson using serializers? Do I have to do it manually? -
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc7 in position 7: ordinal not in range(128)
Before asking this question, I have searched SO, find several related links:UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128), regarding reading in files But they are no useful for my post, all of them are about program, but mine is for installation. After I install the pip, I check the pip list: C:\Users\jin>pip list DEPRECATION: The default format will switch to columns in the future. You can use --format=(legacy|columns) (or define a format=(legacy|columns) in your pip.conf under the [list] section) to disable this warning. pip (9.0.1) setuptools (28.8.0) When I install django use pip, I get the bellow error: C:\Users\jin>pip install django Collecting django Exception: Traceback (most recent call last): File "C:\Python27\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "C:\Python27\lib\site-packages\pip\commands\install.py", line 324, in run requirement_set.prepare_files(finder) File "C:\Python27\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "C:\Python27\lib\site-packages\pip\req\req_set.py", line 620, in _prepare_file session=self.session, hashes=hashes) File "C:\Python27\lib\site-packages\pip\download.py", line 821, in unpack_url hashes=hashes File "C:\Python27\lib\site-packages\pip\download.py", line 659, in unpack_http_url hashes) File "C:\Python27\lib\site-packages\pip\download.py", line 880, in _download_http_url file_path = os.path.join(temp_dir, filename) File "C:\Python27\lib\ntpath.py", line 85, in join result_path = result_path + p_path UnicodeDecodeError: 'ascii' codec can't decode byte 0xc7 in position 7: ordinal not in range(128) -
Django Rest Framework Token for Vue js (with axios) requests
How can I pass the token in vue js requests, actually axios requests. For example, I need to specify: axios.defaults.headers.common['Authorization'] = "Token " + $how_can_i_get_the_token_here; I don't understand how can I get the token inside the template without some security risks (I'm just being paranoic here). The code that generates the token is: @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) So, I need the token for the specific user that is logged in. For csrf, I have done this: # in template <script>window.csrf = "{{ csrf_token }}";</script> # in js file axios.defaults.headers.post['X-CSRFToken'] = window.csrf; Is this a good idea? What's the best approach? Thanks in advance for answers! -
The program runs to rfuser = RFUser.objects.filter(user=request.user)[0] Being given
def homepage(request): if request.user.is_authenticated(): # get authenticated rfuser rfuser = RFUser.objects.filter(user=request.user)[0] print rfuser # show info of current user project_list = rfuser.project_set.all().order_by('project_name') # project_list = RFUser.objects.filter(user=request.user).order_by('project_name') context_dict = {'projects': project_list} return render(request, 'homepage.html', context_dict) else: return render(request, 'homepage.html') operation result: Internal Server Error: / Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 249, in _legacy_get_response response = self._get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\rfui_web\myaccoutsite\views.py", line 13, in homepage rfuser = RFUser.objects.filter(user=request.user)[0] File "C:\Python27\lib\site-packages\django\db\models\query.py", line 295, in __getitem__ return list(qs)[0] IndexError: list index out of range list index out of range But can not find why the reason is,Do not know if the index is not due to the array of the relevant value -
year date month in django template
I have a home page http://127.0.0.1:8000/home/ which presents a list of blogposts which are a snippet of each blogpost and each snippet links to the full blogpost page which has url for example http://127.0.0.1:8000/home/blog/2017/10/14/. the template for the full blogpost url with year month and day is working correctly however I get a NoReverseMatch on the homepage : Reverse for 'view_blogpost_with_pk' with keyword arguments '{'year': 2017, 'month': 10, 'day': 1}' not found. 1 pattern(s) tried: ['home/blog/(?P[0-9]{4})/(?P[0-9]{2})/(?P[0-9]{2})/$'] I dont know why its using 2017/10/01 instead of the correct year month day. I think im missing something from the view Here is my template for the home page: <div class = "container"> <div class = "col-md-10"> <div class ="well"> {% for p in allposts %} <a href="{% url 'home:view_blogpost_with_pk' year=p.date.year month=p.date.month day=p.date.day %}"><img src="{{MEDIA_URL}}/{{p.pic}}"></a> <h1 class="text-uppercase"><a href="{% url 'home:view_blogpost_with_pk' year=p.date.year month=p.date.month day=p.date.day %}"> {{p.title}}</a></h1> <h3 id ="smallicons"> <i id ="user" class="fa fa-user" aria-hidden="true"></i> <a href="{% url 'accounts:view_profile_with_pk' pk=p.author.pk %}"> {{p.author.username}}</a> <i id = "clock" class="fa fa-clock-o" aria-hidden="true"></i>{{p.date}} <i id = "comments" class="fa fa-comment" aria-hidden="true"></i> <a href= "{% url 'home:view_blogpost_with_pk' year=p.date.year month=p.date.month day=p.date.day %}"> {{p.comment_set.count}} comments</a> </h3> <p>{{p.body|truncatewords:"50"}}<a id= "readmore" href="{% url 'home:view_blogpost_with_pk' year=p.date.year month=p.date.month day=p.date.day %}"> read more</a></p> <hr id = "horizontalrule"> … -
Post empty date field error with Django rest framework
#model.py class Form(models.Model): no = models.IntegerField() finish_date = models.DateField(blank=True, null=True) >http http://127.0.0.1:8000/api/forms no=112 "finish_date"="" Return error: "finish_date": [ "Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]." ] If I set "finish_date" to null , this post works. And StringField(blank=True, null=True) will not get the error. How to solve? -
many to many table in django without using manytomanyfield
rather than using the models.ManyToMany field in django i just set up a intermediary field with a bunch of foreign keys. is there any reason why this wouldn't work. I can't think of any but why not see if any of you have tried the same. class Authorization(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) permission = models.ForeignKey( 'venueadmin.Permissions', blank=True, null=True) #venue = models.ForeignKey(venue) <-- commented out cause I haven't made the model its referencing yet. -
Django - Comment form in an existing template. How to define it in views.py?
I have 4 models: Post, Comment, Blogger and User. I have an post_description template, in below of that, i has placed an comment form. But how to define it in views? I'm getting problem in - to get its username, like the user who is logged in will be stored as "posted_by" and in which blog post he post will be stored as "topic" of the blog. How to store these information, so they automatically get added? Form that i has described in post_desc.html {% if user.is_authenticated %} <form method="post"> {% csrf_token %} <input type="text" name="comment" style="width: 800px; height: 145px;"> <button type="submit">Submit Comment</button> </form> {% else %} <p><a href="{% url 'login' %}">Login</a> to comment</p> {% endif %} Current view of that post_desc: def post_desc(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'post_desc.html', {'post': post}) -
Python not importing dotenv module
I am setting up an imageboard that uses Django and when i try to load manage.py for the first time i am greeted with this error message Traceback (most recent call last): File "./manage.py", line 3, in import dotenv ImportError: No module named 'dotenv' I have tried using python-dotenv rather than dotenv and it still doesn't work. Any solution for this? -
Automatically update a field on one model after saving another [Django 1.11][Python3.x]
I am learning how to use the post_save signal on Django. Though I am not getting any errors, what I want to do will not work. I have a model (Model) that is supposed to aggregate and average the ratings from the Review model and saves that number in a field called "average_rating." I want the averaging to be done once a user provides a rating on the "Review" model and for the average rating to automatically be calculated and updated on the "Model" model. I know that I can do this with a post_save signal. But I am not sure how. How can I do what I am trying to do? Thanks in advance. models.py from django.db import models from django.db.models import Func, Avg from django.urls import reverse from django.template.defaultfilters import slugify from django.db.models.signals import post_save from django.dispatch import receiver class Model(models.Model): name = models.CharField(max_length=55, default='') slug = models.SlugField(unique=True) average_rating = models.DecimalField(decimal_places=1, max_digits=2, default=0.0, blank=True, null=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.average_rating = self.review_set.aggregate( rounded_avg_rating=Round(Avg('rating')))['rounded_avg_rating'] self.slug = (slugify(self.name)) super(Model, self).save(*args, **kwargs) class Review(models.Model): RATING_CHOICES = [ (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), ] model = models.ForeignKey(Model, null=True) rating = models.IntegerField(choices=RATING_CHOICES, default=1) review_date … -
NameError: name 'Honeywords' is not defined ; custom password hasher
hye im little bit confused on how to define Honeywords actually . can anyone help me ? im trying to create a custom password hashers called Honeyword and i already create an app called honeywordHasher and already install it in INSTALLED_APP in settings.py . i manage to make the django to not hash the password by default and use my honeywordHasher but unfortunately it did not store in the db . can anybody give a tip on how to fix this ? i try to figure out this for a week already hashers.py : def salt(self) salt = get_random_string() while Honeywords.objects.filter(salt=salt).exists(): salt = get_random_string() return salt -
braintree drop in having two forms rendered instead of one
My drop in is being registered twice. (Meaning two forms with paypal / credit card fields are showing up) instead of just one in the dropin div. Here's my code. What am I doing wrong that's causing this? I tried setting the checkout variable which is what another answer recommended... Also, require.js throws a massive error in console is there a better version? HTML <div id="dropin-container"></div> <form id="checkout-form"> <input type='submit' value='Pay' id="pay-btn" disabled/> </form> Braintree script <script src="https://js.braintreegateway.com/js/braintree-2.28.0.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.5/require.js"></script> <script type="text/javascript"> var checkout; </script> <script type="text/javascript"> var braintree_client_token = "{{ braintree_client_token }}"; var amount = parseFloat("{{ cart.total }}");; function braintreeSetup() { braintree.setup(braintree_client_token, "dropin", { authorization: braintree_client_token, paymentOptionPriority: ['card', 'paypal'], paypal: { singleUse: true, amount: amount, currency: 'USD', flow: 'checkout', button: { type: 'checkout', } }, container: "dropin-container", form: 'checkout-form', onPaymentMethodReceived: function (obj) { }, onReady: function (integration) { checkout = integration; $("#pay-btn").prop('disabled', false); }, onError: function (obj) { } }); if (checkout) { // When you are ready to tear down your integration checkout.teardown(function () { checkout = null; // braintree.setup can safely be run again! }); } } braintreeSetup(); $('form').submit(function () { $('[type=submit]').prop('disabled', true); $('.braintree-notifications').html(''); }); -
pycharm 'Command' object has no attribute 'usage'?
in pycharm, running django project,but have the error. Failed to get real commands on module "MyShop": python process died with code 1: Traceback (most recent call last): File "F:\PyCharm 5.0.4\helpers\pycharm\_jb_manage_tasks_provider.py", line 22, in <module> parser.report_data(dumper) File "F:\PyCharm 5.0.4\helpers\pycharm\django_manage_commands_provider\_parser\parser.py", line 47, in report_data command_help_text=VersionAgnosticUtils().to_unicode(command.usage("")).replace("%prog", command_name)) AttributeError: 'Command' object has no attribute 'usage' -
What should i use Reactjs with.. Nodejs or Django
I am in the process or starting to learn Django. I have been building web applications with Nodejs/Express and have recently decided to start to learn Django because it seems to be a powerful backend framework. How is Django different from Nodejs and which one should I stick with. I feel like Django is a more powerful engine to write back-end code on, but I am still new to it. And lastly, can I even use front-end frameworks/libraries with Django ie. Angularjs and Reactjs -
Getting a NoReverseMatch error even though my 'Identity_nest_list' uniform resource locator contains the pk parameter
I am attempt to update an instance and return to the Template view of the instance. Problem : The code renders the edit view however when I edit the instance and press save it returns this error. I realize that the error is telling my that my Identity_nest_list URL doesn't havea pk parameter. However I added it and it is still giving me the error. Essentially I want to be able to edit the object, save the edit and redirect the user to the updated version of the Identity_unique instance, along with the other instances that are already there Request Method: POST Request URL: http://127.0.0.1:8000/nesting/Identity-edit/L882394/?csrfmiddlewaretoken=umHqs06uQmn0fsBNPjnqpuv4yyBIPkGGJNmN1l83TLUSVFh3ja1WPd8reE3IvSEX Django Version: 1.10.5 Python Version: 3.5.3 Installed Applications: ['Identities', 'nesting', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'Identity.middleware.LoginRequiredMiddleware'] Traceback: File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/edit.py" in post 240. return super(BaseUpdateView, self).post(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/edit.py" in post 183. return self.form_valid(form) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/edit.py" in form_valid 163. … -
Limit number of model object page views for an anonymous user until they have to sign up (Django)?
I'm trying to track the number of views an anonymous (Non-authenticated) user makes on my model object detail pages (Map pages) so that I can redirect them to the sign up page after they view the pages ~5 times. For example: the anonymous user gets 5 free map views before having to sign up (Or these pages will be unaccessible). Not sure if I should use cookies, sessions, or just some kind of javascript for this. I can't really wrap my head around it. A point in any direction would be great, thanks! -
Django View Error - NoReverseMatch
I am new to django and I am trying to solve a NoReverseMatch issue. I think it has something to do with the views but i'm new to this. The code is from a popular boiler plate repo from a few years ago. PLEASE NOTE: I tried reading like every answer on stack overflow already and have been stuck for hours. Any help would be greatly appreciated main urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^login/', include('shopify_app.urls')), url(r'^', include('home.urls'), name='root_path'), url(r'^admin/', admin.site.urls), ] urls.py inside of app from django.conf.urls import url from shopify_app import views urlpatterns = [ url(r'^$', views.login, name='shopify_app_login'), url(r'^authenticate/$', views.authenticate, name='shopify_app_authenticate'), url(r'^finalize/$', views.finalize, name='shopify_app_finalize'), url(r'^logout/$', views.logout, name='shopify_app_logout'), ] views.py inside of app from django.shortcuts import redirect, render from django.contrib import messages from django.core.urlresolvers import reverse from django.conf import settings import shopify def authenticate(request): shop = request.GET.get('shop') print('shop:', shop) if shop: scope = settings.SHOPIFY_API_SCOPE redirect_uri = request.build_absolute_uri(reverse('shopify_app.views.finalize')) permission_url = shopify.Session(shop.strip()).create_permission_url(scope, redirect_uri) return redirect(permission_url) return redirect(_return_address(request)) def finalize(request): shop_url = request.GET['shop'] try: shopify_session = shopify.Session(shop_url) request.session['shopify'] = { "shop_url": shop_url, "access_token": shopify_session.request_token(request.REQUEST) } except Exception: messages.error(request, "Could not log in to Shopify store.") return redirect(reverse('shopify_app.views.login')) messages.info(request, "Logged in to shopify store.") response = … -
How to replace ALL django "Status Code Exception" pages
Any Status Code exceptions like 404, 403, 405, 500, CSRF and more return their own "Django" specific pages, a few are HTML. handler403, handler404, and handler500 exist and can be easily overridden, but there are a lot of these "hidden" Django pages that are being returned upon error, an example is 405 (method does not exist) or CSRF (if no CSRF token is in the request) and probably many more. Is it possible to have a custom view (such as just a generic 404 return) for ALL of these "hidden" Django HTML pages?