Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Overriding Token class in Django Rest Framework
New to Django, but here goes, in our use case we need token based authentication but require the token to be linked to a model other than the default 'User' model (django.contrib.auth.models.User). Now to do this, we can rewrite the Token model/class, or we can inherit the Token model and add the new field and set the user field to None but the Django Docs says In Django, this isn’t usually permitted for model fields. If a non-abstract model base class has a field called author, you can’t create another model field or define an attribute called author in any class that inherits from that base class. But shortly after it says, This restriction doesn’t apply to model fields inherited from an abstract model. Such fields may be overridden with another field or value, or be removed by setting field_name = None. Now if we don't add rest_framework.authtoken to settings.py, the Token class is technically abstract. Since in the source code for Token, abstract = 'rest_framework.authtoken' not in settings.INSTALLED_APPS So is it permissible to override the Token class in this way or is it simply better to re-write the model altogether? -
invalid literal for int() with base 10: 'João Santos'
I'm developing in django and my goal is to get a number of a user input and return some data about that number, and I'm having this error: "invalid literal for int() with base 10: 'João Santos'" my code is: def dadosCartao(request): if request.method == 'POST': utext = request.POST.get('usertext') numeroCartao = Card.objects.get(card_number = int(utext)) extrato = CardTransactions.objects.filter(card = str(numeroCartao)) mov = [] for m in extrato: mov.append(m) return render(request, 'CartaoCliente/dadosCartao.html', {'mov': mov}) -
Django Sum on distinct values
I have three models: ModelA, ModelB and ModelC ModelB has a field called value, which I try to aggregate. However to find the correct ModelB instances I have to filter through fields of ModelC, which means I will have duplicates. Using the distinct clause on ModelB instances, means that I cannot use the Sum aggregate because that will raise a NotImplementedError from Django (Distinct + Aggregate is not NotImplemented). Query: ModelB.objects.filter(model_a=some_model_a, model_c__in=[some_vals]).distinct('id').aggregate(Sum('value')) I could do something like this: models_b = ModelB.objects.filter(model_a=some_model_a, model_c__in=[some_vals]).distinct('id') sum = 0 for model_b in models_b: sum += model_b.value This is obviously quite heavy and slow. Is there anyway to circumvent the issue of the NotImplementedError? I already tried SubQueries, pg_utils with DistinctSum (almost what I need, but I need the distinction on id not on value) and some stuff with values. -
How to write a proper unit test case for this middleware file django?
I am working with django and now in a position to write unit test cases for a middleware file, views were easy since I could use a client and check with the response object. But this has become a little tricky. How do I write test cases for these two conditional statements. def process_request(self, request): connection.set_schema_to_public() hostname = self.hostname_from_request(request) if hostname == settings.MAIN_SITE_HOST_NAME: return None elif hostname == 'tenant.test.com': request.tenant = request.institute = Institute.objects.get( domain_url=hostname, schema_name='test') connection.set_tenant(request.tenant) return None Have attached the host_name_from_request method too, def hostname_from_request(self, request): """ Extracts hostname from request. Used for custom requests filtering. By default removes the request's port and common prefixes. """ domain_parts = request.get_host().split('.') if len(domain_parts) > 3: return remove_www(request.get_host().split(':')[0]) else: return (request.get_host().split(':')[0]) While checking how to write test cases for middleware, I found this site but I am still not sure about how to go about it in my case. I tried something like this def test_from_client(self): self.middleware = InstituteMiddleWare() self.request = Mock() self.request.path('/') self.assertIsNone(self.middleware.process_request(self.request)) and it said mock object has no attribute get_host -
django writing custom context processor
I'm writing my own custom context_processor on django (1.11) and to get infos of an authenticated user from auth0. It's not my first time writing it and I don't understand where this error comes from : ImportError : Module "auth.context_processors" does not define a "auth0_processors" attribute/class Here's what it looks like : auth/settings.py : 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'auth.context_processors.auth0_processors', ], auth/context_processors/auth0_processors.py : def auth0_user(request): try: user = request.session['profile'] except Exception as e: user = None return {'auth0_user': user} accounts/views.py : def home(request): return render(request, 'home.html', {}) Any idea? -
Django-mama-cas per site authorization and password expiration
I am studying a project in which I will launch a CAS server based on the django-mama-cas package. As an authentication backend on the client, I will use the django-cas-ng package. In principle everything works correctly but the system with the use of these packages, presents two limitations to which I need to give a solution. On the one hand, the CAS server will serve several portals and the issue is that users can access one or more of the portals, without having access to all by default. On the other hand I need the passwords to expire in a certain period of time, functionality that I also need to implement in the CAS server. -
How can we insert dictionary(json) in mongodb with Django using djongo library?
I am building REST API Using Django, MongoDB and djongo lib My requirement is, I have to store the dynamic JSON in MongoDB through djongo model. data={"name":"xyz","age":12} year=2017 month=10 class TestModel(models.Model): year = models.IntegerField() month = models.IntegerField() customer = "In this feild i want to store above dictonary" I am using djongo library. my approach is: we should add EmbeddedDictField in djongo/djongo/models.py class EmbeddedDictField(Field): def __init__(self, model_container: typing.Type[dict], model_form_class: typing.Type[forms.ModelForm] = None, model_form_kwargs: dict = None, *args, **kwargs): super().__init__(*args, **kwargs) self.model_container = model_container self.model_form_class = model_form_class self.null = True self.instance = None if model_form_kwargs is None: model_form_kwargs = {} self.model_form_kwargs = model_form_kwargs def deconstruct(self): name, path, args, kwargs = super().deconstruct() kwargs['model_container'] = self.model_container if self.model_form_class is not None: kwargs['model_form_class'] = self.model_form_class return name, path, args, kwargs def pre_save(self, model_instance, add): value = getattr(model_instance, self.attname) # print(value) ret_val = {} # for fld in value._meta.get_fields(): # if not useful_field(fld): # continue # # fld_value = getattr(value, fld.attname) # ret_val[ self.attname] = fld.get_db_prep_value(value, None, False) ret_val[self.attname] = self.get_db_prep_value(value, None, False) return ret_val def get_db_prep_value(self, value, connection=None, prepared=False): if isinstance(value, dict): return value if not isinstance(value, Model): raise TypeError('Object must be of type Model') mdl_ob = {} for fld in value._meta.get_fields(): if not … -
Django - An existing connection was forcibly closed by the remote host
I'm having a problem coding this: 1. my web page sends request to the server with parameter X which is a URL 2. server gets X and opens a new connection to X and get data from there 3. server sends a response to my webpage with the retrieved data I send the request with JS get. The problem is that once the server gets the request and open the new connection to X it drops the connection to my webpage. I'm using Django, as I understand it can only handle one request at a given time. any workaround to make it work? Thanks -
funtion python wih django
hey guys I hav any problem!! i hav a file views.py and next funtion: @userRegistered def getSyncGit(request, section): print 'POTATOE' #(<-debug print) cmd = '. script.sh 1' p = sp.Popen(['/bin/bash', '-c', cmd], stdout=sp.PIPE, stderr=sp.PIPE) result = p.wait() return HttpResponseRedirect(getURL(request.LANGUAGE_CODE, '/assistant/configuration/project/list/')) next step i hav on url.py: from .views import getSyncGit url(r'^/project/sync/$', getSyncGit, {'section':'configuracion'}, name='pgetSyncGit'), on the last step , i hav on .html : <script type="text/javascript"> function sendSyncProject() { $.ajax({url: "{% url 'pgetSyncGit' %}", success: function(result){ alert('cool'); }}); } </script> <td> <input id="butSendSyncProject" type="button" name="butSendSyncProject" style="margin-left:1px;" value="{% trans 'Sinc' %}" onclick="sendSyncProject()" /> </td> <td> <a href = "{% url 'pgetSyncGit' %}"> asdasdasdasdasddas </a> </td> when i call to action with boton, i can saw the msg alert,but the getSyncGit function not executed. when i call to action with url href, redirects me to the url "/project/sync/", but the function neither execute.... -
Django Unittest runs into Error
Enviroment: Intellij PyCharm, Python Django, Sqlite3 I use a standard Django setup project. I try to write some Unittests but I run in the following error. After some research and I ended up here. DB Config DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Code of tests.py from django.test import TestCase as djangoTestCase import os import unittest # Create your tests here. class TestExample(djangoTestCase): def setUp(self): print('setup') print(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) def test_abc(self): self.assertEqual(1,1) def tearDown(self): print('tearDown') if __name__ == '__main__': unittest.main() This is the output django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. I try to find the mistake by reading documentation, but without success. What could be the problem ? -
django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'message' used in key specification without a key length")
I am trying to create a model using django 1.11 and mysql(latest) as my backend using mysqlclient.I have searched various blogs and docs but was still not able to find my solution. This is my code Posts.models.py Please forgive the indentation error here if any. class Post(models.Model): user=models.ForeignKey(User,related_name='posts', on_delete=models.CASCADE) created_at=models.DateTimeField(auto_now=True) message=models.TextField() group=models.ForeignKey(Group,related_name='posts', null=True,blank=True,on_delete=models.CASCADE) def __str__(self): return self.message def save(self,*args,**kwargs): super().save(*args,**kwargs) def get_absolute_url(self): return reverse('posts:single',kwargs{'username':self.user.username,'pk':self.pk}) class Meta: ordering=['-created_at'] unique_together=['user','message'] -
Django - how to set language manually?
i set the language in my Django app during login with: user_language = user.profile.language translation.activate(user_language) request.session['django_language'] = user_language request.session[translation.LANGUAGE_SESSION_KEY] = user_language What happens is that app doesnt load language as I would like to. If i use in my template {% get_current_language %} I see in my template 'en' or 'pl'. I press 'refresh page' and language changes. It's also strange that if i change a language for one user, it also affects every user. So my question is how to set the language manually, that stays constant, and for only specific user. I would like to set the language just after the login. Thanks is advance. Gerard -
Save cookie for tile/list view
I have a page with a list of my products, using a listview. On this page I have 2 buttons that switch between tile and list view. Ones the user clicks one of the buttons one div hides and the other shows. My problem is that if a customer is using the tile view for example and refreshes the page or goes to a detail page of a product and then comes back that he pages is again in de default layout (list, not tile). Now I want to save that value in a cookie. So ones they click the tile button it's been saved in a cookie and ones they come back they have the correct layout. I hope someone will help me because I can't figure out what to do. My code: List template: {% extends 'listbase.html' %} {% load static %} {% load libs %} {% load hosts %} {% block filter %} <ul class="collapsible" data-collapsible="expandable"> <li> <div class="collapsible-header active primary"><i class="material-icons">date_range</i>Date</div> <div class="collapsible-body"><span>Insert sexy range slider here</span></div> </li> <li> <div class="collapsible-header active primary"><i class="material-icons">label_outline</i>Geography</div> <div class="collapsible-body"> {% for eventcategory in eventcategories %} <form action="#"> <p> <input type="checkbox" id="{{ eventcategory.name }}" name="geo"/> <label for="{{ eventcategory.name }}">{{ eventcategory.name … -
Django - redirect to the previous page
I am creating a function of adding friend to a user's friend list. After a user click the button, the friendship will be created and the page should be redirected to where the user was. For instance, I want to add another user in the first page in the forum, I should stay in the same page after I click the "add friend" button. This is how I design it: When I redirect to any page of the forum, I pass the path of the current page as a variable in the page: def to_post_page(request, post_id, page_nr): post = get_object_or_404(Post, id=post_id) form = CommentForm() comments = Comment.objects.filter(post=post) return render(request, 'post/post.html', { 'post': post, 'form': form, 'comments': comments, 'page_nr': int(page_nr), 'user': request.user, 'path': request.path, }) And in the template: <input type="button" class="btn btn-info" value="Add Friend" onclick="location.href='{% url 'user:add_friend' to_friend_id=post.poster.id path=path %}';"> @login_required(login_url='user:login') def friend_add(request, to_friend_id, path): friend = get_object_or_404(User, id=to_friend_id) if friend == request.user: return HttpResponseRedirect(request.path) friendship = FriendShip( from_friend=request.user, to_friend=friend ) try: friendship.save() except IntegrityError: return path finally: return path My url looks like this: url(r'^add_friend/(?P<to_friend_id>[0-9]+/)/(?P<path>[\w\-]+)/$', views.friend_add, name="add_friend"), It raises an exception: Reverse for 'add_friend' with keyword arguments '{'to_friend_id': 1, 'path': '/forum/1/0/post'}' not found. 1 pattern(s) tried: ['users/add_friend/(?P[0-9]+/)/(?P[\w\-]+)$'] Can any … -
'AxesSubplot' object has no attribute 'savefig' error happens
'AxesSubplot' object has no attribute 'savefig' error happens. I wrote def past_result(request): return render(request, 'registration/result.html', {'chart': _view_plot(request)}) def _view_plot(request): results = ImageAndUser.objects.filter(user=request.user).order_by('-consultation_date') dates = [r.date for r in reversed(results)] heights = [r.score for r in reversed(results)] if len(dates) > 5: dates = dates[-5:] heights = heights[-5:] df = pd.DataFrame() df['DATE'] = dates df['RESULT'] = heights col_width = 3.0 row_height = 0.625 font_size = 14 header_color = '#40466e' row_colors = ['#f1f1f2', 'w'] edge_color = 'w' bbox = [0, 0, 1, 1] header_columns = 0 ax = None if ax is None: size = (np.array(df.shape[::-1]) + np.array([0, 1])) * np.array([col_width, row_height]) fig, ax = plt.subplots(figsize=size) ax.axis('off') mpl_table = ax.table(cellText=df.values, bbox=bbox, colLabels=df.columns) mpl_table.auto_set_font_size(False) mpl_table.set_fontsize(font_size) for k, cell in six.iteritems(mpl_table._cells): cell.set_edgecolor(edge_color) if k[0] == 0 or k[1] < header_columns: cell.set_text_props(weight='bold', color='w') cell.set_facecolor(header_color) else: cell.set_facecolor(row_colors[k[0] % len(row_colors)]) jpg_image_buffer = io.BytesIO() ax.savefig(jpg_image_buffer) array = base64.b64encode(jpg_image_buffer.getvalue()) jpg_image_buffer.close() return array I know the writing of plt.savefig(jpg_image_buffer) is ok, so I think ax.savefig can be done but it is wrong.I know ax does not have savefig method,so,how can I change ax as image?ax is for making table and plt is for making images ,so I think ax&plt is same thing.How should I fix this?What should I write to this … -
django admin queryset filter with TeacherUser using Proxy User model
I have proxy model with User model and extended to TeacherUser with Teacherprofile models.py Model:1 class TeacherUser(User): objects = UserManager() class Meta: proxy = True Model:2 class Teacherprofile(models.Model): teacheruser = models.OneToOneField(TeacherUser) mobile_no = models.PositiveIntegerField() collegename = models.CharField(max_length=20) admin.py @admin.register(TeacherUser) class TeacherUserAdmin(admin.ModelAdmin): pass def queryset(self, request): qs = super(TeacherUserAdmin, self).queryset(request) return qs.filter((query with join form TeacherUser,Teacherprofile) here all the user records are showing,but i need to display the common records from both models .. How can i make query set. Thanks in Advance. -
Django url/page displayed with development server but not apache server
I'm working on Django 1.11, the URL, http://djangoserver:8002/dj/dev/userlogin/789 works with development server, but with apache URL: http://djangoserver/dj/dev/userlogin/789 it throws Page not found (404) error. Regex used for the URL is : url(r'^[0-9]+$', views.userlogin.login , name='login'), The reset of pages are displayed properly. I have tried solution posted in the following posts which did not work for me: django application works on development server but I get 404 on Apache working on django development server but not on apache django production server: root path -
Django static files are not being loaded in Google App Engine
I've been trying out Django with Google App Engine and have been following along their official tutorial https://cloud.google.com/python/django/appengine. I then restructured my the folder structure a bit. This is the folder structure: And shown below is my app.yaml handlers: handlers: - url: /static static_dir: static-only/ - url: .* script: src.codechum.wsgi.application But for some reason I don't know (and have been researching for hours already), the static files are not loading when it is deployed. I also ran the collectstatic function by the way before I actually deployed. Can anyone please help me of where I might be missing something? Thanks! -
What changes should i need to make , to my (django-drf) project settings.py file to integrate it with VueJs frontend?
How the project structure would look like for a project with Django-DRF backend and vue frontend ? -
Django filter not working with lookup object
I have the next code using Django Rest Framework images = ImageUploaded.objects.filter(offer__end_date > date.today()) However, I got the next error: global name 'offer__end_date' is not defined The ImageUploaded model is the next: class ImageUploaded(models.Model): offer = models.ForeignKey(Offer, related_name='images', on_delete=models.DO_NOTHING) image = models.ImageField("Uploaded image") And the offer model is: class Offer(models.Model): ARGENTINA = 'ARG' URUGUAY = 'URG' COUNTRIES = ( (ARGENTINA, 'Argentina'), (URUGUAY, 'Uruguay') ) name = models.CharField(max_length=200) description = models.TextField() created = models.DateField(auto_now_add=True) end_date = models.DateField() available = models.IntegerField() current = models.IntegerField(default=0) I appreciate any help! -
django-channels/celery: how to track progress of a list of tasks?
I'm "successfully" sending a message from the view to the client with the status of a group of tasks (not an actual celery group). The problem is: This really ignores whether all tasks are actually performed. I've attempted to add a callback (task.apply_async(link=)) but that didn't help either. The tasks themselves don't really take a lot of time, but I'd really like to be able to increment the counter when the task has actually been performed: if 'selected' in request.GET: selected_as_list = request.GET.getlist('selected') print(selected_as_list) searches = list(set([s.strip() for s in selected_as_list if s.strip()])) task_group = [refresh_func.s(str(user_profile.id), search, dont_auto_add=True) for search in searches] for i,task in enumerate(task_group): task.apply_async() Group(str(request.user.id)).send({"text": json.dumps({"tasks_completed": i+1, "task_id": "fb_import", "completed": True if i == len(task_group) -1 else False, "total": len(task_group)})}) So I moved the code out of the view, and into the same block that actually calls the operation to be done. Though it meant I was passing many parameters now, this solved the initial problem. But it presents another one: A task with an index of "1" can finish after a task with an index "3", and this obviously updates the counter incorrectly. What can be done to solve this? -
Deleting the original User model in Django
I am having a bit of difficulty understanding custom User models in Django. I get how we can make a custom User model by inheriting from AbstractBaseUser and it'll provide the core implementation of the User model, however, what I don't get is shouldn't the original auth_User table be deleted? When I make migrations, I notice that I get both an implementation of myapp_User and auth_user along with all the other auth tables. Why is this? I thought we are overriding auth_User with our own implementation. Why does auth_User exist? Is there a purpose for it to exist? -
request.user returns None Django social-auth-app-django
I am a newbie in django social auth. I am using social-auth-app-django to authenticate Microsoft Azure AD user. Authentication process works well and user object is created inside the database. But request.user is returing null inside view. Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', # 'social.apps.django_app.default', ] AUTHENTICATION_BACKENDS = ( 'social.backends.azuread.AzureADOAuth2', ) #settings.py SOCIAL_AUTH_PIPELINE = { 'pipeline.new_users_handler' } View def home(request): """Renders the home page.""" assert isinstance(request, HttpRequest) context = { 'title':'Home Page', 'year':datetime.now().year, 'request': request, 'user': request.user, } context_instance = RequestContext(request,context) return render( request, 'index.html',context) -
web server of airflow i not running
m configuring email scheduler in Airflow in Django but its not working. error in terminal: airflow webserver [2017-12-29 10:52:17,614] {__init__.py:57} INFO - Using executor SequentialExecutor [2017-12-29 10:52:17,734] {driver.py:120} INFO - Generating grammar tables from /usr/lib/python3.5/lib2to3/Grammar.txt [2017-12-29 10:52:17,765] {driver.py:120} INFO - Generating grammar tables from /usr/lib/python3.5/lib2to3/PatternGrammar.txt ____________ _____________ ____ |__( )_________ __/__ /________ __ ____ /| |_ /__ ___/_ /_ __ /_ __ \_ | /| / / ___ ___ | / _ / _ __/ _ / / /_/ /_ |/ |/ / _/_/ |_/_/ /_/ /_/ /_/ \____/____/|__/ /usr/local/lib/python3.5/dist-packages/flask/exthook.py:71: ExtDeprecationWarning: Importing flask.ext.cache is deprecated, use flask_cache instead. .format(x=modname), ExtDeprecationWarning [2017-12-29 10:52:18,354] [8169] {models.py:167} INFO - Filling up the DagBag from /home/hitesh/airflow/dags Running the Gunicorn Server with: Workers: 4 sync Host: 0.0.0.0:8080 Timeout: 120 Logfiles: - - ================================================================= Error: 'airflow.www.gunicorn_config' doesn't exist -
TypeError at /create
I am making basic CRUD in Django 1.11. While saving values to the DB I am getting this error, 'breed' is an invalid keyword argument for this function. Although there is a valid field in DB, even if I remove 'breed' I get the same error with 'name'. Environment: Request Method: POST Request URL: http://e0c0a02d057f4394aa9e52d4f67c7edb.vfs.cloud9.us-east-2.amazonaws.com/create Django Version: 1.11 Python Version: 2.7.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.dog_app'] 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 "/usr/local/lib64/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib64/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib64/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ec2-user/environment/dogs/apps/dog_app/views.py" in create 14. dog = Dog(breed=request.POST['breed'],name=request.POST['name']) File "/usr/local/lib64/python2.7/site-packages/django/db/models/base.py" in __init__ 571. raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0]) Exception Type: TypeError at /create Exception Value: 'breed' is an invalid keyword argument for this function Views.py: # -*- coding: utf-8 -*- from __future__ import unicode_literals from models import Dog from django.shortcuts import render,redirect # Create your views here. def index(request): dogs=Dog.objects.all() context={ 'dogs': dogs} return render(request, 'dog_app/index.html', context) def create(request): #print (request.POST['name'],request.POST['breed']) dog = Dog(breed=request.POST['breed'],name=request.POST['name']) dog.save() return redirect('/') index.html: <!DOCTYPE html> <html> <head> <title>Hello</title> </head> <body> <form …