Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, getting cookie after login you set before login?
I'm trying to implement an anonymous cart where he can put stuff in the cart before signing in. and set cart id in the cookie. After he's logged in, I'd like to use the same cart he was using. I would retrieve the cart with the cart id stored in the cookie. Would this be possible using cookie? -
Testing Django commands file or stdin
I am writing a django command that takes a bunch of input and processes it. It seems natural that because of the volume of the data, the input should either come in as a file or as stdin. I would like to easily test it, and by easily, I mean, without having to create a bunch of files in my test environment. Now, I remember somewhere (can't find it properly documented, but I did find the "PR"), that the "-" is supposed to read from stdin, but I can't get it to work. It seems the command should do something like this: class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument("foo", type=file) def handle(self, *args, **options): file = options["foo"] # Then read the file, and process it But then when I run the command, it doesn't like the - parameter (says it isn't a file). The command docs recommend writing to self.stdout for better testing. I tried something similar for self.stdin but couldn't get that to work either. Assuredly this is a common pattern, but I couldn't find any good helps on how to do this best. It seems like "There should be one-- and preferably only one --obvious way to do it.", … -
Should I apply to jobs as a programmer around now?
My question is based on the following criteria mentioned in the middle section should i apply programming jobs as of now ? My Case: I am a self-learner in programming for 2 years now. I've searched for other, more appropriate SE communities, but I couldn't find one. I hesitated between superuser, meta-exchange, or here. I am still doing my phd on Egyptology. I started programming to cut down the manual labour of going through online databases to search for inscriptions. However in the meanwhile, I am hooked up to programming, plus I know around 5 ancient languages, and 2 modern foreign ones, but still, if some egyptian pharaoh doesn't decide to speak with a mesopotamian king at the presence of a greek messenger in future europe, i have very little hopes of landing a steady job in real life, so programming for me is also an alternative means of maintaining my life standards. Criterias: Though important as it is, since I am not majored in CS, i literally don't know, what an engineer should know, what kind of criteria is applied to fresh CS students on job interviews, or what people normally demand from them and thus have no idea … -
Django - Create object if field not in database
I want to create an object only if there's no other object with the same ID already in the database. The code below would create the same item if one the parameters below like the State was modified. returns = Return.objects.all() for ret in returns: obj, created = Return.objects.get_or_create(ItemID="UUID", ItemName="Hodaddy", State="Started") obj.save() -
Python/Django: Trouble using Slug in URL
I'm building an application using Python 2.7 and Django 1.10 (my first one), and right now I'm having trouble to create the links using slugs for a product detail page. When I manually type the product URL it works fine (/courses/analise-swot/), it reads the details.html page and builds it apropriately using the information from the database. Here's the erros I'm getting: Page not found (404) Request Method: GET Request URL: Using the URLconf defined in simplemooc.urls, Django tried these URL patterns, in this order: ^ ^$ [name='home'] ^ ^contato/ [name='contato'] ^courses/ ^$ [name='cursos'] ^courses/ ^(?P<slug>[A-Za-z0-9_\-]+)/$ [name='details'] ^admin/ ^media\/(?P<path>.*)$ The current URL, courses/(u'details', (), {u'slug': u'analise-swot'}), didn't match any of these. Here is my code: class where I create the slug in models.py: class Course(models.Model): name = models.CharField('Nome', max_length=100) slug = models.SlugField('Atalho', max_length=100, unique=True) get_aboslute_url method in models.py: def get_absolute_url(self): return ('details', (), {'slug': self.slug}) entire urls.py: from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^$', views.cursos, name='cursos'), url(r'^(?P<slug>[A-Za-z0-9_\-]+)/$', views.details, name='details'), request in views.py: def details(request, slug): courses = get_object_or_404(Course, slug=slug) context = { 'course': courses } template_name = 'courses/details.html' return render(request, template_name, context) Thanks a lot! -
Django password is not changed
I don't know what I'm doing wrong, but when I try to change the password it doesn't change it and it doesn't give any errors. urls.py from django.contrib.auth.views import logout,password_change,password_change_done ... url(r'^change_password/?$',password_change, name='password_change'), url(r'^password_changed/?$',password_change_done, name='password_change_done'), url(r'^logout/?$',logout, name='logout'), password_change_form.html <form action="{% url 'password_change_done' %}" method="post"> {% csrf_token %} {% bootstrap_form form layout="inline" form_group_class="form-group col-md-6" %} <div class="clearfix"></div> {% buttons %} <button type="submit" name="save" class="btn btn-primary">{% bootstrap_icon "plus" %} {% trans 'save' %}</button> {% endbuttons %} </form> When I click on save, it shows the template "password_change_done.html" but the password hasn't been changed. However, there are no errors in the console and I don't know what fails. Thank you all -
How do I get a drop down menu with dynamic values in Django?
I have a Django form with two fields: Date field - With a jQuery calendar widget that lets me choose a date Time field - A drop down menu with times from 9:00 AM to 5:30 PM at 30 minute intervals (9:00AM, 9:30AM etc) Now, based on the date picked by the user in the date field, I'd like to restrict times. For example if the user makes the choice of tomorrow, at 2:00PM today, I'd like to restrict the times to only after 2:00 PM tomorrow. I want there to be a 24 hour gap. How would I go about enforcing complex rules like these when dealing with Django forms? I read in a blog that I could use an if condition in the forms.py file to restrict the options, but I want to keep this to the client side. How would I achieve this? This is what I have so far. My Template: <!doctype html> <html lang="en"> {% load staticfiles %} <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jQuery UI Datepicker - Default functionality</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script type="text/javascript" src="{% static 'js/datepair.js' %}"></script> <script type="text/javascript" src="{% static 'js/jquery.datepair.js' %}"></script> </head> <body> … -
Installation problems - Django for python
can you please help? I've spent hours on google to no avail and still cant install django... pretty much lesson 1 on building web apps with python... Csongors-MBP:~ iamcsongor$ pip install Django==1.10.5 Collecting Django==1.10.5 Using cached Django-1.10.5-py2.py3-none-any.whl Installing collected packages: Django Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 784, in install **kwargs File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/django' -
How to represent Django money field with currency symbol in list template and plain decimal for edits?
When I display money in a list template or detail (read-only) template I would like to be able to display a pretty version of the field's value which includes the currency symbol: "$100.00" However, when the record is being edited, I would like to display "100.00" in the TextInput box without any currency symbol. I made a custom models.DecimalField class and forms.DecimalField class to represent money in my Django application. So I'm trying to come up with a way to have an alternate version of the field's value in the template that is pretty (i.e. properly formatted for viewing but not ideal for editing). I know there are template filters that let you accomplish this, but I believe that would prevent me from iterating through the fields in a form and displaying their values. If I can add a pretty attribute to my custom field class, I can check if it exists in the template and display it. So far I tried this: class MoneyFormField(forms.DecimalField): def __init__(self, *args, **kwargs): # I plan to add symbol localization code here self.symbol= '$' def prepare_value(self, value): # assign pretty value to an attribute that template can access self.pretty = self.pretty_value(value) try: return round(Decimal(value),2) … -
Unresolved attribute reference 'first' for class 'property'
I've created two properties within my class: @property def images(self): return PictureImage.objects.filter(picture=self) @property def max_size_image(self): images = self.images # Skipped some code here return images.first() # Unresolved attribute reference 'first' for class 'property' As you can see, the first property returns queryset, which has first() method. But PyCharm shows me warning for the code above. Is it OK? -
How to run Django task periodically on Heroku?
I have a Django application deployed on Heroku using 1 web dyno, basically just hosting a website where people can signup, then the app can send emails to those people. Right now I send all the emails manually; I go in django shell everytime on heroku server, and call function like a.send_customized_email() I'm wondering how to make a scheduler thing to send emails periodically without me coding in commands in the backend everytime? I heard about Django celery, but how to integrate it exactly? Should I fire up another dyno? What should be the configuration files? Thanks in advance. -
Django ORM Filtering Related Objects By Field Value?
I am working on a project that involves a channel/post mechanism. I am currently implementing functionality to "delete" posts by setting a field named "deleted" to a timestamp of when it was deleted. It needs kept for historical significance (last activity) and to track people who are inflammatory (the service is a privilege based portion of the whole project). models.py class Post(models.Model): deleted = models.DateTimeField(null=True, blank=True) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now_add=True) post_text = models.CharField(max_length=1000) post_to = models.ForeignKey('Channel', related_name='post_to_channel') post_from = models.ForeignKey(User, related_name='user_from_post') class Channel(models.Model): created_date = models.DateTimeField(auto_now_add=True) channel_title = models.CharField(max_length=50, unique=True) channel_description = models.CharField(max_length=100) channel_creator = models.ForeignKey(User) channel_private = models.BooleanField(default=False) channel_users = models.ManyToManyField(User, through='Membership', related_name='channels', blank=True) channel_posts = models.ManyToManyField(Post, related_name='channel_post', blank=True) initial_invites = models.ForeignKey(User, null=True, blank=True, related_name='initial_invites') objects = models.Manager() class Membership(models.Model): channel = models.ForeignKey(Channel) channel_user = models.ForeignKey(User, related_name='channel_membership') join_date = models.DateTimeField(auto_now_add=True) I have an endpoint which updates the "deleted" field of the "Post" object to be a timestamp from null. How do I then avoid returning all Posts which have a timestamp when queried at the "Channel" level, having the Posts be loaded through their relationship and a separate serializer? Basically, I need to be able to query "Channel" and get a list of channels I am a … -
AJAX requests not working properly with gunicorn when logged out from server
I've made my first django application deploy on server this weekend. It was clear VPS server so I have to install PostgreSQL, PostGIS, set virtualenv and so on. It takes some time to make application works. On django development server everything works fine, but when I deployed my app with gunicorn (cooperates with Nginx) on VPS server AJAX requests not working properly. I have three AJAX request sending right after the other. And only one or two requests have returned value. So I found gevent and this thread (Django AJAX requests during regular request not going through) and run gunicorn with this command: gunicorn myapp:wsgi:application --bind 0.0.0.0:9000 -k gevent --worker-connections 1001 --workers=3 and it works. All requests return values and everything looks ok. So I put process to background with and logged out from server. But everytime when I log out from server the requests stop work. The behavior is the same as firstime without gevent. Could be the problem of activating virtual environment, setting or this is standard behaviour of Ubuntu as server? I don't even know where should I find solution so I will be glad for any help. -
Best admin with multilingual features and multisite
I'm running into an issue right now. I have to make an admin with the possibility to create : multiple sites make these sites translatable in multiple language the frontend will serve the data as JSON mainly I used Wordpress which is pretty good for that but the interface is somewhat lame for the user. I used also active admin from rails which is very nice for users but it takes so much time to make this multisite and translatable. Make the json on both is pretty easy. I aim at doing it right and fast, as usual. Programming language/framework shouldn't be a problem as long as it's documented enough. Do you have any guess? Thanks guys, don't know if it's the right place to post it thought. -
scope/context issue in ajax success causing Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined
Apologies for asking already heavily answered question. But i am unable resolve my issue with all the available answers. I am creating my forms on an html screen on the fly using json schema and a js form generator call Alpaca. Now i want to access the form submit object in my django backend. I am trying to do this using json-rpc method, which has worked for me in the past. But right now i think i am getting the mentioned error because of scope or context issue. I have tried everything but am unable to get this working. I have included following js on my onsubmit event. "click": function() { var csrftoken = '{{ csrf_token }}'; //val.csrfmiddelwaretoken = csrftoken; var data = {'form_submit': this.getValue()}; id = 0; var form_data = { method: 'my @jsonrpc_method view function', id: ++id, params: data, jsonrpc: '2.0' }; var self = this; $.ajax({ url: '/json/', type: 'POST', crossDomain: true, data: JSON.stringify(form_data), //context: self, xhrFields: { withCredentials: true }, //dataType: "json", beforeSend: function (xhr) { xhr.setRequestHeader('__RequestVerificationToken', csrftoken); xhr.setRequestHeader("X-CSRFToken", csrftoken); }, success: function(data, status, xhr){ if (data.error){ alert(data.error.message); } else { console.log(data.result); // Context issue in below statement. $(self).text(data.result); setTimeout(function() { $(self).text('click to view'); console.log("this worked!") … -
RuntimeError when building CSS from SCSS files of Foundation-sites with Django-pipeline
My issue is in the same context as Django-Bower + Foundation 5 + SASS. I'm trying to compile foundation from scss to css. The problem is that I'm encountering the following RuntimeError: /home/hakim/.gem/ruby/2.4.0/gems/sass-3.4.23/lib/sass/exec/sass_scss.rb:287:in `watch_or_update': File /home/hakim/github/myquotes/static/quotes/app.css doesn't exist. (RuntimeError) Did you mean: sass --update /home/hakim/github/myquotes/static/quotes/app.scss:/home/hakim/github/myquotes/static/quotes/app.css from /home/hakim/.gem/ruby/2.4.0/gems/sass-3.4.23/lib/sass/exec/sass_scss.rb:51:in `process_result' from /home/hakim/.gem/ruby/2.4.0/gems/sass-3.4.23/lib/sass/exec/base.rb:52:in `parse' from /home/hakim/.gem/ruby/2.4.0/gems/sass-3.4.23/lib/sass/exec/base.rb:19:in `parse!' from /home/hakim/.gem/ruby/2.4.0/gems/sass-3.4.23/bin/sass:13:in `<top (required)>' from /home/hakim/.gem/ruby/2.4.0/bin/sass:22:in `load' from /home/hakim/.gem/ruby/2.4.0/bin/sass:22:in `<main>' The static files are stored in os.path.join(BASE_DIR, 'static'). Here is the relevant part of my setting.py: # Manage static files with pipeline STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' # Where to generate CSS from SCSS STATIC_ROOT = os.path.join(BASE_DIR, 'static') # Specify SCSS files to be compiled to CSS PIPELINE = { 'STYLESHEETS': { 'librairies': { 'source_filenames': ( 'quotes/app.scss', ), 'output_filename': 'quotes/app.css', }, }, 'COMPILERS': ( 'pipeline.compilers.sass.SASSCompiler', ), 'SASS_ARGUMENTS': "--trace --update -I '%s'" % os.path.join( BOWER_COMPONENTS_ROOT, 'bower_components', 'foundation', 'scss' ), } app.scss contains only @import 'foundation';. -
Django 1.10 unable to get variable into the context
I'm working on a django site (my first) and I was trying to add a form to the context. I wasn't able to see the variable in my template, so I simplified to a string variable, and still no result. I'm not entirely clear on what I'm doing wrong so I was hoping to get some help. Here's the view: from django.shortcuts import render from django.http import HttpResponse from django.template.context import RequestContext from forms import LoginForm # Create your views here. def index(request): return HttpResponse("Index page for Chefables portal") def login(request): lFormContext = RequestContext(request,{'mystring' : 'mystring'}) return render(request, 'login.html', lFormContext ) and here's the template: {% extends 'base.html' %} {% load i18n %} {% load debug_tags %} {% block container %} <div class="content"> {% variables %} {% if form.errors %} <div class="alert alert-danger"> <p><strong>{% trans "Oh snap!" %}</strong> {% trans "Please enter a correct username and password. Note that both fields are case-sensitive." %}</p> </div> {% endif %} <form action="{% url 'login' %}" method="post" class="form-horizontal" role="form">{% csrf_token %} <legend><span class="col-sm-offset-1">{% trans 'Log in' %}</span></legend> {% for field in form.fields %} <p>iterating over form.fields </p> {% include 'registration/form_field.html' %} {% endfor %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">{% … -
how run virtualenv with gulp?
I usually run source .ven/bin/activate in the terminal and on a new tab the python manage.py runserver I would like to run the virtualenv and runserver with Gulp, I tried with cross-spawn and I have not succeeded, any suggestions? -
Django CMS Plugin Change Form
I'm wondering how can i put fields from the model inside the edit window in django cms. Right now when i enter the edit mode i can only choose what instance i want or edit it by clicking the pen. But i want the customer to be able to edit straight from the white window. From the docs i red that you were suppose to edit change_Form.html which i have tried with no success. I can put custom code in there and it shows up on the window. But i cant get the fields from the model in there... Can anyone give me a example or explain how you do it? Thanks in advance! -
Using Wagtail CMS Collections to Manage Permissions to Custom Settings
I am building an app for an Association with many Chapters. I setup the default site (localhost) for the Association corporate office, and a Chapter Site (denver.localhost) with a default landing page - they have dozens of other chapters that will be setup similar to this. I went into Collections and setup a collection called Denver and then in Groups, setup a custom group called Denver as well. This allows me to setup group permissions for the Denver chapter to only have access to the Denver landing page root directory, Denver images and Denver Documents. These permissions are all controlled by Collections. I would like to setup custom snippets or models with Chapter specific information such as address, phone, social links, etc.. but cannot figure out how to create them in a way that will allow me to assign them to their specific collection, thus allowing the chapter users to modify their data only. Thank you. -
Why django urls end with a slash?
Django official documentation and other tutorials on the web always use a trailing slash at the end of url. ex: url(r'^accounts/login/', views.login) # login view in turn calls login.html # instead of url(r'^accounts/login', view.login) Since account is the directory and login (login.html) is the file, shouldn't we be using second url? This will also make GET parameters look more structured: accounts/login?name='abc' # login is a file that is accepting parameters vs. accounts/login/?name='abc' # login directory (maybe index) is accepting parameters?? -
Django loop over modelchoicefield queryset
My Problem: I need to loop over the queryset of a ModelChoiceField in my template so that I can create a radio button list that includes the area field of the model along with the description field. So my model looks like this... models.py class AnExample(models.Model): id = models.AutoField(primary_key=True) area = models.CharField(max_length=50) description = models.TextField(blank=True, null=True) def __unicode__(self): return self.area ...and I'd like to create radio button inputs in my template, so that the form would look like this: <input type="radio">{{ model_instance.area }}: {{ model_instance.description }} What I've tried: {% for choice in form_from_view.an_example.field.choices %} {{ choice }} {% endfor %} This gives me a list of tuples with the primary key and area, but I do not have access to the description field if I do this. {% for item in form_from_view.an_example.field.queryset %} {{ item }} {% endfor %} This gives me the actual model instance, and I do have access to {{ item.description }} but unfortunately this doesn't loop over the entire queryset; it only gives me the first record, not each record in the queryset like I'd expect. -
Adding new Wagtail CMS Snippets
I would like to add new Wagtail Snippet models but cannot find any documentation regarding proper file naming to begin building them; do I place them in my apps model.py file or does it have a specific method similar to wagtailadmin? Thank you. -
Python how i can parse list?
How i can parse it? check = request.POST.getlist('check') print(check) [u'["1","2"]'] send ajax JSON data to server -
Why does django's default filter show quotes of a string?
Is there a way to get django's default filter to output just the strings contents and not the quotes themselves? <div>{{ data.title|default:"StackOverflow's Favorite Products" }}</div> Right now, the above template outputs literally "StackOverflow's Favorite Products" instead of StackOverflow's Favorite Products