Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django URLs with AngularJs routeProvider
for a project, I am using Django on the back-end and AngularJs on the front end. Basically, what I want is to run the Angular app only when the url starts with projectkeeper/. In other words, lets say my website is example.com. I want the angular app to run for the URLs example.com/projectkeeper/dashboard/, example.com/projectkeeper/projects/ and so on, but not on example.com/about/. Hope I have made myself clear. Anyway, in order to do this, I am doing the following with my code: urls.py urlpatterns = [ url(r'^projectkeeper/$', TemplateView.as_view(template_name='base.html')), ] In the template base.html, I refer to my angular app obviously. For the angular routing, I have done the following: myapp.config(['$routeProvider', function($routeProvider) { $routeProvider .when('/dashboard/', { title: 'Dashboard', controller : 'DashboardController', templateUrl : 'static/app_partials/projectkeeper/dashboard.html' }) .otherwise({ redirectTo : '/' }); }]); So, ideally, what I thought was that going to example.com/projectkeeper/#/dashboard/ would run the DashboardController from my angular app. However, this is not the case, I only get an empty page which means the routing was incorrect. Any solutions to this? As I said before, I want is to run the Angular app only when the url starts with projectkeeper/. -
Django QuerySet Doesn't render
I have a QuerySet that I can see via print has items , , , , ]> which when I then try to render in template via: return render(request, 'tasks.html',{'tasks:': tasks}) template: {% for task in tasks %} {{ task }} edit delete mark_done {% endfor %} shows up as if tasks was None -
Layout not transffering to pages
So I have some code in my base layout that has this: <h2>{{ main.character_name }}</h2> In the same page of above code I am using {% block content %}{% endblock content %} to insert multiple layout from different pages. The issue I am having is that if I load up a separate page that extends upon the base layout using the same code above, the header from the top most code will not work on the new page. I do not know why it does not. -
Keeping configuration information in Django for frequent use
I read a JSON file for configuration information that the Django app needs. Rather than read it every time, I'd like to keep it in memory somewhere. Only, I don't know how to do this in Django. What's the best way to keep simple configuration information in RAM, so that it's accessible anywhere in the app? -
Dynamic removal and change start time celery periodic tasks in django code
I've got a problem and i haven't found its solution in docs. I'm dynamically adding periodic tasks from our program, like it is shown in documentation example. But i need to change the starting period of tasks or delete unused tasks. How can i do it inside the python program? It is possible? part of code in settings: CELERYBEAT_SCHEDULE = { ... 'refresh-tours':{ 'task': 'core.celery.refresh_tours', 'schedule': 30.0, } ... } code celery tasks: @app.on_after_configure.connect def setup_refresh_tasks(**kwargs): # Here I would something like this # app.delete_periodic_task('add-task') # app.add_periodic_task(timedelta, test.s(str), name='other-task') app.add_periodic_task(2.0, test.s('hello'), name='add-task') @app.task() def test(arg): print(arg) @app.task def refresh_tours(): setup_refresh_tasks() -
ReportLab Generate PDF Error
I am trying to generate a pdf with ReportLab in Django (1.10) with Python (3.5). I just found that I could not make the doc build from paragraph work. Whenever I run, I got the following error: Exception Type: LayoutError Exception Value: Flowable <Paragraph at 0x59c4400 frame=normal>Mike Driscoll(439.27559055118104 x 12) too large on page 2 in frame 'normal'(439.27559055118104 x -4426.110236220473*) of template 'Later' Does anyone know what has gone wrong and advise any solution to that? I attach my code as below for your reference. Many thanks. def downloadpdf(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"' buffer = BytesIO() pdfmetrics.registerFont(TTFont('PMingLiu', 'PMingLiU.ttf')) doc = SimpleDocTemplate(buffer, rightMargin=inch*1, leftMargin=inch*1, bottomMargin=inch*1, topMargin=inch*inch*1, pagesize=A4, fontName = 'PMingLiu', fontSize=10) Story =[] styles=getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) full_name = "Mike Driscoll" ptext = '<font size=12>%s</font>' % full_name Story.append(Paragraph(ptext, styles["Justify"])) print (Story) doc.build(Story) doc.save(buffer) pdf = buffer.getvalue() buffer.close() response.write(pdf) return response -
initial value for ModelForm field not working
I'm tring to set the user field as the logged-in user, but it's returning None. Here's my model: class Post(models.Model): user = models.ForeignKey(User, blank=True, null=True) title = models.TextField(max_length=76) date = models.DateTimeField(auto_now=True) content = models.TextField(null=False, default='') image = models.FileField(null=True, blank=True) category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='1') my form: class PostForm(forms.ModelForm): content = forms.CharField(widget=PagedownWidget) title = forms.TextInput(attrs={'placeholder': 'title'}) class Meta: model = Post fields = [ 'title', 'content', 'category', 'image', 'id', 'user' ] and my view where users make a post using a form: def post(request): allauth_login = LoginForm(request.POST or None) allauth_signup = SignupForm(request.POST or None) if request.user.is_authenticated(): data = {'user': request.user} form_post = PostForm(request.POST, request.FILES, initial=data) if form_post.is_valid(): category = form_post.cleaned_data['category'] for a, b in CATEGORY_CHOICES: if a == category: category = b form_post.save() return HttpResponseRedirect('/%s' % category) else: form_post = PostForm() context = { 'allauth_login': allauth_login, 'allauth_signup': allauth_signup, 'form_post': form_post } return render(request, 'post.html', context) else: return HttpResponseRedirect("/accounts/signup/") When I actually render the form in my template, {{ obj.user }}returns None. Any idea why? -
Django QuerySet OR statement
Is there a way to obtain a QuerySet in Django so that the remaining objects satisfy at least one of a number of constrains (i.e. an OR statement)? Something like: remaining = Fruits.objects.all() fruit_type = ['apple', 'orange'] # input from user for fruit in fruit_type: remaining = remaining.filter(FruitType__icontains=fruit) However, the above only returns FruitTypes that contains both orange AND apple (rather than orange OR apple). -
Django Push notification not working
Hi i am having trouble sending push notification to ios devices my code is as follows, it gets executed and doesn't raise any errors def create_push(sender, instance, **kwargs): if not instance.is_push_sent: tagged_users = instance.get_user_tag() if tagged_users: for tagged_user in tagged_users: device = APNSDevice.objects.filter(user_id=tagged_user, active=True) for each_device in device: each_device.send_message("Someone tagged you in their picture!") instance.is_push_sent = True instance.save() m2m_changed.connect(create_push, sender=Model_Name.user_tag.through) I am using django push notifications and django v1.6 -
Time filter commands in django (timezone.now())
I'm brazilian, and i was reading a django tutorial, and find this, but i do not know what i'm seeing. Somebody could help me please? what is more black than others it's what i'm not understand very well Post.objects.filter(published_date__lte=timezone.now()) i'm sorry if my english are wrong kkkkk Thanks -
Exception Type: ValidationError at /home Exception Value: [u"'1a3288b3-7588-483f-8e85-1affa952dbbf' value must be an integer."]
I have created registration page , model for it and when user gets registered he gets redirected to home page. When i click on register user is getting inserted in database but when it redirects to home page i am getting this error: Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\KR\Desktop\projects\project2\welcome\homeview.py" in home 14. if request.user.is_authenticated(): File "C:\Python27\lib\site-packages\django\utils\functional.py" in inner 234. self._setup() File "C:\Python27\lib\site-packages\django\utils\functional.py" in _setup 380. self._wrapped = self._setupfunc() File "C:\Python27\lib\site-packages\django\contrib\auth\middleware.py" in 24. request.user = SimpleLazyObject(lambda: get_user(request)) File "C:\Python27\lib\site-packages\django\contrib\auth\middleware.py" in get_user 12. request._cached_user = auth.get_user(request) File "C:\Python27\lib\site-packages\django\contrib\auth__init__.py" in get_user 180. user_id = _get_user_session_key(request) File "C:\Python27\lib\site-packages\django\contrib\auth__init__.py" in _get_user_session_key 59. return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY]) File "C:\Python27\lib\site-packages\django\db\models\fields__init__.py" in to_python 927. params={'value': value}, Exception Type: ValidationError at /home Exception Value: [u"'1a3288b3-7588-483f-8e85-1affa952dbbf' value must be an integer."] This is the model: class user_model(AbstractBaseUser): user_id = models.CharField(max_length=50, primary_key=True) username = models.CharField(max_length=50, unique=True) first_name = models.CharField(max_length=50, default="None") last_name = models.CharField(max_length=50, default="None") email = models.EmailField(default="None") password = models.CharField(max_length=150, default="abc123") '''Custom user information fields. ''' myself = models.CharField(max_length=300, default="None") address = models.CharField(max_length=300, default="None") mobilePh = models.CharField(max_length=20, default="None") workPh = models.CharField(max_length=20, default="None") workEmail = models.EmailField(default="None") last_login = models.CharField(max_length=50, default="None") … -
Django Admin extra forms with two widgets
In Django admin, I tried adding an extra field for my model like forms.py from django import forms from .models import Provider class IntervalForm(forms.ModelForm): ''' @brief Used to set the interval of each provider's queue task ''' interval = forms.CharField() class Meta: model = Provider fields = '__all__' admin.py from .models import Provider from .forms import IntervalForm class ProviderAdmin(admin.ModelAdmin): form = IntervalForm list_display = ('code', '__unicode__', 'get_accounts', 'get_all_prefixes', 'get_columns') admin.site.register(Provider, ProviderAdmin) This will work fine for now. But I want my extra 'interval' field to be like two fields. The first one is a select field with the options of 'minute', 'seconds' and 'hour' and the other one is an Integer Field.. I wist the fields with the label to be displayed as one-line as well -
Django - Restricting views
I am building a website where you can keep your private portfolio, logs, etc using Django. All courses, documentation, I came accross so far give all users the possibility to view all entries made by all users (e.g. blog, posts etc.). However I want to restrict any user from viewing & READING other users' data. How can this be best achieved? Is there an extension available? I know that django doesn't have row-level permissions, but there are extensions for that available such as Django-rules. In my case however I want restrict a user from viewing other users' data. In other words, a user can only see his/her porfolio and is also not in any way able to CHANGE, UPDATE, DELETE any entries which is not its own. -
HttpResponseRedirect vs render in Django?
WHat is the difference between HttpResponseRedirect and render in Djago when either one can output an html template just the same? WHat is the rule on when to use one or the other especially when used in Django forms? -
ImportError: No module named 'myproject.settings'
I was running nicely a Django python project on Openshift. But from the moment that I tried to create and push a 'requirements.txt' file to be able to include the 'requests' library, the problems started to come: ImportError: No module named 'myproject.settings' Even after deleting the requirements.txt file again, this errormessage stayed . Can someone help me please? This is how my structure looks like : screenshot file structure And this is what can be found in my 'Application' file ## GETTING-STARTED: make sure the next line points to your settings.py: os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings' ## GETTING-STARTED: make sure the next line points to your django project dir: sys.path.append(os.path.join(os.environ['OPENSHIFT_REPO_DIR'], 'wsgi', 'myproject')) And here is a screenshot of the tail log on the server : error log -
Django Migrate Change of App Name (active project)
So... I've done a lot of research on this... there are answers, but not complete or appropriate answers. I have an in-use and in-production django "project" in which the "main" application is called "pages" ... for reasonably dumb reasons. My problem is now to add mezzanine ... which has a sub-module mezzanine.pages (seems to be required .... but I'm pretty sure I need it). mezzanine.pages apparently conflicts with "pages" ... Now ... my pages contains a slew of non-trivial models including one that extends user (One-to-One ref), and many references to other app's tables (fortunately only outbound, ForeignKey). It also has management/commands and about 20 migrations of it's own history. I gather I either have to changes pages to mypages or is there another route (seemingly changing mezzanine.pages seems wrong-headed). for reference, The project is on Django 1.8 right now, so the preferred answer includes migrations. -
django-rest-framework: How to serialize join of database models?
I am working on a simple project for selling products from a website for which the model definition is as follows: class Product(models.Model): """ Model for Products """ price = models.FloatField() description = models.TextField() url = models.CharField(max_length=200) def __str__(self): return self.description class Order(models.Model): """ Model for Orders """ UNPAID = 0 PAID = 1 FAILED = 2 STATUS = ( (UNPAID, 'UNPAID'), (PAID, 'PAID'), (FAILED, 'FAILED'), ) user = models.ForeignKey(User) product = models.ForeignKey(Product) orderdate = models.DateTimeField() token = models.CharField(max_length=30) paymentstatus = models.IntegerField(choices=STATUS) Correspondingly the Serializers are defined as following: class ProductSerializer(serializers.ModelSerializer): """ Serialize Product list """ class Meta: """ Metadata for Product Serializationt to expose API """ model = Product fields = ('id', 'price', 'description', 'url') class OrderSerializer(serializers.ModelSerializer): """ Serialize Order of Product """ class Meta: """ Order metadata """ model = Order fields = ('id', 'user', 'orderdate', 'token', 'paymentstatus', 'product') class OrderDetailSerializer(serializers.ModelSerializer): """ Serialize Order Details """ product = ProductSerializer(read_only=True) class Meta: """ Order metadata """ model = Order fields = ('id', 'user', 'orderdate', 'paymentstatus', 'product') In the above example, is it possible to combine OrderSerializer and OrderDetailsSerializer into a single serializer ? I use the OrderSerializer when the user places a new Order i.e writes to database and … -
Django Ajax 'GET'
newbie here. I am trying to get some data from my database using ajax. In my views.py, def getEvents(request): eventList = Events.objects.all() events=[] for event in eventList: events.append({"name": event.name, "start": event.start, "end": event.end}) return HttpResponse(events, content_type="application/json") Note that Events is the model that I am trying to parse. After I collect the data from this model, I want to return it to my template using the following ajax code: $.ajax({ url: 'getEvents/', datatype: 'json', type: 'GET', sucess: function(data) { alert(data.name); } }); In my urls.py: url(r'^getEvents/', views.getEvents, name='getEvents'), However, I think I am doing something wrong because it doesn't work. I have been stuck on this for hours...Any ideas? -
How to run Django test as specific user
I am new to Django and need to write some API tests. The views that I am testing have the decorator @permission_classes((permissions.IsAdminUser,)) I am using TestCase and Client. Would Admin already be "logged in" for the test or do I need to somehow set the user to Admin? Thanks -
Django translation reverse
Is it possible to get msgid from msgstr? Suppose I have msgid "Table" msgstr "Tisch" If active language is German is there any function to execute inverse_ugettext('Tisch') -> Table? -
python3.5 on heroku doesn't work
I am trying deploy django using heroku. When I type "git push heroku master" All the traceback in this picture. Accoring to this traceback it seemed to tried import markdown_deux in but no module named 'markdown_deux. I check my pip list and this module is django-markdown-deux and I have installed So I don't know why caused the error.Thank you. -
Rendering a table of values with ManyToMany relationships
I have the following models class Sport(models.Model): name = models.CharField(max_length=200) class Week(models.Model): name = models.CharField(max_length=200) class Field(models.Model): name = models.CharField(max_length=200) sports = models.ManyToManyField(Sport) weeks = models.ManyToManyField(Week) class Event(models.Model): name = models.CharField(max_length=200) field = models.ForeignKey(Field) sport = models.ForeignKey(Sport) week = models.ForeignKey(Week) I need to render the table like so: table { margin: 2em 0; border-collapse: collapse; } th, td { padding: 10px; border: 1px solid #000; } <table> <tr> <th rowspan="4"><b>Field1</b> </th> <th><b>Week</b> </th> <th><b>Football</b> </th> <th><b>Baseball</b> </th> <th><b>Soccer</b> </th> </tr> <tr> <td>Week1</td> <td>a</td> <td>b</td> <td>c</td> </tr> <tr> <td>Week2</td> <td>-</td> <td>d</td> <td>e</td> </tr> <tr> <td>Week3</td> <td>f</td> <td>g</td> <td>-</td> </tr> </table> <table> <tr> <th rowspan="4"><b>Field2</b> </th> <th><b>Week</b> </th> <th><b>Football</b> </th> <th><b>Baseball</b> </th> <th><b>Soccer</b> </th> </tr> <tr> <td>Week1</td> <td>h</td> <td>-</td> <td>i</td> </tr> <tr> <td>Week2</td> <td>j</td> <td>k</td> <td>l</td> </tr> <tr> <td>Week3</td> <td>-</td> <td>-</td> <td>-</td> </tr> </table> <table> <tr> <th rowspan="4"><b>Field3</b> </th> <th><b>Week</b> </th> <th><b>Football</b> </th> <th><b>Baseball</b> </th> <th><b>Soccer</b> </th> </tr> <tr> <td>Week1</td> <td>m</td> <td>n</td> <td>o</td> </tr> <tr> <td>Week2</td> <td>-</td> <td>-</td> <td>-</td> </tr> <tr> <td>Week3</td> <td>-</td> <td>-</td> <td>-</td> </tr> </table> The issue i'm facing is, when it comes time to show an event for a given week and sport on a given field, django has no mechanism for performing that query when it gets there. … -
How should I test Celery in Django unit tests?
When running tests in Django applications that make use of Celery tasks I can't fully test tasks that need to get data from the database since they don't connect to the test database that Django creates. Setting task_always_eager in Celery to True solves this problem but as the documentation for testing says, this doesn't fully reflect how the code will run on a real Celery worker and isn't suitable for testing. How can I test Celery tasks from a Django application without setting task_always_eager = True? -
How to pre-populate field in ModelForm
Here's my Post model which makes up the contents of a user's post: class Post(models.Model): user = models.ForeignKey(User, blank=True, null=True) title = models.TextField(max_length=76) date = models.DateTimeField(auto_now=True) content = models.TextField(null=False, default='') image = models.FileField(null=True, blank=True) category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='1') Here's my form: class PostForm(forms.ModelForm): content = forms.CharField(widget=PagedownWidget) title = forms.TextInput(attrs={'placeholder': 'title'}) class Meta: model = Post fields = [ 'title', 'content', 'category', 'image', 'id', ] And here's my view: def post(request): allauth_login = LoginForm(request.POST or None) allauth_signup = SignupForm(request.POST or None) form_post = PostForm(request.POST, request.FILES) if form_post.is_valid(): category = form_post.cleaned_data['category'] for a, b in CATEGORY_CHOICES: if a == category: category = b form_post.save() return HttpResponseRedirect('/%s' % category) else: form_post = PostForm() context = { 'allauth_login': allauth_login, 'allauth_signup': allauth_signup, 'form_post': form_post } return render(request, 'post.html', context) When the user submits the PostForm to submit a post, how do I automatically set the user field to whoever is posting? -
Prevent circular imports for related object
I have two django models in two files: parent.py from child import Child from django.db import models def Parent(models.Model): name = models.CharField() def createChild(self): return Child() child.py from parent import Parent from django.db import models def Child(models.Model): parent = models.ForeignKey(Parent) However, this would lead to circular imports - is there a better way to organize this to prevent this?