Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to disable pre-commit for specific folders
I have a simple Django project and I have Travis and pre-commit. Travis launches pre-commit. - repo: git://github.com/chewse/pre-commit-mirrors-pydocstyle sha: v2.1.1 hooks: - id: pydocstyle And pydocstyle show me errors in my migrations folders. I did not find how to disable it for specific folders, maybe do you know? Thank you. -
Execute management command from admin with arguments
My little podcast backend written in Django contains a ShowModel. I have also written a custom management command to update episodes for each show from an external API. For ease of use I'd now like to put a button next to the list of shows in the Django admin to be able to update them from there. I know there's call_command() that also takes the argument but I'm getting a bit stuck in how to bring this into the admin area where the shows are already. Also, if possible I'd also pass the output to the web admin. -
Django Access to Foreign Key data to set a field default value
I'm new to Python and Django and I'd like some help to solve a problem. I have two models with their respective forms. One has a Foreign Key link to the other and from, here I would like to set some fields default data. class Lexicon(models.Model): [...] case_sensitive = models.BooleanField(default=True) invariant = models.NullBooleanField(default=False) diacritics = models.BooleanField(default=True) [...] class Meta: verbose_name = "lexicon" ordering = ["filename"] def __str__(self): return self.filename class Lexeme(models.Model): lexicon = models.ForeignKey(Lexicon, on_delete=models.CASCADE) case_sensitive = models.BooleanField(default=True) diacritics = models.BooleanField(default=True) [...] class Meta: verbose_name = "lexeme" I would like the Lexeme model fields "case_sensitive" and "diacritics" to default from Lexicon. I suppose the forms may be a better place to do this. Any idea ? -
Use of paratheses symbols in django-viewflow flow
I have been at a loss understanding the use of parentheses in django-viewflow flow code. For example in the code below start = ( flow.Start(views.StartView) .Permission('shipment.can_start_request') .Next(this.split_clerk_warehouse) ) # clerk split_clerk_warehouse = ( flow.Split() .Next(this.shipment_type) .Next(this.package_goods) ) from here It seems as though, a tuple containing functions is assigned to start and to split_clerk_warehouse e.t.c. What does it mean. From my best guess it would seem that the .Next functions accept a tuple as input. NOTE I do understand the method chaining used here. I am just at a loss to understand the use of braces. Thanks. -
What is your best tutorial for starting a Django project with connection to DataBase?
What is your best tutorial for starting a Django project with connection to DataBase? -
`NameError: name 'args' is not defined` with overriden __init__
I am trying to instanciate an empty ModelForm with a simple overriden __init__ method. I call form = SimulationForm(), and I get an error NameError: name 'args' is not defined that I can't understand. class SimulationForm(models.ModelForm): class Meta: model = Simulation fields = ('name','description','numero') def __init__(self, *args, **kwargs): super(SimulationForm, self).__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs['class']='form-control' Do you have an idea of what's wrong in my approach ? -
How to search a word in elasticsearch in python
I have a index in elasticsearch contains two fields as like below Merchant Type Mcdonald restaurent Grand Hotel Hotel carryfore supermarket I have a list of bank transaction as like below ['POS TXN AT CARRYFORE.COM M','POS TXN AT MCDONALD M','POS TXN AT CAFE M','POS TXN AT GRAND HOTEL M',-------] If any word in list matches with merchant column in elasticsearch, it has to print there respective type. For example MCDONALD matches with merchant column MCDONALD in elasticsearch and print restaurent I am new to elasticsearch so help me. -
Can't retrieve images from application in Docker container
I'm trying to dockerize a python/django application.When Docker runs the build script in web container, it is unable to retrieve the images from application. it shows an error: [https://i.stack.imgur.com/FKTSL.png and on Google chrome console it shows: [https://i.stack.imgur.com/YHzZc.png] But what is interesting is that I don't get any errors when I do the same on my local machine. Everything goes as expected. Docker version 18.03.1-ce, build 9ee9f40 -
Django: ValidationError as ugettext or ugettext_lazy
I read a lot about ugettext and ugettext_lazy now. I understand _lazy is mostly for these things: - models.py (fields, verbose_name, help_text, methods short_description); - forms.py (labels, help_text, empty_label); - apps.py (verbose_name) ugettext for these: - views.py - Other modules similar to view functions that are executed during the request process (Source) However I am still not sure, should ValidationError's then also be done with ugettext_lazy? from django.utils.translation import ugettext as _ def check_if_form_is_empty(self): [...] if not quantities: raise forms.ValidationError( _("You didn't choose any tickets."), # TODO _ for translations code='no_tickets', ) -
How to convert UTC timezone to IST timezone while displaying in django?
The date time object is stored in UTC in database and i want to convert to IST while displaying for my specific use case without changing the TIME_ZONE value in setting.py file. I'm using django defaultfilters.date(event['test'].start_time, 'DATETIME_FORMAT') to format. -
Display Model name instead of 'Users' on the admin page
I've created a custom user model using abstractuser titled employee. class Employee(AbstractUser): username = models.CharField(max_length = 30) first_name = models.CharField(max_length = 30) last_name = models.CharField(max_length=30) email = models.CharField(max_length=255) password = models.CharField(max_length=30) user_type = models.ForeignKey('UserProfile', null = True) status = models.CharField(max_length = 30, default='Not Verified',) def __str__(self): return self.first_name + ' ' + self.last_name That is my models.py pertaining to Employee On the Admin page I see this - Admin Page Learningsys is my app name. How do I make it so that I see ''Employee or preferably 'Employees' under my app name instead of 'Users' and why does it show Users in the first place? I suspect it is because I am technically creating a 'Custom User' but would like clarification regardless. Thanks, Rohan. -
How to get a full url using reverse in Django
I want to save in a variable the url to access a service, so I am using reverse and the name for the entry in urlpatterns, and I get something like /es/general/provider_types/, but I want to get a full url, like https://127.0.0.1:8000/es/general/provider_types/ This is how I am using reverse: {'name': models.ProviderType._meta.verbose_name_plural.title(), 'url': reverse('rest_provider_types_list')} Is there any way I can do this? -
How to make a dynamic form
I have different Product Attributes like size, color, brand etc I want to display them in checkboxes on HTML to filter them I want to dynamically display them (currently I have hardcoded them as ) class Att(django_filters.FilterSet): q1 = AttributeChoiceValue.objects.filter(attribute__name='color') q2 = AttributeChoiceValue.objects.filter(attribute__name='size') color = django_filters.ModelMultipleChoiceFilter( queryset=q1.values_list('name', flat=True).distinct(), widget=forms.CheckboxSelectMultiple) size = django_filters.ModelMultipleChoiceFilter( queryset=q2.values_list('name', flat=True).distinct(), widget=forms.CheckboxSelectMultiple) class Meta: model = AttributeChoiceValue fields = () my models are class ProductAttribute(models.Model): slug = models.SlugField(max_length=50, unique=True) name = models.CharField(max_length=100) op = models.CharField(max_length=20,default='in') class Meta: ordering = ('slug', ) def __str__(self): return self.name def get_formfield_name(self): return slugify('attribute-%s' % self.slug, allow_unicode=True) def has_values(self): return self.values.exists() class AttributeChoiceValue(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100) attribute = models.ForeignKey( ProductAttribute, related_name='values', on_delete=models.CASCADE) class Meta: unique_together = ('name', 'attribute') def __str__(self): return self.name -
Django proxy model
class DeviceType(models.Model): device_type = models.CharField(max_length=200,unique=True) def __str__(self): return self.device_type class Device(models.Model): device_type = models.ForeignKey(DeviceType,to_field='device_type') serial_number = models.CharField(max_length=200,unique=True) in_use_by = models.ForeignKey(User,to_field='username') brand = models.CharField(max_length=200,default="-", null=False) model = models.CharField(max_length=200,default="-", null=False) type_number = models.CharField(max_length=200,blank=True,null=True) mac_address = models.CharField(max_length=200,blank=True,null=True) I want to make a django form that would have a drop-down as follows: (Below is the general pattern of the data present in drop-down menu): devicetype-serialnumber-model-brand e.g: Laptop-abcd1234-T45k-QWER How can I achieve this using Django proxy model? -
django celery monitor doesn't show any tasks
I cannot see the tasks in admin. I followed the steps in https://github.com/jezdez/django-celery-monitor I used celery==4.1.1 django-celery-results==1.0.1 django-celery-beat==1.0.1 django_celery_monitor==1.1.2 ran manage.py migrate celery_monitor The migrations went well. ran celery -A lbb events -l info --camera django_celery_monitor.camera.Camera --frequency=2.0 and celery -A lbb worker -l info in separate shells. But still cannot see the tasks I ran in celery-monitor > tasks table. Any help really appreciated. thanks -
Generate Nested List Django
I've got a spreadsheet like this. I have to generate a nested list. if parent id is 0, then it will have no parent i.e. root. The resulted list will be look like below please show me a way to do this. Thanks -
How to use GO with an existing Django Project?
I have a Django project which fetches data from MongoDB with multiple apps. Now, I want to use GO instead of python for one particular app in Django. How do I go ahead with this? Should I still be using Django's web server whichever I was using earlier or use GO web server and serve static files? Any help would be appreciated. -
Give me an exapmple of usage django-taggit-labels
https://github.com/bennylope/django-taggit-labels Here is an example of code: from taggit_labels.widgets import LabelWidget class ContentForm(forms.Form): tags = TagField(required=False, LabelWidget(model=MyTag)) But this code gives an error. I asked about it in Freenode, but they say that in README have a bug. Give me please example of working views, models, and forms :3 -
how to queryset manytomanyfiled through foreignkey(model only has 2 field)
guys, how to queryset manytomanyfiled through a foreignkey, my model only has 2 field as below: class Model_A(models.Model): b = models.ForeignKey(Model_B, on_delete=models.CASCADE, null=True) c = models.ManyToManyField(Model_C, related_name="+", blank=True) Thanks so much, really appreciate for any advice!!! -
Ajax working on Localhost but not on Live Server
I'm working on a website on which users can comment something below the posts, running on Python & Django. As soon as a user comments something, then I'm updating comments without refreshing the web-page. Here's the code, In views.py postType1 = sorted(Posts.objects.filter( . . . ), key=lambda x: random.random()) postType2= Posts.objects.filter( . . . ) In template, // BLOCK - 1 {% for post in postType1 %} <p>{{ post }}</p> <div class="comm_update" action="{% url 'comment:create' post.id %}"> <form class="comm_form" action="{% url 'comment:create' post.id %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <textarea id="id_comment"></textarea><br /><br /> <button type="submit">Submit</button> </form> </div> {% endfor %} <hr /> // BLOCK - 2 {% for post in postType2 %} <p>{{ post }}</p> <div class="comm_update" action="{% url 'comment:create' post.id %}"> <form class="comm_form" action="{% url 'comment:create' post.id %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <textarea name="comment_text" id="id_comment"></textarea><br /> <button type="submit">Submit</button> </form> </div> {% endfor %} Auto updating comments without refreshing webpage, $(document).on("submit", ".comm_form", function(t) { t.preventDefault(); var o = $(this), e = $.post(o.attr("action"), o.serialize()), n = o.attr("action"); e.done(function(t) { var e = $(t).find(".comm_update[action='" + n + "']"); o.closest(".comm_update").html(e), o[0].reset() }) }); On localhost everything is working fine. *But on live server the first block BLOCK - 1 is not updating … -
Why can't Django Channels Daphne use multi-threading to process request concurrently?
I am aware of Python's GIL and threading in Python isn't as easy as spawning a go routine in Go. However, it seems to me that Ruby was able to pull it off with Puma and Unicorn to achieve concurrency with multi-threading. My question is actually two-fold. My experience is limited to Django Channel's Daphne. Besides Daphne, what are the other choices of web server that is multi-threading like the puma and unicorn in Rails? From Daphne's documentation, I learned that parallelism is achieved by spawning new processes (workers) Because the work of running consumers is decoupled from the work of talking to HTTP, WebSocket and other client connections, you need to run a cluster of “worker servers” to do all the processing. Each server is single-threaded, so it’s recommended you run around one or two per core on each machine; it’s safe to run as many concurrent workers on the same machine as you like, as they don’t open any ports (all they do is talk to the channel backend). As stated, each worker is single threaded. When it comes to I/O function call, the worker is blocked completely. My question is, why can't Daphne spawn multiple threads for … -
how to continuously update log file excluding response message of console of django server using logging module?
I am new to logging module. i want to know that how to continuously update log file excluding response message like 2018-06-07 11:33:22,330|INFO|"POST /MyProject/ HTTP/1.1" 200 36. settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(asctime)s|%(levelname)s|%(message)s' } }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': "logging.handlers.RotatingFileHandler", 'formatter': 'standard', 'filename': "C:\\ProgramData\\PROGRAMX\\Logs\\PROGRAMX_logs_%s.txt" % (datetime.today().strftime("%Y_%m_%d")) } }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, 'format': '%(asctime)s|%(levelname)s|%(message)s' } } } i am updating log in django like, import logging log = logging.getLogger('django') log.error("Internal Error: X happened.") I want to complete two tasks: 1. Update log file immediately after request get processed. 2. In log file, i don't want to add message like "POST /MyProject/ HTTP/1.1" 200 36. PROGRAMX_logs_2018_06_07.txt 2018-06-07 11:33:14,317|ERROR|Internal Error: X happened. 2018-06-07 11:33:14,319|INFO|"POST /MyProject/ HTTP/1.1" 200 36 2018-06-07 11:33:22,327|ERROR|Internal Error: X happened. 2018-06-07 11:33:22,330|INFO|"POST /MyProject/ HTTP/1.1" 200 36 -
Display part of the content data
I have the following template code: <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">{{ article.title }}</h3> </div> <div class="panel-body"> {{ article.content }} <!--will display the full text--> </div> I intend to show the first 200 characters of the content, like: {{ article.content|length=200 }} How to achieve such a constrain on the text. -
How to send transaction using ethereum contract?
I am going to send token(made by myself) transaction to the other address. So I wrote code as follow in order to get code from token contract address in ethereum project(Python project). Web3(HTTPProvider('https://ropsten.infura.io/MY-API-KEY')) web3.eth.getCode(str(contract_address)) But this code raise error. Could not transact with/call contract function, is contract deployed correctly and chain synced? I can't know the reason. If anyone know about that, plz help me. thanks. -
Adding basic search to your Django site
I am trying to implement basic search in the detail view. Following is the code for the views. The detail view has the function get_queryset() this is actually linked to detail.html Once i click on search error : FieldError at /update/1/ Cannot resolve keyword 'insurance_name' into field. Choices are: client_name, clientinfo, id views.py class IndexView(generic.ListView): template_name = 'update/index.html' context_object_name = 'all_client' def get_queryset(self): return Clients.objects.all() class DetailView(generic.DetailView): model = Clients context_object_name = 'client' template_name = 'update/detail.html' paginate_by = 10 def get_queryset(self): result = super(DetailView, self).get_queryset() query = self.request.GET.get('q') if query: # query_list = query.split() result = result.filter(Q(insurance_name__icontains=query) | Q(update__icontains=query)) return result index.html {% for client in all_client %} <div class="col-xs-18 col-sm-6 col-md-3" align="center"> <div class="thumbnail"> <div class="caption"> <!--<img src="{% static 'update/img/top.png' %}" class="img-rounded" height="100" width="100">--> <h2>{{ client.client_name }}</h2> <!-- View Details --> <a href="{% url 'update:detail' client.id %}" class="btn btn-primary btn-sm" role="button">View Details</a> <!-- Delete --> <form action="{% url 'update:client-delete' client.id%}" method="post" style="display: inline;"> {% csrf_token %} <input type="hidden" name="client_id" value="" /> <button type="submit" class="btn btn-default btn-sm"> <span class="glyphicon glyphicon-trash"></span> </button> </form> <form action="{% url 'update:client-update' client.id %}" method="post" style="display: inline;"> {% csrf_token %} <input type="hidden" name="client_id" value="" /> <button type="submit" class="btn btn-default btn-sm"> <span class="glyphicon glyphicon-edit"></span> </button> </form> detail.html …