Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm having trouble with my Jquery-Ajax upvoting code
In my project, it is possible to upvote posts. This works fine, when I'm not using Jquery-Ajax. It reloads the page, though, and I don't want that. I implemented some Jquery-Ajax to do a POST request, and update the button to say upvoted. Unfortunately, this causes all posts in the list to be upvoted, instead of just the one that I clicked. Let me show you the HTML (inside the post list for loop): {% with user=request.user %} <a class="upvote" href='#' > <span class="btn btn-primary" aria-hidden="true"> Upvote | {{ post.followers }} </span> </a> <span style="display: none; class="upvoted btn btn-primary" aria-hidden="true"> Upvoted | {{ post.followers }} </span> {% endwith %} That was the HTML for the upvote and upvoted buttons. Here is my Jquery script: <script src="{% static 'posts/jquery-3.1.1.js' %}"></script> <script type="text/javascript"> $(".upvote").click(function(event) { $.ajax({ url: "{% follow_url post %}?next={{ request.path }}", success: function(data) { event.preventDefault(); $(".upvoted", this.parentElement).fadeIn(); } }); }); </script> To sum it up, how do I cause this function to only vote on the post that I click, instead of upvoting every one in the list? Thanks! -
Django Heroku CreateView Post Bad Request 500 in Production only
I'm deploying a Django App live for the first time, and everything has gone relatively smoothly so far. My site works fine, except for one CreateView (EstRequestCreateView) that works locally, but when I try to create new Estimate Request in Production I receive a Bad Request (500) response. I've added some print statements to the code just to identify where it's failing, but it appears to be behind the scenes somewhere as it makes it all the way through both of my functions no problem. Here is my View: class EstRequestCreateView(CreateView): model = EstRequest # fields = ['market', 'builder', 'plan', 'due_date', 'notes'] form_class = EstRequestModelForm template_name = 'requests/request_form.html' success_url = '/requests/' def post(self, request, *args, **kwargs): if request.user.is_authenticated(): print(request.POST) form = self.get_form() print('form') if form.is_valid(): print('is_valid') return self.form_valid(form) else: print('not valid') return self.form_invalid(form) def form_valid(self, form): print('form_valid func') form.instance.added_by = self.request.user print('user') market = self.request.POST['market'] print('market') note = self.request.POST['notes'] print('notes') due_date = self.request.POST['due_date'] print('duedate') form.instance.trello_id = create_card(market, note, due_date) print('trello created') return super(EstRequestCreateView, self).form_valid(form) And here is my log in Heroku: Dec 21 15:40:51 ao-prime app/web.1: <QueryDict: {'csrfmiddlewaretoken': ['ympCUozBK7qYEoMHgAffBWCoQce7nrqC'], 'plan': [''], 'due_date': ['2016-12-26 18:40:39'], 'market': ['1'], 'builder': ['1'], 'notes': ['Test 1 with Logging']}> Dec 21 15:40:51 ao-prime app/web.1: form Dec … -
navbar links , such as about and contac, don't work
Can anyone tell me please how I can fix my navbar link problem in the code below? I tried almost everything. and read all related stackoverflow article and sort of things but cant figure it out! nothing happens when i click on about or contact i REALLY appreciate if someone has a clue or any idea that could be helpfull for me! thanks in advance <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Welcome</title> <!-- Bootstrap core CSS --> {% load staticfiles %} <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"> <link href="{% static 'personal/css/bootstrap.min.css' %}" rel="stylesheet" /> <link href="{% static 'personal/css/navbar-static-top.css' %}" rel="stylesheet"> <link href="{% static 'personal/css/custom.css' %}" rel="stylesheet"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <!-- NAVBAR ================================================== --> <div class="container"> <nav class="navbar navbar-default navbar-static-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="{% url 'home' %}"><img src="{% static 'personal/img/mvp_landing_logo.png' %}" /></a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="{% url 'home' %}">Home</a></li> <li><a href="{% url 'about' %}">About</a></li> … -
Django-tinymce full featured in admin
I set up django-tinymce to work with admin just like the docs described in settings INSTALLED_APPS = [ ..., 'tinymce',] in models I added from tinymce.models import HTMLField content = HTMLField() and in urls urlpatterns = [ ...., url(r'^tinymce/', include('tinymce.urls')),] But I can not figure out how to add icons and plugins ! I did a lot of research and I could not find anything useful. I need a Full Featured editor. -
Django Create Multiple Objects (Same Model) From One Form
I have been researching this issue for a couple days now with no luck. Hoping someone out there can help. Let's say we have the following models: User model (django.contrib.auth.models) class Children(models.Model): name = models.CharField(max_length=200, blank=False) user = models.ForeignKey(User, on_delete=models.CASCADE) The goal: When a new user wants to create an account, they will fill out the User form and be able to add x amount of children to their account. Essentially, the template will have a user form, and x amount of children forms (depending on how many children the user has) all bundled under the same < form > tag. I used this reference when creating the view: https://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/ The view looks like it should work. My problem is with the template. The trick is that I am not sure how many children each new user will have so I can't hardcode the children form. Does anyone know what a template would like look for this issue or how I can accomplish my goal? -
Django view not rendering after Ajax redirect
The main page of my website has multiple buttons at the top. Whenever one of these buttons is pushed, a get request is sent to a django view, which is redirected and a queryset of django models is filtered and eventually displayed on the web page. I know that my ajax works because the terminal says the request is redirected properly. The function it redirects to also seems to be working, as it is quite simple and has not thrown any errors. However, my view remains the same and I'm not sure why. urls.py url(r'ajax_filter/', views.ajax_filter, name='ajax_filter'), url(r'filter=(\w+)/$', views.filtered_index, name='filtered_index'), views.py def filtered_index(request, filter): clothes = Clothes_Item.objects.filter(gender=filter) if request.user.is_authenticated(): favorite_clothes_ids = get_favorite_clothes_ids(request) return render(request, 'test.html', {'clothes': clothes, 'favorite_clothes_ids': favorite_clothes_ids}) else: return render(request, 'test.html', {'clothes': clothes, }) def ajax_filter(request): if request.is_ajax(): gender_filter = request.GET.get('gender_filter') #filter type if gender_filter is not None: return HttpResponseRedirect(reverse('filtered_index', args=[gender_filter])) return HttpResponse('') -
Unable to inject factory into test suite using Karma/Jasmine
I have an Angular app with a Django back end. I am just starting with Karma and Jasmine unit testing. I am unable to inject my factory into my test suite. Is there any suggestions or glaring errors that I am making? Here are my files... karma.conf.js file module.exports = function(config) { config.set({ basePath: '', frameworks: ['jasmine'], files: [ './node_modules/angular/angular.js', './node_modules/angular-ui-router/release/angular-ui-router.js', './node_modules/angular-mocks/angular-mocks.js', './fake/path/fake/js/directory/src/modules.js', './fake/path/fake/js/directory/src/factories/projectinfostorage.js', './fake/path/fake/js/directory/src/factories/projectinfostorage.spec.js', ], exclude: [ ], preprocessors: { }, reporters: ['progress'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, concurrency: Infinity }) } Angular module... var app = angular.module("tablebrowser", ["ngRoute"]); Factory... app.factory('projectInfoStorage', function(){ var factory = {}; return factory; }) Factory Unit Test... describe('projectInfoStorage factory', function() { var projectInfoStorage; beforeEach(angular.mock.module('tablebrowser')); beforeEach(inject(function(_projectInfoStorage_) { projectInfoStorage = _projectInfoStorage_; })); console.log(projectInfoStorage) }); Karma shows me this in the command line... Chrome 55.0.2883 (Mac OS X 10.10.5) LOG: undefined Chrome 55.0.2883 (Mac OS X 10.10.5): Executed 0 of 0 SUCCEChrome 55.0.2883 (Mac OS X 10.10.5): Executed 0 of 0 ERROR (0 secs / 0 secs) -
Implement roles in django rest framework
I am building an API that should have the following kind of users super_user - create/manage admins admin - manage events(model) and event participants participants - participate in events, invited to events by admins Additional i want to have each type of user to have phone number field I tried class SuperUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(max_length=20) class Admin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(max_length=20) class Participant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(max_length=20) But gut is telling me its a wrong way to handle this. Can someone please help. -
Learning Django - models.py ForeignKey or ManyToManyField or else?
Trying to get some Django skills. I would like to have a class with one field being multiplied. So I can have more then one connected to my main class with an option of being active or not (for future needs). So my subclass would look something like this: class Subclass(models.Model) STATUS=( ('A', Active), ('U', Unactive) status = modelsCharField(max_lenght=1, choices=STATUS) name = models.CharField(some options) On main class I would like to call it as a reference but if I go for : field=models.ManyToManyField(Subclass) It is represented as a second table and for each entity I have to chose from all the entities of it. So if I have 2k entities in subclass I have to scroll true all of them to find my connection (in default admin page for instance) I do not want that. All I need is 2 out of 2k entities that are connected and displayed in admin. And later on anly those with status Active would be displayed on the page itself. So I figured I shall try a ForeinKey relation: field=models.ForeignKey(Subclass, on_deleate=models.CASCADE) This gives me errors about missing default values during migration though. Any help would be welcome, since I am a bit stuck right … -
Django - Retrieve Values of Checkboxes
How do I retrieve the values of multiple html checkboxes and send it back to my view? The checkboxes have the same name: <input type="checkbox" value="document_1" name="checkbox_1"> <input type="checkbox" value="document_2" name="checkbox_1"> <input type="checkbox" value="document_3" name="checkbox_1"> I'm trying to give the user the option the select multiple checkboxes and then send that data back to a Django view. My hope is to send the data back to a Django view as a list of all the selected values with Ajax, although I'm just working out a regular form right now. So If I selected the first and last checkbox, I would send this back to the view: data = ["document_1", "document_3] I have tried setting a variable like this: var data = $('.checkbox_1:checked').val() and I'm still working on the Ajax but haven't been able to make much progress. -
Django: Change url based on result of user authentication
I'm new to django and getting stuck on what I think is a simple issue. I've set up user authentication in my app which is working fine, the problem I'm having is with the url address that appears when my form is submitted. Here is the problem: The action on my form that takes in a user's login credentials is set to "{% url 'home' %}" which is a reference to /dashboard/home. This is exactly what I want the url to be in the event of a successful login. However, when the login is unsuccessful, I want to stay on the login url, which is /dashboard/login. As you can imagine, what's happening instead is that in the event of an unsuccessful login, the url is still changing to /dashboard/home. I think this is misleading for the user and generally just bad practice, but I don't know how to dynamically change the url depending on the result of the login attempt. How can I change the url to /dashboard/login when the attempt is unsuccessful but keep it as /dashboard/home when it is successful? -
Read-Only Field in Django Form
How do I set a field to read-only in a Django form? I know how to disable a field but that's not what I'm looking for. Any help would be appreciated. -
Nginx 502 Bad Gateway - Django - Gunicorn - When running MySQL reports (Stored Procedures) that take longer than 30 seconds
I have a Django, Nginx, Gunicorn, and MySQL on AWS. Running a postback from django which calls a stored procedure that takes longer than 30 seconds to complete causes a return of "502 Bad Gateway" nginx/1.4.6 (Ubuntu). It sure looks like a timeout issue and that this post should resolve it. But alas, it doesn't seem to be working. Here is my gunicorn.conf file: description "Gunicorn application server handling formManagement django app" start on runlevel [2345] stop on runlevel [!2345] respawn setuid ubuntu setgid www-data chdir /home/ubuntu/AARC-ServiceManager/ServerSide/formManagement exec ve/bin/gunicorn --timeout 300 --workers 3 --bind unix:/home/ubuntu/AARC-ServiceManager/ServerSide/formManagement/formManagement.sock formManagement.wsgi:application And my Nginx.conf: user www-data; worker_processes 4; pid /run/nginx.pid; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## # set client body size (max http request size) # client_max_body_size 50M; #upping the timeouts to allow time for the DB to return from a long running sproc proxy_connect_timeout 300s; proxy_read_timeout 300s; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } Any thoughts? -
SyntaxError: invalid syntax in Python Django
I am currently using Python 3.4 with Django 1.10.3 to make a website that is basically an 'online notebook' where the user can store their notes (entries and respective topics). My project's main folder directory is in C:\Users\Steven\mynotes My apps' folder directory is in C:\Users\Steven\mynotess (with double s -> I apologize for terrible naming. I'm a novice in web app development, and I don't want to go through the trouble changing the name right now) So I was given this error in the command prompt when I ran the server. `Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0465FB70> Traceback (most recent call last): File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python34\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "C:\Python34\lib\site-packages\django\core\management\base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "C:\Python34\lib\site-packages\django\core\management\base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "C:\Python34\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python34\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "C:\Python34\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "C:\Python34\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python34\lib\site-packages\django\urls\resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python34\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python34\lib\site-packages\django\urls\resolvers.py", line 306, in … -
Suggested architecture for rewrite a client desktop app written in python (pyqt) as a web app
I have a desktop client application written in python. I used pyqt to develop the gui. This application mainly works exploiting a bunch of very specific python libraries. In order to have data some services provided by a web server are used. Now I need to rewrite this client app as a web app, because my real need is to allow users to use this application without downloading any software on their laptops. My question is, in order not to waste all the work and all the code already written in python with pyqt and all this other libraries, in your opinion what's the best solution to adopt? Keep in mind also that I spendt few days tring to figure out if rewriting the application with javascript and angularjs could be possibile, but I realized that its a lot of work to do and a lot of already written code to waste. In addition could be django or flask a good idea also? thanks in advance -
Is there a converter between django.forms.Form and rest_framework.serializers?
I already have plenty of forms defined in my django 1.9 project. Now I need to export them as REST (DRF 3.5.3) as well. With just a bit of hacking, I was able to provide GET and PUT methods. But I also need to provide the OPTIONS method and I can't seem to find anything that would help me do that. So, is there something that would convert an instanced form to DRF Serializer / ViewSet? -
Install fails with requirements.txt but works with pip install
I'm seeing some weird behavior when using requirements.txt vs. when installing directly with pip. Hoping you can shed some light on this. This may be the same as this unanswered question: pip install -r requirements.txt fails on scipy, but works when run manually line-by-line Python 2.7.6 Django 1.6.11 When I install mailchimp3 using requirements.txt like this: sudo /usr/local/python/django/bin/pip install -r config/myvr/requirements.txt The install fails and I see: Collecting mailchimp3==2.0.3 (from -r config/myvr/requirements.txt (line 73)) 2016-12-21 11:23:22,286 [salt.loaded.int.module.cmdmod][ERROR ][1759] stderr: /usr/local/python/django/local/lib/python2.7/site-packages/pip/req/req_f ile.py:129: UserWarning: Disabling all use of wheels due to the use of --build-options / --global-options / --install-options. cmdoptions.check_install_build_global(options, opts) /usr/local/python/django/local/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLCon text object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more informati on, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning Could not find a version that satisfies the requirement mailchimp3==2.0.3 (from -r config/myvr/requirements.txt (line 73)) (from versions: ) No matching distribution found for mailchimp3==2.0.3 (from -r config/myvr/requirements.txt (line 73)) 2016-12-21 11:23:22,286 [salt.loaded.int.module.cmdmod][ERROR ][1759] retcode: 1 However, when I install directly like this: sudo /usr/local/python/django/bin/pip install mailchimp3==2.0.3 The install succeeds: (django)ubuntu@dev:~/myvr$ sudo /usr/local/python/django/bin/pip install mailchimp3==2.0.3 The directory '/home/ubuntu/.cache/pip/http' or its parent directory is not owned by the current user and … -
django query return primary key related column values
I'm new to using databases and making django queries to get information. If I have a table with id as the primary key, and ages and height as other columns, what query would bring me back a dictionary of all the ids and the related ages? For instance if my table looks like below: special_id | ages | heights 1 | 5 | x1 2 | 10 | x2 3 | 15 | x3 I'd like to have a key-value pair like {special_id: ages} where special_id is also the primary key. Is this possible? -
How to deploy a local django website?
I'm very new to Django. I'd like to know how to deploy a local website from start to finish. I just bought the most basic GoDaddy plan, and I want to deploy the Django Polls website. Please give me the instructions of what I should do, in a beginner way. I've tried deploying a Django website following a video tutorial it was very stressful and complicated, so I want to overcome this frustration and publish something. -
Add class on modelform django
How to dynamically add a class to a field on a modelForm. class MyForm(ModelForm): class Meta: model = Post fields = ['type'] widgets = { 'type' : RadioSelect()} def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields['type'].widget.attrs.update( {'class':'radio-inline'}) I did the code above but it is not working for some reason. The class 'radio-inline' is not created on the template. -
Extending Django models
Suppose there are models: Game, Player, Team. I need to display a calendar day, with all games and lineups. The model "Game" automatically reads the foreign key "Team" model and populate QuerySet. How to add a set of players to this queryset? Or I need to create another queryset of players with filter by team and extend game queryset? -
How to use --failfast in django test command line?
I want to use --failfast so that if my one test fail, remaining all other test gets executed. Do I need to create new test runner or I can use it in command line ? -
Django ModelForm widget overriding issues
I've been having issues for the past few days with trying to get a model form to use a different widget than what is in the model. I'm trying to make a form that dynamically updates a list of channel options from Slack and I'm having problems getting it the form to work. Model: class Team(models.Model): team_id = models.CharField(editable=False, primary_key=True, max_length=30) access_token = models.CharField(max_length=128, editable=False) post_channel = models.CharField(max_length=21, default=None) approval_channel = models.CharField(max_length=21, default=None) last_edit = models.CharField(max_length=21, default=None) admin_only_approval = models.BooleanField(default=True) admin_only_edit = models.BooleanField(default=True) Form attempt 1: class TeamSettingsForm(forms.ModelForm): post_channel = forms.ChoiceField() approval_channel = forms.ChoiceField() def __init__(self, *args, **kwargs): super(TeamSettingsForm, self).__init__(*args, **kwargs) slack = Slacker(kwargs['instance'].access_token) priv_ch = [(g['id'], g['name']) for g in slack.groups.list().body['groups'] if not g['is_archived']] pub_ch = [(c['id'], c['name']) for c in slack.channels.list().body['channels'] if not c['is_archived']] users = [(u['id'], u['profile']['real_name']) for u in slack.users.list().body['members'] if not u['deleted']] self.fields['post_channel'].widget.choices=tuple(pub_ch) self.fields['approval_channel'].widget.choices=tuple(pub_ch + priv_ch + users) class Meta: model = Team fields = ['post_channel', 'approval_channel', 'admin_only_approval', 'admin_only_edit'] Every time the form is submitted, it says that the data is invalid and that the input for the choice fields were not one of the available options. Form attempt 2: class TeamSettingsForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(TeamSettingsForm, self).__init__(*args, **kwargs) slack = Slacker(kwargs['instance'].access_token) priv_ch = [(g['id'], … -
Django-debug-toolbar extremely slowing down loading page
I want to profile my project to figure out what indices to create in db. I've installed django-debug-toolbar. The problem is that it is extremely slowing down page loading. Moreover, couple minutes ago it was showing about 80 000 queries, now it takes about 48 seconds and it says that there are 2300 queries (which is according to Django Querycount correct). But when I turn django-debug-toolbar off, it works correctly (about 3 or 4 seconds). Do you know what could cause problem? I've found that this was bug, but it was a couple years ago. -
Creating a 21 character unique field for a model in Django
I know the id is unique by itself, I want to create a unique field thats longer and less easy to guess. In short, this field will be a unique, 21 character alphanumeric string. I am doing this using this code below: class Organization(models.Model): name = models.CharField(max_length=255) key = models.CharField(max_length=21, unique=True, blank=True, null=True) def save(self, *args, **kwargs): if self.key == '' or self.key == None: key = '' for i in range(21): key += random.choice(string.lowercase + string.uppercase + string.digits) if Organization.objects.filter(key=key).exists(): self.save() # Try again else: self.key = key super(Organization, self).save(*args, **kwargs) In the save method, I do the following things: See if the object's key exists or not. If not, I generate a 21 character key. Then I check if an Organization with the key I generated exists or not. If not, then the object's key is set to the generated one and saved. Is this the right way to do this? Is there a better way with less code perhaps? Also, notice how my key field is unique, but also can be blank. Can that be an issue? So far, this has worked pretty well. Any help is appreciated.