Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get_object_or_404 is undefined
I'm trying to update my Profile model with some data that I get from a form, but I get this error name 'get_object_or_404' is not defined Here's my code for the view (It's pretty basic at this point) from django.shortcuts import render from django.contrib import messages from django.contrib.auth.models import User from users import models from users.models import Profile from .forms import WeightForm # Create your views here. def home(request): profile = get_object_or_404(pk=id) form = WeightForm(request.POST, instance=profile) if form.is_valid(): form.save return render(request, 'Landing/index.html',{'form':form}) -
Facebook has detected Believer isn't using a secure connection to transfer information
Well I am trying to add login and sign up with facebook functionality and when i click on login with facebook it takes me to facebook but shows an error such as Facebook has detected Believer isn't using a secure connection to transfer information. Until Believer updates its security settings, you won't be able to use Facebook to log into it. -
Django - can't compare offset-naive and offset-aware datetimes or no result appears
I got a model / view for Story project. My goal is to give only a time to stories to appear on my website. class Story(models.Model): ... ... image = models.ImageField(upload_to='story/') created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def save(self): super().save() @property def is_active(self): #now = timezone.now() if (self.created_on + timedelta(days=10)) > datetime.now(): return False return True @method_decorator(login_required(login_url='/cooker/login'),name="dispatch") class StoryList(generic.ListView): queryset = Story.objects.order_by('-created_on') template_name = 'user_list_story.html' model = Story I get this issue: can't compare offset-naive and offset-aware datetimes So I've tried to correct it in order to the same comparaison. @property def is_active(self): now = timezone.now() if (self.created_on + timedelta(days=10)) > now: return False return True But nothing appears on my page. Here is the code template. {% for story in story_list %} {% if story.is_active %} {{ story.title }} {% endif %} {% endfor %} -
Create spacing in data list
How do I space out the output, i considered using the each() method but I couldn't figure out how to use it. I can do this with Django for loop without ajax, but with ajax it seems the for loop tag doesn't work here's the code. current output = 1.0768411833.01.28164125.6340.91000 expected output = 1.07684 11833.0 1.28164 125.634 0.91000 <h2 id="prices"></h2> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> const doAjaxWithDelay = (delay) => { setTimeout(() => { var data = $(this).data() $.ajax({ url: "/price", type: "GET", success: function(data) { document.getElementById('prices').innerHTML = data; console.log(data) } }).done(() => { doAjaxWithDelay(5000) }) }, delay) } doAjaxWithDelay(0) </script> -
Django's invalid regular expression: invalid escape \ sequence [duplicate]
I'm trying to filter my records with __regex field lookup. It works fine until I started using unicode property group (\p{whatever}), or, letter group (\p{L}). DB i'm using - postgresql. Code that I got looks like this: f1 = Q(field__regex=r'[^\d\p{L}]anystr[^\d\p{L}]') f2 = Q(field__regex=r'[^\d\p{L}]strany[^\d\p{L}]') MyModel.objects.filter(f1 | f2) After launch of this code, I got this error: django.db.utils.DataError: invalid regular expression: invalid escape \ sequence I tried to dig deeper and found nothing that could cause problem in python code. Last point of exception is: django\db\backends\utils.py", line 86, in _execute, so, i placed pdb point there. There are 2 variables, sql and params. sql - contains raw sql code without values of django's Q objects yet (seems like it will be added by format strings, because of %s's) params - Q object's values itself. In my example it was: ('[^\\d\\p{L}]anystr[^\\d\\p{L}]', '[^\\d\\p{L}]strany[^\\d\\p{L}]') 1 line later exception like above was thrown again. But, If I paste one of generated values of Q in search of DB itself, no error seen. -
Adding additional serializer field that will be using posted data from the client
How can I use Django Channels with my Django Rest Framework so that I can use it with my Flutter Mobile App ? -
how to assign different id in button in django template so that javascript click event won't select all post
I am new to django and also have very little knowledge in javascript. Here I am trying to assign id to the delete and update button so that when clicking them javascript won't select all the same button. If anyone can help this poor man. this is my django template that contains update and delete button {% for obj in queryset %} <div class="ui grid"> <div class="row"> {% ifequal request.user obj.author.user %} <button class="ui button bwhite-lg " id='modal-udt-btn'>Update</button> <button class="ui button bwhite-lg " id='modal-dlt-btn'>Delete</button> <!-- modal --> <div class="ui basic modal update"> {% url 'posts:post_update' obj.pk %} </div> <div class="ui basic modal delete"> {% url 'posts:post_delete' obj.pk %} </div> {% endifequal %} </div> </div> {% endfor %} Here is the part with javasript <script> $(document).ready(function(){ $('#modal-dlt-btn').click(function(){ console.log('deletebtn') $('.ui.basic.modal.delete') .modal('show') ; }) }); $(document).ready(function(){ $('#modal-udt-btn').click(function(){ console.log('updatebtn') $('.ui.basic.modal.update') .modal('show') ; }) }); </script> -
How can I reuse Django admin search feature?
I'm developing an application with Django.I'm using Django admin's search feature like this: class ProductAdmin(admin.ModelAdmin): search_fields = ('image_name', 'product_name', ) And it gives a very nice search on these columns. Now I want to use this search in my views and inside my code. I mean I want to reuse this search which Django uses for the admin page in my code. I've read the code of ModelAdmin class but I couldn't reuse it, because it uses some objects from other layers of Django. So I couldn't figure out how can I do this. -
The SECRET_KEY setting must not be empty, django by example
I am getting this error while running the following command: python manage.py runserver The is a result of the execution of the code from the book; 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 "D:\Anaconda_3\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "D:\Anaconda_3\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Anaconda_3\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "D:\Anaconda_3\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "D:\Anaconda_3\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "D:\Anaconda_3\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "D:\Anaconda_3\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "D:\Anaconda_3\lib\site-packages\django\conf\__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "D:\Anaconda_3\lib\site-packages\django\conf\__init__.py", line 161, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. -
How to retrieve information in Django - Post Request?
I am trying to send a JavaScript array to Django via ajax, as follows: document.getElementById('input-generate').onclick = () => { // Get the token const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; // Create new request add token const generateRequest = new XMLHttpRequest(); generateRequest.open('POST', '/generate'); generateRequest.setRequestHeader('X-CSRFToken', csrftoken); generateRequest.onload = () => { console.log('generateRequest'); }; // Add the motif to send with the request const data = new FormData(); console.log(notes); // [{…}] 0: {duration: "4", note: "E4", dot: false} length: 1 __proto__: Array(0) data.append('motif', notes); // Send request generateRequest.send(data); }; On views.py: @require_http_methods(["POST"]) def generate(request): # See if method was post if request.method == "POST": # Retrive seed seed = request.POST.get("motif") print(seed) print(type(seed)) # Sanity check if not seed: return JsonResponse({"succes": False}, status=400) # Return the seed return JsonResponse({"seed": seed}, status=200) But when I print seed and type(seed) I only see: [object Object] <class 'str'> How can I print the actual array I am sending? -
Django models.CASCADE in ManyToManyRelation
I have a m2m relationship with users and posts. A user can like a many posts and at the same time a post can be liked by many users. If i do this: post.liked_by.remove(current_user) With this model structure: class Posts(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="posts") creation_date = models.DateTimeField(auto_now_add=True, blank=True) content = models.TextField(null=True) class User(AbstractUser): follows = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followed_by') likes = models.ManyToManyField(Posts, related_name='liked_by') pass As far as i know, the user object will be removed from the liked_by part of the relationship. But my question is: Will also the post object be removed from the likes part of the relationship? -
Form not showing on template
I've created a model form and it does not show on the page models.py class Newsletter(models.Model): email = models.EmailField(max_length=254) name = models.CharField(max_length=50) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email forms.py class NewsletterForm(forms.ModelForm): class Meta: model = Newsletter fields = ['name', 'email'] views.py class HomeNewsletterFormView(FormView): template_name = 'home/base.html' form_class = NewsletterForm base.html <form method="POST" action=''> {% csrf_token %} {{ form.as_p }} <input type="submit"> Everytime I reload the page, I see browser popup mentioning "The page that you're looking for used information that you entered. Returning to that page might cause any action that you took to be repeated. Do you want to continue?" -
Django LoginView with custom email form
I am trying to create LoginView with a custom email form instead of a username, but having a hard time to manage it to work. Here is my code below urls.py ********** urlpatterns = [ path("login/", views.LoginView.as_view(), name="login"), path("logout/", views.log_out, name="logout"), ] forms.py class LoginForm(forms.Form): email = forms.EmailField(widget=forms.EmailInput(attrs={"placeholder": "Email"})) password = forms.CharField( widget=forms.PasswordInput(attrs={"placeholder": "Password"}) ) def clean(self): email = self.cleaned_data.get("email") password = self.cleaned_data.get("password") try: user = models.User.objects.get(email=email) if user.check_password(password): return self.cleaned_data else: self.add_error("password", forms.ValidationError("Password is wrong")) except models.User.DoesNotExist: self.add_error("email", forms.ValidationError("User does not exist")) views.py class LoginView(FormView): template_name = "users/login.html" form_class = forms.LoginForm success_url = reverse_lazy("core:home") def form_valid(self,form): email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = authenticate(username=email,password=password) if user is not None: login(self.request,user) return HttpResponse(request.user.is_authenticated) else: return HttpResponse("Login failed") return super().form_valid(form) def log_out(request): logout(request) return redirect(reverse("core:home")) html file <form method="POST" action="{% url 'users:login' %}"> {% csrf_token %} {{ form.as_p }} <button>Login</button> </form> In the code above i didn't copy paste from .. import .. things since i am sure thats is not what causing a problem. The error message i am getting is "Login Failed" in this line `if user is not None: login(self.request,user) return HttpResponse(request.user.is_authenticated) else: return HttpResponse("Login failed")` in setting.py i have this AUTH_USER_MODEL = "users.User" and my models.py … -
Command Error status 1 when I import an app in django
I'm working with Django Channels tutorial. When i'm trying to import app_name.routing i get this type of error: ERROR: Command errored out with exit status 1: command: 'd:\koronatime\djangopython\djangochannels\env\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Admin\\AppD ata\\Local\\Temp\\pip-install-1ws3h4ct\\numpy\\setup.py'"'"'; __file__='"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-1ws3h4ct\\numpy\\setup.py'"'"';f=ge tattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' instal l --record 'C:\Users\Admin\AppData\Local\Temp\pip-record-8ado413q\install-record.txt' --single-version-externally-managed --compile --install-headers 'd:\koronatim e\djangopython\djangochannels\env\include\site\python3.8\numpy' cwd: C:\Users\Admin\AppData\Local\Temp\pip-install-1ws3h4ct\numpy\ Complete output (1795 lines): Running from numpy source directory. Note: if you need reliable uninstall behavior, then install with pip instead of using `setup.py install`: .... Hundred rows of mistake ... ERROR: Command errored out with exit status 1: 'd:\koronatime\djangopython\djangochannels\env\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv [0] = '"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-1ws3h4ct\\numpy\\setup.py'"'"'; __file__='"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-1w s3h4ct\\numpy\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, _ _file__, '"'"'exec'"'"'))' install --record 'C:\Users\Admin\AppData\Local\Temp\pip-record-8ado413q\install-record.txt' --single-version-externally-managed --compil e --install-headers 'd:\koronatime\djangopython\djangochannels\env\include\site\python3.8\numpy' Check the logs for full command output. I've included it in INSTALLED_APPS. I am on OS Windows. P.S. When I've include app in settings and had installed some packages already, I always need to click on Install package app_Name, when i importing it on code, like it was with Channels. Why is it happening? -
Problems implementing django-babeljs in my project
I'm trying to implement django-babeljs 0.2 but I can't get it to work with my code, I'm not using react. I just want my js files to be transpiled with babel, they have an example of how to implement it correctly, I am reading the documentation of the library at https://pypi.org/project/django-babeljs/#description but it really is not very explicit. Could someone help me with this issue. -
GET Method works on localhost but return 500 Internal Server Error on server (Django)
I'm sending an API request from Angular to Django. The request is working on localhost but returns a 500 Internal Server Error on server. I tried running migrations, changing the API URL but nothing is working. Here's my code: @api_view(['GET','POST','DELETE']) def get_favorite_annonces(request): if request.method == "GET": favorite_annonces = [] user = request.user all_favorites = AnnoncesFavorite.objects.filter(user_id=user.id) for favorite_id in all_favorites: annonce = Annonces.objects.filter(id=favorite_id.annonce_id) favorite_annonces.append(annonce[0]) print(favorite_annonces) qs_json = serializers.serialize('json', favorite_annonces) return HttpResponse(qs_json, content_type='application/json') my component: this.ApiService.get_favorite_annonces().subscribe( data=>{ this.favorites_list = data; console.log(this.favorites_list); }, api.service.ts get_favorite_annonces():Observable<any>{ return this.http.get<any>(this.auth.getApiUrl() + 'favorites/annonces'); } -
How do I filter a Django model by an attribute of a relationship field?
I am trying to query my 'Profile' model by the 'username' attribute of its OneToOneField relation 'User'. I have attempted to accomplish this by setting my queryset using: Profile.objects.get(owner.name = ...), however in doing so I get an error saying 'SyntaxError: expression cannot contain assignment, perhaps you meant "=="?'. This is confusing as if I set this these parameters to something like 'id = ...', I get no such error. What am I doing wrong here? If I wanted to query the 'Profile' table by the 'username' of its 'owner' relation, how would I best do this? I have attached my code below. models.py: class User(models.Model): username = CharField(max_length = 80) class Profile(models.Model): owner = models.OneToOneField('User', related_name = 'profile', on_delete = models.CASCADE) views.py: class UserProfile(generics.GenericAPIView, mixins.RetrieveModelMixin): def get_queryset(self): username = self.kwargs['username'] return Profile.objects.filter(owner.username=username) serializer_class = UserProfileSerializer def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) urls.py: urlpatterns = [ path('user/<str:username>/profile/', views.UserProfile.as_view()), ] Thanks -
I cant able to send email using django even I gave all permission from google side
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIT_PORT = 587 EMAIL_HOST_USER = 'your@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True EMAIL_USE_SSL= False send_mail(msg,"Thank-You for using our Website ,Mail us if you have any Problem in Our Website.Thank-You Once again" , settings.EMAIL_HOST_USER,[emailto,],fail_silently=False,) I cant send mail it showing timeout error even i have tried EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' I cant send the mail instead of that i am getting printed in console box [11/Sep/2020 23:07:49] "POST / HTTP/1.1" 200 3502 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Hello User From: tamilan0tamill@gmail.com To: bahubali@gmail.com Date: Fri, 11 Sep 2020 17:39:50 -0000 Message-ID: 159984599099.7876.4877994479538514933@UNIVERSE Thank-You for using our Website ,Mail us if you have any Problem in Our Website.Thank-You Once again -
How to get Required result in framework?
I have the following models and want to display some required results in web API. class Poll(models.Model): question = models.CharField(max_length=100) created_by = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateTimeField(auto_now=True) class Choice(models.Model): poll = models.ForeignKey(Poll, related_name='choices', on_delete=models.CASCADE) choice_text = models.CharField(max_length=100) class Vote(models.Model): choice = models.ForeignKey(Choice, related_name='votes', on_delete=models.CASCADE) poll = models.ForeignKey(Poll, on_delete=models.CASCADE) voted_by = models.ForeignKey(User, on_delete=models.CASCADE) And i set the in te way like below: class VoteSerializer(serializers.ModelSerializer): voted_by = serializers.StringRelatedField(many=False) class Meta: model = Vote fields = '__all__' class ChoiceSerializer(serializers.ModelSerializer): votes = VoteSerializer(many=True, required=False) class Meta: model = Choice fields = '__all__' class PollSerializer(serializers.ModelSerializer): choices = ChoiceSerializer(many=True, read_only=True, required=False) created_by = serializers.StringRelatedField(many=False) class Meta: model = Poll fields = '__all__' class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User( email=validated_data['email'], username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() Token.objects.create(user=user) return user I want an result where only those votes are display in choices where vote_by='the choicse id'. **But the result include all the votes ** { "id": 1, "votes": [ { "id": 1, "voted_by": 1, "choice": 1, "poll": 1 }, { "id": 2, "voted_by": 2, "choice": 1, "poll": 1 } ], "choice_text": "it provide web API and authentication permissions for security.", "poll": 1 } -
Using local timezone in django admin template
After crying under my desk for a while over this problem I got the courage to come on SO and ask this question. I have a django model: entry_time = models.DateTimeField(auto_now_add=True) On my admin change_form.html and change_list.html I would like to display that object in local time. I've read the django docs on this, my biggest problem I think is that I'm modifying the template and am not directly calling the object. Settings.py: TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True I have tried changing the TIME_ZONE to US/Arizona which didn't work. I tried solutions i found at Setting Django admin display times to local time? such as custom templates using {% extends "admin/change_list.html" %} {% load tz %} {% block content %} {% timezone "US/Eastern" %} {{ block.super }} {% endtimezone %} {% endblock %} This did nothing, my time is still UTC on change_form. I tried installing a middleware package (awesome-django-timezones) that uses js to find local timezone and change it using middleware. This did nothing as well. I also tried going into options.py and adding activate() into the view that calls change_form.html-- no success. Am I missing something? How can I extend the … -
GET /static/vendor/select2/dist/css/select2.css HTTP/1.1" 404 1832
I want to add autocomplete_light to a django field as explained here. I will explain you shortly the steps and error: in setting.py: INSTALLED_APPS = [ 'dal', 'dal_select2', 'cities_light'] in views.py: class CountryAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated(): return Country.objects.none() qs = Country.objects.all() if self.q: qs = qs.filter(name__icontains=self.q) return qs in urls.py: urlpatterns = [ path('country-autocomplete/', CountryAutocomplete.as_view(), name='country-autocomplete'),.. ] in models.py: class Person(models.Model): birth_country = = models.ForeignKey(Country, on_delete=models.CASCADE) in forms.py: class PersonForm(forms.ModelForm): birth_country = forms.ModelChoiceField( queryset=Country.objects.all(), widget=autocomplete.ModelSelect2(url='country-autocomplete') ) class Meta: model = Person fields = "__all__" and in html: {% extends "myapp/base.html" %} {% load static %} {% block content %} <form id="anything" method="POST" enctype="multipart/form-data"> <div class="searchable"> {{form.birth_country}} </div> </form <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet"/> {{ form.media }} {% endblock content %} This is the Error: The birth_country field in Person form is not populated to be autocomplete. Also in terminal I get this error (not quit sure if this is the reason): GET /static/vendor/select2/dist/css/select2.css HTTP/1.1" 404 1832 and this should be the path to this file, however it looks empty: and I would like to know where can I find it, or why it is not imported! -
Is it possible to get a python program that uses tkinter to run in a web page using flask?
I have a python program that I would like to use in a web server. For that I need to convert it to web environment. I read that you can do it with flask. the challenge is that the program is a GUI made with tkinter. If I run the following program through the cmd: flask run, it runs in the local host, (http://127.0.0.1:5000/). If I copy the address and put it in a web browser, I get the error Internal Server Error in the web window, but a new window open in my computer with the checkbutton and the label. The program works; What I need is to put that window with the checkbutton and the label inside the web window, so I can eventually put it on a server. (I have hundreds of widgets for what i was forced to use the place.method and I don't want to code everything from scratch in another language). Is there anyway to do it? from flask import Flask from tkinter import * app = Flask(__name__) @app.route("/") def hello(): root = Tk() out = Label(root, text="0", bg="red") def out_result(): out.configure(text="button pressed") button1 = Checkbutton(root, command=out_result) button1.place(x=20, y=20) out.place(x=50, y=20) root.mainloop() -
How to add inbox notification system and delete message from one user django channels
I am trying to build a messenger like application using Django, Django-rest-framework, and Django-channels. Right now I can only send messages from one user to another user. But I want to add features like, new messages will be on top in the inbox along with the username and one user can delete messages from his side, just like messenger, whats app, etc. When someone sends a message his message will be on top and will show a notification. I am unable to find out perfect model design and perfect system for doing it. Model.py from django.contrib.auth import get_user_model from django.db import models User = get_user_model() class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender_messages') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver_messages') text = models.TextField() date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return '{} to {}'.format(self.sender.name, self.receiver.name) consumer import json from asgiref.sync import async_to_sync from django.contrib.auth import get_user_model from channels.generic.websocket import WebsocketConsumer from .models import Message User = get_user_model() class ChatConsumer(WebsocketConsumer): def connect(self): """ Join channel group by chatname. """ self.group_name = 'chat_{0}'.format(self.scope['url_route']['kwargs']['chatname']) async_to_sync(self.channel_layer.group_add)( self.group_name, self.channel_name, ) self.accept() def disconnect(self, close_code): """ Leave channel by group name. """ async_to_sync(self.channel_layer.group_discard)( self.group_name, self.channel_name ) def receive(self, text_data): """ Receive message from websocket and send message to channel group. """ … -
i am trying to fetch notes materials that are related to one specific course
enter code here**` <div class="site-section"> <div class="container"> <div class="row"> {% for course_item in courses%} <div class="col-lg-4 col-md-6 mb-4"> <div class="course-1-item"> <figure class="thumnail"> <div class="category"><h3>{{course_item.title}}</h3></div> </figure> <div class="course-1-content pb-4"> <h2>How To Create Mobile Apps Using Ionic</h2> <div class="rating text-center mb-3"> <span class="icon-star2 text-warning"></span> <span class="icon-star2 text-warning"></span> <span class="icon-star2 text-warning"></span> <span class="icon-star2 text-warning"></span> <span class="icon-star2 text-warning"></span> </div> <p class="desc mb-4">{{course_item.description}}</p> <p><a href="{% url 'notes' course_item.id %}" class="btn btn-primary rounded-0 px-4">Enroll In This Course</a></p> </div> </div> </div> {% endfor %} </div> </div> </div> {% endblock %} def Courses(request): current_user = request.user courses = Course.objects.filter(students__user__id=current_user.id) return render(request, 'e-learning/courses.html', {'courses':courses}) def Materials(request): notes = NotesMaterial.objects.filter(course_id) return render(request, 'e-learning/materials.html',{'notes':notes}) urlpatterns = [ url(r"^courses/$", views.Courses, name="courses"), url(r'^notes/$', views.Materials, name="notes"), ] class NotesMaterial(models.Model): note_title = models.CharField(max_length=200, null=False) note_description = models.CharField(max_length=200, null=False) course = models.OneToOneField(Course, on_delete=models.CASCADE, null=True) NoReverseMatch at /e-learning/courses/ Reverse for 'notes' with arguments '(1,)' not found. 1 pattern(s) tried: ['e-`learning/notes/$'] Blockquote i am trying to fetch notes materials that are related to one specific course.. ive tried filtering using the course_id which i passed in the template as the course_item.id. Notes material model is related on a one to one relationship with the course. `** -
How can i keep selenium connections open in django?
so i'm using Django and i have a web api liket this https://example.net/open-get-string i want to open a connection to a url and get a string , then return that string as the web api response. i want to keep open the connection i've opened until i get that string back in this url https://example.net/send-string and i want to pass the string given in this url to the selenium connection i've made before. I don't have any idea about how can i keep connection open until i get the string back.