Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
store date type data into database while user django
i cannot store the date into database. When I use debug, there is: cleaned data = {'nick_name': 'Leren', 'gender': 'male', 'birday': None, 'address': '617 bridge', 'mobile': '2263408858'} data = <QueryDict: {'nick_name': ['Leren'], 'birthday': ['2018-04-04'], 'gender': ['male'], 'address': ['617 bridge'], 'mobile': ['2263408858'], 'email': ['1@qq.com'], 'csrfmiddlewaretoken': ['1bzcpBzTOra7yTFBiwXc9sPLw8V6ETf7ciCDNqt1Jo9EtXZ4Q1qVBCIEWVVwPxGi']}> i do not know why the birday does not exist in cleaned data but it exist in the data. And how can i store it into my database? html file: <form class="perinform" id="jsEditUserForm" autocomplete="off"> <ul class="right"> <li>nickname: <input type="text" name="nick_name" id="nick_name" value="{{ request.user.nick_name|default_if_none:'' }}" maxlength="10"> <i class="error-tips"></i> </li> <li>birthday: <input type="text" id="birth_day" name="birthday" value="{{ request.user.birday|date:'Y-m-d H:i:s' }}" /> <i class="error-tips"></i> </li> <li>gender: <label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" name="gender" value="male" {% ifequal request.user.gender "male" %}checked="checked"{% endifequal %} >male</label> <label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="radio" name="gender" value="female" {% ifequal request.user.gender "female" %}checked="checked"{% endifequal %}>female</label> </li> <li class="p_infor_city">address: <input type="text" name="address" id="address" placeholder="" value="{{ request.user.address|default_if_none:'' }}" maxlength="10"> <i class="error-tips"></i> </li> <li>phone <input type="text" name="mobile" id="mobile" placeholder="" value="{{ request.user.mobile|default_if_none:'' }}" maxlength="10"> </li> <li>email: <input class="borderno" type="text" name="email" readonly="readonly" value="{{ request.user.email }}"/> <span class="green changeemai_btn">[edit]</span> </li> <li class="button heibtn"> <input type="button" id="jsEditUserBtn" value="save"> </li> </ul> {% csrf_token %} </form> views.py: class UserInfoView(LoginRequiredMixin,View): #用户个人信息 所以必须登陆才可以访问 def get(self,request): return render(request,"usercenter-info.html",{ }) def post(self, request): # 不像用户咨询是一个新的。需要指明instance。不然无法修改,而是新增用户 user_info_form = UserInfoForm(request.POST, … -
Where to put service worker and manifest in a django project?
I am planning to convert a django project to Progressive Web App. I am not being able to figure out where to put the service_worker.js and manifest.json files in my django project. I've tried the following: myproject/ |__app1 |__app2 |__manage.py |__manifest.json |__service_worker.js and then tried to register the service worker from html file using relative path ../../../service_worker.js. That didn't work. It showed this error: "A bad HTTP response code (404) was received when fetching the script." Another approach I tried is to put the service_worker.js and manifest.json in the static folders: myproject/ |__app1/ |__static/ |__app1/ |__service_worker.js |__manifest.json |__app2 |__manage.py and access those using {% static 'app1/service_worker.js' %}. The problem with this approach is that the scope of the registered service_worker.js becomes limited to that static folder. I've seen in one stackoverflow answer that I can explicitly set the scope of the service worker as {scope: '/'}. But, I think there might be a better approach which I am missing. Please let me know if anyone has a solution to this. -
Create a Custom Link in Admin section django
I'm finding a way to create a custom link like "Add" or "Change" for each section model. I have Voucher model which current have add and change link. But, I want to add a new Add link with it (in which i want to add 3 more custom fields which are not present in first add link) -
Can't create django(1.11) superuser on mac
I m trying to create superuser in Django (1.11) on Python (3.6.4) on Mac (10.13.3). After entering username, I'm pressing enter. enter won't take me to next input. $ python manage.py createsuperuser Username (leave blank to use 'neon'): admin^M^M^M^M^M^M^M^M^C^CKeyboardInterrupt The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/neon/workspace/jp/lib/python3.6/site-packages/Django-1.11-py3.6.egg/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/Users/neon/workspace/jp/lib/python3.6/site-packages/Django-1.11-py3.6.egg/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/neon/workspace/jp/lib/python3.6/site-packages/Django-1.11-py3.6.egg/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/neon/workspace/jp/lib/python3.6/site-packages/Django-1.11-py3.6.egg/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute return super(Command, self).execute(*args, **options) File "/Users/neon/workspace/jp/lib/python3.6/site-packages/Django-1.11-py3.6.egg/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/neon/workspace/jp/lib/python3.6/site-packages/Django-1.11-py3.6.egg/django/contrib/auth/management/commands/createsuperuser.py", line 116, in handle username = self.get_input_data(self.username_field, input_msg, default_username) File "/Users/neon/workspace/jp/lib/python3.6/site-packages/Django-1.11-py3.6.egg/django/contrib/auth/management/commands/createsuperuser.py", line 192, in get_input_data raw_value = input(message) SystemError: <built-in function input> returned a result with an error set -
Send two selected values in form submission with Django
I want the user to filter month and year they want, to view them data based on their selection. so this is my html form <form id="time-select-form"> <select id="month-selector"> <option value="1">January</option> <option value="2">February</option> . . . </select> <select id="year-selector"> <option value="2018">2018</option> . . </select> </form> And I have this javascript code to submit the selected month to the server $("#month-selector").change(function () { var selectedValue = $(this).val(); var form = $('#month-select-form'); var action = form.attr("action"); var method = form.attr("method"); $.ajax({ url: action, method: method, data: { "month": selectedValue }, success: function (data, textStatus, jqXHR) { $('#monthly-reports-list-div').html(data); }, error: function (jqXHR, status, error) { console.log(status + ": " + error); } }); }); The JS code works for month but I want it to send both month and year to my Django backend at the same time. Because I tried to duplicate it for year but turns out it submits the form twice and in the second submission month value becomes None. -
Django - 'WhereNode' object has no attribute 'output_field' error
I am trying to query and annotate some data from my models: class Feed(models.Model): # Feed of content user = models.ForeignKey(User, on_delete=models.CASCADE) class Piece(models.Model): # Piece of content (video or playlist) removed = models.BooleanField(default=False) feed = models.ForeignKey(Feed, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) Other fields are not used in the following queries so I skipped them here. In my view I need to get queryset of all feeds of an authenticated user. Annotation should contain quantity of all pieces that are not removed. Initially, Piece model didn't contain removed field and everything worked great with the queryset like this: Feed.objects.filter(user=self.request.user).annotate(Count('piece')) But then I added the field removed to Piece model and needed to count only pieces that were not removed: Feed.objects.filter(user=self.request.user) .annotate(Count('piece'), filter=Q(piece__removed=False)) It gave me the following error: 'WhereNode' object has no attribute 'output_field' It is only a little fraction of what django outputs on the error page, so if it is not enough, please let me know what else I need to include in my question. I tried to include output_field with options like models.IntegerField() or models.FloatField() (properly imported) here and there but got some errors which I do not provide here because I believe those actions made no … -
ValueError: Cannot serialize function: lambda while using makemigrations
When I do python manage.py makemigrations, i get above error and I am unsure where the error is happening. I saw some post regarding this issue but i find mainly in DateTimeField() where the function was passed but in my case I have used auto_now attribute instead of some datetime related function. However, I have used lambda function in the class method as follow. @classmethod def get_content_models(cls): """ Return all Package subclasses. """ is_content_model = lambda m: m is not Package and issubclass(m, Package) def set_helpers(self, context): current_package_id = getattr(current_package, "id", None) current_parent_id = getattr(current_package, "parent_id", None) self.is_current_child = self.parent_id == current_package_id self.is_child = self.is_current_child def is_c_or_a(package_id): parent_id = context.get("_parent_package_ids", {}).get(package_id) return self.id == package_id or (parent_id and is_c_or_a(parent_id)) self.is_current_or_ascendant = lambda: bool(is_c_or_a(current_package_id)) I am not clear on this issue, So i have posted for understanding the cause. Is above code creating that issue? If it is the cause, what should be done instead? -
Can I use Django/Python API calls, and still use Javascript to manipulate the DOM in real time?
I'm in a full stack course and would like to use Django/Python to post/get my API calls, but use Javascript/Vue to stay on the same page. Can you still do that by essentially having a one page app that doesn't reload or change url? Just wondering before I go full on with it. Also, what's a good way to use Javascript to get info onto the DOM from an API using an api key and secret key? I've experimented so much but haven't got back anything useful to my knowledge. Help is appreciated, thank you. -
Django: Live Server Not Loading Images
I'm trying to deploy my school project on server, everything is working fine accept the images are showing up at all, Here's my main project urls.py, urlpatterns = [ # common urls ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here's settings.py Debug = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'project/media') Template, <img src="{{ data.image.url }}" class="Images" /> Everything worked fine when I was developing it, images were being loaded very well. But on Live server it's not loading the images :( What should I do? -
Django Rest Framework list missing records
I have set up a Django Rest Framework (v.1.11.7) Viewset called CustomerViewset. It's as simple as follows: class CustomerViewSet(viewsets.ModelViewSet): queryset = Customer.objects.all() serializer_class = CustomerSerializer The serializer looks like: class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ('id', 'name', 'website', 'email') This should work with no problem, however after a change (update or partial-update) is made to a Customer object, the particular object that was updated won't be listed again. Not even restarting the server (caché issues). But it still can be retrieved. No errors displayed on console or logs; it simply ignores the record when listing. This is really weird and don't know what I'm missing here. Any idea would be appreciated. -
ModuleNotFoundError: No module named 'HomePage'
I cannot figure out why I keep getting the ModuleNotFoundError: No module named 'HomePage' error I'm fairly new to Django but have spent a majority of the day trying to figure out how to make a homepage where I could link a Homepage.html and have a different page on my original page. Any help would be appreciated this is my second question ever on here please be gentle. This is inside my mysite/urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('music.urls')), url(r'^blog/', include('blog.urls')), url(r'^HomePage/',include('HomePage.urls')), ] This is my installed apps in settings.py in the mysite directory. # Application definition INSTALLED_APPS = [ 'music', 'blog', 'homepage', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] This is my urls.py for the music/urls.py from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^contact/$', views.contact, name='contact'), url(r'^HomePage/$', views.HomePage, name='HomePage'), ] This is the views.py music/views.py from django.shortcuts import render def index(request): return render(request, 'music/home.html') def contact(request): return render(request, 'music/basic.html', {'content':['If you would like to contact me, please email me','@gmail.com']}) def HomePage(request): return render(request, 'HomePage/homepage.html') -
django create instant messaging
I'm building a django website and would like a to add an instant messaging feature to my userbase. What are some good ways to go about implementing this functionality? Does Channels and websockets have anything to do with this? Scratch that... so I'm looking at Django channels and it looks like a way to build a chat feature. Do many people just build theirs from the ground up or do they use an existing app? I'm looking for more of a user-user chat as opposed to user to chatroom. I've looked around a bit, but there are many answers from 7-8 years ago. I'd appreciate some guidance. Thanks! -
Is it okay to have multiple url patterns with the same view?
I have an app that shows a list of "Issues". The main urls.py file sends /issues/ to the urls.py file in the "issues" app. urlpatterns = [ path('', RedirectView.as_view(url='/issues/')), path('admin/', admin.site.urls), path('issues/', include('issues.urls')), ] In the issues app's urls.py file I have: path('', views.IssueListView.as_view(), name='issue-list'), That calls the IssueListView which is a generic ListView view: class IssueListView(generic.ListView): model = Issue Now, I want to add a sidebar menu with links users can click to sort the issues list by category. I understand that I can rewrite the get_queryset() method of the IssueListView to accept a kwarg, and just load all the issues if that kwarg is missing (with an if statement that checks for the presence of the kwarg, right?), but I think to do this I need to have two urlpatterns that point to the same view like: path('', views.IssueListView.as_view(), name='issue-list'), path('<category>', views.IssueListView.as_view(), name='issue-category-list'), But I am wondering if that's the normal "Django way" to do it. Thank you. -
Not Found "/lobby/" django-channels routing error
routing.py from channels import include, route from chat import consumers from . import game_consumers channel_routing = [ #game routing route('websocket.connect', game_consumers.ws_connect_lobby, path=r"^/lobby/$"), route('websocket.receive', game_consumers.ws_receive_lobby, path=r"^/lobby/$"), route('websocket.disconnect', game_consumers.ws_disconnect_lobby, path=r"^/lobby/$"), app.js Websocket = { lobby_socket: null, setup_ws_lobby : function(){ Websocket.lobby_socket = new ReconnectingWebSocket(Websocket.ws_scheme + '://' + window.location.host + '/lobby/'); Websocket.lobby_socket.onmessage = function(message) { //nothing yet }; }, } Websocket.setup_ws_lobby(); The url is 127.0.0.1:8000/game. Websocket.setup_ws_lobby() is executed on page load. I don't see what I'm doing wrong. I get the error Not Found: /lobby/ in my python manage.py runserver console when I load the page. My routes are clearly set and my js setup seems to route to those routes. Can anyone help? Thanks in advance. -
How To Create Business Hours Via Django
I am creating a program that allows people to user to sign up their restaurants for a delivery program but, I'm trying implement methods that would allow users to enter their hours of operations when they sign up. So far I got this: Models.py WEEKDAYS = [ (1, _("Monday")), (2, _("Tuesday")), (3, _("Wednesday")), (4, _("Thursday")), (5, _("Friday")), (6, _("Saturday")), (7, _("Sunday")), ] weekday = models.IntegerField( choices=WEEKDAYS, unique=True ) from_hour = models.TimeField() to_hour = models.TimeField() Forms.py class RestaurantForm(forms.ModelForm): class Meta: model = Restaurant fields = ("restaurant_name", "phone", "logo", "tagline", "street_address", "state", "city", "zip_Code","weekday", "from_hour", "to_hour") But, when I run it, the options show ups up in an unusable format that doesn't allow the user to enter more than day and time: I'm not sure what I should do to be able to setup this form and allow restaurants to add all the days and hours that they are opened or closed. -
What is the result of the add function in manytomany?
this is my model class MyUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) items = models.ManyToManyField(Item, related_name='myuser') when i write following code MyUser.items.add(item1) i want to know if it was added or duplicated -
Why does my docker container intermittently stop accepting incoming network connections?
I am currently working on a django rest-based server. Said REST server is for a mobile app, and thus I want a development server running on a VPS with remote access for testing in the field. I used a django rest framework cookiecutter to set up and develop my project, and it uses Docker to contain everything. When I first run the container using docker-compose up everything seems to work fine. The django server runs, and I can access it without issue on port 8000 of the host VPS. However, after a few minutes, the server simply stops responding to requests (I get timeouts). It'll time out for 3-4 minutes, and then suddenly start working again. I thought it might be some django issue, but looking at the django logs, the server sees no hits during that timeout phase (the connection logs dont have any new connection attempts). I have tried disabling the VPS firewall to test, and it seems to make no difference- the timeouts still start happening intermittently. I am new to docker, and have no idea how to figure out what is going on here. Here are my docker config files: docker-compose.yml: version: '2' services: postgres: image: … -
modelformset_factory and Class Based View in Django
I am trying to update many objects start & end fields at the same time. I'm doing this using ModelFormSet & the modelformset_factory() method. The template will be a table of forms with the object name to the left of the fields (see image below). I found this example, but I am stuck on how to implement the class based view & template. My Formset class BaseFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): super(BaseFormSet, self).__init__(*args, **kwargs) self.queryset = Reference.objects.filter( start__isnull=True) ReferenceFormSet = modelformset_factory( Reference, fields=('start', 'end'), formset=BaseFormSet, extra=0) My View class ReferenceFormSetView(LoginRequiredMixin, SuperuserRequiredMixin, FormView): model = Reference form_class = ReferenceFormSet template_name = "references/references_form.html" def form_valid(self, form): for sub_form in form: if sub_form.has_changed(): sub_form.save() return super(ReferenceFormSetView, self).form_valid(form) My Template {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <h1>{{ headline }}</h1> <div class="row"> <form action="" method="post"> {% crispy form %} <div class=""> <input type="submit" value="Submit" /> </div> </form> </div> </div> {% endblock content %} Questions The view seems odd with the Formset in the form_class. Is there a better way to handle this? How can I access the instance name to display in the form? -
Django serializer update all
When adding a definition for update in my serializer, do I have to put each field in or is there a way to do "any" or "all"? def update(self, instance, validated_data): instance.id = validated_data.get('id', instance.id) instance.user.id = validated_data.get('user_id', instance.user.id) instance.city = validated_data.get('city', instance.city) # instance all fields? instance.save() return instance -
Django collect the static files fails
While I run python manage.py collectstatic It says You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. This is my settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static'), ] How can I solve this issue? -
Django REST framework 2 example not working
I'm working the very first example of the Django REST framework (version 2). I've followed the Installation and Example instructions to the letter but when I open the API in my browser at http://127.0.0.1:8000/ per their instructions, I get the error shown below. What am I doing wrong? This example seems pretty elementary. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in conf.urls, Django tried these URL patterns, in this order: ^admin/ ^api-auth/ The current URL, , didn't match any of these. -
related models queries in django
I have tree models related to each others as follow : The first class has basic informations about the project. class Project(models.Model): customer = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete = models.CASCADE,) title = models.CharField(max_length=200) pub_date = models.DateTimeField(default=timezone.now) The second class is used to register the categories related to every project. class ProjectCategory(models.Model): project = models.ForeignKey( Project, on_delete = models.CASCADE) projectCategory = models.ForeignKey( Category, on_delete=models.CASCADE) The last model indicates the locations of the project. class ProjectLocation(models.Model): project = models.ForeignKey( Project, on_delete = models.CASCADE) projectLocation = models.ForeignKey( Location, on_delete=models.CASCADE) I was trying to render in a template a list of projects. I want to show the informations (Categories and Locations) related to each project. How can achieve that ? Using the query Project.objects.all() doesn't allow me to access the fields "projectLocation" and "projectCategory". -
Django atomic transaction not rolling back
I'm trying to do something like this: with transaction.atomic(): Model.objects.create(name="something") raise Exception Since an exception is raised, this should mean that the transaction should roll back and the Model with name "something" should not exist. However, if I query for Model.objects.get(name="something"), the object still exists in the db. Am I not understanding transactions correctly? -
Open Embedded PDF with Max Width in Django
I have a pdf that I am currently embedding into a webpage using this view: def pdf_view2(request, pk, pdk): document = DocForm.objects.get(pk=pdk) filename=str(document.file) response = FileResponse(open(settings.STATIC_ROOT + filename,'rb'), content_type="application/pdf") response['Content-Disposition'] = 'filename=some_file.pdf' return response I need for the view to fit the pdf by width when it opens. Apparently PDFs have Open Parameters such as "filename.pdf#view=FitH" that should do this however I have not been successful in integrating it into django. How would I pass this parameter, or if this isn't possible, emulate the same functionality at render time? -
Django Admin URL Routing Issue
I've been trying to incorporate my Django app called farms into my current project but for some reason localhost:8000/admin/ no longer routes to the admin page whenever I try to incorporate it. My urls.py files are as follows: Main App: urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('farms/', include('farms.urls', namespace='farms')) ] Farms App: urls.py from django.urls import path from . import views app_name = 'farms' urlpatterns = [ path('', views.index, name='index'), path('profile/', views.profile, name='profile'), path('form/', views.profile_form, name='profile_form'), path('about/', views.about, name='about'), ] Whenever I try to go to localhost:8000/admin Django tries to go to localhost:8000/admin/profile_form and produces the following error: Environment: Request Method: GET Request URL: http://localhost:8000/admin/ Django Version: 2.0.2 Python Version: 3.5.2 Installed Applications: ['farms.apps.FarmsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap4'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.app_directories.Loader: /mnt/d/Projects/hawaiian-soil/farms/templates/admin/profile_form.html (Source does not exist) * django.template.loaders.app_directories.Loader: /mnt/d/Projects/hawaiian-soil/dep/lib/python3.5/site-packages/django/contrib/admin/templates/admin/profile_form.html (Source does not exist) * django.template.loaders.app_directories.Loader: /mnt/d/Projects/hawaiian-soil/dep/lib/python3.5/site-packages/django/contrib/auth/templates/admin/profile_form.html (Source does not exist) * django.template.loaders.app_directories.Loader: /mnt/d/Projects/hawaiian-soil/dep/lib/python3.5/site-packages/bootstrap4/templates/admin/profile_form.html (Source does not exist)