Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I filter and count objects in DJANGO template?
Hello I justa want to ask this because Im new in django, my trouble is that i want to count how many comments have a post and put it in to the html template. But the thing is that im using for to gather all the events in the db, but i just want to show only the count of comments that have every event that the "for" are showing. this is my models, view, and template. Thank you so much. MODELS class Event(TimeStampModel): name = models.CharField(max_length=200, unique=True) slug = models.SlugField(editable=False) summary = models.TextField(max_length=255) content = models.TextField() category = models.ForeignKey(Category) place = models.CharField(max_length=50) start = models.DateTimeField() finish = models.DateTimeField() image = models.ImageField(upload_to = 'eventos') is_free = models.BooleanField(default=True) amount = models.DecimalField(max_digits=6, decimal_places=0, default=0) views = models.PositiveIntegerField(default=0) organizer = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.name) super(Event, self).save(*args, **kwargs) def __unicode__(self): return self.name class Comments(TimeStampModel): user = models.ForeignKey(settings.AUTH_USER_MODEL) event = models.ForeignKey(Event) content = models.TextField() def __unicode__(self): return "%s %s" % (self.user.username, self.event.name) VIEW class IndexView(TemplateView): template_name = 'eventos/index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['events'] = Event.objects.all().order_by('-created')[:6] context['categories'] = Category.objects.all() context['comments'] = Comments.objects.all() return context HTML TEMPLATE {% for event in events %} <li class="span4 … -
Mounting a ProxyPass site at the same root url as wordpress
We have a site that is currently running on Wordpress. We are developing a Django site to replace it. Overtime, the goal is to slowly replace parts of the Wordpress site with Django. We would typically set this up for Django something like this: ProxyPass /newcontent/static ! ProxyPass /newcontent uwsgi://127.0.0.1:3031/ retry=0 ProxyPassReverse /newcontent uwsgi://127.0.0.1:3031/newcontent/ retry=0 This will mount the Django/uWSGI app at ourwebsite.com/newcontent. However, this means that all Django URLs will begin at that root, so something like ourwebsite.com/newcontent/aboutus. Is there a way to configure Apache where all requests would go to Wordpress, unless specifically indicated in the conf? I can imagine that making numerous uWSGI entries would be one way to do it, but then Django is seeing all sorts of base paths, which doesn't work so well internally. In the end, it would be best if I could do something like: # Normal Wordpress config, DirectoryIndex, etc # Django Specific Stuff /about-us # Goes to Django /admin/* # Django admin /our-products/* # This and all subpaths to Django /static/* # Same, all static content Additionally, we serve httpS always on Django sites, so It would be preferable to also redirect any Django served URLs to https within Apache. … -
How to use reddit api in Django?
Is this even possible? Where should I put a code for it? In views.py or stand-alone file? However deserializing a json/xml could be an option but I dont know where and how to put it -
mezzanine cms: can the values of meta fields in the form page be saved in database?
I am new to mezzanines cms. I have some questions about the form page. In the admin interface, I added a form page. On the bottom of the form page, there is a "meta" section which I can add some fields to the form page I created. My questions are: 1) for the meta fields I added, can I save the values of the fields in the database? 2) can the meta fields be from a database table fields? For example, I have a user profile model, can I use the fields in the profile model as meta fields in the form page? and how? 3) what are the purposes of the form page in mezzanine cms? Thank you! -
Django get all ManyToMany relationships of an object
All my models have several ManyToMany relationships with other models and themselves, and they all have a "through" table Let's say I have model A , that has a ManyToManyField with model B and C, let's also consider the field name is the same as the related model And I have model D that has a ManyToManyField with model A. Now, I want to get all objects related to an A object of classes B, C and D This is what I had tried : a1 = A.objects.get(pk = 1) #Get all B objects related to A a1.b.all() #Get all C objects related to A a1.c.all() #Get all D objects related to A but from D class because that's where the field is #Raises error 'ManyToManyDescriptor' object has no attribute 'all' D.a.all(pk=1) Actual models can be found here : http://pastebin.com/UQxwpbdN (My problem is with Pessoa and CCir) -
How to use landing pages (bootstrap) in a Django project?
I'm working on a Dajngo project and I want to include a landing page to use it for home page, I was trying to use it on my own and guiding me in tutorials but I could not get it to load the CSS style. I am new using this framework (bootstrap), could anyone help me identify my error to load the CSS style please? Files: setting.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crm', #app's name 'bootstrap3', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') LOGIN_REDIRECT_URL = '/' mysite\urls.py from django.conf.urls import include, url from django.contrib import admin from django.views.generic.base import RedirectView#TemplateView from django.core.urlresolvers import reverse from django.shortcuts import redirect from crm import views admin.autodiscover() urlpatterns = [ url(r'^$', views.HomePageView.as_view()), url(r'^admin/', include(admin.site.urls)), url(r'', include('crm.urls')), ] crm\urls.py from django.conf.urls import url, include from django.contrib import admin from crm import views urlpatterns = [ url(r'^$', views.HomePageView.as_view()), url(r'^admin/', admin.site.urls), url(r'^', include('crm.urls')), ] crm\views.py from django.shortcuts import render from django.views.generic import TemplateView # Create your views here. class HomePageView(TemplateView): def get(self, request, **kwargs): return render(request, 'crm/index.html', context=None) In my … -
Learning DRF: Serialize models in a group
I'm new to both Django and DRF. I need to expose the following JSON via GET, but I seem to be having trouble getting each class to be a part of classes []. I belive I can use StringRelatedField for this, but the examples I have found don't seem to click with me. Thanks in advance! { "classes":[ { "id":24, "name":"Math 101", "starts_on":"2016-08-09", "ends_on":"2016-08-14", "entries_url":"https://example.com/classes/24/classes.json" }, { "id":23, "name":"English 101", "starts_on":"2016-07-28", "ends_on":"2016-07-30", "entries_url":"https://example.com/classes/23/classes.json" } ] } -
How to Repopulate Django ChoiceField Out-of-Band If Another ChoiceField Changes?
I have a Django form that displays the country and state/province/region that the user lives in. In this form, I display all the countries in a form ChoiceField called 'country' using a Select widget that I pre-populate from a list. If the user lives in either the United States or Canada, I'll create another form ChoiceField called 'region' that also uses a Select widget and which I pre-populate using either a list of US states or Canadian provinces. The form label for either of these fields is "State" or "Province" respectively. If the user is from any other country, I represent the region field as a CharField using a TextInput widget and I allow them to optionally enter a region name in this field. Its label is "State/Province/Region". When the user first comes to this page, I know the country they're in so I prepopulate the country and region fields appropriately. Here are my requirements but I'm not sure how to implement them in Django. If the user is in the US and changes the country pulldown to Canada, I'd like to go "out-of-band" back to the server, fetch the list of Canada's regions, and repopulate the region pulldown with … -
Transaction of multiple table in different views using django
I am creating an ordering system, I want to let the users order some goods from our store and during their ordering I want to reserve the goods they choose for them which nobody could not take that one, but they can remove a good from their basket or add any other good to their basket. This could be a simple example: class DeliverTools(models.Model): name = models.CharField(max_length=20) total_quantity = models.PositiveIntegerField() product = models.ForeignKey('Product') class Product(models.Model): name = models.CharField(max_length=20) total_quantity = models.PositiveIntegerField() class Order(models.Model): person = models.CharField(max_length=20) peoducts = models.ManyToManyField(Product) In this example assume that a person are searching through a site and fill his basket, during this task I want that my tables were updated depend on each user order even they do not accept their orders. I want to use a transaction on some tables(Product and delivery tools) that record the quantity of store`s good and other related data between intermediary tables. Because a costumer can cancel the order or change the order completely I must be able to roll back all tables to their initial state. I know that this could be possible using manual coding but I'm looking for a nicer and more standard way. I have … -
How can I run django using apache2?
I'm trying to run django on apache2 using mod_wsgi, but when I'm trying to connect "locatoka.ru" I get "Forbidden You don't have permission to access / on this server." My actions: I added to httpd.conf LoadModule wsgi_module /usr/local/Cellar/mod_wsgi/3.2/libexec/mod_wsgi.so changed httpd.conf WSGIScriptAlias / /Users/Loginov/Desktop/project/project/wsgi.py <VirtualHost locatoka.ru:80> ServerName locatoka.ru ServerAlias www.locatoka.ru DocumentRoot "/Users/Loginov/Desktop/project" <Directory /Users/Loginov/Desktop/project/project> <Files wsgi.py> Order deny,allow Require all granted </Files> </Directory> </VirtualHost> wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") application = get_wsgi_application() I'm using Mac OS X EI Capitan and python3. It is my first attempt to do something on django, so it would be nice if you explain me. Please help to solve this problem. Thanks in advance. -
Django: UpdateView - dispatch : reduce the number of queries
I have a Product Model, foreign key to Company Model, onetoone key to User. I override the dispatch(method) to check if the user has rights to edit the object(product). I'm trying to optimize the queries to the database because some of them are duplicates. def dispatch(self, request, *args, **kwargs): obj = self.get_object() if obj.company.user != request.user: raise PermissionDenied else: print('ok') return super().dispatch(request, *args, *kwargs) query to products obj = self.get_object() query to company and query to user twice if obj.company.user != request.user: query to products again return super().dispatch(request, *args, *kwargs) How can I optimize and remove duplicated queries ? -
Using RedShift as an additional Django Database
I have two Databases defined, default which is a regular MySQL backend and RedShift (using a postgres backend). This works fine until makemigrations is called—because Django tries (and fails) to create a django_migrations table in RedShift. See: Column 'django_migrations.id' has unsupported type 'serial' [ with Amazon Redshift] I understand that this is an atypical use case but I'm simply doing it just to have the convenience of the ORM for a management command. I imagine that it would be a similar use case to a read-replica. So my question is, how do you completely disable Django Management for a database? Things I've Tried: Created a Router which returns False for allow_migrate() when the db == 'redshift' -
How to display only ID field Django
I would like to solve a little problem with Django and QuerySet. I have in my views this command : query_car = Car.objects.get(pk=value) But I want to get only one field from the CarModels, for example : color or another one but just one. How I can handle my script in order to do that ? Thank you so much ! -
Using Django's ImageField, how to store files in STATIC_ROOT?
Using Django's ImageField(), how would I store the image file in STATIC_ROOT rather than MEDIA_ROOT? I realise this is a bad idea for images which are uploaded through the admin, but these images are stored with the rest of the code in git, and attached to the objects when the site is set up using a script which imports all the objects' data. The images are not added/edited/deleted after this. -
Django Session variables not updating properly
I am trying to figure out how sessions work. Basically I am trying to make a restaurant menu and store ordered food into session for further use. However, I ran into a problem and I cant figure out what might be the problem. The problem is that if I submit the form 1st time. The success view shows the correct data. I click Submit (pridat) and it works correctly The output is: ('2', 1) Where number 2 is food ID and 1 is the quantity. Then I go back to the menu and I want to update the quantity to lets say 3 I change quantity (mnozstvo) to 3 and submit But the output is still: ('2', 1) The weirdest thing that has me confused is the fact that for example different food, even though it should be generated the same way works and updates just fine. If I want to "order" multiple things it works fine with some and sometime one or multiple just refuse to update properly. As I am writing this 3 out of 4 works just fine. ('3', 5)('4', 8)('1', 15)('2', 1) I can change 3-5, 4-8 and 1-15 but the 2-1 just never ever changes. … -
Django, ManyToManyField(model) while defining model
I'm new to Django and I've encountered some problem: I'm trying to prepare website where users can attach themselves to custom model "UserGroup" (not these from User.group) so they'll become it's members as ManyToManyField relation. But I would like also to add information to these groups whether they're linked to other groups. How can do such thing? I've tried to do this like here, in UserGroup definition: related_groups = models.ManyToManyField('UserGroup', blank=True) But apparently I can't do that this way, I'm getting some problems during migration: django.core.exceptions.FieldDoesNotExist: UserGroup_related_groups has no field named 'from_usergroup' I suppose it might be because of faulty way of thinking. Thanks for help in advance! :) -
Django: Send SMTP Email Through office365 from GoDaddy
There is a similar question here but apparently the settings are not working. I have used the settings here as well and I get Service unavailable error when I try sending an email. My settings. EMAIL_HOST = 'smtp.office365.com' EMAIL_HOST_USER = 'admin@******.com' EMAIL_HOST_PASSWORD = '********' EMAIL_PORT = 587 EMAIL_USE_TLS = True I get SMTPServerDisconnected at /contact-us/ Service unavailable -
Django - UnicodeEncodeError in Production Environment with Apache
I've a Django application in production that is throwing the following error: 'ascii' codec can't encode character u'\xe9' in position 97: ordinal not in range(128) Unicode error hint The string that could not be encoded/decoded was: P Gen@rica. P Gen@rica is part of the name of an uploaded file. The code where the error appears is this: files_list = [uuid_temp_files + '/' + f for f in os.listdir(uuid_temp_files) if os.path.isfile(os.path.join(uuid_temp_files, f))] In my Development machine everything is OK, I can add accented filenames to the names of files. Any clues on what the causes of this error in the production environment? Could be some Apache configuration? Best Regards, -
Error in sending mail using outlook rest api in python
I am using the following code to send an email using outlook rest api in python. outlookservice.py import requests import uuid import json outlook_api_endpoint = 'https://outlook.office.com/api/v2.0{0}' # Generic API Sending def make_api_call(method, url, token, user_email, payload = None, parameters = None): # Send these headers with all API calls headers = { 'User-Agent' : 'python_tutorial/1.0', 'Authorization' : 'Bearer {0}'.format(token), 'Accept' : 'application/json', 'X-AnchorMailbox' : user_email } # Use these headers to instrument calls. Makes it easier # to correlate requests and responses in case of problems # and is a recommended best practice. request_id = str(uuid.uuid4()) instrumentation = { 'client-request-id' : request_id, 'return-client-request-id' : 'true' } headers.update(instrumentation) response = None if (method.upper() == 'GET'): response = requests.get(url, headers = headers, params = parameters) elif (method.upper() == 'DELETE'): response = requests.delete(url, headers = headers, params = parameters) elif (method.upper() == 'PATCH'): headers.update({ 'Content-Type' : 'application/json' }) response = requests.patch(url, headers = headers, data = json.dumps(payload), params = parameters) elif (method.upper() == 'POST'): headers.update({ 'Content-Type' : 'application/json' }) response = requests.post(url, headers = headers, data = json.dumps(payload), params = parameters) return response def get_me(access_token): get_me_url = outlook_api_endpoint.format('/Me') # Use OData query parameters to control the results # - Only return the DisplayName … -
Django dev server web page shuts down every 24 hours
New Django learner here! I have a Django web page that I want to run continuously. This is what I do to start the server in cmd. manage.py runserver 0.0.0.0:80 This starts the server and then I keep it running in the background. When I start working over it the next day, it gives me a connectivity issue which I resolve by Ctrl-C followed by that same runserver command again. Then it works normal again. Bear in mind that I do not lose connectivity to the internet of any sort( if it matters, I guess). Is there a specific setting that keeps doing this and if yes how could I configure it so that I do not have to restart the server every day? FYI, the python code and webpage work fine as expected. Just needed help so that I can avoid the every day task of restarting the server. -
Set and invalid field to None in django rest
I have models.py class Report(models.Model): field_1 = models.Integerfield(blank=True, null=True, validators=[MaxValueValidator(10)]) field_2 = models.Integerfield(blank=True, null=True) serializers.py class ReportSerializer(serializers.ModelSerializer): class Meta: fields = (field_1, field_2) When I try r = ReportSerializer(data={'field_1':0, 'field_2': 50} r.is_valid(True) It raises: {'field_1': ['Ensure this value is greater than or equal to 10.']} Even if field_1 is not required (required=False) I would like my report to be created with field_2 set and field_1 at None but cannot find a way to achieve this properly. What would be a good way to achieve this, ie not raising ValidationError on optionnal fields. -
Hosting local DOJO for django server
This question was probably asked before, but I am not able to find a good answer. I am using DJango and want to host a local DOJO instead of using CDN . I have a copy of dojo located in /share/dojo-release-1.11.2. That folder has subfolders - dijit dojo dojox themes Should I use dojoConfig = {..} ? if so , what is the syntax for it ? Appreciate your help. Thanks ! -
How can I set a table constraint "deferrable initially deferred" in django model?
I am trying to set a constraint to a table model in django with a postgresql database. Reading the django official documentation I have not found anything related. I need something like this: class Meta: unique_together = (('field1', 'field2',), DEFERRABLE INITIALLY DEFERRED) Is it possible to do something like this? -
'views' is not defined in Django 1.10
My app is called courses and I can't import my urls. from django.conf.urls import url from django.contrib import admin from . import views urlpatterns = [ url(r'^courses/', course.urls), url(r'^admin/', admin.site.urls), url(r'^$', views.hello_world), ] And I always get this error NameError: name 'courses' is not defined -
Custom query set in django-admin with taggit
I'd like to take custom queryset, when my tests' Result model is ordered_by and grouped by tags. I use taggit, and relations to tag are: Test > Result, Test > Taggit. So I want to take analytics about results when it is counted, and queryset should give top Tags with biggest count from results.