Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to apply contains to list?
I want to search for filtered objects. Below is the filtered object. questions = models.Question.objects.filter(creator=user, tags__name__in=hashtags) and I tried the following command. But it does not work. questions = models.Question.objects.filter(tags__name__contains=hashtags) I think, __contains does not seem to work on the list p.s. hashtags is a list -
Mail traffic between MailDev container and Django container delivers Errno 111] Connection refused
Mail traffic between MailDev container and Django container delivers [Errno 111] Connection refused Email traffic to console backend works, so the function should be correct. send_mail( 'Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False ) After I switched to SMTP backend and started MailDev in Container, I got: [Errno 111] Connection refused in settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' in Shell: sudo docker run -p 1080:80 -p 1025:25 --name maildev djfarrelly/maildev My Docker Containers are: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES a46040dd1259 djfarrelly/maildev "bin/maildev --web..." 11 seconds ago Up 9 seconds 0.0.0.0:1025->25/tcp, 0.0.0.0:1080->80/tcp maildev 4fed036f92d4 exposee "/usr/src/start.sh" 42 minutes ago Up 42 minutes 0.0.0.0:8000->8000/tcp exposee 2c2cf7ce19e9 winauth "gunicorn -b 0.0.0..." 43 minutes ago Up 43 minutes 127.0.0.1:9876->9876/tcp winauth afe4a449aa01 postgres "docker-entrypoint..." 44 minutes ago Up 44 minutes 127.0.0.1:5432->5432/tcp postgres My Settings in settings.py are: EMAIL_HOST = CONFIG.get('EMAIL_HOST', '127.0.0.1') EMAIL_PORT = CONFIG.get('EMAIL_PORT', 1025) EMAIL_USE_TLS = CONFIG.get('EMAIL_USE_TLS', False) EMAIL_USE_SSL = CONFIG.get('EMAIL_USE_SSL', False) My Conigurations in config.json are: "EMAIL_HOST": "127.0.0.1", "EMAIL_PORT": 1025, "EMAIL_USE_TLS": false, "EMAIL_USE_SSL": false -
Django ManyToMany field - access fields of through table
Say I have the following model: class User(Model): username = CharField(...) class Project(Model): project_name = CharField(...) workers = ManyToManyField(User, through="ProjectAssignment") class ProjectAssignment(Model): user = ForeignKey(User) project = ForeignKey(Project) role = CharField(...) # name of the role a user has on a project How a query that gets the users who have role Developer on a project named XY looks like? I could not find an example in Django documentation. -
Django rest view retrieve chained objects
I have models with following relationships: A 'User' can have a 'Wishlist' and a 'Wishlist' will have many 'Book's. I want to retrieve all the books in a specific user's wishlist. I am writing my view like following: # Get specific user's wishlist @api_view(['GET', 'POST', 'PUT', 'DELETE']) def wishlist(request): """ List all the boosk in wishlist of a specific user """ if request.method == 'GET': books = Wishlist.objects.filter(request.user) serializer = BookSerializer(books, many=True) return Response(serializer.data) How can I write logic inside my filter? Or could there be a better approach (e.g. not serializing books instead wishlist)? -
django charge users based on how many counties they want to access
I'm building a web app, basically I currently have 3 models , 1- State: which represents all US states 2- County: which represents all counties with foreign key of state 3- Home: which represents all homes with foreign key of County the app will show homes, but users needs to subscribe for certain counties (the counties prices can vary) the goal is : when users subscribe to certain counties they can see the related "Homes" to these counties I'm not sure how should I represent these relations between users, subscriptions and how to connect it to County model I have. and how to make a view for the user to add new counties. Thank you. -
Why a for cycle in a django template add space at the end of my elements? (taggit)
My template.html: {% for x in post.tags.all %} <a href="{% url 'blog:post_list_by_tag' x.slug %}"> {{ x.name }} </a> {% if not forloop.last %}, {% endif %} {% endfor %} I haven't space at the end of the lines and I haven't space in the name (in database) but the output is: tag1 , tag2 , tag3 with a space between name and comma and a space at the end. Even with one tag there's a space at the end. I use taggit, maybe the problem is there. Also the links underline even the white spaces when after there's the comma (so not at the end). If I write {{ x.name }}</a> the spaces are there but the links underline only the tags, not the spaces. In myview print(post.tags) => AttributeError: '_TaggableManager' object has no attribute 'name' print(post.tags.all) => <bound method BaseManager.all of <taggit.managers._TaggableManager object at 0x03EFEA70>> -
Model formset with abstract model and foreign key
Is it possible to create a formset with two models, one of which is abstract? A simplified case of what I have is: #models.py class ProductRelationship(models.Model): ... product = models.ForeignKey('Product',verbose_name="Product") Status= models.CharField() class Meta: abstract=true class Product(models.Model): ... #forms.py ProductRelationshipFormSet = inlineformset_factory( models.Product, models.ProductRelationship, fk_name='product', fields=('Status','product',)) However this returns ValueError: fk_name 'product' is not a ForeignKey to 'rdb_valet.Product'. If I use the child models, it works without any issue. Currently my workaround is therefore to just redefine the formset for each child class, but I want to know if it's possible to do it using the abstract parent class. Thanks! -
Database driven framework with dashboard
Do you know some good alternative to KeystoneJS and Django ? I'm developing app based on KeystoneJS, but keystone has much limitations, I can't overwrite look of dashboard, I can't create custom role. I can't create nested schema of UI. I made research and I can't find framework which follows my requirements. -
Django - parse object from fk
I have a model called Friendship: class FriendShip(models.Model): from_friend = models.ForeignKey(User, on_delete=models.CASCADE, related_name='friend_set') to_friend = models.ForeignKey(User, on_delete=models.CASCADE, related_name='to_friend_set') def another_person(self, this): if self.from_friend == this: return self.to_friend elif self.to_friend == this: return self.from_friend else: return None also in my user model, I about to create a friend list: def __str__(self): if self.anonymous: return "anonymous user" else: return self.username def get_friend_list(self): friend_list = [] for friendship in FriendShip.objects.all(): friend_list.append(friendship.another_person(self)) return friend_list I print the list out and get the result : How can I get the object but not the key? (the str in my User model only returns username) -
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.