Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django syndication function error
I'm trying to create a custom Django RSS feed using django syndication (actually using django wagtail feeds). I have an error which I think I've identified as stemming from a NoneType object which is returned by the get_object() function inside syndication/views.py. That function is called as part of class Feed() and looks like this: def get_object(self, request, *args, **kwargs): return None That function is called at line 36 but fails because get_object() returns a None object. Can anyone tell me why that might be? I'm missing something about the expected functioning of this. Thanks! -
worker_class egg:gunicorn#gevent VS gevent
I run website project with Django + Gunicorn + Gevent below WSGI. And I try to running command "gunicorn --config gunicorn.conf.py project.wsgi:application". In the gunicorn.conf.py where I set worker_class = 'egg:gunicorn#gevent' as document said(http://docs.gunicorn.org/en/19.0/settings.html). But this configuration file does not work! When I set worker_class = 'gevent' in gunicorn.conf.py which makes project work! Any can tell me What's the problem! Thks!! -
Processing Calculations With TemplateTag Returns None
I have a model Coper and a field that ask user to select whether they need to get price quotes dynamically or not. So if a user selects 'dynamic', the user will get the quote for the product and other charges. So I wrote a template tag that will take the id of the product, filter the currency of the seller and lookup for the rate in another model and finish up the quote. @register.filter(name='get_total_quote') def get_total_quote(value): tap = Coper.objects.get(pk=value) get_cnd = VAM.objects.get(money_code = tap.seller.profile.currency) ratex = get_cnd.money_rate if tap.margin_type == 'plus': percent = tap.margin_figure / 100 addup = ratex * percent total_amt = ratex + addup return total_amt if tap.margin_type == 'minus': percent = tap.margin_figure / 100 addup = ratex * percent total_namt = ratex - addup return total_namt Template {% load quote_filter %} {% for m in all_quotes %} {% if m.pricing == 'dynamic' %} {{m.id|get_total_quote }} {% else %} <p> Fixed price is $3500 </p> {% endif %} {% empty %} <p> No product yet. </p> {% endfor %} When I load the site, I got NONE as the price of the dynamic quote instead of the actual figure. What am I missing? -
How to create mysite.wsgi file?
I am following this tutorial http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html to setup django with nginx and uwsgi. But I am confused about this line: uwsgi --http :8000 --module mysite.wsgi In the tutorial there's nothing about mysite.wsgi file. What should be the content of this file? -
Fetching specific value for nested object in a queryset for serializing
I have two models in my django project which are Followup and User, every followup has a user instance mapped to it [actor field]. What happens is when I run this code I get the primary key for actors by default I need to get the first_name field which is in user model for all the rows fetched from followups result = Followup.objects.filter(lead_name = lead).only('lead_name','followup','comments','actor') plan = PlanType.objects.filter(lead_id = lead) response["followup"] = serializers.serialize('json', result) -
OperationalError during django migration postgres on large tables
Sometimes during migrations in django on big tables (>50 millions rows) i receive the following error: Traceback: Traceback (most recent call last): File "src/audit/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/operations/fields.py", line 86, in database_forwards field, File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/schema.py", line 439, in add_field self.execute(sql) File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.5/dist-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python3.5/dist-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) django.db.utils.OperationalError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. Can … -
Django - manytomany field with though and foreign key dont show user data why?
Im trying to get data from the user's model from another model, that is between the both to models. My main model is Team from there there's a members field that is a manytomany field where it's going through its own model called team memberships that has 3 fields where one is a relation to a user. Short saying: Calling model.Teams -> field.membersmanytomany -> model.TeamMembership -> field.userforeignkey -> model.users -> getting info But every time im trying it I don't get any info, why? My Models: Users model is standard from Django. class Team(models.Model): name = models.CharField(max_length=16) logo = models.ImageField(upload_to='teams/avatars', default='static/img/userpreload.png') background = models.ImageField(upload_to='teams/backgrounds', default='static/img/userpreload.png') description = models.TextField(blank=True) people_needed = models.PositiveSmallIntegerField() members = models.ManyToManyField(User, through='TeamMembership') accepts_applications = models.BooleanField() @property def teamleaders_listable(self): leaders = self.members.filter(teammembership__leader=True) return ", ".join(l.extendeduser.nickname for l in leaders) @property def multiple_teamleaders(self): if len(self.members.filter(teammembership__leader=True)) > 1: return True else: return False def __str__(self): return self.name class TeamMembership(models.Model): user = models.ForeignKey(User) team = models.ForeignKey(Team) leader = models.BooleanField() My View: def team(request, team_pk): requested_team = get_object_or_404(Team, pk=team_pk) feedback = FeedbackSupportForm() context = { 'requested_team': requested_team, 'feedback': feedback, } if requested_team.multiple_teamleaders: context["multiple_teamleaders"] = True if request.user.is_authenticated(): if requested_team.members.all().count() > 0: context['teamhasmembers'] = True logged_in_user = get_object_or_404(User, pk=request.user.pk) context['logged_in_user'] = logged_in_user return … -
Django: Why does this test fail?
I an new to Django and to Test Driven Devolopment as well. After working through the tutorials in the 1.11 official documentation I am starting my first app: wos_2017_2 This test fails and I cannot figure out why: import unittest from django.test import TestCase from django.test import Client from .models import * from .views import * class SimpleTest(unittest.TestCase): def test_index(self): client = Client() response = client.get('/') self.assertEqual(response.status_code, 200) FAIL: test_index (wos_2017_2.tests.SimpleTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/js/django/wos/wos_2017_2/tests.py", line 16, in test_index self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 This link in the browser works without a problem: http://localhost:8000/wos_2017_2/ In the shell (run from the project root): >>> from django.test import Client >>> client = Client() >>> response = client.get('/') >>> response = client.get('wos_2017_2/index') Not Found: /wos_2017_2index >>> response = client.get('wos_2017_2/') Not Found: /wos_2017_2 >>> response = client.get('/wos_2017_2/') >>> response = client.get('/wos_2017_2/index/') Not Found: /wos_2017_2/index/ >>> response = client.get('/wos_2017_2/') >>> response.status_code 200 in wos_2017_1.urls.py: from . import views from django.conf.urls import url urlpatterns = [ url(r'^$', views.index, name='index'), ] -
Python hendrix : hx start command doesn't work / python run.py works
My problem is "hx start" command is not working. It displays the output "Ready and Listening on port 8000..." but the demo my_noodle (https://github.com/jMyles/hendrix-demo-django-nyc) is not working : a view is displayed but the websocket got a 404 error. However, when I do "python run.py" instead of hx start--dev, it works but I guess it's not a production way to start hendrix server. What do you think of that ? Is it normal ? How to make hx start commands working ? Is python run.py a good way to start a production server ? -
Experiencing TypeError (expected string or Unicode object, NoneType found) when saving a form instance to request.session
I'm running into trouble trying to save an instance of a form class in Django's request.session dictionary. I get TypeError: expected string or Unicode object, NoneType found. The whole traceback being: File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in get_response response = middleware_method(request, response) File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/newrelic-2.56.0.42/newrelic/hooks/framework_django.py", line 331, in wrapper return wrapped(*args, **kwargs) File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/user_sessions/middleware.py", line 46, in process_response request.session.save() File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/user_sessions/backends/db.py", line 73, in save session_data=self.encode(self._get_session(no_load=must_create)), File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py", line 86, in encode pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL) TypeError: expected string or Unicode object, NoneType found What's the scenario? I'm testing form validation for image uploading. I'm disallowing file sizes beyond a certain limit, raising a validation error. The form instance bound to request.POST is saved in request.session, e.g.: form = PhotoForm(request.POST,request.FILES)) request.session["photo_form"] = form request.session.modified = True and then I redirect to a different view to use the said form instance. I've noticed all this works successfully most of the times, but for certain very, very big files where I'm supposed to raise a validation error, I instead get the error shown above. Not all validation errors result in this. For now, the pattern is that only extremely large files induce this. I can't make sense of that. Can anyone shed light on … -
how to start gunicorn automatically in server with Ubuntu 16.04
client name is siar , unroot here is my idea: 1 sudo mkdir -p /usr/lib/systemd/system 2 sudo vim /usr/lib/systemd/system/siar.service and it's context: [Unit] After=syslog.target network.target remote-fs.target nss-lookup.target [Service] # 你的用户 User=siar # 你的目录 WorkingDirectory=/home/siar/sites/django-blog-learning/blogproject # gunicorn启动命令 ExecStart=/home/siar/sites/env/bin/gunicorn --bind unix:/tmp/siar.socket blogproject.wsgi:application Restart=on-failure [Install] WantedBy=multi-user.target 3 sudo systemctl start siar and here i get error: Failed to start siar.service: Launch helper exited with unknown return code 1 See system logs and 'systemctl status siar.service' for details. andthen i try sudo systemctl start other .server'file here has the same error. i was confused and please you help me -
Is it possible to bundle Django web apps with Nuitka?
I want to bundle a python web app based on Django for off-internet business usage. I found Nuitka maybe suitable for such problem. -
Execute task on specific time in Django
I have to execute a task at a specific time, which is specified by the user. This will not be fix time... It will be according to user... On that time I have to execute my task... To achieve this I tried to use django-cron also tried to use django-crontab... But in both case either we have to specify cron details in settings.py or we've to execute runcron commands. I also checked django-celery (I don't have any idea about celery much. I may be wrong). In celery we have to specify time while defining task... Can any one help me how can I do this... I am using django as a backend... -
How to extend my django web application with a wordpress blog?
I have a Django web application at https://www.reelbugs.com I need to extend the application to have a blog of static content at https://reelbugs.com/blog I can create a Blogpost model, comment system, etc myself, but I'd rather have a good premium Wordpress template with Disqus, etc plugins for my blog. How can I go forward with this? Any hints would help. -
Inner loop on condition in list comprehension
I have a function to check availability of product and its variations. both model has quantity_left field. If a product has variations i want to get quantity_left from variation, otherwise i will take quantity_left from product. def check_quota(products): q_list = [] for p in products: if p.has_variations: for v in p.variations: q_list.append(v.quantity_left) else: q_list.append(p.quantity_left) return sum(q_list) So above function will return either 0 or any number. if it is zero means product sold out. Above code is working fine, but i want to optimize this function using list comprehension. I tried this but this doesn't seems to work. return sum([v.quantity_left if p.has_variations else p.quantity_left for p in products for v in i.variations]) How can i apply if p.has_variations on inner loop. -
MultiValueField returning data back to field
I have made a custom widget that holds a TextInput() and Select() fields, which looks like so: Now I'm struggling to get this working with the data that is captured. As of now i can input 12 days and the data will appear in the models as 12 days But i have had it as [u'12', u'days'] before. So my problem is the fields text not displaying again once saved. It will save completly fine but it will not render the data like it should back in the widget. class LeadTimeWidget(MultiWidget): def __init__(self, attrs=None): CHOICES = (('Days', 'Days'), ('Weeks', 'Weeks'), ('Months', 'Months'),) widgets = (forms.TextInput(), forms.Select(choices=CHOICES)) super(LeadTimeWidget, self).__init__(widgets, attrs) def decompress(self, value): if value: return value.split(' ') return [None, None] class LeadTimeMultiField(MultiValueField): widget = LeadTimeWidget # TODO struggling to convert data recieved from widget to a usable format def __init__(self, *args, **kwargs): list_fields = (forms.fields.CharField(max_length=31), forms.fields.CharField(max_length=31)) super(LeadTimeMultiField, self).__init__(list_fields, *args, **kwargs) def compress(self, data_list): return ' '.join(data_list) Can anyone help me understand and fix the issue as to why its not rendering like it should be? Thanks J -
django url issue using mutiple regular expressions
I am having an issue with an url and regular expression I get the error AttributeError: Generic detail view EmployeeDetailView must be called with either an object pk or a slug. What I am to achieve is to get to a user detail page coming from a specific project url(r'^project/(?P<pk>[0-9]+)/$',views.ProjectDetailView.as_view(), name='ProjectDetails'), url(r'^project/(?P<pk1>[0-9]+)/(?P<pk2>[0-9]+)/$',views.EmployeeDetailView.as_view(), name='EmployeDetails'), my view is : Project detail : class ProjectDetailView(generic.DetailView, LoginRequiredMixin): #import pdb; pdb.set_trace() model = Project template_name = 'project_details.html' def get_context_data(self, **kwargs): context = super(ProjectDetailView, self).get_context_data(**kwargs) try: team_name = Project.objects.get(id=self.kwargs['pk']).team_id.members.all() context['team_name'] = team_name except AttributeError: pass return context class EmployeeDetailView(generic.DetailView, LoginRequiredMixin): #import pdb; pdb.set_trace() model = MyUser template_name = 'Employee_Details.html' def get_context_data(self, **kwargs): context = super(EmployeeDetailView, self).get_context_data(**kwargs) employee_name = MyUser.objects.get(id=self.kwargs['pk']) context['employee_name'] = employee_name return context HTML link : <span class="fa fa-id-card-o" aria-hidden="true"><a href="{% url 'website:EmployeDetails' pk1 = project.id pk2 = member.id %}"> Show Results</a> could you please help me to figure it ? thx you ;) -
Can I combine view functions in one view class?
Below I have included two view functions that I am currently working with. I was thinking that since both functions operate on the same template that it would be wise to combine them. Can i just put a class decorator above these functions? Is the functionality then still the same? My main point is that one function only takes 'request' but the other takes 'request and 'slug' in its function. @login_required(login_url='/') def choose(request): if request.method == 'POST': print(request.POST.get) # Make a shoplist model instance, # define title, # define user as author, # define slug, # save budget value from the Budget view # save dagen value from the Budget view # save shoplist shoplist = Shoplist() shoplist.title = str(make_aware(datetime.now(), timezone=None, is_dst=None)) shoplist.author = request.user shoplist.slug = slugify(str(shoplist.author) + '-' + shoplist.title) shoplist.budget = request.POST.get('budget') shoplist.dagen = request.POST.get('dagen') shoplist.vegetarisch = request.POST.get('vegetarisch') shoplist.save() # Get recipes from database and POST data form previous view if request.POST.get('vegetarisch') == 'True': recipes = Recipe.objects.filter(vegetarisch=True).all() else: recipes = Recipe.objects.all() budget = shoplist.budget dagen = shoplist.dagen template = loader.get_template('recipes/choose.html') c = {'object_list': recipes, 'budget': budget, 'dagen': dagen} return HttpResponse(template.render(c)) else: return HttpResponseNotAllowed('GET') @login_required(login_url='/') def add_to_shoplist(request, slug): # Get the shoplist that is made in the choose … -
AttributeError: 'module' object has no attribute '__file__'
import google google.file Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'file' -
Django: jQuery autocomplete with multiple queryset
I am trying to code an autocomplete for django which would display multiple queryset instead of a single list, an example of another site that have this implementation can be found here: https://www.uala.it/ Now i was able to send in a queryset the objects of two model: def multi_autocomplete(request): if request.is_ajax(): # In base a cosa sta scrivendo l'utente mostro un set di aziende. query = request.GET.get("term", "") companies = Company.objects.filter(name__icontains=query) treatments = Treatment.objects.filter(name__icontains=query) results = [] for company in companies: place_json = company.name results.append(place_json) for treatment in treatments: place_json = treatment.name results.append(place_json) data = json.dumps(results) return HttpResponse(data, "application/json") As you can see i'm returning the json.dumps with the data from the two models, how can I change the ui to show the values in different columns like in the link i provided? -
Unable to reference HTML values in Javascript
I am building a Django app and need to do some Javascript processing in the HTML Template. In order to pass values from Django's templating language into Javascript, I have saved the values into meta tags as below: <head> {% for candidate in candidates %} <meta id="cand" data-id="{{candidate.id}}" data-order="{{forloop.counter}}"> <h3>{{forloop.counter}}</h3> {% endfor %} </head> I then try to access the data here: <script type="text/javascript"> var metatags = document.getElementsByTagName('meta'); for (var i = 0; i < metatags.length; i++) { console.log(metatags[i].data-id) } </script> However, an issue is thrown trying to access the data: Uncaught ReferenceError: id is not defined In reference to the line console.log(metatags[i].data-id) Why is this not working, am I attempting something impossible, and is there a better or more elegant way of accessing template values in Javascript? Thanks in advance. -
How create REVERT opportunity in django-reversion app?
I have task to rewrite correct Function Based View to Class Based View. Below you can see my code. My question is whats wrong with my Class Based View? It raise error. Where is my mistake? FBV: @reversion.create_revision() def article_revert(request, pk, article_reversion_id): article = get_object_or_404(Article, pk=pk) revision = get_object_or_404(Version.objects.get_for_object(article), pk=article_reversion_id).revision reversion.set_user(request.user) reversion.set_comment("REVERT to version: {}".format(revision.id)) revision.revert() return redirect('project:article_list') CBV: class ArticleRevert(RevisionMixin, View): model = Article def get(self, request, *args, **kwargs): article = get_object_or_404(Article, pk=pk) revision = get_object_or_404(Version.objects.get_for_object(article), pk=article_reversion_id).revision reversion.set_comment("REVERT to version: {}".format(revision.id)) revision.revert() return redirect('project:article_list') When I use CBV it raise next error: Traceback (most recent call last): File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/reversion/views.py", line 43, in do_revision_view return func(request, *args, **kwargs) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/Applications/Projects/web/project/article/views.py", line 166, in get reversion.set_comment("REVERT to version: {}".format(revision.id)) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/reversion/revisions.py", line 122, in set_comment _update_frame(comment=comment) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/reversion/revisions.py", line 87, in _update_frame _local.stack = _local.stack[:-1] + (_current_frame()._replace(**kwargs),) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/reversion/revisions.py", line 53, in _current_frame raise RevisionManagementError("There is no active revision for this … -
Create django form from ajax request
I have a cutom form of the following outline: class NewTestForm(forms.ModelForm): class Meta: model = TestModel fields = ['field1', 'field2'] and i want to use it in a view def post(self, request): self.form = NewTestForm(request.POST) form_instance= self.form.instance ... i'm submitting it using ajax $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize(), But the data of the form is not available in NewTestForm(request.POST), because ajax request has different structure, than the regular form submit, i think. How is it possible to create new form from request made by ajax. I've tried to do this like $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: {'data': frm.serialize()}, dataType: "application/json", headers: {"X-CSRFToken": getCookie('csrftoken')}, and get data in a view like self.form = NewTestForm(request.POST.get('data')) but no effect. -
Error in django-app-metrics
I am using django-app-metrics for recording some metrics in my webapp. I using python3 and i installed app-metrics using following command - pip3 install django-app-metrics. But when I am importing from app_metrics.utils import create_metric it is giving me this error : File "/usr/local/lib/python3.6/site-packages/app_metrics/utils.py", line 92 except Exception, e ^ SyntaxError: invalid syntax Can someone tell me what i am doing wrong ? -
If I try to call multiple methods from django views sequentially with ajax, only the last call's response is returned
Hi everyone, I am building a web application in django, that takes a file from the user, processes it server side, zips the results and downloads the zip file to the user. The downloading part is done with an ajax call from a template. After downloading the file, I would like to delete it from the server, so I made a method called clean_up, that wipes all folders. Ajax call from the template: (I tried other things too, like calling window.location in the complete() part with no success. If I only run the first ajax call, that works, the two together do not, but the logger.debug prints the messages in my command line, so I know the methods are called and run, just the response is not returned) function my_download() { $.ajax({ url: '/ymap_webtool/result', type: "GET", data: { }, success: function (data) { alert("The browser is now going to download the results") window.location = '/ymap_webtool/result'; }, complete: function () { }, error: function () { } }).then($.ajax({ url: '/ymap_webtool/clean_up', type: "GET", data: {}, success: function (data) { window.location.href = '/ymap_webtool/clean_up'; }, complete: function () { }, error: function () { window.location.href = '/ymap_webtool/submission_failed'; } })); }; Called methods from the …