Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Local mail server development in Django
By using the application 2 users should be able to send and receive emails with the help of an address user1@appname.com and user2@appname.com. Third party mailing services like gmail, yahoo should not be brought into picture. -
How to build functional custom model field by warpping existing python class?
I'm trying to build a custom model field. It wraps up a python class which is an extension of uuid.UUID class. The objective is to build a field which encodes and decodes uuids to/from barcodes. I'm currently using the following package python-barcode to access the methods required to make this happen, as follows: import barcode import uuid from io import BytesIO import base64 from django.db import models from django import forms _CODE128 = barcode.get_barcode_class('code128') class barcode(uuid.UUID): """Barcode class based on uuid""" def code(self,value): '''Convert this uuid object into 128 bit integer string''' return str(self(value).int) def barcode(self,value): '''Generate barcode as base 64 encoded image''' bs = BytesIO() _CODE128(self.code, writer=barcode.writer.ImageWriter()).write(bs) bs.seek(0) return base64.b64encode(bs.getvalue()) class BarcodeField(models.Field): attr_class=barcode description = "Barcode class field." def __init__(self,standard='code128',*args, **kwargs): #Already defined parameters override kwargs['unique'] = True kwargs['editable'] = False kwargs['default'] = uuid.uuid4 super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() #Already defined parameters override del kwargs["unique"] del kwargs['editable'] del kwargs['default'] return name, path, args, kwargs def formfield(self, **kwargs): defaults = {'form_class': forms.UUIDField} defaults.update(kwargs) return super().formfield(**defaults) def get_internal_type(self): return 'UUIDField' class Barcode(models.Model): barcode_id = BarcodeField(primary_key=True) barcode_nid = BarcodeField() name = models.TextField() The goal is to have a field having: Default uuid with an unique and immutable … -
Django Static Folder Forbidden (403) on Nginx Digital Ocean
I've successfully followed this tutorial on digital ocean: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 on deploying a django app - the app works fine but one thing I noticed is that the app can't render styles in the static folder - it returns a 403. Am I missing something? Is it a server issue or do I need to configure something additionally in Django. Please note if I run python manage.py runserver 0.0.0.0:8000 the styles render fine. -
How to compare Django Querysets
I have been struggling all morning trying to figure out how to compare two different querysets. I have two manytomanyfields in my model, and I'm trying to figure out if they are identical. I research this by viewing this particular issue: How do I test Django QuerySets are equal? I am using class based views...and I have a model with two manytomanyfields... My model... class Author(models.Model): title = models.ManyToManyField(User,blank=True,related_name='title') title1 = models.ManyToManyField(User,blank=True,related_name='title1) My View... class AuthorDetailView(DetailView): model = Author def get_context_data(self, **kwargs): context = super(AuthorDetailView, self).get_context_data(**kwargs) title = list(Author.objects.filter(title)) title1 = list(Author.objects.filter(title1)) test_instance = Author.objects.all() proxy4 = self.assertQuerySetEqual(Author.objects.all(), map(repr, [test_instance])) I am trying to compare fields title and title1. However when try to run the code above I continually get a 'View' object has no attribute 'assertQuerysetEqual'. I can't even get this function to work. I running Django 1.11 and Postgresql. Perhaps this function doesn't work with Postgresql? Any help to get me on the right track is appreciated. Been playing with this and researching all morning with no luck. Thanks in advance. -
Dynamic namespaces socketio
I would like to know how to add dynamic namespaces in socketio like how in websockets you have something like ws://echo.websockets/(?Pusername). I am using Django, Redis Nodejs and socketio. -
how to prepopulate a normal form with values from model instance
I have seen this Load Django Form Object with data from Model instance already “loaded” I think it is for modelforms Can I create a form with data from model instance blog = Blog.objects.get(pk=blogid) form = BlogForm(instance=blog) here BlogForm is a normal form, If not how can prepopulate the form with values from the model instance -
How to make a drop-down menu scrollable
I am trying to build a drop-down menu in a navbar. I have done this, but the list of items is too long to fit on the page (the bottom of the list is hidden) so I therefore need to make the list scrollable. As of now, when the menu is "open" and I scroll, it scrolls the page behind the menu rather than the menu. Please help me figure this out! Below I have posted a bit of my HTML and CSS as it pertains to this drop down menu. <li class="nav-item dropdown"> <a href="#" class="nav-link dropdown-toggle scrollable-menu" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">INSTRUMENTS</a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> {% for instrument in instruments %} <a href="{% url 'instruments:individual_display' instrument.id %}" class="dropdown-item"> {{ instrument.name }} </a> {% endfor %} </div> </li> .scrollable-menu { height: auto; max-height: 500px; overflow-x: hidden; } -
Missing files after npm run eject command
I was working on integrating reactjs with django using django-webpack loader, following this link: http://v1k45.com/blog/modern-django-part-1-setting-up-django-and-react As shown in the tutorial, when we run npm run eject command, in config folder total 6 .js files are installed. But when I run the same command following the same procedure, polyfills.js and webpack.config.dev.js doesn't install. I need to edit the webpack.config.dev.js file for proper working of application but somehow not able to do. -
json post request object showing unevaluated keys
I'm trying to send an ajax post request to django. I have a valid json object, which i can print/view/stringify in browser, but when it arrives in django, the keys are unevaluated (see django view in 2nd code block). JS: /* prettify payload for back */ var makeUpdatePayload = function(fieldType, fieldArray) { var orderInfo = fieldArray.map(function(field, idx) { var fieldInfo = field.split('-field-') return { 'pk': fieldInfo[1], 'order': idx } }); return {[fieldType]: orderInfo} }; /* post payload */ var updateFieldOrder = function( payload ) { console.log('in ajax') console.log(JSON.stringify(payload)) // {"search":[{"pk":"9","order":0},{"pk":"7","order":1},{"pk":"6","order":2},{"pk":"8","order":3},{"pk":"5","order":4},{"pk":"4","order":5}]} $.ajax({ type: "POST", url: "update_field_order/", dataType: "json", data: JSON.parse( JSON.stringify(payload)), }); }; var payload = makeUpdatePayload('search', ["search-field-9", "search-field-7", "search-field-6", "search-field-8", "search-field-5", "search-field-4"]) updateFieldOrder(payload); in my django view: def update_field_order(request, recipe_pk): print('post') print(request.POST) # <QueryDict: {'search[0][pk]': ['9'], 'search[0][order]': ['0'], 'search[1][pk]': ['7'], 'search[1][order]': ['1'], 'search[2][pk]': ['6'], 'search[2][order]': ['2'], 'search[3][pk]': ['8'], 'search[3][order]': ['3'], 'search[4][pk]': ['5'], 'search[4][order]': ['4'], 'search[5][pk]': ['4'], 'search[5][order]': ['5']}> I've tryes JSON.stringify then JSON.parse -ing the payload before senting, but this doesn't help, i still see the same formatting. With JSON.stringify(payload), i get the expected output: `<QueryDict: {'{"search":[{"pk":"9","order":0},{"pk":"7","order":1},{"pk":"6","order":2},{"pk":"8","order":3},{"pk":"5","order":4},{"pk":"4","order":5}]}': ['']}>` Why is this happening? -
Setting up docker for django, vue.js, rabbitmq
I'm trying to add Docker support to my project. My structure looks like this: front/Dockerfile back/Dockerfile docker-compose.yml My Dockerfile for django: FROM ubuntu:18.04 RUN apt-get update && apt-get install -y python-software-properties software-properties-common RUN add-apt-repository ppa:ubuntugis/ubuntugis-unstable RUN apt-get update && apt-get install -y python3 python3-pip binutils libproj-dev gdal-bin python3-gdal ENV APPDIR=/code WORKDIR $APPDIR ADD ./back/requirements.txt /tmp/requirements.txt RUN ./back/pip3 install -r /tmp/requirements.txt RUN ./back/rm -f /tmp/requirements.txt CMD $APPDIR/run-django.sh My Dockerfile for Vue.js: FROM node:9.11.1-alpine # install simple http server for serving static content RUN npm install -g http-server # make the 'app' folder the current working directory WORKDIR /app # copy both 'package.json' and 'package-lock.json' (if available) COPY package*.json ./ # install project dependencies RUN npm install # copy project files and folders to the current working directory (i.e. 'app' folder) COPY . . # build app for production with minification RUN npm run build EXPOSE 8080 CMD [ "http-server", "dist" ] and my docker-compose.yml: version: '2' services: rabbitmq: image: rabbitmq api: build: context: ./back environment: - DJANGO_SECRET_KEY=${SECRET_KEY} volumes: - ./back:/app rabbit1: image: "rabbitmq:3-management" hostname: "rabbit1" ports: - "15672:15672" - "5672:5672" labels: NAME: "rabbitmq1" volumes: - "./enabled_plugins:/etc/rabbitmq/enabled_plugins" django: extends: service: api command: ./back/manage.py runserver ./back/uwsgi --http :8081 --gevent 100 --module websocket --gevent-monkey-patch … -
cannot import name 'views' from 'superlists'
Im working with Harrys Percivals book about TDD and i have problem with django. I got an ImportError: cannot import name 'views' from 'superlists' there is showing me tht the problem is with: from . import views This is my code in file urls.py from django.conf.urls import include, url from django.contrib import admin from . import views urlpatterns = ['', url(r'^$',views.home_page, name = 'home'), ] Does somebody know what to do with that problem? -
Django Loop doesn't work at Pythonanywhere
I deployed my django app on Pythonanywhere with Git clone. It has a navbar.html template so I add category loop on there, when I run my code on my pc It works correctly but If I deploy same code to Pythonanywhere with SQLite3 It doesn't work. Pythonanywhere View Localhost view view.py: def index(request): products = Product.objects.filter() catloops = Category.objects.filter() context = { "products":products, "catloops":catloops } return render(request,"index.html", context) models.py: class Category(models.Model): category_name = models.CharField(max_length = 50, verbose_name="Category Name") def __str__(self): return self.category_name urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('',views.index, name="index")] navbar.html: <li class="nav-item dropdown"><a href="javascript: void(0)" data-toggle="dropdown" class="dropdown-toggle">Categories<b class="caret"></b></a> <ul class="dropdown-menu"> {% for category in catloops %} <li class="dropdown-item"><a href="/products" class="nav-link">{{category.category_name}}</a></li> {% endfor %} </ul> </li> -
Page Not Found: /<int:pk>.pk
Can someone tell me why the urls generated from clinking the template link is /.pk. I am trying to understand how the urls work. New to Django here. Traceback (most recent call last): File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 647, in process_request_thread self.finish_request(request, client_address) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 357, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 717, in init self.handle() File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 154, in handle handler.run(self.server.get_app()) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 144, in run self.close() File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\wsgiref\simple_server.py", line 35, in close self.status.split(' ',1)[0], self.bytes_sent AttributeError: 'NoneType' object has no attribute 'split' Not Found: /.pk [10/Jan/2019 00:18:34] "GET /%3Cint:pk%3E.pk HTTP/1.1" 404 16594 template <h1><a href="{% url 'details' pk=Testimony.id %}">{{testimony.Title}}</h1> urls.py urlpatterns = [ ... path('<int:pk>/$', views.detail, name='details'), ] views.py def details(self, pk): print('1') testimony=get_object_or_404(Testimony, pk= pk) print('2') return render(request, 'details.html', {'testimony': testimony}) -
How to fix 'Argument must be a string' TypeError
I have a tuple that i am trying to use for choice filed in my model I am using MySQL 5 with Django 2.1 and Python 3.6. I have tried previous suggestion on this platform but still showing same error class SemesterData(models.Model): YESNOCHOICE = ( ('Y', 'Yes'), ('N', 'No'), ) sid = models.ForeignKey(SessionData,on_delete=models.CASCADE) semester_name = models.CharField(max_length=50) status = models.CharField(max_length=3, choices=YESNOCHOICE, null=True, default=YESNOCHOICE[1][0]) def __str__(self): return self.semester_name i got the following error TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple' -
How can I add bootstrap styles to my django form?
I created a django form and output it in template. But I can't understand how I can add bootstrap styles 'cause this django form isn't good. image of output here {% extends 'base.html' %} {% block title %} Contact Us {% endblock %} {% block content %} <h1>Contact Us</h1> <form method="post"> {% csrf_token %} {% for field in form %} <div class="form-group"> {{ field.label }} {{ field }} </div> {% endfor %} <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> <button class="btn btn-primary" type="submit" name="button">Send</button> </form> {% endblock %} -
Django application on Windows server 2012 R2
I have been stuck trying to deploy a Django application on a windows server for a while now. Tried many steps but I always ran into one problem or the other. Please can anyone take me through a step by step on how to go about this. Forgive the absence of code. -
problem assigning data to mdelset in view and save it
i am trying to create sale invoice form, in which i am using model and modelformset, but it giving error that NOT NULL constraint failed: saleinvoice_saletransiction.transiction_date i am not sure where problem lies def testCreate(request): form = Sale_Invoice_Main_Page modelformsets = Sale_Transction_formset if request.method == 'POST': forms = form(request.POST) formset = modelformsets(request.POST) if forms.is_valid() : forms.save(commit=True) and formset.save(commit=True) date = forms.invoice_date invoice = forms.invoice_no inv = Invoice_max.objects.get(invoice_name='sale') inv.invoice_no = invoice + 1 inv.save() transiction_type = "sale" for set in formset: set.transiction_date = date set.invoice_no = invoice + 2 set.transiction_type == transiction_type set.author = request.user.username forms.author = request.user.username forms.save() formset.save() return HttpResponseRedirect(reverse_lazy('saleinvoice:sale invoice home page')) else: forms = form(initial= { 'invoice_no' : sale_invoice.invoice_no + 8 , 'invoice_date': datetime.now()}) formset = modelformsets() return render(request, 'saleinvoice/test for model factory.html',{ "saleform" : forms, "saletransiction" : formset}) class Sale_Invoice_Main_Page(forms.ModelForm): class Meta: model = SaleInvoice fields = '__all__' exclude = ['created_at','updated_at','transiction_type','author'] widgets = {'description' : forms.TextInput(attrs={ 'placeholder' : 'description'}), 'invoice_no' : forms.TextInput(attrs={ 'readonly' : 'True'}), 'total_amount' : forms.TextInput(attrs={ 'readonly' : 'True'}), 'invoice_date' : forms.DateInput(attrs={ 'class' : "vdate" }), 'due_date' : forms.DateInput(attrs={ 'readonly' : "True" }), } Sale_Transction_formset = modelformset_factory(SaleTransiction, fields=( 'description', 'price','quantity','total','item'), exclude= ('author','invoice_no','transiction_type','transiction_date'), extra=1, widgets={ 'description' : forms.TextInput(attrs={ 'placeholder' : 'optionall','class' : 'description'}), 'price' : forms.NumberInput(attrs={ … -
In Django python forms, how do I give a form field a 'second name'?
I have a form on my website. The form is created using a python loop, which calls the fields by their variable name. Here is the HTML code: {% csrf_token %} {% for form_field in task_form %} <div class="wrap-input2 validate-input" data-validate="Name is required"> <input class="input2" type="text" name="{{ form_field.name }}"> <span class="focus-input2" data-placeholder="{{ form_field.name }}"></span> </div> {% endfor %} The variable {{ form_field.name }} is displayed on the website for each field, but it is a crude version of what I would like to actually display. This is how the fields are created in the python code: class Task(models.Model): name = models.CharField(max_length=200,default = 'Untitled task ',blank=True,) description = models.TextField(null=True,blank=True) cost = models.DecimalField(max_digits=19,decimal_places=2,null=True,blank=True,default=0) profit = models.DecimalField(max_digits=19,decimal_places=2,null=True,blank=True,default=0) start_date = models.DateField(null=True,blank=True) end_date = models.DateField(null=True,blank=True) hours_to_finish = models.IntegerField(null=True,blank=True,default=0) hours_finished = models.IntegerField(null=True,blank=True,default=0) project= models.ForeignKey(Project,on_delete=models.CASCADE) parent_task = models.ForeignKey('self', on_delete= models.SET_NULL ,null=True,blank = True) def __str__(self): return self.name is there any way I could call the form field with its name, but have a seperate variable tied to each field which I could call to display on the site, for example {{ form_field.nickname }} -
Link column with link to a file in static subdirectory; django-tables2
I am trying to use django-tables2 to render a table where one of the columns is a link to a file. The Link column with link to a file in static (django-tables2, Django) response is quite close however, in my case I have placed my files in static/pfd/. pdf = tables.TemplateColumn(template_code='{% load static %}<a href="{% static value %}">{{record.pdf}}</a>') This snippet of code works if my pdf is in the static directory, otherwise I get an missing file error. I have tried to add the subdirectory, but when I do I get an invalid syntax error. pdf = tables.TemplateColumn(template_code='{% load static %}<a href="{% static 'pdf/' %}">{{record.pdf}}</a>') ^ SyntaxError: invalid syntax How can I update that line so that the path is correct and will result in this url: http://xx.xx.xx.xxx:8000/static/pdf/lapidus_1_0.pdf Instead of: http://xx.xx.xx.xxx:8000/static/lapidus_1_0.pdf Thank you in advance. -
Django Pagination: switch between paginated/non-paginated ListView
I'm trying to elaborate a smart way to switch between a paginated template and a non-paginated one. I already have a working paginator and I was thinking of adding a button next to it that read "Show all results" that linked to a non-paginated list, from there then there would be another button to go back to the paginated list. 1) Easy Solution Use 2 ListViews with different assignations of the attribute paginate_by (django default to set pagination), but since I have many lists in my project it wouldn't be convenient (not much smart either). 2) Solution I'm stuck on Write a Mixin (that will later be extended by my ListViews) to set the variable paginate_by based on a condition and then add some useful variables to the context : class PaginationMixin: no_pagination = False no_pagination_url = '' def get_paginate_by(self, queryset): # overwrite django method if self.no_pagination: return None else: return super().get_paginate_by(queryset) def get_no_pagination_url(self): return self.no_pagination_url def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['no_pagination'] = self.no_pagination context['no_pagination_url'] = self.get_no_pagination_url() return context class MyListView(PaginationMixin, ListView): #... def get_no_pagination_url(self): return reverse('mylist_urlname') PROBLEM: I don't know how to set the no_pagination variable from the template. Is there some way to do this? Thanks for … -
How to handle Celery WorkerLostError due to c++ assertion in python imported module?
I have a python module with c++ code using pybind11 that I have imported in my django + celery 3.1.25 app. The c++ code contains assertions that might trigger inside of a celery worker which then leads to the WorkerLostError. I have tried to put the calls to the python c++ module inside try: except: scopes, however this does not work and the celery worker still crashes. I have also tried to bind an error callback function using the link_error= argument in my apply_async call to my celery task, however the method never gets called. Ideally I would like to catch the error somehow so I can display an error message to the user. Any suggestions is appreciated! -
Reset Password Functionality
I have an api built with Django Rest framework and a Front end that's built with Angular For the reset password functionality, when the user clicks on the reset password they should provide email within a reset password component on Angular. Then via submit action It hits the POST method of reset_password with the email in the body. Then the reset password controller should send an email to the user with this format base_url/reset_password/<token> When the user hits this url, they should be redirected to a reset password form with new password and confirm password The Question is: Where should this template be stored? Angular component or Django template? What is the best practice for such case? -
TypeError: __init__() takes 1 positional argument but 2 were given( "GET /%3Cint:pk%3E.pk HTTP/1.1" 500 61744)
Help needed. I can't seem to solve this problem. New to Django here. Traceback (most recent call last): File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\hanya\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: init() takes 1 positional argument but 2 were given template <h1><a href="{% url 'details' Testimony.pk %}">{{testimony.Title}}</h1> urls.py urlpatterns = [ ... re_path('<int:pk>/', views.detail, name='details'), ] views.py def details(self, pk): print('1') Testimony=get_object_or_404(Testimony, pk= pk) print('2') return render(request, 'details.html', {'Testimony': Testimony}) -
Signalling server performance issue: Python vs NodeJS
I'm developing a WebRTC application that requires a specific signalling server implementation. Initially I was developing the server in NodeJS but then I decided to migrate to Python (using Django Channels AsyncWebsocketConsumer to communicate with the clients through Websockets). After the migration I used the WebSocket benchmarking tool Thor to compare both implementations and these are the results obtained (5000 websocket connections, each one sending 1000 messages): Python (Django Channels) Implementation: class SignallingConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.peer = None self.signal = None self.is_peer_registered = False async def connect(self): await self.accept() async def disconnect(self, close_code): pass async def receive(self, text_data=None, bytes_data=None): pass NodeJS implementation: method.start = function () { this.webServer = this.createWebServer(); this.webServer.listen(this.config.port, function (){ console.log("Web server is listening"); }); this.socket = this.createWebSocket(this.webServer); this.socket.on('connection', function(ws) { var pingsCompleted = 0; ws.on('message', function(evt) { }.bind(this)); // Set out ping/pong mechanism var pingInterval = setInterval(function() { if(pingsCompleted > 2) { ws.close(); } else { ws.ping(); pingsCompleted++; } }.bind(this), config.pingPeriod); ws.on('pong', function(evt) { pingsCompleted = 0; }.bind(this)); ws.on('close', function(evt) { }.bind(this)); Python (Django Channels) Results: Online 30792 milliseconds Time taken 30792 milliseconds Connected 3714 Disconnected 0 Failed 1286 Total transferred 4.43MB Total received 525.91kB Durations (ms): min mean stddev median max … -
Adding custom methods to a Django model_factory object
I have this definition : ProfileForm = modelform_factory(User, fields=('username')) How do I add custom methods to ProfileForm ?