Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Weird CSRF error in Django with Nginx and Gunicorn
Background When I try to access into my Django administration panel, I get Forbidden (403) CSRF verification failed. Request aborted., even if I disable the CSRF middleware. This affects all users, in different locations with different browsers. I've followed the steps to fix this error of several questions in stackoverflow, but still the same. This has been killing me for weeks. Issue I'm using https with Cloudflare (Free plan), but this error persist if I deactivate https. This occurs in mydomain.com/admin Known facts I'm using Django 2.0 and gunicorn 19.0 I've checked the cookies of my browser I've tried removing django.middleware.csrf.CsrfViewMiddleware This occurs just in the Django Admin dashboard, when CSRF middleware is enabled, the another POST or GET forms works fine. I'm logged into my Django Admin dashboard, and if I logout, I can login again with no problems, but if I try from another place, or with another user, the problem occurs again. Gunicorn config it's the default. Configuration files Settings.py CSRF_TRUSTED_ORIGINS = ['.domain.com'] CSRF_COOKIE_DOMAIN = ['.domain.com', '127.0.0.1'] CSRF_COOKIE_SECURE = True ALLOWED_HOSTS = ['127.0.0.1', 'domain.com', 'www.domain.com', '104.336.44.153', '.domain.com'] MIDDLEWARE = [ 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Nginx server { server_name domain.com; access_log off; location … -
Embedding Bokeh Graph in Django using Ajax - It just outputs HTML text of the graph data
I have been searching for a while but there is not a good example out there really build upon. Right now I am trying to output stock data from an API and use Bokeh to graph the user selected option to display it. As I am still learning this, some help would be greatly appreciated. For starters this is how it works: The user selects from the dropdown what type of stock time frame he wants and types in whatever stock symbol he wants. "/dashboard/update" takes the data and processes the API request which gathers the JSON data and sends it off to the "/result" which sorts and processes the data. "/result" then outputs it on "results.html" using Bokeh. This is where my refactoring to use AJAX comes in. Due to not knowing how to embed bokeh with AJAX properly, I had used another example which apparently worked but managed to output the entire JSON into the HTML of the page. The error being shown says "Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing\". I have inside my HTML placed the Bokeh CDN. Perhaps there is more needed? <script type="text/css" src="http://cdn.pydata.org/bokeh/release/bokeh-tables-0.13.0.min.css"></script> <script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-0.13.0.min.js"></script> This is … -
Django: while displaying list of articles show favourite status of each articles based on the user
I have List of articles to be displayed as per date. Every User can mark any article as his favourite. If a user is logged in, then he should be able to see some indication whether the article is already marked as his favourite or not. the following are my models: class Favourite(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) article = models.ForeignKey(Article, null=True,on_delete=models.CASCADE) class Meta: unique_together = ('user', 'article') class Article(models.Model): title = models.CharField(max_length=256) intro_image = models.ImageField(null=True, blank=True, upload_to=doc_hash) description = models.TextField(null=True, blank=True) I was thinking for every article get all the user ids who marked that article as favourite and then later check it at front end with the current user. But if some article is marked as favourite by 1000 users , then unneccessarily i will have to get the data of 1000 users along with that article which is too much. Is there a way if i pass the user i can get the favourite data only with respect to that user for each article so that i can save both on queries and amount of data to be passed to front end. -
What if django model incremental pk finished
In Django, if you don't specify primary key, it will add an integer autofield. My question is that if this incremental id, reaches integer limit, what is expected to happen after? -
How to delete products from inventory in Django?
What I want: I have the model classes named Book and Issue. In Book, there is a field named quantity that defines how many books are there. When the Admin issue a book to a student, there will be a -1 in quantity. how may I implement this. N.B: I want to implement this in Django Admin Dashboard from django.db import models from datetime import date, timedelta, datetime # Create your models here. class User(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) depertment_name = models.CharField(max_length=30) roll_number = models.CharField(max_length=10, primary_key=True) semester = models.CharField(max_length=10) def __str__(self): return self.depertment_name.upper() + ', ' + self.roll_number + ', ' + self.first_name.upper() class Book(models.Model): name = models.CharField(max_length=30) author_name = models.CharField(max_length=30) category = models.CharField(max_length=30) quantity = models.IntegerField() def __str__(self): return self.name # def book_left(self): class Issue(models.Model): issue_id = models.CharField(max_length=10) roll = models.ForeignKey(User, on_delete=models.CASCADE) book_name = models.ForeignKey(Book, on_delete=models.CASCADE) issue_date = models.DateField(auto_now=False, auto_now_add=True) # return_date = models.DateField(default=datetime.now()+timedelta(days=3)) # def remaining: # return Book.remaining - 1 def return_date(self): return datetime.now()+timedelta(days=3) def fine(self): return_date = datetime.now() + timedelta(days=3) if datetime.now() > return_date: return 'Fine' else: return 'No Fine' -
jquery.min.js:4 GET http://127.0.0.1:8000/RiskxTokenSale.json 404 (Not Found)
I've got the following code for my app.js: App = { web3Provider: null, contracts: {}, init: function() { console.log("App initialized...") return App.initWeb3(); }, initWeb3: function() { if (typeof web3 !== 'undefined') { App.web3Provider = web3.currentProvider; web3 = new Web3(web3.currentProvider); } else { App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545'); web3 = new Web3(App.web3Provider); } return App.initContracts(); }, initContracts: function() { $.getJSON("/RiskxTokenSale.json", function(RiskxTokenSale) { App.contracts.RiskxTokenSale = TruffleContract(RiskxTokenSale); App.contracts.RiskxTokenSale.setProvider(App.web3Provider); App.contracts.RiskxTokenSale.deployed().then(function(RiskxTokenSale) { console.log("Riskx Token Sale Address:", RiskxTokenSale.address); // Try loading this App with the Truffle suite on the iMac }); }) } } $(function() { $(window).load(function() { App.init(); }) }); I was expecting the web console to return the contract address, but instead I get this error jquery.min.js:4 GET http://127.0.0.1:8000/RiskxTokenSale.json 404 (Not Found) Is this because I haven't included jQuery into the window scope? If so, how would I go about implementing this? Just to give you a bit more information I'm trying to run this in a Django development framework. Please let me know if you need more information about my code and dependencies. cheers, -
Downside of using non-ASCII language as source-code in django i18n?
Is there any downside, in terms of performance or difficulty, to use non-ASCII language as the source-language during an i18n? Specifically, will it be equal, performance-wise, to have: _("这是一条中文信息") translated by from Chinese to English rather than: _("this is an English message") translated by from English to Chinese? -
pytest-django how test excel response
I have a HttpResponse with excel file, but I don't know how to test it. def request(): wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('test') # write data to sheet, balabala... # ws.write(0, 0, 'hello') response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="test.xls"' wb.save(response) return response When I use pytest-django to test this this function, I dont know how to get excel which is in the response and how test it. thanks very much :) -
django form is not validating
So I have been trying to implement a way to post a project post in my website. However, it seems that there is something wrong with my validation with forms. Even if the form is correct and complete, it still wont validate. No posts are being made in my projects page and nothing gets added in my database. I am not sure what is going on My code is below: views.py class CreateProjectsView(View): def get(self, request): p_photos = P_Images.objects.all() #project_form = ProjectsForm(initial=self.initial) project_form = ProjectsForm() context = { 'p_photos': p_photos, 'project_form': project_form, } return render(self.request, 'projects/forms.html', context) def post(self, request): project_form = ProjectsForm(request.POST or None, request.FILES or None) p_formset = P_ImageForm(request.POST, request.FILES) # Checks if the project_form is valid before save if project_form.is_valid(): instance = project_form.save(commit=False) instance.user = request.user instance.save() # Checks if multiple image upload is valid before save if p_formset.is_valid(): #if project_form.is_valid() and p_formset.is_valid(): #instance = project_form.save(commit=False) #instance.user = request.user #instance.save() images = p_formset.save(commit=False) images.save() data = { 'is_valid': True, 'name': images.p_file.name, 'url': images.p_file.url } else: data = { 'is_valid': False, } return JsonResponse(data) forms.html {% extends "projects/test.html" %} {% block javascript %} <form action="{% url 'create_post:retrieve_projects' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for hidden in project_form.hidden_fields … -
Django CMS superuser login /logout by default logs-in / logs-out the site-user [respectively]
Use case: I have header htmls different for logged-in and logged-out customers.[ logged-in-header.html and logged-out-header.html] I am using django's user.is_authenticated to check whether user is logged-in or not and deciding my header html accordingly. This setup was working fine. Requirement: Now I wanted to bring logged-out header under django CMS as it contains / redirects to static pages. Given this, when i login the DJango-CMS portal , this user.is_authenticated is made true from django that for any cms page, i could only be able to see the logged-in header.This pushes me to the scenario where am not able to create placeholders for logged-out-header. Is it because request.user for Django-CMS app is intruding with request.user of my django app ? Or is it because of something else in django-cms ? Django version : (1, 8, 6, 'final', 0) django_cms version : 3.5.2 -
Can I create a custom decorator for a model method in Django?
Let's say I have the following model - class Banana(models.Model): name = models.CharField(max_length=255) def get_banana(self): return f'Banana: {self.name}' Now I want to add a logger that generates a log whenever the method starts and ends successfully to this get_banana method. The logger is as follows - class Log(models.Model): type = models.CharField(max_length=255) message = models.CharField(max_length=255) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() So I create a logger decorator - def log_status(f): def wrapper(**fields): Log.objects.create(**{k: (v if k != 'message' else v + ':STARTED') for k, v in fields.items()}) return_value = f() Log.objects.create(**{k: (v if k != 'message' else v + ':COMPLETED') for k, v in fields.items()}) return return_value return wrapper How can I add this decorator to my get_banana method? The following doesn't work because it can't see self. @log_status(type='info', message='Get Banana.', content_object=self) def get_banana(self): return f'Banana: {self.state}' -
UpdateView gives KeyError with cleaned_data
I am creating objects in a model as shown below. What I want to be able to do is update the "class_list" with an UpdateView. The update seems to refer back to my object's modelform which has a clean routine in it, which causes a problem. class ClassroomForm(ModelForm): class Meta: model = Classroom fields = ['course_name', 'course_block','class_list'] def clean(self): try: Classroom.objects.get(course_block=self.cleaned_data['course_block']) self.redirect = True raise forms.ValidationError("Exists already") except Classroom.DoesNotExist: pass return self.cleaned_data I'm now implementing an UpdateView for this same model. The view is simple: class BlockUpdateView(UpdateView): model = Classroom fields = ['class_list'] success_url = reverse_lazy('classroom:blocklist') update_classroom_view = BlockUpdateView.as_view() This is called from the template code below: {% for block in classroom_blocks %} <li>{{ block.get_course_block_display }}<a href ="{% url 'classroom:blockUpdate' block.id %}" class="button">EDIT</a><a href ="{% url 'classroom:blockDelete' block.id %}" class="button">DELETE</a></li> {% empty %} <li>No classes set up yet.</li> {% endfor %} I successfully get to the view where I can update the model. After making my edit I press Submit and I get the following error: Exception Type: KeyError Exception Value: 'course_block' Exception Location: C:\Users\dwsmith\mysite\classroom\models.py in clean, line 59 line 59: Classroom.objects.get(course_block=self.cleaned_data['course_block']) I would like to know if and how I can use UpdateView in this situation. However, the situation … -
django-easy-pdf displays no content
I want to render a pdf file with Django using django-easy-pdf. I followed these instructions, but I get an empty pdf. This is my html: {% extends "easy_pdf/base.html" %} {% block extra_style %} {% endblock %} <% block content %> <div id="summary-block"> <p>Here goes that square with data.</p> </div> <div id="declarations-block"> <p>Here goes the Main content.</p> </div> <div id="data-block"> <p>Here goes all the data from the contract.</p> </div> <div id="clause-block"> <p>Here goes the Clause content.</p> </div> <div id="signatures-block"> <p>Here goes the signatures content.</p> </div> <% endblock %> And this is my views.py: from django.shortcuts import render from django.conf import settings from easy_pdf.views import PDFTemplateView # Create your views here. class ContractPDFView(PDFTemplateView): template_name = 'contract.html' base_url = 'file://' + settings.TEMPLATES_DIR download_filename = 'contract.pdf' def get_context_data(self, **kwargs): return super(ContractPDFView, self).get_context_data(pagesize='letter', title='Contract', **kwargs) I don't know what I am missing. -
How to pass parameter from views to formset Django
I want to pass parameter from views.py to formset in forms.py Django ? My setup: Django 2.0.7, Python 3.6.5 Thank you for helping me. -
When am I allowed to use the "request" object in Django?
I am trying to pass an instance of the current user using "request.user", but when I try to access the "request" object where I need to, I get an error: NameError: name 'request' is not defined When I try to use self.request.user I get a similar error (PasswordChangeForm inherits SetPasswordForm): AttributeError: 'PasswordChangeForm' object has no attribute 'request' This is form class I use (request usage in def __init__ ): class SetPasswordForm(forms.Form): """ A form that lets a user change set their password without entering the old password """ error_messages = { 'password_mismatch': _("The two password fields didn't match."), } new_password1 = forms.CharField( label=_("New password"), widget=forms.PasswordInput, strip=False, help_text=password_validation.password_validators_help_text_html(), ) new_password2 = forms.CharField( label=_("New password confirmation"), strip=False, widget=forms.PasswordInput, ) def __init__(self, *args, **kwargs): self.user = request.user super().__init__(*args, **kwargs) def clean_new_password2(self): password1 = self.cleaned_data.get('new_password1') password2 = self.cleaned_data.get('new_password2') if password1 and password2: if password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) password_validation.validate_password(password2, self.user) return password2 def save(self, commit=True): password = self.cleaned_data["new_password1"] self.user.set_password(password) if commit: self.user.save() return self.user Any suggestions? -
Convert string to list of dictionaries in Javascript in Django
in my context there is a variable called "spots". I have a script where I print it in the document <script > var spotss = "{{ spots }}"; document.write(spotss) </script> The above code produces the following result: [{u'rider_ability': u'Beginner, Intermediate, Expert', u'spot_distance': 2, u'water_type': u'Shallow, Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.4026, u'lng': 14.9949, u'spot_name': u'Paestum'}, {u'rider_ability': u'Beginner, Intermediate, Expert', u'spot_distance': 2, u'water_type': u'Shallow, Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.4271, u'lng': 14.9818, u'spot_name': u'Ponte di Ferro'}, {u'rider_ability': u'Beginner, Intermediate, Expert', u'spot_distance': 9, u'water_type': u'Shallow, Flat, Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.343, u'lng': 14.9717, u'spot_name': u'Agropoli'}, {u'rider_ability': u'Beginner, Intermediate, Expert', u'spot_distance': 21, u'water_type': u'Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.2315, u'lng': 14.9566, u'spot_name': u'Case del Conte'}, {u'rider_ability': u'Beginner, Intermediate, Expert', u'spot_distance': 26, u'water_type': u'Small wave', u'water_quality': u'Clean', u'lat': 40.1856, u'lng': 15.0239, u'spot_name': u'Acciaroli'}, {u'rider_ability': u'Intermediate, Expert', u'spot_distance': 28, u'water_type': u'Flat, Chop', u'water_quality': u'Crystal clear', u'lat': 40.1732, u'lng': 15.0846, u'spot_name': u'Pioppi'}, {u'rider_ability': u'Beginner, Intermediate, Expert', u'spot_distance': 31, u'water_type': u'Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.1641, u'lng': 15.1423, u'spot_name': u'Marina di Casal Velino'}, {u'rider_ability': u'Expert', u'spot_distance': 35, u'water_type': u'Flat, Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.6436, u'lng': 14.6984, u'spot_name': u'Cetara'}, {u'rider_ability': u'Intermediate, Expert', u'spot_distance': 35, u'water_type': u'Shallow, Flat, Chop, Small wave', … -
Passing a Dictionary to Django Form
I am trying to pass a list of Python dictionaries to the Form on POST, and not sure how to do it. I am assembling a dictionary, then add it to a master dictionary, and pass them to the FORM for display. Very simplified example: Views.py vehicles = { 'vehicle1': {'car': 'pontiac', 'engine': '400', 'model': 'GTO'}, 'vehicle2': {'car': 'chevrolet', 'engine': '396', 'model': 'Chevelle'}, 'vehicle3': {'car': 'ford', 'engine': '289', 'model': 'Mustang'} } return render(request, "vehicle_detail.html", {'vehicles': vehicles}) HTML <p> {% for vehicle in vehicles %} <b>{{ vehicle.car }}</b> <b>{{ vehicle.engine }}</b> <b>{{ vehicle.model }}</b> {% endfor %} </p> I have tried several different ways to do this, but not working. What is the proper way to handle this? -
Let's encrypt after installing Django ha errors
After installing Django I tried to install SSL using Let's Encrypt with Nginx, sudo certbot --nginx -d [mydomain.com] But I get this error, Domain: [mydomain.com] Type: unknownHost Detail: No valid IP addresses found for [mydomain.com] My domain is accessible and there are A entries. What is wrong? -
TypeError at /goods/ __init__() got an unexpected keyword argument 'name'
I am learning Django REST Framework. And I want to use the django-filter in django rest framework to choose the result I want. I wrote a filter.py to get goods whose price is between pricemin and pricemax: class GoodsFilter(filters.FilterSet): pricemin = filters.NumberFilter(name="shop_price", lookup_expr='gte') pricemax = filters.NumberFilter(name="shop_price", lookup_expr='lte') class Meta: model = Goods fields = ['pricemin', 'pricemax'] then I used this filter in view.py: class GoodsListViewSet(mixins.ListModelMixin,viewsets.GenericViewSet): queryset = Goods.objects.all() serializer_class = GoodsSerializer pagination_class = GoodsPagination filter_backends = (DjangoFilterBackend,) filter_class = GoodsFilter when I run my project, there is an error like this: TypeError at /goods/ __init__() got an unexpected keyword argument 'name' I did not use argument 'name' in my code, so I have no idea about this error. Traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/goods/ Django Version: 2.0.3 Python Version: 3.6.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'DjangoUeditor', 'users.apps.UsersConfig', 'goods.apps.GoodsConfig', 'trade.apps.TradeConfig', 'user_operation.apps.UserOperationConfig', 'crispy_forms', 'xadmin', 'rest_framework', 'django_filters'] 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'] Traceback: File "C:\Users\Harry\Envs\testvir2\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\Harry\Envs\testvir2\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\Harry\Envs\testvir2\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Harry\Envs\testvir2\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "C:\Users\Harry\Envs\testvir2\lib\site-packages\rest_framework\viewsets.py" in view 103. return … -
How can I find an ID where the datetime field matches the datefield, but where another field is null?
I have a model for keeping track of an employee clock-in/clock-out app.. class ClockPunch(models.Model): employee = models.ForeignKey(settings.AUTH_USER_MODEL) date = models.DateField(auto_now_add=True) punch_in_time = models.DateTimeField(blank=True, null=True) punch_out_time = models.DateTimeField(blank=True, null=True) hours_for_the_day = models.DecimalField(max_digits=4, decimal_places=2, default="0.00", blank=True, null=True) class Meta: ordering = ['date', ] def __str__(self): return self.pk and 2 views, one for clocking in, and one for clocking out... class ClockPunchInView(LoginRequiredMixin, CreateView): context_object_name = "clock_punch" fields = ['punch_in_time'] model = ClockPunch template_name = 'pages/layout.html' success_url = '/' def form_valid(self, form): object = form.save(commit=False) object.employee = self.request.user object.punch_in_time = timezone.now() object.save() return super(ClockPunchInView, self).form_valid(form) class ClockPunchOutView(LoginRequiredMixin, UpdateView): context_object_name = "clock_punch" model = ClockPunch template_name = 'pages/layout.html' def form_valid(self, form): object = form.save(commit=False) object.employee = self.request.user object.punch_out_time = timezone.now() object.save() return super(ClockPunchOutView, self).form_valid(form) the clock-in works fine, but I need to somehow get the ID of the last clock-in for the clock-out view to know which line to update. How would I get the pk of the last clock-in with a blank or null value in the clock-out field? Thanks! -
Django rest framework nested serializer not working for M2M relations
My models.py looks like this: class IP(models.Model): hostname = models.CharField(max_length=50, unique=True) ip_address = models.CharField(unique=True) class IPGroup(models.Model): name = model.CharField(max_length=50, unique=True) ips = models.ManyToManyField(IP, through=IPGroupToIP) class IPGroupToIP(models.Model): ip_group = models.ForeignKey(IPGroup) ip = models.ForeignKey(IP) My serializers.py looks like this: class IPSerializer(serializers.ModelSerializer): class Meta: model = IP fields = ['id', 'host_name', 'ip_address'] class IPGroupSerializer(serializers.ModelSerializer): ips = IPSerializer(many=True) class Meta: model = IPGroup depth = 1 fields = '__all__' def create(self, validated_data): # Pop out ips since these are M2M relations and have to be created separately ips_data = validated_data.pop('ips', None) # Create the IPGroup object ip_group_obj = IPGroup.objects.create(name=validated_data['name']) if ips_data: for ip in ips_data: # Get the ip object id if already created or create it on the fly and save it ip_obj, created = IP.objects.get_or_create(host_name=ip['host_name'], ip_address=ip['ip_address']) # Update through table for M2M relationship IPGroupToIP.objects.create(ip_group_id=ip_group_obj.id, ip_id=ip_obj.id) and finally my views.py look like this: class IPGroupCreateView(generics.CreateAPIView): queryset = IPGroup.objects.get_queryset() serializer_class = IPGroupSerializer This works as expected and sending the following JSON create request to the API endpoint does the job: { "name":"TestIPGroup1", "ips": [{"name":"host1","value":"8.8.4.4"}, {"name":"host2","value":"8.8.8.8"}] } However, if I send another JSON create request with the same IPs for a new IPGroup as follows: { "name":"TestIPGroup2", "ips": [{"name":"host1","value":"8.8.4.4"}, {"name":"host2","value":"8.8.8.8"}] } it gives me an … -
Django Oauth2 Toolkit custom mixin
I have a particular situation were using django oauth2 toolkit i need to answer to a request with a wrong token with a 401 (with a json) instead of a 403 forbidden. Following this commit I managed to come with this change to: oauth2_provider/views/mixins.py class ProtectedResourceMixin(OAuthLibMixin): def dispatch(self, request, *args, **kwargs): if request.method.upper() == "OPTIONS": return super().dispatch(request, *args, **kwargs) valid, r = self.verify_request(request) if valid: request.resource_owner = r.user return super().dispatch(request, *args, **kwargs) else: request.oauth2_error = getattr(r, "oauth2_error", {}) print(str(self.request.oauth2_error['error'])) data= { "errors": [ { "message": str(self.request.oauth2_error['error']) } ], } return HttpResponse(json.dumps(data,ensure_ascii=False),content_type="application/json; charset=utf-8",status= 401) #return HttpResponseForbidden() my problem is that even though this solution works it is on the actual file of the library, i would like to implement this with out modifying the library is of my understanding that i should be able to create my own custom mixin but i have yet to be able to find an example of that sort of implementation I'm not using django rest framework -
How tocreate dynamic sections in page?
I have base mezzanine project and I want to create page with with different number of sections (banner, posts list, some gallery, box with icons - every section has its own html template). I want to add any number of sections to one page. For now I created custom models inherits from mezzanine Page, and in admin I did structure something like this: - menu item (page) - section 1 - section 2 - section 1 - section 3 but how can I render subpage in current page? I don't know how to go about it. -
Django Postman Import Error
I'm getting an import error on a model I created in the postman app in my django site. I duplicated a previous project because I want to store both on two different sites. The first project works flawlessly. Once I cloned into the second project, I'm getting an import error. I tried commenting the models and then uncommenting them, but that didn't work. The models are in the database and the same setup works on my first project. What could be causing this error on the second one? ImportError: cannot import name MessageColleague 2018-08-14 21:31:53,645: File "/home/xxx/xxx/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__ 2018-08-14 21:31:53,645: return self.application(environ, start_response) 2018-08-14 21:31:53,645: 2018-08-14 21:31:53,645: File "/home/xxx/xxx/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 157, in __call__ 2018-08-14 21:31:53,645: response = self.get_response(request) 2018-08-14 21:31:53,645: 2018-08-14 21:31:53,646: File "/home/xxx/xxx/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 124, in get_response 2018-08-14 21:31:53,646: response = self._middleware_chain(request) 2018-08-14 21:31:53,646: 2018-08-14 21:31:53,646: File "/home/xxx/xxx/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 43, in inner 2018-08-14 21:31:53,646: response = response_for_exception(request, exc) 2018-08-14 21:31:53,646: 2018-08-14 21:31:53,646: File "/home/xxx/xxx/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 93, in response_for_exception 2018-08-14 21:31:53,647: response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) 2018-08-14 21:31:53,647: 2018-08-14 21:31:53,647: File "/home/xxx/xxx/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 142, in handle_uncaught_exception 2018-08-14 21:31:53,647: callback, param_dict = resolver.resolve_error_handler(500) 2018-08-14 21:31:53,647: 2018-08-14 21:31:53,647: File "/home/xxx/xxx/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 418, in resolve_error_handler 2018-08-14 21:31:53,647: callback = getattr(self.urlconf_module, … -
My data insertion system in django does not work
I will explain my problem : I'm working on a commentary system, but I do not succeed at insert my datas in the table. I possesses an formulary based on my model in the file forms.py, then in my file views.py an function for treat the datas of my input textarea, then a html file with a field textarea, here is my code : models.py : class Commentary(models.Model): contents = models.CharField(max_length=500, null=True) created_at = models.DateTimeField(auto_now_add=True)) edited_at = models.DateTimeField(null=True) article = models.ForeignKey(Article, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) forms.py : class CommentForm(forms.Form): contents = forms.CharField(widget=forms.Textarea, max_length=500, required=True) views.py : def createComment(request): if request.method == "POST": form = CommentForm(request.POST) if form.is_valid: commentary = form.save(commit=False) author = request.user commentary.contents = contents commentary.author = author commentary.created_at = timezone.now() commentary.save() return redirect('/home') read.html : <textarea name="contents" required id="contents"></textarea> I looked on the forum and in the documentation of Django, alas nothing is stock, my way is it good? Thanks all!