Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Displaying the objects from my class on the base template in Django
Sorry if my english is confusing I created a class Button on my app menu models.py (App 'menu') from django.db import models class Button(models.Model): button_name = models.CharField(max_length=30, verbose_name='xxx') button_dirurl = models.CharField(max_length=40, verbose_name='xxx') button_corequise = models.BooleanField(default=False, verbose_name='xxx') def __str__(self): return self.button_name What I would like to do is to display all the objects into base.html, located into the template at the root. I tried to do a tag, but I would like to add some html elements and as far as it goes I won't be able to do much menu_tags.py (App 'menu') from django import template from menu.models import Button register = template.Library() @register.simple_tag def show_menu(): a = Button.objects.all() return a I'm sorry if this was already asked but I don't know how to google this as my english is quite bad. Thanks ! -
Display URLS as links(Higlight, blue color, clickable etc) in Django Text Area Field
I have a site where users can post stuff (mainly links with comments.) Now when I render the text area filed, the links are being displayed as plain text. They are not clickable, blue links. I want to render identified urls as links which are clickable. Don't suggest a language or syntax in which the user has to prepend something to make it a link. Instead I want an automatic way for links to be clickable. Like how SO and SE and other forums do it. -
Using Sql Server with Django 2.0
I would like to use Django 2.0 with legacy MS SQL Server database. Latest information regarding usage Django with MS SQL Server i could find is Using Sql Server with Django in production/These days and it is about Django 1.11 Most supported seems django-pyodbc-azure but it's not supporting Django 2.0 yet: django-pyodbc-azure issue #124 Is there any alternative? -
Django Test: TypeError: __init__() got an unexpected keyword argument
I get the error from the ProductTestCase: ...setUp department = DepartmentForm(department_name_text=self.department_name) ... ...in __init__ super(DepartmentForm, self).__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'department_name_text' It would be great to know how to fix this issue and why it only occurs when on Foreign keys. I have added in Department test as well, it works fine. Thank you for your time. Department Test class DepartmentTestCase(ModelTestCase): def setUp(self): super(DepartmentTestCase, self).setUp() self.department_form = self.get_department_form(department_name_text=self.department_name) def test_valid_input(self): self.assertTrue(self.department_form.is_valid()) Product Test class ProductTestCase(ModelTestCase): @classmethod def setUpTestData(cls): super(ProductTestCase, cls).setUpTestData() def setUp(self): super(ProductTestCase, self).setUp() self.product_data = {'barcode_text': self.barcode } department = DepartmentForm(department_name_text=self.department_name) department_inst = None if department.is_valid(): department_inst = department.save(commit=False) department_inst.pk = None department_inst.save() maker = MakerForm(maker_name_text=self.maker_name) maker_inst = None if maker.is_valid(): maker_inst = maker.save(commit=False) maker_inst.pk = None maker_inst.save() self.product_data.update({'name_text': department_inst, 'from_maker': maker_inst}) def test_valid_input(self): product_form = ProductForm(**self.product_data) self.assertTrue(product_form.is_valid()) Department Form class DepartmentForm(ModelForm): field_names = {'department_name_text': 'Department Name'} class Meta: model = Department fields = ['department_name_text'] def __init__(self, *args, **kwargs): super(DepartmentForm, self).__init__(*args, **kwargs) for field, name in self.field_names.items(): self.fields[field].label = name -
Django: Problems regrouping a regroup
I'm trying to get a list of countries that are stored in my Post model. Models: Articles App: class Post(models.Model): title = models.CharField(max_length=100, unique=True) ... country_slug = models.ManyToManyField(Country_Data, related_name='nation_slug') Nation App: class Country_Data(models.Model): name = models.CharField(max_length=250) country_slug = models.CharField(max_length=250) View: get_context_data: self.sport = get_object_or_404(Sport, sport_slug=self.kwargs['sport_slug']) context['country'] = Post.objects.filter(post_category=self.sport) Template: {% for nation in country %} <ul> {% regroup nation.country_slug.all by name as country_list %} {% for country in country_list %} <li>{{ country.grouper }} <ul> {% for item in country.list %} <li>{{ item.name }}</li> {% endfor %} </ul> </li> {% endfor %} </ul> {% endfor %} The problem I'm having is looping through the list of countries and only pulling out one result. Currently, because of how it needs to be set up, it is pulling out one country per news article, which is obviously not useful for this because I'll end up with hundreds of duplicates. I cant work out how to get it to loop through the Post model, pull out all the "country_slug" fields, then regroup that into a list of unique countries. I've read through the documentation and a few other questions multiple times, I'm just failing to understand exactly what I'm doing wrong. -
Securing API's with Multi Factor Authentication
I want to secure my API with Multi-factor-Authentication on top of Auth Token/JWT. I have been searching but couldn't find any package that can work with drf. I am thinking to write my own django app. Any comments on what should be the architecture ? One solution that comes to my mind is to introduce the token base architecture.If a user is accessing the mfa secured api then the request instance should be saved alongside a token and a sms should be sent to his mobile (In case of mobile as mfa) and response should be a that token. Then another request should be made to a mfa endpoint with token and mfa-code. Once verified, We would take his previous request object and complete the request. -
How can I ensure that python files/scripts executed by the web server have been signed and valid so that alteration to script will not run?
Can I create loader or verification that the python files/scripts executed by the web server have been signed and valid so that alteration to script will not run if signature doesn't match? Is this possible with Django or any other python framework and server? -
How to test new Django 1.10+ MIDDLEWARE classes
I'm upgrading existing middleware to a new style 1.10+ Django middleware. Previously it was one similar to this: class ThreadLocalMiddleware(MiddlewareMixin): """ Simple middleware that adds the request object in thread local storage.""" def process_request(self, request): _thread_locals.request = request def process_response(self, request, response): if hasattr(_thread_locals, 'request'): del _thread_locals.request return response def process_exception(self, request, exception): if hasattr(_thread_locals, 'request'): del _thread_locals.request after rewrite to the new style: class ThreadLocalMiddleware: def __init__(self, get_response=None): self.get_response = get_response def __call__(self, request): _thread_locals.request = request response = self.get_response(request) if hasattr(_thread_locals, 'request'): del _thread_locals.request return response def process_exception(self, request, exception): if hasattr(_thread_locals, 'request'): del _thread_locals.request My question is how to test that the middleware sets the request in the _thread_locals? Previously it was as easy as calling the process_request method in tests. Now I have only the call which will erase the variable at the end. -
Is it possible to pass extra command line arguments in django integration testing?
I want to pass extra argument in my integration testing of django app. I'm trying below command line argument for same. python ./manage.py test my_api.test.end_to_end_test "IPaddress of AWS instance" but I'm getting error. Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/test.py", line 62, in handle failures = test_runner.run_tests(test_labels) File "/usr/local/lib/python2.7/dist-packages/django/test/runner.py", line 600, in run_tests suite = self.build_suite(test_labels, extra_tests) File "/usr/local/lib/python2.7/dist-packages/django/test/runner.py", line 484, in build_suite tests = self.test_loader.loadTestsFromName(label) File "/usr/lib/python2.7/unittest/loader.py", line 91, in loadTestsFromName module = __import__('.'.join(parts_copy)) ImportError: No module named 35 -
Django: python venv: Can i edit files in the lib/python3.6/site-packages
I am using Django 2.0. and package fcm-django==0.2.13 After upgrading to Django 2.0 I have found an error in lib/python3.6/site-packages/fcm_django/api/rest_framework.py it says 'bool' object is not callable at the below line if user is not None and user.is_authenticated(): I have found the solution at https://github.com/xtrinch/fcm-django/issues/43 and also is_authenticated() raises TypeError TypeError: 'bool' object is not callable I have to replace is_authenticated() with is_authenticated (without the brackets) in the lib/python3.6/site-packages/fcm_django/api/rest_framework.py file. The latest package fcm-django==0.2.13 is not yet updated with this error. SO i have edited the file /home/test/venv/lib/python3.6/site-packages/fcm_django/api/rest_framework.py Then i save the file. But when i run the url. It shows the same error in the file rest_framework.py if user is not None and user.is_authenticated(): but i have changed is_authenticated() to is_aunthenticated Why django/venv is not reflecting the changes? -
What is causing my consumer to be sent 2 arguments--one, in addition to the "message"?
I'm implementing the multichat example and unable to figure out what's causing this error. Here's the full traceback: 2018-01-05 07:35:48,017 - ERROR - worker - Error processing message with consumer chat.consumers.chat_join: Traceback (most recent call last): File "/Users/sng/.virtualenvs/blog-api/lib/python2.7/site-packages/channels/worker.py", line 119, in run consumer(message, **kwargs) File "/Users/sng/.virtualenvs/blog-api/lib/python2.7/site-packages/channels/sessions.py", line 78, in inner return func(*args, **kwargs) File "/Users/sng/.virtualenvs/blog-api/lib/python2.7/site-packages/channels/auth.py", line 42, in inner return func(message, *args, **kwargs) File "/Users/sng/Dev/django/blog-api/src/chat/utils.py", line 14, in inner return func(message, args, **kwargs) TypeError: chat_join() takes exactly 1 argument (2 given) I believe I've copied the code nearly as is, so I don't know how it went wrong. Here's the consumer: @channel_session_user @catch_client_error def chat_join(message): room = get_room_or_error(message["room"], message.user) if NOTIFY_USERS_ON_ENTER_OR_LEAVE_ROOMS: room.send_message(None, message.user, MSG_TYPE_ENTER) room.websocket_group.add(message.reply_channel) message.channel_session['rooms'] = list(set(message.channel_session['rooms']).union([room.id])) message.reply_channel.send({ "text": json.dumps({ "join": str(room.id), "title": room.title, }), }) Routing: custom_routing = [ route("chat.receive", chat_join, command="^join$"), route("chat.receive", chat_leave, command="^leave$"), route("chat.receive", chat_send, command="^send$"), ] In regular Django, I think the parallel would be the URLconf sending one too many args to the view. I'm not sure where message is being sent from, and so unsure if anything else is being sent alongside it. The traceback hints at it being caused in relation to sessions. Not quite sure where, or how to debug in … -
Automatically Append host, port no and media folder path in url while retrieve in Django rest framework
I'm using Django rest framework APIView method to retrieve image field (Image saved in local and name saved in DB). Is there any way to append Host, Port and media Folder automatically. Now i'm appending manually. But if i'm using Viewset it appended automatically. Both method i'm using for different scenario. Can anyone suggest some way to solve the issues. -
Include stuff from another app in base template?
Sorry for the confusing title I'm not a native english speaker. I'm trying to add a condition to my base.html but I don't know where to import the stuff from my other app. I would like to import my class Button in my folder "models" in my app "menu" to do this (If it's not wrong) : {% for Button in menu.Button %} Thanks for the help ! -
How to view the Django website deployed on AWS EC2? Apologies for this silly query.
After deploying my django website on AWS EC2 Linux instance, its running at the local server http://127.0.0.1:8000/ . At which URL can I now see my website live? I have the server IP and port number but doesn't seem to work. -
Django, make model that refer more than equal 2 foreign key but not be deleted CASCADE
I have django model: @python_2_unicode_compatible class TestModel(models.Model): description = models.CharField(max_length=34) def __str__(self): return "TestModel %s" % self.description @python_2_unicode_compatible class TestModelLog(models.Model): description = models.CharField(max_length=34) foreignkey = models.ForeignKey(TestModel_2, related_name='test_foreignkey_1', null=True, blank=True) foreignkey_2 = models.ForeignKey(TestModel_2, related_name='test_foreignkey_2', null=True, blank=True) def __str__(self): return "TestModelLog %s" % self.description Let say I made a model object like this: testmodel_a = TestModel.object.get_or_create(descripton=A_test) testmodel_b = TestModel.object.get_or_create(descripton=B_test) testmodel_log = TestModelLog.object.get_or_create(descripton=Log, foreignkey=testmodel_a, foreignkey=testmodel_b) Although I set null=True, blank=True to TestModelLog's foreignKey fields in models.py, not on_delete=models.CASCADE, When I try to delete just testmodel_a(or testmodel_b) in django admin, it keep saying it will delete related testmodel_log also. I thought testmodel_log will still be exist whether testmodel_a or testmodel_b is deleted or not. Question: Why this happened and How to make testmodel_log be independent from testmodel_a or testmodel_b's change? -
Ajax POST function not running successfully with Django
I am trying to run the Ajax POST function. But I am not able to see any alert message after completion of the function. function SendData() { $.ajax({ url : window.location.href,// the endpoint,commonly same url type : "POST", // http method data : { csrfmiddlewaretoken : csrftoken, lastMessage : lastMessage, NewMessage : NewMessage }, // data sent with the post request // handle a successful response success : function(json) { console.log(json); // another sanity check //On success show the data posted to server as a message alert('User : '+json['lastMessage'] +' . User : '+ json['NewMessage']); ***//Not showing this alert*** }, // handle a non-successful response error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console } }); } I am calling the SendData() function from another function KepPress() that runs when the 'enter' key is pressed. Data in 'lastMessage' and 'NewMessage' are received from input type text tag in HTML. -
Dynamically generate accompanying model in django
In my project i have many models in multiple apps, all of them inherit from one abstract model. I would like to create a model that would hold the changes to the history for every one of my models, so that every model would have its own history model. Each model would also have one-to-many relation to its history model. All history models would be the same, except for the foreign key to their respective model. My problem is that I do not want to write all the history models manually. Instead i would like to have the history model created for every model automatically, so I don't have to write all that boilerplate code. Can this be achieved? -
Django installation admin page not getting
I installed Django and created myproject & myapp by refer the tutorial https://www.tutorialspoint.com/django/django_creating_project.htm I got below output while run the command $ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). January 05, 2018 - 06:32:21 Django version 1.11, using settings 'myproject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. But while I run the URL in the browser http://127.0.0.1:8000/admin/, it shows "Unable to connect" -
Got an unexpected keyword argument 'pk1' issue
I am getting an error, that I do not know how to fix and even why I am getting that error. I am rendering a form to link a team to a project in a url where like : http://127.0.0.1:8000/website/project/20/linkteam2 where 20 is my pk1 = 20 which is the project id. I am using pk1 and pk2 because when the team is linked, the url become : http://127.0.0.1:8000/website/project/20/team_id For some reason I am getting: TypeError at /website/project/21/linkteam2/ TeamSelect() got an unexpected keyword argument 'pk1' my code is : def TeamSelect(request): import pdb; pdb.set_trace() if request.method == "POST": select_form = EditSelectTeam(request.user, request.POST) if select_form.is_valid(): data = select_form.cleaned_data['team_choice'] obj2 = Project.objects.filter(project_hr_admin=request.user) obj3 = obj2.latest('id') if obj3.team_id == None: obj3.team_id = data obj3.save() obj4 = obj3.team_id obj5 = obj4.members.all() for i in obj5: current_site = get_current_site(request) message = render_to_string('acc_join_email.html', { 'user': i.first_name, 'domain':current_site.domain, }) mail_subject = 'You have been invited to SoftScores.com please LogIn to get access to the app' to_email = i.email email = EmailMessage(mail_subject, message, to=[to_email]) email.send() messages.success(request, 'test') return HttpResponseRedirect(reverse('website:ProjectDetails', kwargs={'pk1':obj3.id, 'pk2':obj4})) else: print('this project has already a team') else: print('Non Valid form') else: import pdb; pdb.set_trace() select_form = EditSelectTeam(request.user) return render(request,'link_project.html', {'select_form':select_form }) my html: {% load static … -
How to format foreignkey conditionally in django admin
My model.py: class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='user_profile') myfield = models.ForeignKey(Mymodel, on_delete=models.CASCADE, blank=True, null=True) ... class Mymodel(models.Model): name=models.CharField(max_length=64) complete = models.BooleanField(default=False) In my admin panel when I add a Userprofile this gives a dropdown menu with all the Mymodel istances. I would like to format (colour red) the ones already taken (I have a more complex problem, based on a field of Mymodel but the concept is the same). Is it possible to do? def model_taken(self): if UserProfile.objects.filter(myfield=self.myfield).exists(): return format_html('<span style="color: red;">{}</span>') What if I would like to filter out this values instead of format them? Thank you -
I am trying to dynamicallyload mynavbar content from my django model database without affecting the display page
My template structure is base.html where i included navbar.html inside the base I have an app called tags and tags has a models.py and a views.py inside the views.py, i have a django code as this from tags.models import Tag class TagList(ListView): model = Tag def get_queryset(self): return Tags.object.all() this works, when i call {{ object_list }} inside my template for the tag_list.html. So i added the {{ object_list }} inside my template navbar.html which was included inside the base.html but it works only when am on the url that displays my tag_list.html and does not show anything when am on other urls or other templates.. How do I make it show irrespective of the template directory am inside or the url am displaying ... i want it to show I've thought of copying my views.py code into every app view and repeat the same process for every templates but i have a lot of template directories i cannnot do this for all of them -
My PostgreSQL database is empty
I'm developing a Django project and as a database I'm working with PostgreSQL 10.1, the "problem" is I can't see my Tables, it doesn't show anything but when in the command line I run "python manage.py makemigrations" it create the files and then when I run "python manage.py migrate" it actually migrate all the info to the database, but I can't see anything in pgAdmin 4. -
Django, update the object after a prefetch_related
I have the following models: class Publisher(models.Model): name = models.CharField(max_length=30) class Book(models.Model): title = models.CharField(max_length=100) publisher = models.ForeignKey(Publisher) In my views.py, When I want to show the publisher page, I also want to show their books, so I usually do something like this: publisher = Publisher.objects.prefetch_related('book_set').filter(pk=id).first() Then, after some processing I also do some work with the books for book in publisher.book_set.all(): foo() This works great, but I have one problem. If there is a book added between the query and the for loop, the publisher.book_set.all() won't have the newly added books because it was prefetched. Is there a way to update the publisher object? -
Is there anyway to filter all ORM queries in Django?
So I have a rather unorthodox idea of using a middleware to filter queries dynamically, as to keep my authentication further away from the views themselves. I've seen a few library's that could log transactions, but there's no way to alter them since it's post-transaction. Essentially any calls to a certain model would be filtered based on authentication credentials. E.g. Some field that states a user's privileges. This is probably insane and would require me hooking into the ORM itself, but I must ask out of curiosity. Maybe I'm just too lazy to change the rest of my code to reflect this. Thanks to anybody who could clarify if this is possible or impossible. Edit: As of writing this question... Wouldn't this be possible to achieve by subclassing a model manager? Am I this thick?! -
Django rest framework import data from one table to another
I am doing a django rest framework API for ios application. And currently, i am doing a function between user and family. Let me explain my logic between these two. User= current user (an account that can be use to login) Family = current user's family member eg:father mother (it is not an account, cannot be use to sign in) What i am thinking right now is that if the current user's family wanted to create an account, is it possible to import the data from family table to user table for that family member to register ? user table : userId, username, password, email, phone_number, identification_num, first_name, last_name family table :Id, userId(foreign key to user table, cannot be null) , familyId(can be null, reason is to allow user to add family member that did not register an account), phone_number, identification_num, first_name, last_name, relationship Example scenario : user sent invitation link to that family member(either by email or other social app, and it will import the data to the family member to register an account family member click on invite link redirect to register page with the detail from family table. If register success, insert the userId of that family …