Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Invoke helper method in Django admin
I have a class for my Django admin in my app's admin.py file. This class has a helper method (filter_items) to format one of the columns in the admin. But when I look at the .html file for this admin (myapp_admin_py.html) I don't see this helper method being used. How to I invoke this method so that it's applied? from django.contrib import admin from myapp.models import Myapp class MyAdmin(admin.ModelAdmin): list_display = (...) def filter_items(self, obj): """Helper method that displays filter_items as a list in the admin""" _filter_items = obj.filter_items ......(make into list)..... return _filter_items admin.site.register(Myapp, MyAdmin) -
Trying to deploy Django in Windows, it seems to be impossible
Hello guys I hope you can help me I’m trying to deploy django 1.11 on a Window machine but it seems to be impossible, I already have apache and wsgi_mod installed correctly in the machine, actually when I setup a project it works fine, the 127.0.0.1 (localhost) show me the django welcome message correctly, I also can install correctly the application, the problem is when I add the application in settings.py it show me (500 Internal Server Error) my project works fine in a virtualenv, even this project was made in the same machine, I hope you can help me because this issue makes me crazy. httpd.conf DocumentRoot "C:\cotizaciones\proyecto" <Directory "C:\cotizaciones\proyecto"> # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.4/mod/core.html#options # for more information. # Options Indexes FollowSymLinks # # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # Options … -
Docker: gracefully stop django server
I'm using docker and docker-compose. Inside docker-compose.yml I have command that starts django server: command: ["./run/web.sh"] In json format command should run in exec mode. Inside web.sh: #!/usr/bin/env bash exec python manage.py runserver When I tried to stop service with docker-compose stop it waited 10 seconds (default timeout) and then just kill service. In logs I've found project_web_1 exited with code 137. How to stop django runserver gracefully with docker stop? -
Collect values from user imput django thegit accross
Im trying to acchieve a task, any ideas could be helpful. I want to have a simple django page that will take values from users e.g Their firstNames, SurnNames and email address. Thereafter clone a master git branch and further checkout to a new branch, make neccesary change with collected values and finally send out a pull request. I am confident python/django can do this. Just wondering best approach to this. Will start writing something for now. Thanks in advance -
django fetching data from 3 models efficiently
I'm new to django so please bear with me. I have the below relationships. If I have the primary key of model A, how can I get all the data from A, B and C in the most efficient query? Note: A -> C is a 1 to many relationship while B -> C is a many to one relationship (ie each C only has 1 B, but multiple Cs may have the same B). I was thinking of some form of prefetch_related but as I understand it, that implies I am making 3 db calls? Also, is there somewhere I can see the SQL query that Django runs? I am using mysql as a db. Class A(models.Model): pass Class B(models.Model): pass Class C(models.Model): a = models.ForeignKey(A) b = models.ForeignKey(B) -
Sending Django Channels 2 Message from View
I have this Django Channels 2 consumer consumer.py class BalanceConsumer(WebsocketConsumer): def connect(self): self.user_id = self.scope['url_route']['kwargs']['user_id'] self.user_balance_group_name = 'balance_%s' % self.user_id # Join stream group async_to_sync(self.channel_layer.group_add)( self.user_balance_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave stream group async_to_sync(self.channel_layer.group_discard)( self.user_balance_group_name, self.channel_name ) def receive(self, balance_data): balance_data_json = json.loads(balance_data) current_balance = balance_data_json['current_balance'] # Send message to stream group async_to_sync(self.channel_layer.group_send)( self.user_balance_group_name, { 'type': 'new_balance', 'current_balance': current_balance } ) # Receive message from stream group def new_balance(self, event): # message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'current_balance': 9999999 })) But I cannot push a message to this channel layer with the following code. api/views.py I tried to send to the channel as well as the group channel but I cant seem to trigger a message send at all. channel_layer = get_channel_layer() # channel_name = '/ws/balance/6/' # channel_name = 'ws://127.0.0.1:8000/ws/balance/6/' channel_name = 'user_6' logger.warn('channel_name %s', channel_name) new_balance_update = { "current_balance": 99999 } channel_layer.group_send( channel_name, { "new_balance": new_balance_update }, ) channel_layer.send( channel_name, new_balance_update ) -
Spotify iOS SDK login with access token from django-allauth
I am creating an iOS app with Spotify playback with a django backend. This is my first programming project, and I am a little hung up on oauth2. I know that I need to do the authorization code flow on the server side to obtain refreshable user tokens. I set up django-allauth on my django project, and managed to get it working to authenticate Spotify users despite the limited documentation for Spotify. I can call localhost:8000/users/spotify/login and the code will be refreshed and a vlid access token is stored in the database (made authorized request on Postman). I believe this will work when I deploy the changes to heroku as well, I just have not yet. Getting back to my iOS app, I am trying to use the sdk to stream songs. I start the SPTAudioStreamingController.sharedInstance() with my client ID, no problem, and then try to login with access token hard coded, with no success. I know that I am missing something, probably involving the session that is returned when authentication is handled completely through iOS. I am hoping for clarification on how to complete this implementation and log in on the SDK properly using the access tokens stored in … -
Django - Update field values in extended user model after a request is performed
My project is a social networking site that can send requests to friends and make friends. I have extended django's existing user model using oneToone field . So far i've been able to do the above said thing but when ever a user accepts the request , Both the user who sent request and also the user accepted it must increment a value in their extended user model which stores the value of their friends count . I'm facing difficulties trying to solve this . I've also used signals but it doesn't work . Here is my code: models.py: class Friends(models.Model): """"Model for saving relationship of user and friends""" request_id = models.ForeignKey(User,on_delete=models.CASCADE,related_name='current_user') friend_id = models.ForeignKey(User,on_delete=models.CASCADE,related_name='user_friend') created_on = models.DateTimeField(auto_now_add=True,auto_now=False) class Meta: verbose_name_plural = "Friends" def __str__(self): return str(self.friend_id) class Profile(models.Model): user = models.OneToOneField(User,related_name='profile',on_delete=models.CASCADE) location = models.CharField(max_length=30,blank=True) friends_count = models.PositiveIntegerField(default=0) profile_pic = models.ImageField(upload_to='profile_pics/',blank=True,null=True) def natural_key(self): return (self.user.username,) @receiver(post_save,sender=Friends) def update_friends_count(sender,instance,created,**kwargs): if created: user_profile = Profile(user = instance.request_id) user_profile.friends_count=F('friends_count')+1 user_profile.save() Any help would be greatly appreciated!!!!! Thank you in advance!!! -
Django/Bootstrap Modal not submitting
I'm trying to submit Django forms in Bootstrap 4 modals with AJAX, but it doesnt submit for some reason. When you click on the submit button it just closes the modal and nothing else happens. The content shows correctly in the modal body at least, but it just doesnt submit. Here is my view class GaasWaferDesignFormView(SuccessMessageMixin, AjaxTemplateMixin, CreateView): template_name = 'engineering/gaas_wafer_designs/gaas_wafer_design_form.html' ajax_template_name = 'engineering/gaas_wafer_designs/gaas_wafer_design_form_inner.html' form_class = GaasWaferDesignForm model = GaasWaferDesign form = GaasWaferDesignForm() success_url = reverse_lazy('engineering:gaas_wafer_design_list') success_message = "Success!" def form_valid(self, form): object = form.save(commit=False) object.created_by = self.request.user object.save() return super(GaasWaferDesignCreateView, self).form_valid(form) And here is my template which has the modal structure and button for the modal(gaas_wafer_design_list.html)... {% extends "pages/list_template.html" %}{% load static from staticfiles %} {% load widget_tweaks %} {% block title %}GaAs Wafer Design List{% endblock %} {% block list_title %}GaAs Wafer Designs{% endblock %} {% block list_title_2 %}Design Inventory{% endblock %} {% block extra_js%} {% endblock %} {% block buttons %} <div class="btn-group" role="group" aria-label="Button group with nested dropdown" style="margin-bottom: -150px; z-index:1000;"> <button class="btn btn-secondary" data-toggle="modal" data-target="#form-modal" id="create-button">Create a new wafer design</button> <div class="btn-group" role="group"> <a id="btnGroupDrop1" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> View </a> <div class="dropdown-menu" aria-labelledby="btnGroupDrop1"> <a class="dropdown-item" href="#">Recycling Bin</a> </div> </div> </div> {% endblock … -
Is it (a) possible and (b) good practice to assign a 'related_name' to an inherited ForeignKey field - Django2.0
I have attempted a reverse query via the PublishedPolicyManager using the 'policies' related_name for the 'process' ForeignKey in BasePolicy. This produced error: AttributeError: 'RelatedManager' object has no attribute 'valid' Is there a way that the PublishedPolicy class can assign a different related_name to the 'process' field allowing the Process reverse query to point at PublishedPolicy instead of BasePolicy? Or is the logic flawed entirely? class BasePolicy(models.Model): title = models.CharField(max_length = 100) process = models.ForeignKey(Process, null=True, blank=True, on_delete=models.SET_NULL, related_name='policies') force_read_again = models.BooleanField(default=False) class DraftPolicy(BasePolicy): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def publish(self): PublishedPolicy.objects.create( draft_policy = self, title=self.title, policy=self.policy, force_read_again=self.force_read_again) process=self.process) class PublishedPolicyManager(models.Manager): def current(self): return super().get_queryset().exclude(archived_at__isnull=True) def valid(self): print('here') return super().get_queryset().exclude(force_read_again=True, archived_at__isnull=False) class PublishedPolicy(BasePolicy): objects = PublishedPolicyManager() draft_policy = models.ForeignKey(DraftPolicy, on_delete=models.SET_NULL, null=True) published_at = models.DateTimeField(auto_now_add=True) archived_at = models.DateTimeField(null=True) class PolicyReadManager(models.Manager): def valid(self): return super().filter(policy__in=PublishedPolicy.objects.valid()) class PolicyRead(models.Model): objects = PolicyReadManager() policy = models.ForeignKey(PublishedPolicy, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='policies_read') read_at = models.DateTimeField(auto_now=True) def __str__(self): return '{user} read {policy} at {read_at}'.format(user=user, policy=policy, read_at=read_at) class Process(models.Model): name = models.CharField(max_length=50) description = models.TextField() class ProcessAllocation(models.Model): process = models.ForeignKey(Process, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) allocated_at = models.DateTimeField(auto_now=True, editable=False) def policies_outstanding(self): policies = self.process.policies(manager='objects').valid() read = self.user.policies_read(manager='objects').valid() return policies.exclude(id__in=read) -
Django 2 - Add User Erro - group with this name already exists
When I try to add a User with a list of groups I get an error stating that "A group with this name already exists". Here are my params: { 'email': 'test@test.com', 'first_name': 'Bob', 'last_name': 'Jones', 'groups': [{'url': 'http://localhost:8000/api/groups/1/', 'name': 'Admin'}] } serializers.py class GroupSerializer(serializers.HyperlinkedModelSerializer): """ Serializer to interact with the Groups model. """ class Meta: model = Group fields = ('url', 'name', 'id') class UserSerializer(serializers.HyperlinkedModelSerializer): """ Serializer to interact with the Users model. """ url = serializers.HyperlinkedIdentityField(view_name='users-detail') groups = GroupSerializer(many=True) class Meta: model = User fields = ('id', 'url', 'username', 'email', 'groups', 'first_name', 'last_name', 'is_superuser', 'is_staff', 'is_active') views.py class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ serializer_class = UserSerializer queryset = User.objects.all() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) -
Django admin site that can access multiple tables in one page (site?)
I'm trying to utilize Django admin page to build a page that presents information queried from multiple tables, so it looks something like page1: account1 account2 account3 when clicking on account1: account1 info page: attri1 from table1 attri2 from table1 attri1 from table2 attri1 from table3 Essentially I just want to get info from multiple tables, but I'm not sure if Django admin does that. I've always only created sites using one table only. All these tables are linked by a foreignKey (account name) Is it even possible? -
Load Django Fixtures Once?
I know this question was asked before, but I was wanting to see if there is a more updated solution. Would there be a way to load all my fixtures in setUp and and flush them when all tests are finished? Right now, I'm loading in my fixtures like so... from django.test import TestCase from django.core.management import call_command class GlobalSetup(TestCase): def setUp(self): # Load fixtures call_command('loaddata', 'test_cfst.json', verbosity=0) call_command('loaddata', 'test_lmt.json', verbosity=0) call_command('loaddata', 'test_qt.json', verbosity=0) class BaseTest(GlobalSetup): fixtures = [ 'test_cfst.json', 'test_lmt.json', 'test_qt.json' ] def setUp(self): super(BaseTest, self).setUp() def test_base(self): # Some random tests With the newer version of django is there a way, or better way, to do this? -
Django deployed with Apache on Ubuntu loses all its styling
I trying to deploy a Django based product on an Ubuntu server with Apache. Everything goes well so far, and I can get de applications served by Apache, but I find that this applications lose all their styling. This is the first time I do this, so I made some research and found and followed this tutorial that is pretty good, but I haven't found any reference to the problem I am having. This is in my settings.py: STATICFILES_DIRS = (os.path.join(BASE_DIR,'FrontEndApp','public'),) STATIC_URL = '/res/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') And this is my 000-default.conf: ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/axel/IntellibookProject/Intellibook/static <Directory /home/axel/IntellibookProject/Intellibook/static> Require all granted </Directory> <Directory /home/axel/IntellibookProject/Intellibook/Intellibook> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess Intellibook python-home=/home/axel/IntellibookProject/IntellibookVenv python-path=/home/axel/IntellibookProject/Intellibook WSGIProcessGroup Intellibook WSGIScriptAlias / /home/axel/IntellibookProject/Intellibook/Intellibook/wsgi.py I made the test serving the applications with pyhton manage.py runserver 0.0.0.0:8000, and everything worked perfectly. The problem exists only when the applications are served with Apache. -
problems in sending email using sendgrid python django?
I am trying to send email using sendgrid using python django. For some reason, the email is being delivered but without the html content in it. What could I be doing wrong ? def sendemail(sender,recipient,subject,content,url): sg = sendgrid.SendGridAPIClient(apikey="") from_email = Email(sender) to_email = Email(recipient) subject = subject objects = { "message":content, "domain":url } html_content = get_template('sendemail.html').render(objects) print ('htmlcontent',html_content) content = Content("text/html",html_content) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) print(response.body) print(response.headers) -
Django and multiprocessing AttributeError: Can't pickle local object
We are trying to proceed multiprocessing in Django, but it never works. We tried the class of: https://engineering.talentpair.com/django-multiprocessing-153dbcf51dab and removed connections.connections.remove_connection("default") and connections.connections.create_connection(hosts=[settings.ELASTIC_FULL_URL], timeout=20). Then, we added the following code into our view: from django.http import HttpResponse from .mp import MultiProcess def DoubleIt(number): print("haha") a = number * 2 return a def mp_view(request): mylist = [111,222,333] with MultiProcess() as mp: mp.map(DoubleIt, mylist) results = mp.results() return HttpResponse("Test") We received the following error message: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/mp/ Django Version: 1.11.14 Python Version: 3.6.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\django-env\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\django-env\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\django-env\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:/multiprocessing_example\mp\views.py" in mp_view 18. mp.map(DoubleIt, mylist) File "C:/multiprocessing_example\mp\mp.py" in map 141. p.start() File "c:\users\robert\anaconda3\Lib\multiprocessing\process.py" in start 105. self._popen = self._Popen(self) File "c:\users\robert\anaconda3\Lib\multiprocessing\context.py" in _Popen 223. return _default_context.get_context().Process._Popen(process_obj) File "c:\users\robert\anaconda3\Lib\multiprocessing\context.py" in _Popen 322. return Popen(process_obj) File "c:\users\robert\anaconda3\Lib\multiprocessing\popen_spawn_win32.py" in init 65. reduction.dump(process_obj, to_child) File "c:\users\robert\anaconda3\Lib\multiprocessing\reduction.py" in dump 60. ForkingPickler(file, protocol).dump(obj) Exception Type: AttributeError at /mp/ Exception Value: Can't pickle local object 'threadwrapper..wrapper' Any idea how to fix that in Django? -
how to send password from frontend to backend using React + Django
I have a django backend using Oauth2. The passwords in the backend are all hashed when stored. My frontend as it is now sends the user login to the backend where it gets hashed in order to compare to user data. When/if it checks out it sends back a token to grant the frontend access. My question is what is the best way of getting the password across to the backend without getting it intercepted and if it intercepted that there'd be no use have it. -
django help to structure a database for a scoring system
i need help to struct the database, and then my models to create a scoring system. In particular, I have 200 runners, and a ranking of the top 10 is compiled every day. The rider's total points should be updated automatically. the site admin should simply see the ranking with the 10 positions and select for each of them only the name of the runner to fill it out. -
Handling a license-like system with Django
I'm trying to come up with a way to handle licenses for a pet-project in Django. Say I wanted customers to have to pay for a license, and that allows them to access the website up until that license expires. Are there built-in tools to handle something like this in Django? Right now all I can think of is creating a new "license" model, with a foreign key to my customer model and a datetime field and then extending the customer model to check whether the license is still valid: class License(models.Model): customer = models.ForeignKey( license_end = models.DateTimeField(default=timezone.now) Then I would extend the customer model with this method: def has_license(self, license): try: license = self.license.get(license=license) except Exception: return False return license.license_end > timezone.now() And I suppose on each view that is restricted by a license I would have to check if customer.has_license(license): (passing their valid license object). Though it would seem like I would be writing the same few lines over and over on each view that needs to be protected. Would there be an easier way to set this up (or something like this)? Though it's a bit relevant, I would also have to come up with a solution … -
Hierarchical tree structure in django project
Python 3.6, Django 2, Sqlite. knowledge = Beginner(Python, Django) I'm trying to create a tree view for the navbar. User creates a post and sets the root node and the node name for his post. Every post is one node, every node has one root node and many child nodes. My idea is to generate a list for every node and then pass this lists to the template. But how to do that with maybe endless deep tree? class Node(models.Model): author = models.ForeignKey(User, on_delete=models.PROTECT) created_date = models.DateTimeField(default=timezone.now) rootnode = models.ForeignKey('Node', on_delete=models.CASCADE, null=True, blank=True, related_name='+') nodename = models.CharField(max_length=32, default='Home', unique=True) def create(self): self.save() def __str__(self): return self.nodename class Post(models.Model): author = models.ForeignKey(User, on_delete=models.PROTECT) node = models.OneToOneField(Node, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title -
How add data_attrs to MultipleSelect in Django?
Data attrs work only for SelectWidget, but not for MultipleSelect. How can i add data_attrs for MultipleSelect? -
leaflet - how to use flyTo() from current view
I'm using Django and Leaflet via django-leaflet. I've set values for default view in settings.py with: LEAFLET_CONFIG = { 'SPATIAL_EXTENT': (minX, minY, maxX, maxY),#omitted numbers for readibility 'MIN_ZOOM': 11, 'MAX_ZOOM': 19 } Suppose I have these endpoints: http://localhost:8000/park http://localhost:8000/school http://localhost:8000/api/park http://localhost:8000/api/school and I load geoJSON data from corresponding api urls. In my html template, I load geoJSON data from those api urls via getJSON(): function map_init_basic (map, options) { var dataurl = "{% url 'place' name %}"; #url of corresponding api $.getJSON(dataurl, function (data) { var lat = data.features[0].geometry.coordinates[1], lng = data.features[0].geometry.coordinates[0]; L.geoJSON(data).addTo(map); map.flyTo([lat, lng], 16); #16 is zoom level }); } My Question: Suppose I load park url, it would pan me to the marker of park from my default view in SPACIAL_EXTENT. If I change to school url, it would also pan me from the default view but I want the view to pan from park view. How can I get this done? -
Get the script of django database
I have to modify my models but I alredy have data in my databse, and I have to clean it to modify my models, How can I make an script file with all the inserted data of django database in order to clean my database and have the data in a script and the uploaded it into the database -
visible workflow engine with django or python?
Is there visible workflow engine with django or python? in front-end webpage, user could handle workflow without coding via visible workflow interface. if have these workflow, pls recommend to me its name. thanks a lot! -
Upload file created by xlsxwriter in docker
I am writing a selenium test for a file upload in Django and Docker. I am currently creating the file I want to upload with xlsxwriter like so: f = io.BytesIO() with xlsxwriter.Workbook(f, {'in_memory': True}) as wb: worksheet = wb.add_worksheet() worksheet.write_row('A1', ['Depot', 'Month', 'Value Sell']) worksheet.write_row('A2', ['Acton', 'January 2017', '567000']) worksheet.write_row('A2', ['Acton', 'February 2017', '567000']) worksheet.write_row('A2', ['Acton', 'March 2017', '567000']) worksheet.write_row('A3', ['Chiswick', 'January 2017', '567000']) worksheet.write_row('A3', ['Chiswick', 'February 2017', '567000']) worksheet.write_row('A3', ['Chiswick', 'March 2017', '567000']) f.name = 'selenium_test.xlsx' f.seek(0) But then when I try to upload the file by running this: file_input = self.find_one('#id_file') file_input.send_keys('/app/selenium_test.xlsx') I get the following error: selenium.common.exceptions.WebDriverException: Message: invalid argument: File not found : /app/selenium_test.xlsx I have also tried this: file_input.send_keys(os.getcwd()+'/selenium_test.xlsx') and got the same error message. Am I doing something wrong here?, as in my mind the file should be saved to the current directory (app) and then I should be able to find it when I want to upload it. As I am running the test in a Docker container could that be the reason why I am struggling to find it? Any help with this would be greatly appreciated.