Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
creating re-usable django library
I am new to django. I want to create a library using django which i can use in multiple projects. This library when imported must must provide functions which can be used in other projects. I have read the documentation of django but according to it the way to interact with library created using django is via urls. How to expose the functions of my library which can be used in other projects? Eg. If I create a library say, calculator, I want to provide functions like add, subtract. Thanks. -
sending arguments to django rest framework mixin is not parsed as keyword
I am using Django rest framework. I am testing my method via postman. I have a view called ActionView, which in I'm using a mixin: class ActionView( mixins.CreateModelMixin, mixins.RetrieveModelMixin, generics.GenericAPIView): queryset = Action.objects.all() serializer_class = ActionSerializer def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def get(self, request,*args, **kwargs): return self.retrieve(request, *args, **kwargs) The URLs are: urlpatterns = [ path(r'action/', views.ActionView.as_view()), path(r'alert/', views.AlertView.as_view()), ] and they are included in the main router function. I am trying to send a get request, like this: http://localhost:8000/actionsAndAlerts/action/?pk=1/ and like this: http://localhost:8000/actionsAndAlerts/action/?1/ but the pk I am sending is not rendered as a keyword at the get method - and so I keep getting this error: AssertionError: Expected view ActionView to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly. I tried adding: @detail_route(url_path='action/(?P[0-9]+)') above the get method but with no success. any idea how to solve this? Thanks a lot in advance. -
How to activate links for a row when checkbox is checked
Update and Delete links are for each row in the table. I want the links of each row to be activated when I click the checkbox for that particular row. Does anyone know how to do it? I added the {{forloop.counter}} and now it is generating a new id but all the ids are still linked to the links of the first row. each row has its own links and those links need to be activated when I click the checkbox for that row. function toggleLink(checkBox) { var link1 = document.getElementById("agreeLink1"); var link2 = document.getElementById("agreeLink2"); var link3 = document.getElementById("agreeLink3"); if (checkBox.checked) { link1.style.display = "inline"; link2.style.display = "inline"; link3.style.display = "inline"; } else { link1.style.display = "none"; link2.style.display = "none"; link3.style.display = "none"; } } <div class="container"> <table class="table table-bordered"> <tbody> <tr> <td> <form> <p><input type="checkbox" id="agreeCheckbox{{forloop.counter}}" name="agreeCheckbox" value="{{catalog.id}}" onchange="toggleLink(this);"></p> </form> </td> <td>{{ catalog.DatasetName }}</td> <td>{{ catalog.Type }}</td> <td>{{ catalog.Classification }}</td> <td>{{ catalog.OriginalSource }}</td> <td>{{ catalog.OriginalOwner }}</td> <td>{{ catalog.YearOfOrigin }}</td> </tr> </tbody> </table> </div> <div class="card-footer text-center text-muted"> <a href="{% url 'catalog_edit' catalog.pk %}" id="agreeLink1" style="display:none;">Update</a> | <a href="{% url 'catalog_delete' catalog.pk %}" id="agreeLink2" style="display:none;">Delete</a> | <a href="{% url 'export_to_xml' %}" id="agreeLink3" style="display:none;">Export to XML</a> </div> -
django mssql inspectdb all schema and tables
Fellows, I am trying to generate models from all the tables of a MSSQL SERVER 2017 legacy database with a django inspectdb. My problem is that it is been generated just the tables that has dbo prefix. Other tables on other schemas, like HumanResources.Department, are not been generated. I already tryed to change the Default Schema for the user connected in the database, but no success. I've seen a few posts that suggests to change the behavior of inspectdb, but I dont know if this is the best solution, or to get it done right. Any ideas about how to change that and get all tables? -
Custom login URL in django
I am a newbie in django and I was experting different options in Django. I have created a class based view which requires user authentication to view the web page. I am using the inbuilt LoginView. When the url pattern is specified as follows url(r'^login/', auth_views.LoginView.as_view(),name='login'), it is correctly redirected to login page. But when I give url(r'^restaurant/login/', auth_views.LoginView.as_view(),name='login'), I get a 404 when trying to access the page that requires user authentication. But when I manually go to that url in browser, it works perfectly fine. Why is that? Shouldn't it both cases work? -
User Registration form not saving data to database in django
I have made a user registration form and it is supposed to redirect to my home page and save the user data. forms.py from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password'] Here is my views.py file views.py from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth import authenticate, login from django.views import generic from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.views.generic import View class UserFormView(View): form_class = UserForm template_name = 'graph/registration_form.html' #display blank form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) #process form data def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) # cleaned (normalized) data username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() # returns the objects if credentials are correct user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('graph:index') return render(request, self.template_name, {'form': form}) Here is my registration_form.html file registration_form.html <form action="" method="post" role="form" style="border:1px solid #ccc"> {% csrf_token %} <div class="container"> <h1>Sign Up</h1> <p>Please fill in this form to create an account.</p> <hr> <label for="email"><b>Username</b></label> <input type="text" placeholder="Enter Username" name="email" required> <label for="email"><b>Email</b></label> <input type="text" placeholder="Enter Email" name="email" required> <label … -
How to add a choices Field that will list currencies from babel
I came across babel documentation and I would like to use it in a model that has a currencies = models.ChoiceField. How do I use babel inbuilt currencies to list in the above field name? -
Django-Filter: Creating checkboxes for Boolean Field
Models.py class Task(models.Model): online = models.BooleanField(blank=False) I would like to use django-filter to create the following checkboxes in the form: [] Online [] Physical If form is empty or both are ticked, get Task.objects.all(). If only one is ticked, then do Task.objects.filter('Online'=True/False). I tried to add the following: import django_filters from app.models import Task from django.db import models class TaskFilter(django_filters.FilterSet): online = django_filters.BooleanFilter(name='online', lookup_expr='isnull') class Meta: model = Task fields = ['online'] filter_overrides = { models.BooleanField: { 'filter_class': django_filters.BooleanFilter, 'extra': lambda f: { 'widget': forms.CheckboxInput, }, }, } I tried the following widgets: Select, RadioSelect, CheckboxInput, but it seems I get the same output for all of them. I get a dropdown list e.g. Online: [ Dropdown to select a value from Yes, No, Unknown ] -
Multiple queries within one view - Django
In Django I am creating a selector app. What I am trying to do is ask a user to enter information and whatever they put, it will return a dog breed. The input must match all attributes of a dog in the database. form.html <form action="/search/" method="POST"> {% csrf_token %} <div class="form-group"></div> <label class="main-label">Must be good with children:</label><br> <input type="radio" name="goodwithchildren" value="Yes"><label class="radio-label">Yes</label><br> <input type="radio" name="goodwithchildren" value="No"><label class="radio-label">No</label> </div> <div class="form-group"></div> <label class="main-label">Drooling:</label><br> <input type="radio" name="drooling" value="Yes"><label class="radio-label">Don't Mind</label><br> <input type="radio" name="drooling" value="No"><label class="radio-label">No Slobbering!</label> </div> <div class="form-group"></div> <label class="main-label">Coat Length:</label><br> <input type="radio" name="coatlength" value="Short"><label class="radio-label">Short</label><br> <input type="radio" name="coatlength" value="Medium"><label class="radio-label">Medium</label><br> <input type="radio" name="coatlength" value="Long"><label class="radio-label">Long</label> </div> <div class="form-group"></div> <button type="submit" class="btn btn-primary">Find My Dog!</button> </div> </form> Currently this is the view I am trying to work from. I am just trying to get the all dongs from just 'Good with Children' but want also other queries def search_form(request): return render(request, 'polls/search_form.html') def search(request): if 'goodwithchildren' in request.POST and request.POST['goodwithchildren']: q = request.POST['goodwithchildren'] breed = Breed.objects.filter(name=q) return render(request, 'polls/search_results.html', {'breed': breed, 'query': q}) else: return HttpResponse('Please submit a search term.') Want to know how I can query all fields and return the names of dogs in another html like this … -
urlpatterns = [...]+static(settings.STATIC_URL) get the escape symbol
When I add STATIC_URL in the urls.py: urlpatterns = [...]+static(settings.STATIC_URL) but there I get the ^static\/(?P<path>.*)$ in the urls. Shouldn't it be ^static/(?P<path>.*)$? like the ^media/(?P<path>.*)$. in settings.py: STATIC_URL = '/static/' -
How to test related_name in django model?
I have a model: @python_2_unicode_compatible class TelegramUser(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, verbose_name=_('User'), related_name='telegramuser', on_delete=models.CASCADE) token = models.CharField(max_length=255, verbose_name=_('Token')) chat_id = models.CharField(max_length=255, verbose_name=_('Chat id'), null=True, blank=False) And I need to test verbose_name and related_name for each fields of this model. So I'm testing verbose_name def test_user_label(self): field_label = self.telegramuser._meta.get_field('user').verbose_name self.assertEquals(field_label,'User') But if I try testing 'related_name', i got error like this: AttributeError: 'OneToOneField' object has no attribute 'related_name' But this problem is not due to the fact that the field is OneToOne In the docs, I found only how to check the related_model: >>> field = user._meta.get_field('user') >>> print(field.related_model) <class 'django.contrib.auth.models.User'> But I never found a way to test related_name. -
Django admin inline duplicate key value violates unique constraint
Python 3.6 Django 2.0 I have two models: from django.contrib.contenttypes.fields import GenericRelation @python_2_unicode_compatible class Domain(models.Model): tool_result = GenericRelation('projects.ToolResult') @python_2_unicode_compatible class ToolResult(models.Model): tool = models.ForeignKey('projects.Tool', on_delete=models.CASCADE) class Meta: unique_together = ('content_type', 'object_id', 'tool') Then in admin class I create generic tabular inline: class ToolResultGenericTabularInline(GenericTabularInline): model = ToolResult extra = 0 @admin.register(Domain) class DomainAdmin(admin.ModelAdmin): inlines = [ToolResultGenericTabularInline, ] And when I try to save same objects via inline, I get an error: duplicate key value violates unique constraint "projects_toolresult_content_type_id_object_i_71ee2c2e_uniq" DETAIL: Key (content_type_id, object_id, tool_id)=(18, 22, 3) already exists. Is this a django bug ? -
How to remove django-filter additional keywords in form fileld label
When i customize search type in the filter: django_filters.CharFilter(lookup_expr='icontains') it adds '[field_name] contains' keyword to the end of displaying label in template {{ field.label }}. I specifically use verbose_name='Some filed' argument in my model to make it accessible in template, but filter modifies it for inexplicable reason. Is there any option for it to be displayed as i set it in versbose_name? -
Django filter for max difference between 2 columns
I have a table named RoundTable and it has 2 fields, the max number of seats and the number of currently occupied seats. I want to find the max difference between these two columns. My model: class RoundTable(models.Model): total_seats = models.SmallIntegerField(validators=[MinValueValidator(1)]) occupied_seats = models.SmallIntegerField(validators=[MinValueValidator(1)]) .... other fields What would the query be like? RoundTable.objects.aggregate(?) -
Django auto select empty value in multiplechoiecfield
I have a MultipleChoiceField in Django 1.11 and it auto selects the empty value in the rendered output what is not desired. choices = [(u'', '(no extra)'), (u'cheese', u'Cheese'), (u'Pepper', u'Pepper')] extra_topics = forms.MultipleChoiceField(required=False, choices=choices) Is there any flag that I can prevent this? -
Unique constraint across 2 django models with the same field type?
I need a way to describe a model constraint where 2 models have the same field (EmailField in this case) and unique across both models (P.S. I do not mean unique_together) What I'm trying to do? One model is the user model, the other is pending invitations. I don't want users to be able to send invitations to emails present already present in either of the tables. I know I can do a multiple-inheritance. But is there any other way to do this? -
http://127.0.0.1:8000/ help refused to connect
. I tried to change server but still not working . I need help from anyone when I run-server, I copied the URL when paste to google chrome it gives me refused to connect ! I need Help -
How to export to XML format from DJango SQLIte
I have a table of datasets in a django template like so: {% extends 'base.html' %} {% block title %}Catalogs{% endblock %} {% block content %} <table class="table table-bordered" id="tblData"> <thead> <tr> <th>DatasetName</th> <th>Type</th> <th>Classification</th> <th>OriginalSource</th> <th>OriginalOwner</th> <th>YearOfOrigin</th> </tr> </thead> </table> {% for catalog in object_list %} <div class="container"> <table class="table table-bordered"> <tbody> <tr> <td> <form> <p><input type="checkbox" id="agreeCheckbox" name="agreeCheckbox" value="agreeCheckbox" onchange="toggleLink(this);"></p> </form> </td> <td>{{ catalog.DatasetName }}</td> <td>{{ catalog.Type }}</td> <td>{{ catalog.Classification }}</td> <td>{{ catalog.OriginalSource }}</td> <td>{{ catalog.OriginalOwner }}</td> <td>{{ catalog.YearOfOrigin }}</td> </tr> </tbody> </table> </div> <div class="card-footer text-center text-muted"> <a href="{% url 'catalog_edit' catalog.pk %}" id="agreeLink1" style="display:none;">Update</a> | <a href="{% url 'catalog_delete' catalog.pk %}" id="agreeLink2" style="display:none;">Delete</a> | <a href="{% url 'export_to_xml' %}" id="agreeLink3" style="display:none;">Export to XML</a> </div> {% endfor %} {% endblock content %} I have implemented the check box functionality for each of the rows of the table like so: function toggleLink(checkBox) { var link1 = document.getElementById("agreeLink1"); var link2 = document.getElementById("agreeLink2"); var link3 = document.getElementById("agreeLink3"); if (checkBox.checked) { link1.style.display = "inline"; link2.style.display = "inline"; link3.style.display = "inline"; } else { link1.style.display = "none"; link2.style.display = "none"; link3.style.display = "none"; } } I have a model of datasets like so: class Catalog(models.Model): DatasetName = models.CharField(max_length=280) Type = models.CharField(max_length=280) Classification … -
possible to add to Django ManyToManyField with only instance IDs
Is it possible to add to a ManyToManyField when you've only the list of IDs, without a db hit to retrieve instances (add_instances_but_with_db_hit does this, but with a hit). Thanks. class WorkerCombinedPayment(AbstractReimbursement): charge_id = models.TextField(blank=True, null=True) paid = models.BooleanField(default=False) worker = models.ForeignKey(Worker) class MassPayment(TimeStampedModel): list_payments = JSONField(blank=True, null=True) paypal_batch_id = models.TextField(blank=True, null=True) success = models.NullBooleanField() response_from_paypal = JSONField(blank=True, null=True) workercombinedpayments = models.ManyToManyField(WorkerCombinedPayment) def add_instances_but_with_db_hit(self, id_list): found = WorkerCombinedPayment.objects.filter(id__in=id_list) self.workercombinedpayments.add(found) -
Hide `***Block` in Wagtail
In Wagtail, I have made a Block with an ImageChooserBlock in it like this: class MyBlock(blocks.StructBlock): background = ImageChooserBlock() Now i want to add some extra fields to the ImageChooserBlock so I moved it to its own Block so now it looks like this: class FancyImageChooserBlock(ImageChooserBlock): extra = blocks.Charfield() class MyBlock(blocks.StructBlock): background = FancyImageChooserBlock() My first issue is that the extra field doesn't get included. (Maybe because the block inherits from ImageChooserBlock? My second and most important issue is that I want to able to have the extra field to be hidden in the form, but included in the template rendering. Does someone know how and if this is possible? I don't want to do any hacky stuff injecting js or css for this. There must be a way to do this using Blocks, Widgets and forms.HiddenInput or something like that. I know i can do some calculations in the clean method of my FancyImageChooserBlock to manually set the value of extra. This is exactly what I want to do. Any help is appreciated, I'm really stuck here. -
django -redis use sort can get dict type?
i'm used django 2.0.2 and django-redis and redis 4.0.8 myredis.py import redis class myredis(): config = { 'host': 'localhost', 'port': 6379, 'db': 0, } r=[] c = redis.ConnectionPool(**config, decode_responses=True) def __init__(self): r = redis.StrictRedis(connection_pool=c) def list(self): result = self.r.sort('mylist',None,None,'nosort', ['*->createDate','*->content','*->username'],True,None,None,True) return result redis mylist is have message:1 message:2 message:3 ~~~~~ message:100 message:1 field content = '1' createDate = '*****' username=*** message:2~100 too i call this method returned this [['20180328','content','user1'],['20180328','content2','user2'], ['20180328','content3','user1'],['20180328','content4','user1'], ['20180328','content5','user1'],['20180328','content6','user1'], ['20180328','content7','user1'],['20180328','content8','user1']] i want this dict [{"createDate":any,"content":any,"username":any}, {"createDate":any,"content":any,"username":any}, {"createDate":any,"content":any,"username":any}] can django-redis sort return dict type? -
Is there a django DRF full messaging cover app via API?
I am looking for a messaging app between users, with API endpoints that gives me something like : API for user messages (get my messages, read message etc...) API for All unread messages (get my unread messages) API send message with category, broadcast (multi recipients),attachments etc ... API For thread conversions API for archive messages Postman and others do not give full API cover, but only send or send to many, Thanks -
Django unit testing middleware error
This is my middleware - class HeadersControlMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) response['Cache-Control'] = "no-cache" # Code to be executed for each request/response after # the view is called. return response and this is my unit test - class TestHeadersControlMiddleware(SubmittalsAPITestCase): def dummy_middleware(self): response = Response() response.status_code = 200 response.json = {"key1": "value1"} return Response def test_cache_control_header_is_added(self): self.middleware = HeadersControlMiddleware(self.dummy_middleware()) self.request = RequestFactory() self.request.META = { "REQUEST_METHOD": "POST", "HTTP_APP_VERSION": "1.0.0", "HTTP_USER_AGENT": "AUTOMATED TEST" } self.request.path = '/testURL/' self.request.session = {} response = self.middleware(self.request) print(str(response['Cache-Control'])) When running the test I'm getting the following error: response = self.get_response(request) TypeError: __init__() takes 1 positional argument but 2 were given I don't understand why. it shouldn't even get to the 'init' part in that line as far as I understand. Any idea? -
how do I change filter position on django admin site.
enter image description here I want those filters to appear on the right side of admin page -
Form data is not bound in dynamically added inline formset in Django
I got a question regarding the validation of a dynamically added inline formset in Django. It seems like I am missing something in my implementation. Here is my case: My project is a team management platform. A team is called Crew and can have several time Schedules. Each Schedule can have several Shifts. Please take a look at my code. At the moment I am able to create a schedule with several, dynamically added forms of the formset for the Shifts, if all fields are valid. If not, the error for the Shift forms is not displayed and it is filled with the initial data again. It looks like the data of the shift forms is not bound after sending the POST request (because form.is_bound() is false). Moreover the data of Shift forms is not populated again after the POST request. What do you think is the cause of this behaviour? Do I have to overwrite the is_valid function? I dont know, because it looks like the function works fine - the data is just not bound correctly to the new forms. Views.py def schedule_add(request, crew_id): if request.method == "GET": form = ScheduleForm() ShiftFormSet = formset_factory(ShiftForm) return render(request, 'schedule_add2.html', {'form': …