Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not able to run django with lighttpd
I am learning Django and configuring Lighttpd as web server. My Lighttpd Server Configuration for running Django is like below server.modules = ( "mod_access", "mod_alias", "mod_compress", "mod_redirect", "mod_scgi", "mod_proxy", ) server.document-root = "/var/www/html" server.upload-dirs = ( "/var/cache/lighttpd/uploads" ) server.errorlog = "/var/log/lighttpd/error.log" server.pid-file = "/var/run/lighttpd.pid" server.username = "www-data" server.groupname = "www-data" server.port = 8899 index-file.names = ( "index.php", "index.html", "index.lighttpd.html" ) url.access-deny = ( "~", ".inc" ) static-file.exclude-extensions = ( ".php", ".pl", ".fcgi" ) compress.cache-dir = "/var/cache/lighttpd/compress/" compress.filetype = ( "application/javascript", "text/css", "text/html", "text/plain" ) # default listening port for IPv6 falls back to the IPv4 port ## Use ipv6 if available #include_shell "/usr/share/lighttpd/use-ipv6.pl " + server.port include_shell "/usr/share/lighttpd/create-mime.assign.pl" include_shell "/usr/share/lighttpd/include-conf-enabled.pl" scgi.protocol = "uwsgi" scgi.server = ( "/" => (( "host" => "127.0.0.1", "port" => 9000, "check-local" => "disable" )), ) I created Django app polls (as part of Django tutorials mentioned in the Django documentation) where in the first part it is to create a simple view under polls/view.py from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") I did as is mentioned in the documentation and able to get above page by executing following command for uwsgi uwsgi --http 127.0.0.1:9000 --chdir ~/new_project/mysite --wsgi-file mysite/wsgi.py … -
Get multiple data from checkbox using "request.POST.get"
I tried to get multiple data from the checkbox using method below in my views.py: if (((request.POST.get('data_choice ')) == ('Salary')) and ((request.POST.get('data_choice ')) and ((request.POST.get('data_choice ')) == ('Overtime')) ): But the problem is the "and" condition is not working but if i use "or" condition it's work. May I know what's the problem with my code ? Is the request.POST.get can only get 1 data ? choices.py class DataChoices(models.TextChoices): salary = 'Salary',_('Salary') bonus = 'Bonus',_('Bonus') allowance= 'Allowance',_('Allowance') overtime= 'Overtime',_('Overtime') models.py class Data(models.Model): Data_choices = Data_choices data_choices = models.CharField(max_length=40,choices=Data_choices.choices,blank = True, null= True) forms.py class dataForm(forms.ModelForm): datachoice = DataChoices data_choice = forms.MultipleChoiceField(label=False,choices=datachoice .choices, required=True,widget=forms.CheckboxSelectMultiple( attrs= { "checked":"checked" })) class Meta: model = Data fields = ('__all__') html <form class="form" method="POST"> {% csrf_token %} <fieldset class="form-group"> <h4 style="display:inline-block;" class="title-section">PRINT FORM</h4> <div class="card"> <div class="card-body"> <div class="row col" > <h5>Please select data to be included in the form</h5> </div> <div class="row mt-4"> <div class="col-lg">{{ form.data_choice |as_crispy_field }}</div> </div> </div> <div class="col " style="text-align:center;"> <button class='btn btn-info btn-block'>Next</button> </div> </div> </fieldset> </form> views.py if form.is_valid: data = { 'data_choice ':request.POST.get('data_choice '), } if (((request.POST.get('data_choice ')) == ('Salary')) and ((request.POST.get('data_choice ')) == ('Bonus')) ): request.session['decision_data'] = data return redirect ('printformA') else: messages.error(request, f'Error in creating … -
One to many Generic Listview Django
I'am new to Django. I have a one to many relationship - Example: A CustomUser can have one to many Memberships. I want to create a view that shows a list of all the Memberships for a specfic CustomUser. I tried the Generic ListView with no success, it only shows a list of all the meberships in the Membership Table and not memberships for a specific user. Model: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True,) personal_Id = models.CharField(max_length=12, blank=False) first_name = models.CharField(_('first name'), max_length=30, blank=True) middle_name = models.CharField('middle name', max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) avatar = models.ImageField(upload_to='images', blank=True) def __str__(self): return self.email def full_name(self): return '%s %s %s' % (self.first_name, self.middle_name, self.last_name) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() class Membership(models.Model): CustomUser = models.ForeignKey(CustomUser, on_delete=models.CASCADE) Membeship_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) reg_date = models.DateTimeField(default=timezone.now) start_date = models.DateTimeField('start date') end_date = models.DateTimeField('end date') member_type= ( ('Y', "Year"), ('Q', "Quarter"), ('H', "Half-Year"), ) membership_type = models.CharField(choices=member_type, max_length=10) View class MemberShipIndex(generic.ListView): model = Membership template_name = 'members/membership_list.html' context_object_name = 'membership_list' def get_context_data(self, **kwargs): context = super(MemberShipIndex, self).get_context_data(**kwargs) return context URL path('<int:pk>/membership/', views.MemberShipIndex.as_view(), name='MemberShipIndex'), HTML {% for Membership in membership_list … -
How to do styling in templates as my styling not working in Django templates?
i downloaded code from github and runned its server it showed me output with styled templates like this: But after two days, my styling gone wrong, similarly in my own project where I was working styling was wroking but now, it gives me view like this: and forms displaying like this: I don't know why it gone like this as two days before it was working fine, and also github project that i have downloaded, its styling also not working, even i didn't make any change in that downloaded project. First it was working. Now in both downloaded and my own express travel project as I was following that downloaded project templates these templates are not working fine. Kindly help in which files i am making mistakes , I am stuck here. Is there any error of static files ? or CSS styling? how can i resolve this? here are my template code: add_manager_template.html form_template.html home_content.html sidebar_template.html -
i am getting this error when try to get token for superuser
Not Found: /get-api-token/ username="rajkumar"password="123" -
django json 404 not found
I have merged my code with a master branch. Before my code was working totally fine. I'm getting Failed to load resource: the server responded with a status of 404 (Not Found):8000/create-sub:1 and Uncaught (in promise) TypeError: Cannot read property 'message' of undefined at (index):387 main file / urls.py path('subscription/', include('subscription.urls')), # add path``` subscription file / urls.py urlpatterns = [ path("", views.checkout, name="checkout"), path("create-sub", views.create_sub, name="create sub"), path("complete/", views.complete, name="complete"), #add ] checkout.html function createPaymentMethod({ card }) { // Set up payment method for recurring usage let billingName = '{{user.username}}'; stripe .createPaymentMethod({ type: 'card', card: card, billing_details: { name: billingName, }, }) .then((result) => { if (result.error) { displayError(result); } else { const paymentParams = { price_id: document.getElementById("priceId").innerHTML, payment_method: result.paymentMethod.id, }; fetch("/create-sub", { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken':'{{ csrf_token }}', }, credentials: 'same-origin', body: JSON.stringify(paymentParams), }).then((response) => { return response.json(); }).then((result) => { if (result.error) { // The card had an error when trying to attach it to a customer throw result; } return result; }).then((result) => { if (result && result.status === 'active') { window.location.href = 'complete'; }; }).catch(function (error) { displayError(result.error.message); }); } }); } -
Can I do direct database updates in Django easily?
I am trying to write a web application that displays the content of a database as a website, e.g. in the form of a table, and lets the user update the table entries, which should automatically be reflected in the database, so that on page reload, the table looks exactly as the user left it. Since my web development skills are fairly outdated, I wanted to take this as an excuse to try some new stuff. I know my way around SQL and Python quite well, so I thought Django would be a good choice. I don't have a lot of experience in Javascript however. I already worked through the tutorial, which covers classic HTML forms where you enter a bunch of data and then hit "submit" to push to the database. What I would really prefer though is to have my whole table freely editable and either immediately save any change to the database (e.g. whenever I click a checkbox or "focus out" of a text box). As a second option I thought about having a single "save" button for the whole page (which may easily be several screens in size). Now, for the first option, I assume I … -
Django Models - Reverse Foreign Key
These two classes have Foreign Key to each other and class OrderRow is representing a row which belongs to an Order, I want to know is there any way to set "rows" attribute inside class Order to show a list or query-set of all related order rows by calling it on an object or instance of class Order? class OrderRow(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) order = models.ForeignKey('Order', on_delete=models.CASCADE) amount = models.IntegerField(default=0) class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) order_time = models.DateTimeField(auto_now_add=True) total_price = models.IntegerField(null=True, blank=True) **rows = models.ForeignKey('OrderRow', on_delete=models.CASCADE, related_name='order_rows')** -
How to call a function in template which is defined in a Django model?
I am extremely newbie to Django, Sorry in the advance for asking the wrong question. I want to create a function to sum the values of a column and call it on my template in Django. Model: class Invoice(models.Model): product_name = models.CharField(max_length=255) purchase_date = models.DateTimeField(auto_now=True) cost_price = models.IntegerField() selling_price = models.IntegerField() @property def get_total(self): amount = Invoice.objects.aggregate(Sum('selling_price')) return amount I created this get_total function to sum of the values of selling_price column. Template Code: {% for item in query_result %} <tr> <td>{{item.product_name}}</td> <td>{{item.cost_price}}</td> <td>{{item.selling_price}}</td> {{item.get_total}} </tr> {% endfor %} Here's the problem, after passing the data, whenever I call this function, the data is shown multiple times in the template. Here's the output. Output Image I know it's quite silly, but I am unable to figure it out. Help, Please. -
TypeError : as_view() takes 1 positional argument but 2 were given in Django
i am getting error that, ` TypeError at /logout/ as_view() takes 1 positional argument but 2 were given ` urls.py url(r'^logout/$', auth_views.LogoutView.as_view, {'next_page': '/'}, name='logout'), -
How to change font-size of datetimepicker xdsoft calendar
I am using this jQuery calendar: https://xdsoft.net/jqplugins/datetimepicker/ I want to increse the size of it and I understood that I have to change the font-size in order to do that. <script> $(function () { $("#id_mydate").datetimepicker ({ format: 'd - m - Y H:i', inline:true, }); }); </script> How can I do this from html/javascript ? I tried this: <style> .datetimepicker { font-size: 20px; } </style> and this: <style> #id_mydate { font-size: 20px; } </style> without success. -
Django Admin CharField Choices List Dependent On Other Field
I have two models class Animal(models.Model): TYPE = ( ('cat', 'Cat'), ('dog', 'Dog'), ('chicken', 'Chicken'), ) type = models.CharField(max_length=10, choices=TYPE, default='cat') class Injury(models.Model): BODY_PART = ( ('leg', 'Leg'), ('eye', 'Eye'), ('beak', 'Beak'), ) animal = models.ForeignKey(Animal, on_delete=models.CASCADE) injured_body_part = models.CharField(max_length=10, choices=BODY_PART, default='Leg') how_it_happened = models.CharField(max_length=100) So in my contrived example an animal can have many injuries and an injury can belong to one animal. When I create a new Injury in Django Admin I want it to restrict the choices for injured_body_part depending on which Animal I have selected. For example, if I select dog the injured_body_part option for beak wouldn't appear. I have found similar questions on SO but they are either very old or have unsuitable answers. Thank you. -
Template Tags not supported in Stylesheets
Suppose i create a stylesheet in Django in static files. So everything else is working fine. Its just that when is use this line it gives an error .PostProfilePic { width: 50px; height: 50px; border-radius: 50%; background-image: url('{{ Profile.ProfilePic.url }}'); background-size: cover; background-position: center; position: relative; top: 5px; } Suppose there is a class name 'PostProfilePic' and I want to use a image from database as my background image so how can we do it??? Error is on this line background-image: url('{{ Profile.ProfilePic.url }}'); It says 'cannot resolve file' And also when I use this style in my html page between the tags as shown below then it works completely fine <style> .PostProfilePic { width: 50px; height: 50px; border-radius: 50%; background-image: url('{{ Profile.ProfilePic.url }}'); background-size: cover; background-position: center; position: relative; top: 5px; } </style> While making a seperate .css file creates trouble...Any Solutions on this?? -
Need help Django rest framework - return user all data with pagination
I'll make an API - 1.User info2 email user_all_post_list -- and user all post list use pagination Example -> data[ name:"semol", email:"semol@gmail.com" user_all_post_list:[ { title:"test" details:"test test test" }, { title:"test" details:"test test test" }, { title:"test" details:"test test test" }, { title:"test" details:"test test test" }, ] ] -
stuck at setting secret key in django
structure = mysite mysite settings - base.py, deployment.py, production.py init.py asgi.py urls.py wsgi.py base.py has all the base settings. deployment.py has code from .base import * DEBUG = True SECRET_KEY = os.environ['SECRET_KEY'] after running py manage.py runserver --settings=mysite.settings.development i got the error as follows : (venv) C:\Users\Pc\PycharmProjects\mysite>py manage.py runserver --settings=mysite.settings.development import export Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Pc\PycharmProjects\mysite\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Pc\PycharmProjects\mysite\venv\lib\site-packages\django\core\management\__init__.py", line 345, in execute settings.INSTALLED_APPS File "C:\Users\Pc\PycharmProjects\mysite\venv\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "C:\Users\Pc\PycharmProjects\mysite\venv\lib\site-packages\django\conf\__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "C:\Users\Pc\PycharmProjects\mysite\venv\lib\site-packages\django\conf\__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\Pc\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Rohan\PycharmProjects\mysite\mysite\settings\development.py", line 5, in <module> SECRET_KEY = os.environ['SECRET_KEY'] File "C:\Users\Rohan\AppData\Local\Programs\Python\Python38\lib\os.py", line 675, in __getitem__ raise KeyError(key) from None KeyError: 'SECRET_KEY' any suggestions -
Running Django tests.py on method that updates object
I'm using Django to try to run a test, and something's going wrong. Here's a minimal example: models.py: class Warrior(models.Model): is_alive = models.BooleanField("Is Alive?", default=True) def kill(self): self.alive = False self.save() tests.py: from django.test import TestCase from .models import Warrior class WarriorModelTests(TestCase): def test_kill(self): """kill() makes .alive False.""" warrior = Warrior.objects.create() warrior.kill() self.assertIs(warrior.is_alive, False) Any advice on this? I'm starting to think this little warrior chap is immortal. Thanks as always! -
How to add an image or an audio file upload support to RichTextUploadField through Django REST?
I have a RichTextUploadField in my models which is added by ckeditor's library. I want to add a support to create simple html field related content which includes some img and audio tags. I have added a support to upload html content through admin just have no idea how to add support to create through API endpoint? models.py from ckeditor_uploader.fields import RichTextUploadingField class Part(models.Model): title = models.CharField(max_length=255) textfield = RichTextUploadingField() created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created_at', ) def __str__(self): return str(self.explanation) settings.py (!some parts) ... INSTALLED_APPS = [ ... # third party installed apps 'rest_framework', 'ckeditor', 'ckeditor_uploader', ... ] CKEDITOR_UPLOAD_PATH = "uploads/" ... ### I am using html5audio package to upload audios CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'extraPlugins': ','.join( [ 'html5audio', ] ), }, } Question: How can I add support to create HTML content through an REST API endpoint? -
Remove help_text from django-autocomplete-light m2m field
I was happy to find this cool library, django-autocomplete-light which gave me exactly what I wanted. But I am unable to hide the default help_text. Implementation was very simple: form.py class MyForm(forms.ModelForm): class Meta: model = MyModel fields = "__all__" widgets = { "field1": autocomplete.ModelSelect2Multiple(), "field2": autocomplete.ModelSelect2Multiple(), } And in admin.py class MyAdmin(admin.ModelAdmin): form = MyForm I have tried setting help_text in model, but it does not help. Thank you for any advice. -
filter values of main table from foreign key table view
I a trying to display the values of a foreign key table sorted upon the values of other foreign table. I am unable to find a way to show all the type of categories available in a specific city in the views. #models.py class restaurent(models.Model): title = models.CharField(max_length=200) category = models.ForeignKey('Type', on_delete=models.SET_NULL, null=True) summary = models.TextField(max_length=1000, help_text="Enter a brief description of the restaurent") city = models.ForeignKey('City', help_text="Select a city for this book") def get_absolute_url(self): return reverse('res-detail', args=[str(self.id)]) def __str__(self): return self.title class Type(models.Model): category_name = models.CharField(max_length=200,help_text="Enter the category") def __str__(self): return self.category_name class City(models.Model): city_name = models.CharField(max_length=200,help_text="Enter a city") def __str__(self): return self.city_name -
Django - Access nested Related Field
I have 3 Models, Province, District, Commune. And Model field somethings like this: Province hasMany District District hasMany Commune i want to access Provice Model from Commune through District. How can i archieve it?? My Model class Province(models.Model): name_eng = models.CharField(max_length=50) name_kh = models.CharField(max_length=50) class District(models.Model): province = models.ForeignKey( Province, on_delete=models.CASCADE, related_name="district") name_eng = models.CharField(max_length=50) name_kh = models.CharField(max_length=50) class Commune(models.Model): district = models.ForeignKey( District, on_delete=models.CASCADE, related_name="commune") name_eng = models.CharField(max_length=50) name_kh = models.CharField(max_length=50) And In ModelViewset class CommuneFilterSet(filters.FilterSet): province = filters.CharFilter(field_name='province__name_kh', lookup_expr='contains') district = filters.CharFilter(field_name='district__name_kh', lookup_expr='contains') class Meta: model = Commune fields = ['district', 'province'] class CommuneViewset(viewsets.ModelViewSet): queryset = Commune.objects.all() serializer_class = CommuneSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = CommuneFilterSet ordering_fields = '__all__' search_fields = [ 'name_kh', 'name_eng' ] Between, I use django-filter. Any Help??? Thanksss.... -
how to write query in Django Templates
I have tried the following without success: {% if forloop.counter % 2 == 0 %} Does anyone have any suggestions that might help me achieve my aim? Any help is much appreciated! -
mocking HTTP requests Django model.save error
I am trying to mock for testing purposes some HTTP calls on Django. The function that is making the requests (lets say it is called reqs() ) is this: try: response = requests.request('POST', url, data=json.dumps(payload), headers=headers, params=querystring) if response.status_code == "200": alpha.pending_sync = False alpha.save() except requests.exceptions.RequestException as e: app_logger.exception("Failed sync, error: %s" % e) Now on the test part i wrote this one: with patch('requests.request') as mock_request: mock_request.return_value.status_code = "200" reqs(alpha) mock_request.assert_called() Everything works fine but there is a problem with alpha.save() and mock.response. I get an error django.core.exceptions.FieldError: Aggregate functions are not allowed in this query. Probably i need to mock a response so the alpha.save() takes that response and not some MagicMock stuff. Also i found this one ref but i did not manage to get anything working. Any ideas ? -
What is the best way to build a document index in Django?
I want to build my own little document management system in Django. Therefore I want to upload files, associate them with other apps and so on. And I want to ocr them and build an index, which I can search through when I am looking for a document. Right now I would just a column with text fields in my db and I would just go through every object, when I look for a certain search phrase. But perhaps there are better approaches and you have some advice for me how to improve the index search :) -
Invalid submitted Django form data being temporarily used elsewhere in a template
I am trying to make a view for users to change their usernames and emails. The page works as expected for the most part. However, there is an issue that occurs when a user inputs another user's username. You see, the profile editing page has a heading that displays the current user's username and email. When the user inputs a duplicate username, the heading becomes the invalid username until the page is refreshed. Here is the relevant code: View @login_required() def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.user, request.POST, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, 'Your account has been updated.') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(request.user, instance=request.user.profile) return render(request, 'users/profile.html', context(title='Procfile', u_form=u_form, p_form=p_form)) Form class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] Template {% extends "courses/base.html" %} {% load crispy_forms_filters %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Profile Info</legend> {{ u_form|crispy }} {{ p_form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Update</button> </div> </form> </div> {% … -
How to fetch data from API when a data is added to the database?
I have a Django API and a Java client. I want to listen for data in database whenever data is added to the database and fetch them like a chat app. Whenever a user in a chat room sends a message, others recieve them. It is like a listener or an event listener. How this is done?