Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't get request.user sub fields
I'm quite new to Django/Python and I'm having trouble to retrieve the user attributes, such as first_name. What am I missing? class principal(LoginRequiredMixin, TemplateView): template_name = 'appPortal/index.html' def get_context_data(self, **kwargs): usuario = self.request.user context = super().get_context_data(**kwargs) print (usuario) ### OK, returns the logged user print (usuario.first_name) ### Don't work, returns nothing print (usuario.get_short_name()) ### Don't work too ### The code continues, but the last two print() don't work Thanks, -
How to fix the Django-allauth settings.py contrib syntax error?
So following the current Django-allauth documentation, I keep getting this minor syntax error when I thought I followed the documentation to every last detail. Terminal error after running: ./manage.py migrate /settings.py", line 43 'django.contrib.auth', ^ SyntaxError: invalid syntax My settings.py file: Was I not supposed to keep the default apps above the allauth section? ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ... # The following apps are required: 'django.contrib.auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', # ... include the providers you want to enable: 'allauth.socialaccount.providers.amazon', 'allauth.socialaccount.providers.angellist', 'allauth.socialaccount.providers.asana', -
NOT NULL constraint failed: alpha_chat.message...i am getting this error. How to correct it?
enter image description here The image is the views.py file of the app. The data is not going into the database. How to correct the problem? -
Django rest framework list by BrowsableAPI and create with custom button
I'm kinda newbie to DRF and need some advice pls. I created some kind of time duration record for each day which is ok with inputing the duration manually, here is a model: from django.db import models from datetime import datetime, date class Record(models.Model): recordDate = models.DateField(blank=True, default=date.today) hourAchieved = models.IntegerField(blank=True, default=0) class Meta: ordering = ["recordDate"] def __str__(self): return "Achieved "+str(self.hourAchieved)+" hour(s)!" and works well with these APIviews: from rest_framework import generics from .models import Record from .serializers import ( recordListSerializer, recordUpdateSerializer ) class recordList(generics.ListCreateAPIView): queryset = Record.objects.all() serializer_class = recordListSerializer class recordUpdate(generics.RetrieveUpdateAPIView): queryset = Record.objects.all() serializer_class = recordUpdateSerializer Then, I want to improve input process by create a button to get 'start_time' and another button to get 'end_time' and calculate the time for me instead of me remember and input duration time(hours) myself. So, I found the 'TemplateHTMLRender' and decided to use it as: class recordList(generics.ListCreateAPIView): queryset = Record.objects.all() serializer_class = recordListSerializer renderer_classes = (TemplateHTMLRenderer,) template_name = 'myTemp.html' def get(self, request): records = self.get_queryset() serializer = recordListSerializer(records,many=True,context={'request': request}) return Response({'serializer': serializer, 'record':records}) and this is myTemp.html: {% load rest_framework %} <html> <body> <h1>Neew Era of REST</h1> <form action="{% url 'record:list' %}" method="POST"> {% csrf_token %} {% render_form serializer … -
django error using pagination and raw queryset
when I try to paginate my page it gives me error python - django error using pagination views: class StudentmessageListView(ListView, LoginRequiredMixin): login_url = '/login/' redirect_field_name = 'redirect_to' template_name = 'student_messagesall.html' context_object_name = 'messages_all' model = Message paginate_by = 3 def get_queryset(self): return Message.objects.raw('SELECT * FROM ertaapp_message where to_prof_id=%s ORDER BY create_date DESC',[self.request.user.id]) def get_context_data(self, **kwargs): context = super(StudentmessageListView, self).get_context_data(**kwargs) context['reps'] = ReplyMessage.objects.raw('SELECT * FROM ertaapp_replymessage') return context how can I solve this? -
Django - Search matches with all objects - even if they don't actually match
This is the model that has to be searched: class BlockQuote(models.Model): debate = models.ForeignKey(Debate, related_name='quotes') speaker = models.ForeignKey(Speaker, related_name='quotes') text = models.TextField() I have around a thousand instances on the database on my laptop (with around 50000 on the production server) I am creating a 'manage.py' function that will search through the database and returns all 'BlockQuote' objects whose textfield contains the keyword. I am doing this with the Django's (1.11) Postgres search options in order to use the 'rank' attribute, which sounds like something that would come in handy. I used the official Django fulltext-search documentation for the code below Yet when I run this code, it matches with all objects, regardless if BlockQuote.text actually contains the queryfield. def handle(self, *args, **options): vector = SearchVector('text') query = options['query'][0] search_query_object = SearchQuery.objects.create(query=query) set = BlockQuote.objects.annotate(rank=SearchRank(vector, query)).order_by('-rank') for result in set: match = QueryMatch.objects.create(quote=result, query=search_query) match.save() Does anyone have an idea of what I am doing wrong? -
How do I redirect errors like 404 or 500 to a custom error page in apache httpd?
I have created a Django project but I am using Apache as the webserver. Can anyone tell me how can I redirect an error code like 404 or 500 or 400 to a custom error html page instead of getting a standard error message on page in case an error was to occur ? -
Getting an error opening a file in Visual Studio 2017
I am trying to access a file in Visual Studio 2017 using the django framework but get the following error: How do I resolve it? Thanks -
Django mock timezone aware datetime on creating model
I have a test where I create a few objects: def test_get_courier_task_returns_couriers_tasks(self): with patch('django.utils.timezone.now', return_value=make_aware(datetime(2018, 1, 24, 11, 57))): task1 = TaskFactory() response = json.loads(MyAPI.get_tasks_list(self.user.username)) print('[*] Response timestamp: {}'.format(response['content'][0]['timestamp'])) The Task has created_timestamp field with auto_add_now set to True and to_json() method which is used in get_tasks_list() above: class Task(models.Model): created_timestamp = models.DateTimeField(auto_now_add=True) def to_json(self): to_return = { 'timestamp': self.created_timestamp.strftime('%d-%m-%Y %H:%M') } return to_return Unfortunately tests give this output: [*] Response timestamp: 24-01-2018 10:57 I have checked that this is timezone aware, but instead of giving me UTC+1 it gives UTC+0 on saving. What do I have to do? I have USE_TZ = True in my settings and I have applied migrations. This question did not help with my problem. -
NoReverseMatch at /posts/ Error in Django project
I write simple Django-blog, django.VERSION - (2, 0, 1, 'final', 0) But I receive an error and don't understand how to fix it. NoReverseMatch at /posts/ Reverse for 'detail' with keyword arguments '{'id': 16}' not found. 1 pattern(s) tried: ['posts\\/(?P<id>\\d)/$'] And Error during template rendering In template djangoblog/posts/templates/posts/base.html, error at line 0 Reverse for 'detail' with keyword arguments '{'id': 16}' not found. 1 pattern(s) tried: ['posts\\/(?P<id>\\d)/$'] 1 {% load staticfiles %} 2 <!DOCTYPE html> 3 <html lang="en"> 4 <head> 5 <meta charset="UTF-8"> 6 <title>{% block head_title %} 7 Django-blog! {% endblock head_title %}</title> 8 <link rel="stylesheet" 9 models.py from django.db import models from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=200) image = models.FileField(null=True, blank=True) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwargs={"id": self.id}) class Meta: ordering = ['-timestamp', '-updated'] My def in views.py look like def post_list(request): queryset_list = Post.objects.all() paginator = Paginator(queryset_list, 5) page = request.GET.get('page') queryset = paginator.get_page(page) context = { 'object_list': queryset, 'title': 'List' } return render(request, 'posts/post_list.html', context) in urls.py urlpatterns look like re_path('^$', post_list, name='list') Thank you very much. -
How can I do join in django?
I'm working with django, expecially with QuerySet right now and I have a very big problem. so, this is my code: resources_rights = Resources_rights.objects.filter( group_id__in = groups ) resources = Resources.objects.filter( id__in = resources_rights__resource_id ) Resources_rights refers to a models that have resource_id, group_id, read, write and execute. Resources, instead, contains last_modify, name, description and of course the id. So, in resource_rights i save some objects and everyone has his resource_id. I would filter Resources using resource_id fields in resource_rights, but like I had do is not possible because the first query returns objects. So, how can I do? there is an operator for that? thank you all! -
How to deploy Django with Channels and Celery on Heroku?
How one deploys the following stack on Heroku platform ? Django Django Channels Celery The limitation surely is on the Procfile. To deploy Django with Celery it would be something like: web: gunicorn project.wsgi:application worker: celery worker --app=project.taskapp --loglevel=info While deploying Django with Channels: web: daphne project.asgi:channel_layer --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker -v2 The web process can use ASGI, but the worker process will be used by Channels and I don't see how Celery can be started alongside it. -
Django Update and CreateView using the same Crispy Form, Add view Error
I'm using the same crispy form for add and edit and have added a variable to so I can change the submit button text from add to edit and vice versa. However the add view is coming up with the below error: Traceback: (removed the in built references) ... File "/itapp/itapp/sites/views.py" in dispatch 954. return super(AddSubnet, self).dispatch(*args, **kwargs) ... File "/itapp/itapp/sites/views.py" in get_context_data 969. context = super().get_context_data(**kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/edit.py" in get_context_data 93. kwargs['form'] = self.get_form() File "/usr/local/lib/python3.6/site-packages/django/views/generic/edit.py" in get_form 45. return form_class(**self.get_form_kwargs()) Exception Type: TypeError at /sites/site/add_subnet/7 Exception Value: 'SubnetForm' object is not callable im not sure as to why as the code for the form looks good to my unskilled eyes at least anyway forms.py: class SubnetForm(forms.ModelForm): class Meta: model = SiteSubnets fields = ['subnet', 'subnet_type', 'circuit', 'device_data', 'vlan_id', 'peer_desc'] def __init__(self, *args, **kwargs): site_id = kwargs.pop('site_id', None) self.is_add = kwargs.pop("is_add", False) super(SubnetForm, self).__init__(*args, **kwargs) self.fields['circuit'].queryset = Circuits.objects.filter(site_data=site_id) self.helper = FormHelper(self) self.helper.form_id = 'subnet_form' self.helper.form_method = 'POST' self.helper.add_input(Submit('submit', 'Add Subnet' if self.is_add else 'Edit Subnet', css_class='btn-primary')) self.helper.layout = Layout( Div( Div( Field('subnet', placeholder='Subnet'), Div('subnet_type', title="Subnet Type"), css_class='col-lg-3' ), Div( Div('circuit', title='Circuit'), Div('device_data', title="Device Data"), css_class='col-lg-3' ), Div( Field('vlan_id', placeholder='VLAN ID'), Field('peer_desc', placeholder="Peer Description"), css_class='col-lg-3' ), css_class='row' ) ) Views: … -
django update many to many field in update view
I am currently working on a project using Django. Below, I have a model that has manytomany fields. employees = models.ManyToManyField(user_model.EmployeeProfile, blank=True) How to add an object from a related model to that field? I use the update view and override the form_valid function. def form_valid(self, form): self.object = form.save(commit=False) self.object.save() employee = user_model.EmployeeProfile.objects.get(user=self.request.user.id) self.object.employees.add(employee) return super().form_valid(form) The above code is not working properly. I need help. Thank you in advance. -
makemigrations failing after moving from Windows to Linux with Postgres
I have a small web app (using Postgres) that I have been developing in a Django Windows environment and it is working fine. I'm now trying to move it to Redhat 6.8 and makemigrations is failing. I've installed Postgres and created the database on Linux. I created the database new because I didn't need any of the old test data on Windows. I moved over all of the files (except the .pyc files). Below is the error I'm getting. It seems it is trying to access a table that is not yet created. (It's not yet created because I haven't been able to run a migration yet( sort of a chicken/egg paradigm). Note, from what I've read, I also removed all of the migrations files except init.py. I've been wrestling with this for many hours. Any help would be greatly appreciated. Thank you. webtest2) [asilver@SDNAUTOS02 sdnlabs2]$ python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/asilver/.virtualenvs/webtest2/lib/python2.7/site-packages/django/core/management/ utility.execute() File "/home/asilver/.virtualenvs/webtest2/lib/python2.7/site-packages/django/core/management/ self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/asilver/.virtualenvs/webtest2/lib/python2.7/site-packages/django/core/management/ self.execute(*args, **cmd_options) File "/home/asilver/.virtualenvs/webtest2/lib/python2.7/site-packages/django/core/management/ self.check() File "/home/asilver/.virtualenvs/webtest2/lib/python2.7/site-packages/django/core/management/ include_deployment_checks=include_deployment_checks, File "/home/asilver/.virtualenvs/webtest2/lib/python2.7/site-packages/django/core/management/ return checks.run_checks(**kwargs) File "/home/asilver/.virtualenvs/webtest2/lib/python2.7/site-packages/django/core/checks/regi new_errors = check(app_configs=app_configs) File "/home/asilver/.virtualenvs/webtest2/lib/python2.7/site-packages/django/core/checks/urls return check_resolver(resolver) File "/home/asilver/.virtualenvs/webtest2/lib/python2.7/site-packages/django/core/checks/urls return check_method() File "/home/asilver/.virtualenvs/webtest2/lib/python2.7/site-packages/django/urls/resolvers.p for pattern in self.url_patterns: … -
Saving URL field value from Django view
I am trying to add the value of a URLField in my views as game_url = "https://stackoverflow.com/" here the value I am assigning is of type string.a in my models I have game_url = models.URLField() but my game_url is saved as (u"https://stackoverflow.com/"). I know it is because of encoding, but I don't know how exactly to solve it in Django. -
How to add Keyboard event in Django
I want to control my website use keyboards buttons, if i press the key "a" i will call an url from my liste of urls , for examples the url who call my index view, is there any recommendation of django packages ? -
nginx Permission denied on Ubuntu
I'm trying to set up my Django app with uWSGI and nginx by following this guide. I'm able to run my app with Django's development server, as well as being served directly from uWSGI. I'm running everything on a university managed Ubuntu 16.04 virtual machine, and my user has sudo access. My problem: When getting to this bit of the tutorial, and try to fetch an image, I get a 403 error from nginx. The next section results in a 502. /var/log/nginx/error.log shows connect() to unix:///me/myproject/media/image.jpg failed (13: Permission denied) while connecting to upstream connect() to unix:///me/myproject/project.sock failed (13: Permission denied) while connecting to upstream for the 403 and 502, respectively. I have read multiple questions and guides (one here, another here and yet another one, and this is not all of them), changed my permissions and even moved my .sock to another folder (one of the SO answers recommended that). What else can I try? Here's my nginx.conf # exam_grader_nginx.conf # the upstream component nginx needs to connect to upstream django { # server unix:///path/to/your/mysite/mysite.sock; # for a file socket server unix:///usr/share/nginx/html/exam_grader.sock; # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of … -
ImportError: No module named blog Django
I am new in python i try to create blog in django, when i try to create module by typing python manage.py startapp blog this command python version : 2.7 django-admin version : 1.8 In settings.py INSTALLED_APPS when i add 'logicmindblog.blog', and try to runserver It give me error ImportError: No module named blog Django But when i remove project name and just add 'blog' in and run server this migration and admin working fine, i can add blog , blog category from admin section Can anyone help me figure this, Thanks in advance logicmindblog/ ├── blog │ ├── admin.py │ ├── admin.pyc │ ├── __init__.py │ ├── __init__.pyc │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── 0001_initial.pyc │ │ ├── __init__.py │ │ └── __init__.pyc │ ├── models.py │ ├── models.pyc │ ├── __pycache__ │ │ └── __init__.cpython-35.pyc │ ├── tests.py │ ├── views.py │ └── views.pyc ├── db.sqlite3 ├── logicmindblog │ ├── __init__.py │ ├── __init__.pyc │ ├── __pycache__ │ │ ├── __init__.cpython-35.pyc │ │ └── settings.cpython-35.pyc │ ├── settings.py │ ├── settings.pyc │ ├── urls.py │ ├── urls.pyc │ ├── views.py │ ├── views.pyc │ ├── wsgi.py │ └── wsgi.pyc ├── manage.py └── views ├── … -
Django button in Modelclass
I'm making an inventory app in which I could update the values of the products from my 'home.html'. My proj name is Inventory App name is myapp Problem I am facing is that every time I update the value of a Stock from my homepage, it adds a new Product instead of updating the one that I want! I am using the ModelsForm Class provided by Django. Using Django=1.11 and Python=3.6 My project's urls.py: from django.conf.urls import url,include from django.contrib import admin from myapp.views import home urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^myapp/', include('myapp.urls', namespace="myapp")), url(r'^myapp/home/', home, name='home'), ] My forms.py: from django import forms from .models import Inventory class Operations(forms.ModelForm): class Meta: model = Inventory fields = ('stocks_left',) My app's Model.py: from django.db import models import uuid class Inventory(models.Model): """ Model representing a the inventory. """ id = models.UUIDField(primary_key=True, default=uuid.uuid4) inventory_name = models.CharField("INVENTORY NAME" ,max_length=200, help_text="This contains the Inventory name:") short_name = models.CharField(max_length=20, help_text="This contains an abbreviation:") inventory_code = models.IntegerField("INVENTORY CODE" ,default = '0', help_text="This contains the Inventory code:") price = models.IntegerField(default = '0') stocks_left = models.IntegerField("STOCKS LEFT",default = '0') def __str__(self): """ String for representing the Model object (in Admin site etc.) """ return '{0} ({1}) ({2})'.format(self.inventory_name,self.inventory_code,self.stocks_left) My app's … -
How to make a writable ManyToManyField with a Through Model
I have a Product class that has "source products"; I use a many-to-many field with a through model to represent it (the database tables already exist, and that's the only way I found to configure the models): class Product(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) product_name = models.TextField() source_products = models.ManyToManyField('self', symmetrical=False, related_name='derived_products', through='Link', through_fields=('product', 'source'),) class Meta: db_table = 'product' managed = False class Link(models.Model): product = models.ForeignKey('Product', models.CASCADE, db_column='uuid', related_name='source_links') source = models.ForeignKey('Product', models.CASCADE, db_column='source_uuid', related_name='+') class Meta: db_table = 'link' unique_together = (('product', 'source'),) managed = False My serializer is dead simple: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('uuid', 'product_name', 'source_products', ) A GET request returns: { "product_name": "dummy.fra", "source_products": [ "17b021e7-3d6b-4d29-a80b-895d62710080" ], "uuid": "48c5a344-877e-4e3f-9a4b-2daa136b68fe" } The since ManyToManyFields with a Through Model are read-only, how do I go about to create a product including the link between products? I'd like to send a POST request that follows the same format as the GET response (i.e., a source_products field that lists UUIDs of existing products). -
Django: Returning Json from view and parse value into d3.js
views.py def get_graph(request): # do some stuff # return json nodes & links back to template return render(request, 'anomaly/index.html',{"nodes": nodes, "links": rels}) index.html <script type="text/javascript"> var width = 800, height = 800; var force = d3.layout.force() .charge(-200).linkDistance(30).size([width, height]); var svg = d3.select("#graph").append("svg") .attr("width", "100%").attr("height", "100%") .attr("pointer-events", "all"); d3.json("/anomaly/graphTEST", function(error, graph) { if (error) return; force.nodes(graph.nodes).links(graph.links).start(); var link = svg.selectAll(".link") .data(graph.links).enter() .append("line").attr("class", "link"); var node = svg.selectAll(".node") .data(graph.nodes).enter() .append("circle") .attr("class", function (d) { return "node "+d.label }) .attr("r", 10) .call(force.drag); // html title attribute node.append("title") .text(function (d) { return d.title; }) // force feed algo ticks force.on("tick", function() { link.attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); node.attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }); }); }); </script> /anomaly/graphTest is the url to call my get_graph method in views.py I couldn't get the json from my method to return into my d3.json function. How can I do that? What I'm trying to do is something similiar to this https://github.com/neo4j-examples/movies-python-bolt to display stuff on a graph using d3.json. Is it because of the python version that is different which causes my application … -
Holoviews and Django - Widgets are not working
I am trying to migrate a Holoviews/Bokeh to a Django app. The code is working just fine with Bokeh server. For django I am converting holoviews DynamicMaps to Bokeh figures using: plot_rm = renderer.get_widget(rmeans, None, position='above').state Then to serve the figure in django: script1, div1 = components(plot_rm) and let Django render the template with these elements in it. in the template I load the following js libraries: <script src="http://cdn.pydata.org/bokeh/release/bokeh-0.12.13.min.js"></script> <script src="http://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.13.min.js"></script> <script src="http://cdn.pydata.org/bokeh/release/bokeh-tables-0.12.13.min.js"></script> The figures render correctly but the widgets do not callback into the server to update the figures. It seems to be missing some JS code to close the AJAX loop. What am I missing? -
Must the app folder be inside the django project folder for a Django REST Framework project?
I'm diving through the Django REST framework learning material. I noticed that in the Quickstart page, they recommend to create the app INSIDE the Django project folder (using the dot at the end of the command django-admin.py startproject tutorial .), whereas the Tutorial starts by just creating the normal Django folder structure: the project folder "tutorial", containing the root app "tutorial" folder and the "snippets" app folder. The Quickstart page defends its way of structuring the folders by stating that it's to avoid name clashes. I just don't understand why, if that would be a best practice, the tutorial doesn't start off the same way. Can someone clarify if this odd folder restructuring (like in the Quickstart page) is really necessary? After having finished learning the Django REST framework, I'm going to set up a real project, and I'd like to know if I can stick to the normal folder structures that I'm used to in Django projects that don't use the Django REST Framework, or not. Kind regards. -
Queryset select latest record for group
Using Django 1.65 Python 3.4.1 Oracle db Table in the db 'Locations': location | update_time | num_01 | num_02 | num_03 | -----------+-----------------+-----------+--------+-------- B | 06 Feb 18 04:14 | 42 | 43 | 55 C | 22 Feb 17 04:14 | 77 | 99 | 23 A | 05 Feb 18 04:14 | 48 | 43 | 21 A | 01 Feb 18 04:14 | 82 | 83 | 74 I would like to select the row with the latest update_time for each location. The results for the above table should be: location | update_time | num_01 | num_02 | num_03 | -----------+-----------------+-----------+--------+-------- A | 05 Feb 18 04:14 | 48 | 43 | 21 B | 06 Feb 18 04:14 | 42 | 43 | 55 C | 22 Feb 17 04:14 | 77 | 99 | 23 I can use a queryset to return the latest update time for each location: latest_updates = Locations.objects.values('location').annotate(max_date=Max('update_time')).order_by('location') but this only returns the location and max update_time when I'm looking for the entire row - num_01, num_02, num_03. I've spent a lot of time searching stackoverflow but nothing quite fits. Oracle doesn't seem to support a sort by and distinct option …