Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django site served on Apache server doesn't work, logs have no error
I've a Django website located at /home/rohit/django-site/infer, in a server. apache2 and wsgi are already installed and working correctly. To see that: $ systemctl status apache2.service ● apache2.service - The Apache HTTP Server Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled) Drop-In: /lib/systemd/system/apache2.service.d └─apache2-systemd.conf Active: active (running) since Fri 2019-05-03 19:12:34 IST; 31min ago Process: 9354 ExecStop=/usr/sbin/apachectl stop (code=exited, status=0/SUCCESS) Process: 9364 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS) Main PID: 9368 (apache2) Tasks: 24 (limit: 4915) CGroup: /system.slice/apache2.service ├─9368 /usr/sbin/apache2 -k start ├─9370 /usr/sbin/apache2 -k start ├─9371 /usr/sbin/apache2 -k start ├─9372 /usr/sbin/apache2 -k start ├─9373 /usr/sbin/apache2 -k start ├─9374 /usr/sbin/apache2 -k start └─9375 /usr/sbin/apache2 -k start Here is the content of /var/log/apache2/error.log: [Fri May 03 17:04:03.885793 2019] [mpm_prefork:notice] [pid 24349] AH00163: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations [Fri May 03 17:04:03.885868 2019] [core:notice] [pid 24349] AH00094: Command line: '/usr/sbin/apache2' [Fri May 03 19:12:34.361607 2019] [mpm_prefork:notice] [pid 24349] AH00169: caught SIGTERM, shutting down [Fri May 03 19:12:34.480584 2019] [mpm_prefork:notice] [pid 9368] AH00163: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations [Fri May 03 19:12:34.480660 2019] [core:notice] [pid 9368] AH00094: Command line: '/usr/sbin/apache2' Looking at which, I understand that everything is okay. The /var/log/apache2/access.log is empty though, which means that all … -
Django Bootstrap Datepicker Plus loads with no default date or placeholder
I'm using Django with Date-Picker-Plus. Everything works correctly, except the date picker displays/has no value until you click the box. I have dug through all the documentation and can't find any references elsewhere of someone having this problem. I'm not familiar with js much so this is a bit foreign to me. Heres the documentation I've gone thru: https://django-bootstrap-datepicker-plus.readthedocs.io/en/latest/Usage.html http://eonasdan.github.io/bootstrap-datetimepicker/Options/#defaultdate class Meta: model = Jobs_DB fields = ['date_scheduled'] widgets = { 'date_scheduled': DatePickerInput( options={ "format": "MM-DD-YYYY", # moment date-time format "showClose": True, "showClear": True, "showTodayButton": True, 'defaultDate': True, }, ), } -
Notifications unclickable once "read": error "notification_id is not defined"
I am using JQuery/JS with Django Channels WebSockets to configure real-time notifications for chat messages. When a user has any Notification objects with nofication_read=False, they are rendered out in the navbar with the code below. {{ notification|length }} displays the number of Notification objects with nofication_read=False. navbar.html <li id="notification_li" class="nav-item"> <a class="nav-link" href="#" id="notificationLink"> <span id="notification_id{{notification_id}}">{{ notification|length }}</span> <div id="notificationContainer"> <div id="notificationTitle">Notifications</div> <div id="notificationsBody" class="notifications"> {% for notifications in notification|slice:"0:10" %} <span id="notification-{{notification.id}}"> {{ notifications.notification_chat.message }} via {{ notifications.notification_chat.user }} at {{ notifications.notification_chat.timestamp }} </span> {% endfor %} I know this isn't realtime at the moment. But the problem is that when the user refreshes the page and clicks on the red icon span id=notification_id to display their list of unread notifications, the data is sent through the websocket (JSON.stringify) as "type": "notification_read" which calls the if message_type == "notification_read": command in consumers.y which marks them as nofication_read=True in the database. When the user refreshes the page, the red icon is no longer there and when they try to click on the background link, it's unclickable with the error in the browser console Uncaught ReferenceError: notification_id is not defined As soon as they get another notification and the page is … -
how to manipulate img src with jquery in django
I'm trying to manipulate my image src with jquery in django and it is not working and this is the jquery code <script> username = $('.comment-user-name').text(); usernameFirstletter = username.charAt(0).toUpperCase(); console.log(usernameFirstletter) $(".comment-image").attr('src', 'img/avatars/' + usernameFirstletter + '.svg'); $(".comment-image").attr('alt', 'Src: ' + img.attr('src')); </script> -
get_object_or_404 returns get() missing 2 required positional arguments: 'self' and 'request'
When I call get_object_or_404() to get the object for my DetailView, I get the following error message: get() missing 2 required positional arguments: 'self' and 'request' I think I'm missing something conceptually that is preventing me from properly troubleshooting this. Any help to point me in the correct direction would be greatly appreciated. Traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/wines/profiles/justin/cabernet-sauvignon/ Django Version: 2.1.4 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'bootstrap4', 'accounts', 'groups', 'wines', 'posts'] 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', 'debug_toolbar.middleware.DebugToolbarMiddleware'] Traceback: File "/anaconda3/envs/wineEnv/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/anaconda3/envs/wineEnv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/anaconda3/envs/wineEnv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/anaconda3/envs/wineEnv/lib/python3.7/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/anaconda3/envs/wineEnv/lib/python3.7/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/anaconda3/envs/wineEnv/lib/python3.7/site-packages/django/views/generic/detail.py" in get 106. self.object = self.get_object() File "/Users/ed/code/wine/wineProject/wineProject/wines/views.py" in get_object 40. wp = get_object_or_404(WineProfile, slug=self.kwargs['w_slug'], winemaker=self.winemaker.winemaker_id) File "/anaconda3/envs/wineEnv/lib/python3.7/site-packages/django/shortcuts.py" in get_object_or_404 93. return queryset.get(*args, **kwargs) Exception Type: TypeError at /wines/profiles/justin/cabernet-sauvignon/ Exception Value: get() missing 2 required positional arguments: 'self' and 'request' models.py class WineMaker(models.Model): winemaker_id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, unique=True) slug = AutoSlugField(null=False, unique=True, populate_from='name', default='winemaker') region = models.ForeignKey( WineRegion, db_column … -
Serialization of nested models in Django Rest Framework
I have nested models and many to many relations. When I try to serialize them, results are not visible. Tried everything in documentation and related names etc. My base model is like this: class Question(models.Model): ques_code = models.CharField(max_length=12, null=True, default='Ques Code') def __str__(self): return self.ques_code Child Model is: class MCQuestion(Question): answer_order = models.CharField( max_length=30, null=True, blank=True, choices=ANSWER_ORDER_OPTIONS, help_text=_("The order in which multichoice " "answer options are displayed " "to the user"), verbose_name=_("Answer Order")) Then linked answer class with key as: class Answer(models.Model): mcquestion = models.ForeignKey(MCQuestion,related_name='answers', on_delete=models.CASCADE) content = models.CharField(max_length=1000, blank=False, help_text=_("Enter the answer text that " "you want displayed"), verbose_name=_("Content")) correct = models.BooleanField(blank=False, default=False, help_text=_("Is this a correct answer?"), verbose_name=_("Correct")) def __str__(self): return self.content Serializers are as: class AnswerSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ('content','correct') class MCQuestionSerializer(serializers.ModelSerializer): answers = AnswerSerializer(many=True, read_only=True) #answers = serializers.SerializerMethodField() quiz = QuizSerializer(many=True) class Meta: model = MCQuestion fields = ('ques_code','answers') Views are: class QuestionViewSet(viewsets.ModelViewSet): queryset = Question.objects.all() serializer_class = MCQuestionSerializer When I access API for questions, nested answers are not visible. I checked all documentation and checked and changed my code. If I try using answers = serializers.SerializerMethodField() and define get_answers function for it, error comes saying "Question has no attribute of answers" … -
raise MultiValueDictKeyError(key) with POST VXML
I get the following error raise MultiValueDictKeyError(key) : django.utils.datastructures.MultiValueDictKeyError: 'redirect' when I try to save the value the user types in. At first, I thought it had something to do with the input value, but since the error explicitly gives 'redirect' back I assume it has something to do with the redirect to the next part of the application. I have tried two different versions of return redirect, but it is very confusing what now exactly the right thing is. At the same time, I get raise NoReverseMatch(msg) when I try to submit the input value to the database. view def InputData(request, element_id, session_id): input_element = get_object_or_404(InputData_model, pk=element_id) voice_service = input_element.service session = lookup_or_create_session(voice_service, session_id) if request.method == "POST": session = get_object_or_404(CallSession, pk=session_id) value = 'DTMF_input' result = UserInput() result.input_value = request.POST.get('input_value') result.session = session result.category = input_element.input_category result.save() return redirect(request.POST['redirect']) template <form id="input_form"> <property name="interdigittimeout" value="2s"/> <property name="timeout" value="4s"/> <property name="termchar" value="#" /> <field name="input_value" type="digits?minlength=1;maxlength=5"> <prompt> <audio src="{{ ask_input_label }}"/> </prompt> <filled> <assign name="redirect" expr="'{{ redirect_url }}'"/> <submit next="{{ url }}" enctype="multipart/form-data" namelist="input_value" method="post"/> <goto next="{{ redirect_url }}" /> </filled> </field> </form> traceback Internal Server Error: /vxml/InputData/33/57 File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/datastructures.py", line 77, in __getitem__ list_ = super().__getitem__(key) KeyError: 'redirect' … -
appluying decorators to formfield_for_foreignkey
I have multiple models using foreign key dropdown, I want to customize the foreign key drop down as per the condition. I tried using decorators but dropdown dissapers in add admin form from .decorators import admin_active_country . . . @admin_active_country def formfield_for_foreignkey(self, db_field, request, **kwargs): return super().formfield_for_foreignkey(db_field, request, **kwargs) i have created decorators to achieve below if db_field.name == "country": kwargs["queryset"] = Country.objects.filter(is_active=True) here is decorators def admin_active_country(func): print(func,"function priniting") @functools.wraps(func) def wraps(*args,**kwargs): # ags[1] is db_field if args[1].name == "country": kwargs["queryset"] = Country.objects.filter(is_active=True) return func(*args,**kwargs) return wraps The below code working fine i want to achieve the same using decorators so that i can apply it to multiple admin by following DRY def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "country": kwargs["queryset"] = Country.objects.filter(is_active=True) return super().formfield_for_foreignkey(db_field, request, **kwargs) Please help me out , thank in advance -
AWS S3 images uploading issue with django and boto3
I want to upload image and load that uploaded images back to my webapp , previously loaded image in S3 bucket(which i uploaded manually) is rendering fine in the page but i am facing problem in uploading image in S3. below is my settings.py config INSTALLED_APPS = [ 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', ] AWS_ACCESS_KEY_ID = "given id" AWS_SECRET_ACCESS_KEY = "given secret key" AWS_STORAGE_BUCKET_NAME = "young-minds-files" AWS_S3_URL = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_REGION_NAME = "us-west-2" AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" views.py class PostCreateView(LoginRequiredMixin,CreateView): model = Post fields = ["title","content","image1","image2","image3"] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) models.py class Post(models.Model): title = models.CharField(max_length=100) category = models.CharField(max_length=100, default='Others') content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image1 = models.ImageField(default='default_content.jpg', upload_to='content_pic') image2 = models.ImageField(default='default_content.jpg', upload_to='content_pic') image3 = models.ImageField(default='default_content.jpg', upload_to='content_pic') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) template {% extends 'blog/base.html' %} {% load crispy_forms_tags %} {% block content %} {% load static %} <section class="site-section"> <div class="container"> <div class="row mb-4"> <div class="col-md-6"> </div> </div> <div class="row blog-entries"> <div class="col-md-12 col-lg-8 main-content"> <form method="post" enctype="multipart/form-data"> <fieldset class="form-group"> <legend class="border-bottom mb-4"> Create Your Blog</legend> {% csrf_token %} {{ form|crispy }} </fieldset> <div class="row"> <div … -
Is there anything in django that can determine whether a website visitor has landed on the website using google search or not?
I wish to find out how a user has landed on my website (built on django1.11, python 3.7)? Whether he found me through google search or is a direct visitor? -
Convert GET parameters to POST data on a Request object in Django REST Framework
I am in the process of rewriting the backend of an internal website from PHP to Django (using REST framework). Both versions (PHP and Django) need to be deployed concurrently for a while, and we have a set of software tools that interact with the legacy website through a simple AJAX API. All requests are done with the GET method. My approach so far to make requests work on both sites was to make a simple adapter app, routed to 'http://<site-name>/ajax.php' to simulate the call to the Ajax controller. Said app contains one simple function based view which retrieves data from the incoming request to determine which corresponding Django view to call on the incoming request (basically what the Ajax controller does on the PHP version). It does work, but I encountered a problem. One of my API actions was a simple entry creation in a DB table. So I defined my DRF viewset using some generic mixins: class MyViewSet(MyGenericViewSet, CreateModelMixin): # ... This adds a create action routed to POST requests on the page. Exactly what I need. Except my incoming requests are using GET method... I could write my own create action and make it accept GET requests, … -
iterate users in friends list over same modal and access database content
I am making a chat box for my website. As per current implementation,i i am iterating over the current friends list and and anchor tag triggers a modal for that particular user. The modal is common for all users as it only changes the data inside. Now, i have used jquery to fetch the message history ( from model object ) and display is modal body. I can click on different users and view the messages in their respective models correctly. However, when i try to submit the form to send another message it gets added to the message box of first user. This is happening for all users in the friend list. How can i trigger the form to post in the model of the correct user. Template {% for friend in friends_list %} <a href="" data-toggle="modal" data-target="#chatbox" data-whatever="{{friend.to_user}}"><li style="padding:10px">{{friend.to_user.usercreation.fname}} {{friend.to_user.usercreation.lname}} <i style ="color:green;font-size:0.65rem;text-align:justify;float:right;margin-top:8.5px;" class="fa fa-circle" aria-hidden="true"></i></li></a> <form action="{% url 'usercreation:addmessage' friend.to_user.usercreation.pk %}" method="post"> {% csrf_token %} <div class="modal fade" id="chatbox" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header text-center"> <h6 class="modal-title w-100">BlogChat</h6> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <pre><div class="modal-body"></div></pre> <div class="modal-footer"> <input style="width:330px;height:40px" type="text" name="addmessage" value="" placeholder="Type.."> <button style="float:right;" type="submit" class="btn btn-primary">Send message</button> … -
ModuleNotFoundError: No module named 'social_django_urls'
I have this error and I can't fix it ;( ModuleNotFoundError: No module named 'social_django_urls' -
Bad Request when accessing request.data
I want to send data via Ajax to my Django Server. But when I want to read these data I get a bad request error back. I dont know why, other methods like request.method or request.stream work well. This is the Ajax Call: jQuery.ajax({ type: 'post', url: 'http://127.0.0.1:8000/termin/get-journey-time/', contentType: 'application/json; charset=utf-8', data: { 'method': 'get_journey_time', 'mandant_id': 1, 'customer_address': customer_address, 'staff_group': staff_group_id }, success: function (resultData) { console.log(resultData) }); This is my view for this post request: class get_journey_time(generics.ListAPIView): """ Handle Ajax Post to calculate the journey time to customer for the selected staff group """ permission_classes = (AllowAny,) def post(self, request, *args, **kwargs): body = request.data return Response(body) I get error code 400 Bad Request. Do you know why? def post(self, request, *args, **kwargs): body = request.method return Response(body) or def post(self, request, *args, **kwargs): body = request.stream return Response(body) Work well -
How can i avoid a user from registering an already used email in django?
I was testing my registration view and i noticed that if i try to register using an alreaxy existing Username, i'll get an error; if i try to register using an already existing email, the app will let me do so. Obviously, i don't want someone to register multiple accounts with the same email on my site. I'm fairly new to Django, and since i noticed that the form checked if an username already exists, i thought it would do the same with the email field. I don't really know how to go from that, should i work on my view or on the form? And how can i make it loop through my DB and find if an e-mail had already been registered? I thought email = form.cleaned_data.get('email') would do the trick, but it didn't. Any help is appreciated. Here is my view: def register(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') messages.success(request, f"New Account Created: {username}") login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect("main:homepage") else: for msg in form.error_messages: messages.error(request, f"{msg}: {form.error_messages[msg]}") form = NewUserForm return render(request, "main/register.html", context={"form":form}) And here is the … -
Django serializer display BooleanField of related model
Context I have 2 models: App & AppVersion. I am trying to serialize fields from AppVersion along with a field from the App model. I am unable to display the related field in my serializer. Goal My goal is to have the API response include the related field like this: [ { "app_version_uuid": "61ee8efa-f79e-4fcd-a6ea-4a33544442e1", "app_version_name": "Test app version", "version_code": 2, "version_name": "0.2", "auto_start": True # related field } ] Models # models.py class App(models.Model): app_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) app_name = models.CharField(max_length=100) package_id = models.CharField(max_length=100, unique=True, null=True, blank=True, editable=False) auto_start = models.BooleanField(default=False) class AppVersion(models.Model): app_version_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) app_uuid = models.ForeignKey(App, on_delete=models.CASCADE, related_name='app_versions') app_version_name = models.CharField(max_length=100) version_name = models.CharField(blank=True, null=True, max_length=100, editable=False) version_code = models.IntegerField(blank=True, null=True, editable=False) Serializers # serializers.py class AppVersionSerializer(serializers.ModelSerializer): auto_start = serializers.SlugRelatedField(read_only=True, slug_field='auto_start') class Meta: model = AppVersion fields = ('app_version_uuid', 'app_version_name', 'version_code', 'version_name', 'auto_start') What I tried I tried to use the SlugRelatedField() as shown in my serializers.py. I also tried to use a SerializerMethodField() like this: # serializers.py class AppSerializer(serializers.ModelSerializer): class Meta: model = App fields = ('auto_start') class AppVersionSerializer(serializers.ModelSerializer): auto_start = serializers.SerializerMethodField(read_only=True) def get_auto_start(self, model): return AppSerializer(model).data class Meta: model = AppVersion fields = ('app_version_uuid', 'app_version_name', 'version_code', 'version_name', 'auto_start') The SlugRelatedField() … -
Not able to mock the django query object that is iterating through for loop
I am trying to mock the django query object while iterating through for loop. for row in MyModel.objects.filter(ListId=id): I am getting the 'TypeError: 'Mock' object is not iterable' Below is my approach @mock.patch('myapp.models.MyModel.objects') def test_myMethod(self, mock_MyModel): mock_queryset = Mock() mock_MyModel.filter.return_value = mock_queryset I am trying to test below django query inside my method. for row in MyModel.objects.filter(ListId=id): files.objects.filter( fileId=(row.fileId).fileId ).update(formName=name, description=description) Can anyone help to solve the chain queries. Any help or lead, I will really appreciate. Please let me know if any information required. -
Docker + Django + PostgreSQL + Heroku = Failed to bind to $PORT within 60 seconds
So I am building a Dockerized Django project and I want to deploy it to Heroku, but I am having a lot of issues. My issues are exactly the same as this post: Docker + Django + Postgres Add-on + Heroku Except I cannot use CMD python3 manage.py runserver 0.0.0.0:$PORT since I receive an invalid port pair error. I'm just running heroku container:push web heroku container:release web heroku open After going to the site it stays loading until it says an error occurred. My log shows the following: System check identified no issues (0 silenced). 2019-05-03T11:38:47.708761+00:00 app[web.1]: May 03, 2019 - 11:38:47 2019-05-03T11:38:47.709011+00:00 app[web.1]: Django version 2.2.1, using settings 'loan_app.settings.heroku' 2019-05-03T11:38:47.709012+00:00 app[web.1]: Starting development server at http://0.0.0.0:8000/ 2019-05-03T11:38:47.709014+00:00 app[web.1]: Quit the server with CONTROL-C. 2019-05-03T11:38:55.505334+00:00 heroku[router]: at=error code=H20 desc="App boot timeout" method=GET path="/" host=albmej-loan-application.herokuapp.com request_id=9037f839-8421-46f2-943a-599ec3cc6cb6 fwd="129.161.215.240" dyno= connect= service= status=503 bytes= protocol=https 2019-05-03T11:39:45.091840+00:00 heroku[web.1]: State changed from starting to crashed 2019-05-03T11:39:45.012262+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch 2019-05-03T11:39:45.012440+00:00 heroku[web.1]: Stopping process with SIGKILL 2019-05-03T11:39:45.082756+00:00 heroku[web.1]: Process exited with status 137 The app works locally through a virtual environment and using Docker but just not on Heroku. Not sure … -
How to extract data from azure database using python?
I have a database in azure, i want to use django/python to extract data from azure and analyze locally. What do i need to do? -
Passing ** kwargs (username) to Django Form
my system the user logged in as user enters the profile page of Company1 and leaves a comment. I need to save the company name in the form, which is passed via url as in the example below http://127.0.0.1:8000/comments/company1/ I am newbie and I am not able to configure Passing ** kwargs to Django Form urls.py url(r'^comments/(?P<username>[\w.@+-]+)/$', comments_form, name='comments_form'), profile.html link for comments <a href="{% url 'comentario_form' user_details.username %}" type="button" > Comments </a> form in profile.html <input type="hidden" value="{{ view.kwargs.company }}" name="company"> views.py def comments_form(request, username): comments = Comments.objects.all() form = CommentsForm() data = {'comments': comments, 'form': form} return render(request, 'comments.html', data) def save_comments(request, username): if request.method == 'POST': form = CommentsForm(request.POST) form.instance.user = request.user form.instance.username = User.objects.get(pk=username) if form.is_valid(): form = form.save() return redirect('system_comments') else: form = CommentsForm() return render(request, 'comments.html', {'form': form}) models.py class Comments(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) company = models.CharField(max_length=255, choices=NOTA_CHOICES, blank=False) comments = models.TextField(max_length=255, blank=False) number = models.CharField(max_length=255, choices=NOTA_CHOICES, blank=False) forms.py class CommentsForm(forms.ModelForm): number = forms.ChoiceField(choices=NOTA_CHOICES, widget=forms.RadioSelect(attrs={'class': 'radio-inline'}),) comments = forms.CharField( widget=forms.Textarea( attrs={ 'width': "100%", 'cols': "80", 'rows': "4"})) class Meta: model = Comments fields = ('comments', 'number') -
How to build a real time iot sever using django rest api and websockets?
I'm building a real time iot server using django and I'm fairly new to django. I have used django REST api so far to get data using HTTP requests, by using JSON. Now I want to further expand my project with the use of django websockets. How can I use websockets with REST api to capture real time data from iot? Or is it even possible to use websockets with REST api. -
Serve static website along side Django App [DRF API] on same subdomain?
I have a subdomain as : app.example.com Now I want to serve a static website on app.example.com which does some API based querying on the Django app which I want to host on same base URL something like : app.example.com/app/api.... But I am unable to do so. My Nginx configuration is as follows : server { root /home/ubuntu/dist/; index index.html index.htm index.nginx-debian.html; server_name app.example.com; location / { alias /home/ubuntu/dist/ ; try_files $uri /$uri index.html last; } location /admind { alias /home/ubuntu/admind/dist/ ; try_files $uri /$uri/ index.html last; } location /app/ { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://gunicorn; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/app.example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } # Virtual Host configuration for example.com # # You can move that to a different file under sites-available/ and symlink that # to sites-enabled/ to enable it. # #server { # listen 80; # listen [::]:80; # # server_name example.com; # # root /var/www/example.com; # index index.html; # # location / { # try_files $uri $uri/ =404; # … -
Django: how to get an object of manager on admin page
I am new to Django and working on a project. In my project admin will have the power to assign the project to manager. So i want to render the name of all the managers from the database so that it will be displayed to the admin. here is my .html file where i want to render the name of the manager. <div class="body table-responsive"> <table class="table table-hover"> <thead> <tr> <th>S No.</th> <th>COMPANY NAME</th> <th>TEAM MEMBER</th> <th>EMAIL</th> <th>ASSIGN TEAM</th> </tr> </thead> <tbody> {%for team in object%} <tr> <form id="form_id" method="POST" action = "{% url 'accept' %}"> {% csrf_token %} <th scope="row"> {{ forloop.counter }}</th> <td>{{team.company_name}}</td> <td>{{team.team_member}}</td> <td>{{team.email}}</td> <td> <select name="manager"> {% for manager in managers %} <option value ="{{manager.id}}">{{manager.name}}</option> {% endfor %} </select> <!-- </div> --> </td> </tr> {% endfor %} </tbody> </table> here is my model for manager class manager(models.Model): name = models.CharField(max_length= 500) designation = models.CharField(max_length= 500) class Meta: permissions = [ ("edit_task", "can edit the task"), ] def __str__(self): return self.name here is my views. py def accept(request): obj= Create_Team.objects.filter(status='Accept') if request.method == 'POST': acc = manager() manager_id = int(request.POST.get('manager', 1)) acc.manager = manager.objects.get(pk=manager_id) return render(request, "admin/accept.html", {"object": obj}) in admin's page i want to display all … -
Redirect from HTTP to HTTPS in Python Django
I want to redirect the python and django website from http to https. When i'm using the "SECURE_SSL_REDIRECT = True" in settings.py. I'm getting the folder structure. Thanks, Pravin Kumar enter image description here -
How to read value from a html image back to django view function?
I generate lots of images in html from local folders. I want to add links to all of these images (And triggered by a view function create_pc) and I want to send the image path to my view function. This is a part of my html file {% load static %} <h1>Color images:</h1> <ul> {% for img_path in Color %} <li><a href="/create_pc/"><img src="{% static img_path %}" width="100" height="100"></a></li> {% endfor %} </ul> In urls.py I have set the address to the function: path(r'create_pc/',views.create_pc) My function in view.py: def create_pc(request): return HttpResponse(str(img_path)) So I want to get the src="{% static img_path %}" in the create_pc function, which means the function knows which image is clicked. I don't know how to handle this. Please help me!