Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Elasticsearch or mongodb for storing data and ploting it (Visualization)
I am willing to work on a project, that take a big excel database, migrate it to a nosql database in order to visulize the data in plots, and then integrate it in a django website. My question is, which is better to do the job, mongoDB or Elasticsearch ? -
Django aggregation for Avg
I have a model as below. class Transaction(models.Model): time1 = models.DateTimeField(null=True) time2 = models.DateTimeField(null=True) I need to get the average of the (time2 - time1) in seconds for a list of records, if both values are not null. -
AJAX post request slow every second time [Django]
As a little side-project I created a Django-based Web Application. So far I have created my webpage with basic Javascript. I can successfully get data from the database and create an AJAX POST-request via Javascript. Everything is working BUT there is something that really bothers me: Every second POST-request takes a significantly longer time to reach the server. For example: Request1 returns successful after 29ms. Request2 needs (for the exact same task!) over 300ms. This goes on and is 100% replicable. I have no idea what the reason for that issue is. I hope someone can guess what the root for this problem is. Image of "request-waterfall" from the developer tool. Used Code: //THIS IS THE POST REQUEST IN THE JS-SCRIPT (CLIENT-SIDE) $.ajax({ type: "POST", url: '/update_database', data: { "habit_name": habits[h].habit_name, "meta_data": meta_data }, success: function(result) { update(); console.log('Successful'); } }); Server-side handling of the POST-request: def update_database(request): post_dict = dict(six.iterlists(request.POST)) habit_name = post_dict["habit_name"][0] meta_data = post_dict["meta_data"][0] change_meta_data(habit_name, meta_data) data = { "Habits": Habit.objects.all().values() } return JsonResponse(list(data["Habits"]), safe=False) -
Authenticating users with ldap in Django project
I am trying to authenticate users against my ldap server. I have successfully ran pip install python-ldap and django-auth-ldap.. I am running python 2.7.. Every time I try to login my to Django admin with my superuser account I get the following error: AttributeError at /admin/login/ 'module' object has no attribute 'LDAPError' Request Method: POST Request URL: http://localhost:8000/admin/login/?next=/admin/ Django Version: 1.11.9 Exception Type: AttributeError Exception Value: 'module' object has no attribute 'LDAPError' Exception Location: C:\Python27\lib\site-packages\django_auth_ldap\backend.py in authenticate, line 384 Python Executable: C:\Python27\python.exe Python Version: 2.7.13 Python Path: ['C:\\Users\\donallane\\Desktop\\My_Django_Stuff\\ldap-login\\learning_users', 'C:\\WINDOWS\\SYSTEM32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages', 'C:\\Python27\\lib\\site-packages\\python_ldap-2.4.10-py2.7-win32.egg'] Server time: Thu, 8 Feb 2018 16:59:10 +0000 ldap configurations in settings.py: ####### --------------- LDAP Configuration ------------ ####### import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType # AUTH_LDAP_START_TLS = True # AUTH_LDAP_GLOBAL_OPTIONS = { # #ldap.OPT_X_TLS_REQUIRE_CERT: False, # #ldap.OPT_REFERRALS: False, # } # # AUTH_LDAP_SERVER_URI = "ldaps://ldap.ecf.orca.ie" # AUTH_LDAP_BIND_DN = 'cn=myapp,ou=apps,o=company' # AUTH_LDAP_BIND_PASSWORD = 'myapp_password' # AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=people,o=company", ldap.SCOPE_SUBTREE, "(uid=%(user)s)") # # AUTH_LDAP_ALWAYS_UPDATE_USER = False # # # AUTH_LDAP_USER_ATTR_MAP = { # "first_name": "givenName", # "last_name": "sn", # "email": "mail" # } # import ldap # # AUTH_LDAP_CONNECTION_OPTIONS = { # ldap.OPT_REFERRALS: 0 # } AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) auth_connection.py: import ldap … -
Django: Creating categories using querysets/filtering
I'm trying to figure out if it's possible to create categories using custom filters. I am building an e-commerce app and I have set up my category model using mptt. I am importing a csv that creates my top level categories which works fine. The problem is I will need to have sub-categories that are more specific e.g Men's Clothing(Top Level) > Jeans. The csv has several fields that contains info relating to each product e.g description: "stone wash bootcut jeans". I would ideally like to check these fields for keywords and add each product to the correct categories. Is it possible to set up categories this way or is there an alternative solution? I am a django newbie so any help is appreciated. models.py from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.CASCADE) slug = models.SlugField() class MPTTMeta: order_insertion_by = ['name'] class Meta: unique_together = (('parent', 'slug',)) verbose_name_plural = 'categories' def get_slug_list(self): try: ancestors = self.get_ancestors(include_self=True) except: ancestors = [] else: ancestors = [ i.slug for i in ancestors] slugs = [] for i in range(len(ancestors)): slugs.append('/'.join(ancestors[:i+1])) return slugs def __str__(self): return self.name class Brands(models.Model): … -
Categories and subcategories in Django
I have a little problem. I've create a model for Categories, and Posts. In my project I used a categories->subcategories model. When I finished, createsuperuser and login in to the Admin Panel I show a Fields 'Category' and 'Posts'. When I want to add a new category as a parent, after I need to add children. I added 1 record 'Biznes' and Child 'Własna Firma'. I clicked add next and for that moment the Admin Panel thinking, thinking and not respond. I can't add Post, delete or Edit Category. Here is my models.py from django.db import models from django.contrib.auth.models import User class Kategoria(models.Model): name = models.CharField(max_length=250, verbose_name='Kategoria') slug = models.SlugField(unique=True,verbose_name='Adres SEO') parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent',) verbose_name = 'Kategoria' verbose_name_plural = 'Kategorie' def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' / '.join(full_path[::-1]) class Firma(models.Model): user = models.ForeignKey(User, default=1, verbose_name='Użytkownik', on_delete=models.CASCADE) title = models.CharField(max_length=250, verbose_name='Nazwa firmy') slug = models.SlugField(unique=True, verbose_name='Adres SEO') category = models.ForeignKey('Kategoria', null=True, blank=True, verbose_name='Kategoria', on_delete=models.CASCADE) content = models.TextField(verbose_name='Opis') draft = models.BooleanField(default=False, verbose_name='Szablon') publish = models.DateField(auto_now=False, auto_now_add=False) class Meta: verbose_name='Firma' verbose_name_plural='Firmy' def __str__(self): return self.title def get_cat_list(self): k = self.category … -
How to write test for class methods?
How to write tests for this manager in pytest? class OperatorLogManager(models.Manager): def active(self): """Mark object as active""" return self.filter(is_delete=False) def get_by_user_id(self, id): return self.active().filter(pk=id) def get_by_client_id(self, client_uid): return self.active().filter(client_uid=client_uid) -
AttributeError: 'DeferredAttribute' object has no attribute 'rel'
I'm new to Wagtail and Django, and I am trying to build a model that will pull data from a REST API and put it into an object that can be iterated on the template. However, when trying to migrate, I get this error: related = getattr(model, self.relation_name).rel AttributeError: 'DeferredAttribute' object has no attribute 'rel' From what I've been able to gather so far, it has something to with the description and image fields in the OFSLOrgWebPage page model. Here are the relevant models: from __future__ import absolute_import, unicode_literals from django.db import models from django.shortcuts import render from django.conf import settings from wagtail.wagtailcore.models import Page, Orderable from wagtail.wagtailcore.fields import RichTextField, StreamField from wagtail.wagtailadmin.edit_handlers import FieldPanel, FieldRowPanel, MultiFieldPanel, \ InlinePanel, StreamFieldPanel from wagtail.wagtailimages.edit_handlers import ImageChooserPanel from wagtail.wagtailsearch import index from wagtail.wagtailcore.blocks import StructBlock, StreamBlock, CharBlock, RichTextBlock, RawHTMLBlock, BooleanBlock from wagtail.wagtailimages.blocks import ImageChooserBlock from wagtail.wagtaildocs.blocks import DocumentChooserBlock from modelcluster.fields import ParentalKey import datetime import json import requests class OFSLOrgWebPage(Page): description = RichTextField(blank=True) image = models.ForeignKey( 'serenity.Images', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', help_text="Council image that appears at the top of the page. Size: 500px x 400px" ) def get_context(self, request): context = super(OFSLOrgWebPage, self).get_context(request) context['greek_orgs'] = self.greek_bios.objects.child_of(self).live() return context search_fields = Page.search_fields + [ … -
Django tests for zero downtime schema migrations
This question touches the subject of zero downtime schema migrations in Django (like this one perhaps). A two-way compatible schema migration deployment is usually as follows (correct me if this list is missing a step): Scale up old code. Create new schema change with all fields nullable. Deploy schema change. Create new code change that uses new fields. Deploy new code. Scale down old code. Optionally deploy new changes that make these fields non-nullable. However, I have not found any resources in the Django docs about testing steps 2, 3, and 4. Ideally, before makemigrations generates a migration file, a series of tests should pass to indicate that the current codebase can run before and after this migration is run. Question: is there already a built-in mechanism in Django, by which the two interleaved states ((old code, new schema), (new code, old schema)) during a hypothetical zero downtime forwards and backwards migration, can be tested? -
Per-user sessions in django
I've been playing with sessions in django, but I have a few questions: I do not really understand where they are useful. I mean, I thought I'd be able to store data for my users without having to create specific fields in my model. But, looks like the session only refers to the browser id (is that right?) the user is currently using, so once they enter from another place the sessions dict is blank again. In the docs of django, it says the data is stored in the server side to avoid security problems related to cookies, but again, as I have understood the data is only temporary, right? Is there any way to keep track (storing data) of the interaction of a specific user with my site with sessions? Or the sessions are not dessigned for that? When it comes to users, loging in just means assigning the session dict to the user hash, id... (previously created), right? Finally, if you could show me a practical and real use of sessions it would be great, bc the comments example in the docs doesn't seem useful, since once you re-enter the site the dict will be blank again. Thank … -
Favicon redirect in django 2.0
I'm trying to redirect the default browsers request of /favicon.ico to serve the picture from my static folder and I get a 404(server log screenshot). settings.py STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") urls.py from django.contrib import admin from django.contrib.staticfiles.storage import staticfiles_storage from django.urls import include, path from django.views.generic.base import RedirectView urlpatterns = [ path('admin/', admin.site.urls), path( 'favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('upload.ico')) ), path('', include('uploader.urls')) ] My directory structure: ../ ├ imguploader/ | ├ __init__.py | ├ settings.py | ├ urls.py | └ wsgi.py ├ static/ | ├ admin/ | └ upload.ico ├ manage.py |... -
Add button against each record on django admin change list page?
I want to add a button against each row on django admin change list page. When that button is clicked, i want to make entries in some database table(all this happens on the backend) and after that the button should be disabled on the same page against that row. How can i achieve this? I have searched a lot button there is no solution available. -
AttributeError: type object 'BaseCommand' has no attribute 'option_list'
Hello i am trying to create search app in My Django project using Haystack and Solr but i receive this error "AttributeError: type object 'BaseCommand' has no attribute 'option_list'" I am running this command : python manage.py rebuild_index I am using : Python 3.6.4 solr-4.10.4 haystack 2.4.0 Django 2.0 If the post isn't clear i am ready to explain it more See the error -
'overflow: scroll' not working in Safari (11.0.2) on MacBook (10.13.2 ) or any browser on iPhoneX (11.2.1)
On the webpage below if you select a barber it reveals a hidden 'div' (id="booking-right") containing an 'iframe' (class="iframe") with a booking page. We have set our CSS to allow the 'iframe' to scroll up and down within the hidden 'div' using 'overflow: scroll'. As you may be able to see, this works fine in Chrome on MacBook, but won't work in Safari on MacBook or on any browser on my iPhoneX. This is a real problem because it means clients won't be able to scroll down to select appointment times for our barbers. http://cuttersclub.webfactional.com/barbers/ Any help would be much appreciated! barbers.html: <div id="div"> <!-- acuity --> <div id="booking-div"> <div id="booking-left"></div> <div id="booking-right"> <a><img id="close-image" src="{% static "img/close-button.svg" %}" alt="My image"></a> {% for BarberProfile in queryset_list %} <iframe class="iframe" id="{{BarberProfile.id}}-iframe" src="" frameBorder="0"></iframe><script src="https://d3gxy7nm8y4yjr.cloudfront.net/js/embed.js" type="text/javascript"></script> {% endfor %} </div> </div> <!-- acuity --> <!-- profile --> {% for BarberProfile in queryset_list %} <a class="profile-div" id="{{BarberProfile.id}}" target="{{BarberProfile.booking_link}}" onClick="toggle_content(this.id)"> <div id="image" style="background-image: url({{BarberProfile.image.url}})"> <div id="image-structure"></div> </div> <h4 id="name"> {{BarberProfile.first_name}} </h4> <p id="bio"> {{BarberProfile.bio}} </p> <img id="experience-image" src="{% static "img/experience.svg" %}" alt=""><p id="experience">{{BarberProfile.years_of_experience}} experience</p> <img id="ideal-image" src="{% static "img/speciality.svg" %}" alt=""><p id="ideal">Ideal for {{BarberProfile.ideal_for}} </p> </a> {% endfor %} <!-- profile --> </div> barbers.css: … -
Not found: /accounts/facebook/login in django allauth
What I am trying to do ? I am trying to login the user using their social account and I am doing this with the help of Django allauth. What is the problem ? My project works fine on my laptop (which is broken now) but I don't know why it doesn't work on my desktop. I get the following error on the console whenever I try to login using a social account: Error: Not Found: /accounts/facebook/login My Code: settings.py: DEBUG = True INSTALLED_APPS = [ ... 'django.contrib.auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook' ] LOGIN_URL = 'login_url' LOGOUT_URL = 'logout_url' LOGIN_REDIRECT_URL = 'redirect_url' SITE_ID = 1 AUTHENTICATION_BACKENDS = [ 'allauth.account.auth_backends.AuthenticationBackend', 'Authentication.backends.EmailBackend', ] SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_EMAIL_VERIFICATION = True SOCIALACCOUNT_EMAIL_REQUIRED = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(SETTINGS_PATH, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ ... 'django.template.context_processors.request' ], }, }, ] html: <div class="modal" id="loginModal" data-backdrop="static" data-keyboard="false"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button class="close">&times;</button> </div> <form id='loginForm'>{% csrf_token %} <div class="modal-body"> <div class="col-xs-12"> <a href="/accounts/facebook/login"> Facebook </a> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-default" id="login"> Login </button> </div> </form> </div> </div> </div> urls.py: urlpatterns = [ url(r'^accounts/', include('allauth.urls')), ... ] And have perfectly setup the social application … -
NoReverseMatch error during url
New to Django framework. Mostly reading through documentations. But this one i am unable to crack. Trying to add a URL to an headline, that will be forwarded to the 'headlines' post. The Error: NoReverseMatch at / Reverse for 'assignment_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['assignment_detail/'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.0.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'assignment_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['assignment_detail/'] Exception Location: C:\Users\internit\Dropbox\Python\codepython\env\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 632 Python Executable: C:\Users\internit\Dropbox\Python\codepython\env\Scripts\python.exe Python Version: 3.6.2 Python Path: ['C:\Users\internit\Dropbox\Python\codepython\codepython', 'C:\Users\internit\Dropbox\Python\codepython\env\Scripts\python36.zip', 'C:\Users\internit\Dropbox\Python\codepython\env\DLLs', 'C:\Users\internit\Dropbox\Python\codepython\env\lib', 'C:\Users\internit\Dropbox\Python\codepython\env\Scripts', 'c:\program files (x86)\python36-32\Lib', 'c:\program files (x86)\python36-32\DLLs', 'C:\Users\internit\Dropbox\Python\codepython\env', 'C:\Users\internit\Dropbox\Python\codepython\env\lib\site-packages'] Server time: Thu, 8 Feb 2018 14:53:07 +0000 Error during template rendering In template C:\Users\internit\Dropbox\Python\codepython\codepython\codepython\templates\base.html, error at line 0 Reverse for 'assignment_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['assignment_detail/'] 1 {% load static %} 2 3 4 5 6 7 8 9 10 CODEPYTHON.NET Traceback Switch to copy-and-paste view C:\Users\internit\Dropbox\Python\codepython\env\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) ... ▶ Local vars C:\Users\internit\Dropbox\Python\codepython\env\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) ... ▶ Local vars C:\Users\internit\Dropbox\Python\codepython\env\lib\site-packages\django\core\handlers\base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ... ▶ Local vars C:\Users\internit\Dropbox\Python\codepython\codepython\home\views.py in home return render(request, 'home.html', {'post':post}) ... ▶ Local vars home/urls.py from … -
FieldDoesNotExist: product_purchase_categories has no field named 'None' ManyToMany
I am trying to add ManyToMany relationships to an instance in and Django continues to throw a strange error. I am hoping someone has seen this before or may have some insight into why I am seeing this. Below are the two models I am working with. My product model is quite large so I slimmed it down. The other fields should not have any relevance. class baseModel(models.Model): created_date = models.DateTimeField(auto_now_add=True,blank=True) updated_date = models.DateTimeField(auto_now=True,blank=True) inactive = models.BooleanField(default = False,blank=True) class Meta: abstract = True class category(baseModel): name = models.CharField(max_length=255, help_text="",blank=True) short_name = models.CharField(max_length=255, help_text="",blank=True) external_id = models.IntegerField(help_text="",blank=True,null=True) sales_channel = models.ForeignKey('sales_channel',related_name = 'sales_categories',null=True,blank=True,on_delete=models.SET_NULL) purchase_channel = models.ForeignKey('purchase_channel',related_name = 'purchase_categories',null=True,blank=True,on_delete=models.SET_NULL) parent_category = models.ForeignKey('self',related_name='child_categories',null=True,blank=True,on_delete=models.SET_NULL) category_level = models.IntegerField(null=True,blank=True) def _product_count(self): "Number of Products" product_count = self.category_products.count() return product_count product_count = property(_product_count) def __str__(self): return self.name# + ' ('+str(self.product_count)+')' class product(baseModel): title = models.CharField(max_length=255, help_text="The title of the product.") additional_details = models.CharField(max_length=255, help_text="Additional product information provided by the supplier",null=True,blank=True,) description = models.TextField(max_length=4000, help_text="") # ... purchase_channel = models.ForeignKey('purchase_channel',related_name = 'products',null=True,blank=True,on_delete=models.SET_NULL) purchase_external_id = models.IntegerField(help_text="external_id from purchasing channel",null=True,blank=True) purchase_cost = models.DecimalField(max_digits=9,decimal_places=2, help_text="pruchase cost of the product.", blank=True, null=True) purchase_categories = models.ManyToManyField(category,related_name = 'categories_products',blank=True) # ... def __str__(self): return self.title Below is what I ran in shell. Grabbed a … -
django admin static isn't working
I'm trying to deploy my website on pythonanywhere and everything is working fine except of django admin. It's not showing css (staticfiles). Here is my static settings (I'm using django 1.8): STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) On pythonanywhere, in static files section I've added: Url: /static/ Directory: /home/erebbit/hypercube/static I've also added this at the end of my urls.py: if True: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) does anyone know what am I doing wrong? -
Azure event hubs python library
I'm trying to get the Azure event hubs python module to work. I've followed the instructions in the readme; which is mostly just "install Proto-c". Everything installs without any problems but when I try to run the receiver I get this: Traceback (most recent call last): File "recv.py", line 16, in from eventhubs import EventHubClient, Receiver, Offset File "/home/garr/Workspace/Bodaytrak/webhost/azure-event-hubs/eventhubs/init.py", line 23, in from proton import DELEGATED, Url, timestamp, generate_uuid, utf82unicode ImportError: No module named proton Anyone got any ideas? -
Django files storage: How to get base url of media file?
I'm using gcloud wrapped into django-storages logic. I have never feed the service with a url path of my bucket: only provided DEFAULT_FILE_STORAGE and GS_BUCKET_NAME which are the name of my glcoud project and storage. My question is: How can I get the full url of my images? My images are saved with a relative url, which make sens into the DB. But I can't found any right documentation about how you can get the base url of the django.core.files.storage collection of object storage. Some filestorage objects ask a valid relative image url in order to retrieve the full path. But this is not what I want: I just want to know (programatically) the base url of my (only one) bucket. The template {% image item.image %} is able to generate the full url, but from the code side view it seems totally obscure for me. Any help or advice? -
Django Modeltranslation: TranslationAdmin class does not copy the correct widget
I`m using a custom form for a django admin model with translated fields. But the widget of the form is not used. My code: models.py class Fact(models.Model): heading = models.CharField(max_length=200) translation.py class FactTranslationOptions(TranslationOptions): fields = ('heading') translator.register(Fact, FactTranslationOptions) admin.py class FactForm(forms.ModelForm): class Meta: model = Fact widgets = { 'heading': forms.Textarea } class FactAdmin(translationadmin.TranslationAdmin): form = FactForm admin.site.register(Fact, FactAdmin) With this code, the field heading does not show up as textarea. It`s a default input field. When I change FactForm to: class FactForm(ProductDataInlineFormBase): class Meta: model = Fact widgets = { 'heading_de': forms.Textarea, 'heading_en': forms.Textarea } the textarea widget is used. Am I doing something wrong, or is this a bug in django modeltranslation? -
Django CBV - set form class based on permissions?
I have created two forms in forms.py one form has less fields than the other. what I would like to now do is get the current users permissions and set the form class of the CBV based on those perms. below is my current view: class EditCircuit(UpdateView): model = Circuits # if user_passes_test(lambda u: u.has_perm('config.edit_circuit'))) form_class = CircuitForm # else # form_class = CircuitFormRestricted template_name = "sites/circuit_form.html" @method_decorator(user_passes_test(lambda u: u.has_perm('config.edit_circuit'))) def dispatch(self, *args, **kwargs): self.site_id = self.kwargs['site_id'] self.site = get_object_or_404(SiteData, pk=self.site_id) return super(EditCircuit, self).dispatch(*args, **kwargs) def get_success_url(self, **kwargs): return reverse_lazy("sites:site_detail_circuits", args=(self.site_id,)) def form_valid(self, form): form.instance.site_data = self.object.site_data return super(EditCircuit, self).form_valid(form) def get_form_kwargs(self, *args, **kwargs): kwargs = super().get_form_kwargs() return kwargs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['SiteID']=self.site_id context['SiteName']=self.site.location context['FormType']='Edit' context['active_circuits']='class="active"' return context -
Authenticating Swagger API docs (drf-yasg)
I've setup DRF-YASG but am unable to figure out how to configure it to show Views that require Authentication. Below is the configuration. schema_view = get_schema_view( openapi.Info( title="Swagger Doc", default_version='v1', description="Test description", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="contact@snippets.local"), license=openapi.License(name="BSD License"), ), validators=['flex', 'ssv'], permission_classes=(permissions.AllowAny,), # If I change the permission it throws an exception. See below public=False, patterns=public_apis, ) the public_apis are the APIs that I want a person to see after they have authenticated themselves. With the above configuration, it does not show a single API. It only shows the Authorize Button and text that says No operations defined in spec!. But if I change public=False to public=True then it shows all the APIs. PS: Earlier I was using Django Rest Swagger and I had been able to configure it to show the APIs only after the JWT token had been provided. Am is using JWT for authentication. Exception on Permission Change: Another issue is that if I change the permission above to a DRF Permission class the rendering fails with the error below: Internal Server Error: /swagger/ Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 217, in _get_response response = self.process_exception_by_middleware(e, request) File … -
Allowing user to register only if field information matches the one from database in Django
I am trying to allow a student user to register in the system only if the student_ID matches the one from database. But I don't know how to do it right. class StudentData(models.Model): name = models.CharField(max_length=30) surname = models.CharField(max_length=50) student_ID = models.CharField(unique=True, max_length=14) class StudentForm(forms.ModelForm): email = forms.EmailField(required=True) name = forms.CharField(max_length=50, required=True) surname = forms.CharField(max_length=50, required=True) student_ID = forms.CharField(required=True, max_length=14, min_length=14) student_data = StudentData.objects.all().values('student_ID') if form2.is_valid(): cd2 = form2.cleaned_data phone = cd2['phone'] for data in student_data: if data == 'student_ID': student_id = cd2['student_ID'] -
Django test post in localhost AttributeError
I have a test.py file that is supposed to send a POST request to my LocalHost site (if LH doesn't work for this I can also do test on test.domain.com). However, I am not getting any new information saved in my DB. I have tried this out with GET before and it worked perfectly. Error message in CMD: File "C:\Users\winkl\Desktop\VE\mysite\payment\views.py", line 36, in webhook user = User.objects.POST(id=request.POST('clientAccnum')) AttributeError: 'UserManager' object has no attribute 'POST' views.py @csrf_exempt def webhook(request): template_name = 'payment/index.html' hook = Webhook() #ERROR MESSAGE FOR LINE BELOW user = User.objects.POST(id=request.POST('clientAccnum')) hook.user = user hook.clientSubacc = request.POST('clientSubacc') hook.eventType = request.POST('eventType') hook.eventGroupType = request.POST('eventGroupType') hook.subscriptionId = request.POST('subscriptionId') hook.timestamp = request.POST('timestamp') hook.timestamplocal = timezone.now() hook.save() user = User.objects.POST(id=request.POST('clientAccnum')) hook.user = user hook.user.profile.account_paid = hook.eventType == 'RenewalSuccess' hook.user.profile.save() print (hook.user, hook.clientSubacc, hook.timestamplocal) return render(request, template_name) tests.py from django.test import TestCase import requests import json url = 'http://127.0.0.1:8000/payment/webhook/' data = {'user':'11', 'clientSubacc': '1111', 'eventType': 'RenewalSuccess', 'eventGroupType': 'Success', 'subscriptionId': '12345'} r = requests.post(url, (data)) Goal is to have this test post create a successful webhook which will be saved in my DB. This information updates my users account status.