Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error in python commands after install virtualenv
I had installed python and django whithnout virtualenv and worked with it. Now I have install virtualenv and my python command don't work!!! For example : C:\Users\omid>pip install django Fatal error in launcher: Unable to create process using '"' why this error is display ??? Is problem with virtualenv? -
How to set index page with path function in django 2.0?
Django 2.0 has introduced new path function in django.urls. So I m using path function to set my index page but as far as I know it doesn't accept regular expression.I have tried couple of options as follows path('/',views.index,name='index'), and path('/index',views.index,name='index'), but it gives 404 page not found. So my question is how to set index page site using path function? -
is it possible to append templates in django
I'm trying to display 2 views on the same page (both from different apps) I've imported the views into a third app which I want to use to put the 2 files together. At the moment I'm able to show 1 of the 2 apps. I'm retreving the views of the app like this: def bar(request): # Get the template template = loader.get_template('topbar.html') #render the template and store the outcome in 'render' render = template.render({}, request) #return the rendered template return render after this I can get this view from another app like this: render = bar(request) return HttpResponse(render) this works and the html file is showing nicely but now I want to append the second view (which can be requested in the same way) to the first one. Is this possible? Am I doing it the right way? -
Django RestframeWork Serializer relations , How to get the data of both of One to One Models?
The mode is: class Userinfo(models.Model): class Meta: verbose_name='用户信息' verbose_name_plural='用户信息' user=models.OneToOneField( User, related_name='userinfo', on_delete=models.CASCADE, verbose_name='用户' ) location=models.BooleanField(verbose_name='地点(勾选宏达,否则福年)') And the Restframework Token class: @python_2_unicode_compatible class Token(models.Model): """ The default authorization token model. """ key = models.CharField(_("Key"), max_length=40, primary_key=True) user = models.OneToOneField( settings.AUTH_USER_MODEL, related_name='auth_token', on_delete=models.CASCADE, verbose_name=_("User") ) created = models.DateTimeField(_("Created"), auto_now_add=True) My serializers is: class UserinfoSerializer(serializers.ModelSerializer): class Meta: model=Userinfo fields="__all__" class UserSerializer(serializers.ModelSerializer): class Meta: model=User exclude=('password',) userinfo=UserinfoSerializer() class TokenSerializer(serializers.ModelSerializer): class Meta: model=Token fields = '__all__' depth=3 user = UserSerializer() I want to Response the data of User and the One to One Model Userinfo,but I just get the user. what can I to? Here is my current result,and The userinfo is null, How can I get the userinfo data? { "key": "2012964fb4ffe07dc58c33a64d0ce48bedd34643", "user": { "id": 3, "userinfo": null, "last_login": null, "is_superuser": false, "username": "333", "first_name": "叶同学", "last_name": "", "email": "", "is_staff": false, "is_active": true, "date_joined": "2017-12-08T16:39:00+08:00", "groups": [], "user_permissions": [] }, "created": "2017-12-14T10:40:58.933072+08:00" } -
Type of obj argument in SerializerMethodField DRF
I have this Django REST Framework serializer class: class DoctorMeetingSerializer(serializers.ModelSerializer): doctor_id = serializers.CharField() patient_id = serializers.CharField() meetings_amount = serializers.SerializerMethodField() class Meta: model = CoachingMeeting fields = ( 'id', 'doctor_id', 'patient_id', 'start_time', 'end_time', 'subject', 'meetings_amount', ) read_only_fields = ('zoom_meeting_id', 'is_live', 'meetings_amount',) def get_meetings_amount(self, obj): print(type(obj)) meetings_amount = DoctorMeeting.objects.filter(patient=obj.patient_id).count() return meetings_amount So when I do GET request, print(type(obj)) shows that obj is serializer instance, but then I do POST request, obj becomes an OrderedDict instance and has no 'patient_id' attribute. Why does this object changes its type in different request methods? -
context not rendering in django App
I am driving to render a context scale that is not rendering in my HTML and I can manage to see the error. I do not get any error in the inspect/console and neither in the Atom terminal. I am developing a survey app using a scale from 0-100% (using JavaScript) but for some reason it is not rendering; here is my code: views.py class SurveyDetail(View): def get(self, request, *args, **kwargs): survey = get_object_or_404(Survey, is_published=True, id=kwargs['id']) if survey.template is not None and len(survey.template) > 4: template_name = survey.template else: if survey.display_by_question: template_name = 'survey/survey.html' else: template_name = 'survey/one_page_survey.html' if survey.need_logged_user and not request.user.is_authenticated(): return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) categories = Category.objects.filter(survey=survey).order_by('order') form = ResponseForm(survey=survey, user=request.user, step=kwargs.get('step', 0)) try: get_scale = form.get_multiple_scale() except: get_scale = None context = { 'response_form': form, 'survey': survey, 'categories': categories, 'scales': get_scale } return render(request, template_name, context) form.py: class ResponseForm(models.ModelForm): WIDGETS = { Question.TEXT: forms.Textarea, Question.SHORT_TEXT: forms.TextInput, Question.RADIO: forms.RadioSelect, Question.SELECT: forms.Select, Question.SELECT_IMAGE: ImageSelectWidget, Question.SELECT_MULTIPLE: forms.CheckboxSelectMultiple, Question.SCALE: forms.TextInput, } class Meta(object): model = Response fields = () def __init__(self, *args, **kwargs): """ Expects a survey object to be passed in initially """ self.survey = kwargs.pop('survey') self.user = kwargs.pop('user') try: self.step = int(kwargs.pop('step')) except KeyError: self.step = None … -
How to unsign signed cookie manually
I am using Django version 1.11.2 and using signed cookies for session store. SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies" I am trying to unsign the cookie using python shell using: from django.core import signing signing.loads(".eJxVjk0.....J708kRdRvubY3RME") but I get BadSignature error. May be I am using the signing.loads in wrong way? -
syntax error for manag.py migration error in django
when I try to make migration it shows me a error File "manage.py", line 10 except ImportError: ^ SyntaxError: invalid syntax enter image description here -
Trying to install latest version of Django
In my cmd i was using python2.7 because i have both python 2.7 and python 3.6 installed.I installed django with pip but pip installed django 1.11.11 because i was using python 2.7.I want to use python 3.6 and the latest version of django so im now using python3.6 in the cmd.I uninstalled django and then installed it while using python3.6.But when i tried to install django with pip it said that some directory is not empty.What can i do?I uninstalled django why the directory is not empty? -
How to make django-meta for SEO work in function based views?
I'm working on including SEO meta data in an Open Source project. I'm trying to use django-meta for this. But it's simply not working. The meta tags are not rendering. Here is my view's code: def threadPage(request, topic_title='', thread_id='', slug=''): if topic_title and thread_id: try: topic = Topic.getTopic(topic_title) thread = Thread.objects.get(id=thread_id) if thread.topic == topic: if not slug or slug != thread.slug: return HttpResponseRedirect(thread.relativeUrl) if "_" in topic_title: return HttpResponseRedirect(thread.relativeUrl) if thread.op.content: description = thread.op.content[:160] else: description = getattr(settings, "DJEDDIT_DESCRIPTION", "The link sharing and discussion portal") meta = Meta( title=thread.title, description=description, ) thread.views += 1 thread.save() context = dict(thread=thread, nodes=thread.op.getSortedReplies(), meta=meta) return render(request, 'djeddit/thread.html', context) except (Topic.DoesNotExist, Thread.DoesNotExist): pass raise Http404 Here is my templates code(beginning): {% extends BASE_TEMPLATE %} {% block meta %} {% include 'meta/meta.html' %} {% endblock %} Here is what I see when I view the page's html source: <head> <meta charset="utf-8" /> <!DOCTYPE html> <link rel="stylesheet" href="/site_media/static/djeddit/bower_components/bootstrap/dist/css/bootstrap.css"> <link rel="stylesheet" href="/site_media/static/djeddit/bower_components/font-awesome/css/font-awesome.min.css"> <link rel="stylesheet" href="/site_media/static/djeddit/bower_components/bootstrap-select/dist/css/bootstrap-select.min.css"> <!-- Bootstrap theme --> <link rel="stylesheet" href="/site_media/static/djeddit/css/theme.css"> <link rel="stylesheet" href="/site_media/static/djeddit/css/callout.css"> <meta name="viewport" content = "width=device-width, initial-scale=1.0"> </head> The doc type seems to be rendered by the django-meta but the tags are not rendering. -
Django ELK logging problems on OpenShift
I've deployed Django 1.11 on Openshift platform with it's S2I image (based on python 3.6). It uses gunicorn to serve Django traffic. Problem: I'm struggling to make it log properly HTTP status codes to RabbitMQ (which is then consumed by ELK).It does work properly with dev server manage.py runserver however when I run it gunicorn it only sends messages of types WARNING and ERROR to rabbitmq and not INFO (which are HTTP 2xx). Seems that Django logging subsystem is not triggered for INFO messages. Here's my logging config LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'root': { 'level': 'DEBUG', 'handlers': ['console'], }, 'formatters': { 'json': { '()': 'pythonjsonlogger.jsonlogger.JsonFormatter', 'fmt': '%(name)s %(levelname) %(asctime)s %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'json' }, 'rabbit': { 'level': 'DEBUG', 'class': 'python_logging_rabbitmq.RabbitMQHandler', 'host': get_env_variable('RB_HOST'), 'port': int(get_env_variable('RB_PORT')), 'username': get_env_variable('RB_USER'), 'password': get_env_variable('RB_PASS'), 'exchange': get_env_variable('RB_EXCH'), 'routing_key_format': get_env_variable('RB_RKEY'), 'declare_exchange': True, 'formatter': 'json', 'connection_params': { 'virtual_host': get_env_variable('RB_VHOST'), 'connection_attempts': 3, 'socket_timeout': 5000 }, 'fields': { 'source': 'MainAPI', 'env': 'testing', 'tags': ['one'], }, 'fields_under_root': True }, }, 'loggers': { 'django.server': { 'handlers': ['rabbit','console'], 'level': 'DEBUG', 'propagate': False, }, 'django': { 'handlers': ['rabbit','console'], 'level': 'DEBUG', 'propagate': True, }, }, } -
batch api call to DRF
I have project with Django-rest-framework, in frontend there is issue for get multiple API routes in one request. I dont want make project complex and dirty for this request, I want create some wrapper to solve this issue for example: post with data: [{'method': 'get', 'url': '/api/v1/get_profile'}, {'method': 'get', 'url', '/api/v1/setting'}, {'method': 'get', 'url', '/api/v1/news'}] and receive something like [{'url': '/api/v1/get_profile', data:{'username':'test'}}, {'url': '/api/v1/setting', data:{'can_see_x': 'true'}}, {'url': '/api/v1/news', data:[{'title':'news1'}]}] is there any open source plugin for this? if no, how can call each api from one view? is it safe? ( all request must be for current user and current token) where is best spot for this module? create new module named batch for example? -
How to use bootbox for Django DeleteView?
I am using Django DeleteView for deleting objects. First, I implemented delete add confirm dialog redirecting another html page. Now, I want to add bootbox pop up. But i don't understand where to add code. Please help models.py class Review(models.Model): review_description = models.TextField(max_length=500) user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) book = models.ForeignKey(Book, on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) views.py class ReviewDelete(DeleteView): model = Review template_name = "confirm_delete.html" def get_success_url(self, *args, **kwargs): review = get_object_or_404(Review, pk=self.kwargs['pk']) return reverse("books:detail", args = (review.book.id,)) confirm_delete.html {% extends "base.html" %} {% block content %} <h1>Delete</h1> <p>Are you sure you want to delete {{ review }}?</p> <form action="{% url "delete" pk=review.id %}" method="POST"> {% csrf_token %} <input type="submit" value="Yes, delete." /> <a href="{% url "books:detail" id=review.book.id %}">No, cancel.</a> </form> {% endblock %} book_details.html <a href="{% url "delete" pk=review.id %}" class="badge badge-danger">Delete</a> {# <a href="{% url "delete" pk=review.id %}" class="badge badge-danger">Delete</a>#} base.html <script type="text/javascript"> $(document).ready(function () { $("#review-delete-btn").click(function (event) { event.preventDefault(); bootbox.confirm({ title: "Destroy planet?", message: "Do you want to activate the Deathstar now? This cannot be undone.", buttons: { cancel: { label: '<i class="fa fa-times"></i> Cancel' }, confirm: { label: '<i class="fa fa-check"></i> Confirm' } }, callback: function (result) { console.log('This was logged in the … -
is there any maximum ffmpeg running simultaneously?
I'm developing a video encoding service using ffmpeg that wrapped by python+django My service is running ffmpeg asynchronously by using celery The problem is, the resulted video sometimes freezing in some part of the video but there's no error raised. Is there any maximum number that ffmpeg running simultaneously? -
Django Simple Calculator using view and template
I am new to django. trying to create simple calculator in django. created project and created view. I am finding very difficult to send a request to django with POST method and to send body parameters. Please help me out. -
Django Calendar app
I am new to this beautiful platform. Please help me creating a calendar/scheduler app. I will explain better what I want. So a person enters my site and select date and hour for an appointment. The app also must recognize other appointments that were already book. After the person finish and confirm the appointment an email will be send. Please help me develop this app -
Django rest_auth.registration is sending back error even in successful registration
I am making a website where I am using Vuejs for front end. For registration, I am using rest_auth.registration. In Vuejs code, I am making the registration post request through axios. axios.post(this.registrationUrl,{ username, email, password1, password2, }).then(res => { console.log('Registration Successful!') }).catch(err => { // console.log('There is error!') let errData = err.response.data this.errors.push(errData) for (let errorType in errData) { for (let error of errData[errorType]) { this.errors.push(error) } } }) The problem is that while registering a user, the promise in the code returns an error even if the registration is successful and a new user can be seen in the django admin panel. The returning error: OSError at /rest-auth/registration/ [Errno 99] Cannot assign requested address Request Method: POST Request URL: http://localhost:8000/rest-auth/registration/ Django Version: 1.11.8 -
InstallationError: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-Jr1szu/Django/
I'm trying to start a Pinax Project for Django. I setup my Python Virtual Environment. Upgraded setup tools. Upgraded pip. Installed Pinax. Then when I tried 'pinax start blog my_site', it gave the following error: Installing Django... Traceback (most recent call last): File "/usr/local/bin/pinax", line 11, in <module> sys.exit(main()) File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 700, in __call__ return self.main(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 680, in main rv = self.invoke(ctx) File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 1027, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 873, in invoke return ctx.invoke(self.callback, **ctx.params) File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 508, in invoke return callback(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/click/decorators.py", line 63, in new_func return ctx.invoke(f, obj, *args[1:], **kwargs) File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 508, in invoke return callback(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/pcli.py", line 97, in start pip_install("Django") File "/usr/local/lib/python2.7/dist-packages/pcli.py", line 23, in pip_install command.run(opts, [package]) File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 335, in run wb.build(autobuilding=True) File "/usr/local/lib/python2.7/dist-packages/pip/wheel.py", line 749, in build self.requirement_set.prepare_files(self.finder) File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 634, in _prepare_file abstract_dist.prep_for_dist() File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 129, in prep_for_dist self.req_to_install.run_egg_info() File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 439, in run_egg_info command_desc='python setup.py egg_info') File "/usr/local/lib/python2.7/dist-packages/pip/utils/__init__.py", line 707, in call_subprocess % (command_desc, proc.returncode, cwd)) pip.exceptions.InstallationError: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-Jr1szu/Django/ I've tried making a python virtual … -
User button to select random View/URL for display
I've started using Django 2.0 and Python 3.6.3 to develop a website which will display customized "Posts", as in a blog Post. My idea is to create hundreds of short Posts which can only be accessed at random, via a "Click here for random post" button. I plan to create a Post model with different text fields, including also a UUID, or custom unique ID. Once I have my model, my idea is for the user to click a button which selects a random instance of a Post, or an individual record from the database. Then, my View would display the random Post instance. I'm not sure of all the possible ways this could be done. One way might be to get a random row from the database, then somehow grab the ID and use that for the URL. Another way might be to simply use template tags to somehow select a random model. This is purely theoretical right now, so I don't have any code yet. If you have any ideas on how to approach this, I'd really appreciate it. Thanks in advance. -
In Django, can a url tag have an arbitrary number of arguments?
BACKGROUND: I'm learning Django by working on a simple to-do-list app using Django 1.11. The app has "groups" and "items", where items are the individual to-do items and every item belongs to exactly one group. The URLs may end up working something like this: # snippet from urls.py url(r'^groups$', views.all_groups, name="all_groups"), url(r'^groups/(\d+)/$', views.view_group, name="view_group"), url(r'^items$', views.all_assets, name="all_items"), url(r'^items/(\d+)/$', views.view_item, name="view_item"), Each of the above pages would display a one or two column table (e.g. all items, or all items in a specific group, etc.), where each table element would be a link to a page to show either a specific group or a specific item. I have a separate view for each of the above URLs, but I was able to have a single HTML template to render each table successfully. Depending on the URL, there are either 0 or 1 arguments to the URL tag: {% url 'my_url' %} or {% url 'my_url' arg1 %} Here is a snippet of the HTML template that can render the table with an arbitrary number of rows and columns, but at most two arguments for the url tag: # lists.html - works for several different views # every table entry is a … -
Django: Add a new property to a model class by other properties in that class
I'm trying to assign a new property, apps, to my User class by using the is_admin and group properties of the User class but I'm not sure how to do this.. this is what I'm trying: In my models.py I have a User class with a method assign_apps. I'm trying to use that method to add a new property to the User class, apps (User.apps) by using an imported function get_user_apps and the is_admin and group properties I'm pretty sure this won't work since I'll somehow have to invoke User.assign_apps() Is there a better way to do this so that User.apps is calculated by User.is_admin and User.group? from .helpers import get_user_apps class User(): is_admin = models.BooleanField(default=False) group = models.ForeignKey(Brand, null=True, blank=True) def assign_apps(self): self.apps = get_user_apps(self.group, self.is_admin) -
Postgresql 9.3 on ubuntu for Django web application Error: cluster_port_ready: could not find psql binary
I'm having some issues with postgresql 9.3 running on ubuntu 14.04.5 I had a django web application running using NGINX/Gunicorn, for a few weeks, then one day I went to use it and I got an OperationalError: Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? After researching, it became apparent that the postgresql server wasn't running. I then attempted to start it, and got the following error: * No PostgreSQL clusters exist; see "man pg_createcluster" Alarming, but my data is backed up just fine, so I did: pg_createcluster 9.3 main --start and then I got: Error: cluster configuration already exists No problem. I'll drop it and create a new one, I thought: pg_dropcluster 9.3 main --stop that ran fine, and so I ran: pg_createcluster 9.3 main --start again, and now it created the cluster apparently, but would not start: Creating new cluster 9.3/main ... config /etc/postgresql/9.3/main data /var/lib/postgresql/9.3/main locale en_US.UTF-8 port 5432 Error: cluster_port_ready: could not find psql binary does anyone have any advice as to how to address this? I have done apt-get remove and install for postgresql, and still same results. Thanks in advance! -
How do you get the PK for a HyperlinkedIdentityField when going through a Many to Many relationship?
I have three models in my Django project: class Model1(models.Model): name = models.CharField(max_length=10) class Model2(models.Model): name = models.CharField(max_length=10) class OneToTwo(models.Model): one = models.ForeignKey(Model1) two = models.ForeignKey(Model2) extra_field_necessitating_intermediate_model = models.IntegerField(default=0) I am using Django REST Framework to build an API for these models, and I have serializers for Model1 and Model2: class Model1Serializer(serializers.HyperlinkedModelSerializer): class Meta: model = Model1 fields = ('url', 'name') class Model2Serializer(serializers.HyperlinkedModelSerializer): class Meta: model = Model2 fields = ('url', 'name') ... so far, so good. The problem arises when I want to nest a Model2 inside the Model1 serializer. I can create an intermediary serializer for OneToTwo entities containing the Model2 data: class TwosSerializer(serializers.HyperlinkedModelSerializer): id = serializers.ReadOnlyField(source='two.id') name = serializers.ReadOnlyField(source='two.name') class Meta: model = OneToTwo fields = ('url', 'id', 'name') class Model2Serializer(serializers.HyperlinkedModelSerializer): twos = TwosSerializer(source='onetotwo_set', many=True) class Meta: model = Model2 fields = ('url', 'name', 'twos') ... but the url field on the TwosSerializer is that of the OneToTwo entity, not of the related Model2 entity. What I want is the url field of the internal serializer to be the URL to Model2.objects.get(pk=two.id) for each two object in the relationship. A naive attempt was to create a url field definition using the HyperlinkedIdentityField class: # this is within … -
Using Django CBV TemplateView with custom render_to_reponse
I'm trying to override the render_to_response method in TemplateView to include an additional parameter for the reponse_class for the HTTP status, but having trouble using: class ErrorView(TemplateView): ''' Inserts http status code into response ''' status = None def render_to_response(self, context, **response_kwargs): if self.status is None: raise ImproperlyConfigured("ErrorView requires definition of status") return super(ErrorView,self).render_to_response(context,{'status': self.status}) class Error404View(ErrorView): template_name = '404.html' status = 404 The render_to_response method (from TemplateResponseMixin) is defined with three parameters: def render_to_response(self, context, **response_kwargs) However, when TemplateView calls it from the get method, it only passes the context: return self.render_to_response(context) How can I pass response_kwargs to render_to_response? -
Django cannot determine queryset for chaining one-to-many with one-to-one relationship
I have a system where there is a many to one relationship with a number a model (say 1 a -> many b) and that many model has a one to one relationship with another model (say 1 b -> 1 c). Drawn like so: /--- b1 --- c1 / a ---- b2 --- c2 \ \--- b3 --- c3 I'm determined to create a method in that collects all the c's that correspond to a. Given an model system with the same structure to mine, the best I could come up with is shown in the method: Person.find_important_treats(). Is there a better way that does not involve so many calls to the database? from django.db import models class Person(models.Model): """ The 'a' from my above example """ def find_important_treats(self): return (pet.treat for pet in self.pets) class Pet(models.Model): """ The 'b' from my above example """ owner = models.ForeignKey( to=Person, related_name='pets' ) favourite_treat = models.ForeignKey( to=Treat, ) class Treat(models.Model): """ The 'c' from my above example """ pass