Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Solve Django rest-framework JSON parse Error
What is wrong with this JSON? when trying to send a POST request with POSTMAN getting JSON PARSE ERROR. Error from Postman { "detail": "JSON parse error - Expecting ',' delimiter: line 5 column 13 (char 82)" } JSON Data sending From Postman { "menu_name": "indian_menu", "slug": "indianmenu", "item_name": [ "category": "indianmenu", ] } rest_framework Serializers class MenuCardSerializer(serializers.ModelSerializer): class Meta: model = MenuCard fields = '__all__' read_only_fields = ('menu_name', ) class MenuSerializer(serializers.ModelSerializer): category = MenuCardSerializer(required=True, many=True) class Meta: model = Menu fields = '__all__' def create(self, validated_data): category = validated_data.pop('category') menu = MenuCard.objects.create(**validated_data) for choice in category: Menu.objects.create(**choice, category=menu) rest_framework API_VIEWS @api_view(['GET', 'POST', 'PUT', 'DELETE', ]) def simple_menu(request, slug): print("simple menu slug : " + slug) if request.method == 'GET': category_list = Menu.objects.all() serializer = MenuSerializer(category_list) return JsonResponse(serializer.data) elif request.method == 'POST': serializer = MenuSerializer(data=request.data, many=False) data = {} if serializer.is_valid(): serializer.save() data["success"] = "item Catagory Created" return JsonResponse(data=data, status=status.HTTP_200_OK) return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Apply Decorator to URL Pattern In Django 3
I want to create custom path function in Django 3, that support applying a decorator to a URL pattern. I see this source in GitHub and try to update that to Django 3. this is my updated codes: from functools import partial from django.core.exceptions import ImproperlyConfigured from django.urls.resolvers import RegexPattern, RoutePattern from django.utils.encoding import force_text import six from django.urls import ResolverMatch, Resolver404, get_callable, URLResolver, URLPattern class DecorateURLResolver(URLResolver): def __init__(self, pattern, urlconf_name, default_kwargs=None, app_name=None, namespace=None, wrap=None): super(DecorateURLResolver, self).__init__(pattern, urlconf_name, default_kwargs, app_name, namespace) if isinstance(wrap, (tuple, list)): self.wrap = wrap elif wrap: self.wrap = [wrap] else: self.wrap = [] def resolve(self, path): path = str(path) # path may be a reverse_lazy object tried = [] match = self.pattern.match(path) if match: new_path, args, kwargs = match for pattern in self.url_patterns: try: sub_match = pattern.resolve(new_path) except Resolver404 as e: sub_tried = e.args[0].get('tried') if sub_tried is not None: tried.extend([pattern] + t for t in sub_tried) else: tried.append([pattern]) else: if sub_match: # Merge captured arguments in match with submatch sub_match_dict = {**kwargs, **self.default_kwargs} # Update the sub_match_dict with the kwargs from the sub_match. sub_match_dict.update(sub_match.kwargs) # If there are *any* named groups, ignore all non-named groups. # Otherwise, pass all non-named arguments as positional arguments. sub_match_args = β¦ -
FATAL: too many connections for role: Heroku/django, only while using ASGI
I know there are other similar questions but I believe I have gone through all of them but none of them was able to solve my problem. Everything is working fine when I am using WSGI server. It only happens when I use ASGI server however I must use ASGI server because my project's functionalities are limited without it. I am using postgres database. Also, I believe there is no problem while running the project on localhost because I checked the number of connections to my database (which is on my machine for development) and I saw just 1. That 1 connection was also not from the django project to my database but it was my own connection which I was using to access the database explicitly. I don't know why there was not even a single connection from my project to the database. Procfile web: daphne aretheycoming.asgi:application --port $PORT --bind 0.0.0.0 -v2 aretheycomingworker: python manage.py runworker --settings=aretheycoming.settings -v2 asgi.py import os import django from channels.routing import get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "aretheycoming.settings") django.setup() application = get_default_application() settings.py import django_heroku import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production β¦ -
Display Dashboard Chart using Existing Sales Records available in Database, in Customised Django admin Panel
I have created customised Admin Panel using Python & Django. Now in my case there are several Tables in Database. But more importantly I want to show charts of Past 6 months sales in Django admin Panel. Can some one guide me how to do this ? Important Note : I have checked several examples but most of them using static data only which comes through JS files. I have already implemented using the Static data adding to the .py file. But now the same thing I need to implement using the Database. Any suggestions or references will be highly appreciated. -
Can't access Django runserver from URL or IP on Ubuntu 18.04
I had a project that I transferred to Ubuntu with Git. Everything was working, then I updated some files and then it did not work. Being I am fairly new to this, I reinstalled the Ubuntu image on the server and tried again, still with no success. I deleted my Django project rm -r my_project and created a brand new project on the server, both with Django 3.0.3 and with Django 2.2.9. Both have the same results. I loaded Nginx on the server and can get the default Nginx page from the URL and IP, but Django is nothing. Below are my settings. I tried with and without the firewall. settings.py # Tried this ALLOWED_HOSTS = ['*'] # And this ALLOWED_HOSTS = ['my_domain','my_IP','localhost'] And then ran this from the virtualenv python3 manage.py runserver 0.0.0.0:8000 Which loaded normally and can be curled from inside the server, but my_domain:8000 and my_ip:8000 never connect and times out. I know not to use the Django server, but I can't get anything to work (gunicorn or anything other than Nginx default page). -
(Auto-) increment Textfield in Django
I want to set a textfield (col2) in Django which autoincrements depending on another columns value (value_column). The DBtable may shall look like this: col1, col2, col3, value_column 0 , a , 0 , x 0 , a , 1 , x 0 , a , 2 , y 0 , b , 2 , y 0 , c , 2 , z 0 , a , 3 , z ... 1 , Za , 4 , t 1 , Zb , 4 , u ... 42 , Zza , 0 , p What are possible implementations? -
Using bootstrap in Django on Ubuntu
I tried to use bootstrap in my app. but I get ERROR 404, for each bootstrap file that my template requests. My Django project is on my website subdirectory (www.example.com/django-project). First I download bootstrap directly from their website and put it in the project directory as follow. But after some failures to load files in website, I installed it using python3 -m pip install django-bootstrap-static .My configuration files are as follow: settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'get_cfp_list', 'bidiutils', 'bootstrap', 'fontawesome', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'bidiutils.context_processors.bidi', 'django.template.context_processors.static', ], }, }, ] STATIC_URL = '/static/' STATICFILES_DIRS = ( '/var/www/portal/portal/static/bootstrap/', ) STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ) Folder Structure:/var/www/portal/portal/ βββ db.sqlite3 βββ get_cfp_list β βββ admin.py β βββ apps.py β βββ cfp.html β βββ __init__.py β βββ models.py β βββ tests.py β βββ views.py βββ manage.py βββ portal β βββ __init__.py β βββ settings.py β βββ urls.py β βββ wsgi.py βββ static β βββ bootstrap β βββ css β β βββ bootstrap.css β β βββ bootstrap.min.css β β βββ bootstrap-responsive.css β β βββ bootstrap-responsive.min.css β βββ img β β βββ glyphicons-halflings.png β β¦ -
Django LDAP groups not seeing Domain group members
I am having a hard times authenticating my HPA account in Django app. I have two LDAP groups added to my settings.py one commented out and one active. AUTH_LDAP_REQUIRE_GROUP = (LDAPGroupQuery("CN=GSAFU3T_ENGINEER,OU=U3,OU=UserGroups,OU=U1,OU=CompanyUsers,DC=ad,DC=net") | LDAPGroupQuery("CN=GSAFU3T_READER,OU=U3,OU=UserGroups,OU=U1,OU=CompanyUsers,DC=ad,DC=net") | LDAPGroupQuery("CN=DSAPB2T_ADMIN,OU=Apps,OU=Security Groups,OU=Groups,OU=B2,OU=Tenants,DC=ad,DC=net")) If i check LDAP (get-adgroup GSAFU3T_ENGINEER -Server ad.net βProperties Members).Members i get list of GSAFU3T_ENGINEER Engineer Members also if i check (get-adgroup DSAPB2T_ADMIN -Server ad.net βProperties Members).Members i can see list of DSAPB2T_ADMINNPA members If i login via somebody from ENGINEER group, it wokrs like a charm, if i try to login via HPA account from ADMIN group, i can't login. Tried to configure groups in settings one by one and still with ENGINEER group configured i can login, but with ADMIN group configured i can't login. Any idea why? -
Oembed code for tweet only displaying text
So i can get the following code to display oembed properly: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4 /jquery.min.js"></script> <script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script> <script type='text/javascript'> $(document).ready(function(){ $.getJSON("https://api.twitter.com/1/statuses/oembed.json?id=287348974577385474&align=center&callback=?", function(data){$('#tweet123').html(data.html);}); }); </script> </head> <body> <div id='tweet123'></div> </body> </html> However this code only displays the tweet text: {% load staticfiles %} <!DOCTYPE html> <html> <head> <script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script> </head> <body> <div class='progress-wrapper'> <div id='progress-bar' class='progress-bar' style="background-color: #68a9ef; width: 0%;">&nbsp;</div> </div> <div id="progress-bar-message">Waiting for progress to start...</div> <script src="{% static 'celery_progress/celery_progress.js' %}"></script> // vanilla JS version <script> document.addEventListener("DOMContentLoaded", function () { var progressUrl = "{% url 'celery_progress:task_status' task_id %}"; CeleryProgressBar.initProgressBar(progressUrl); }); </script> <div id="celery-result"> {{ result }} </div> </body> </html> This is in my tasks.py tweet = random.choice(result) tweet_id = str(tweet.id) embReqUrl = 'https://publish.twitter.com/oembed?url=https://twitter.$ embResp = requests.get(embReqUrl) json = embResp.json() html = json['html'] pprint(html) return html This is in my views.py def progress_view(request): count_pag = 200 print(request.POST.get('account_name')) account_name = request.POST.get('account_name') result = hello.tasks.my_task.delay(8, account_name) # pprint(result) if(result is None): result = "No tweets available." # result = hello.tasks.my_task.delay(8) # context = {'task_id': result.task_id} return render(request, 'display_progress.html', {'task_id': result.task_id, 'result': result}) # return HttpResponse(request.POST.items()) pprint(str(result)) I've tried searching for various solutions to this problem but none seem to work! Your help is greatly appreciated........................................................................................ -
ModuleNotFound Error is happening when deploying code on AWS but working absolutely fine on local server?
Why the code files are not able to import properly when deploying the django based project on AWS. I have added init.py files everywhere but seems like this is not the issue. all the python code files in a folder is not able to be imported. Please let me know how it can be fixed. ------------------------------------- /var/log/eb-commandprocessor.log ------------------------------------- File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 64, in _run_checks issues = run_checks(tags=[Tags.database]) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/checks/database.py", line 9, in check_database_backends for conn in connections.all(): File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/db/utils.py", line 216, in all return [self[alias] for alias in self] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/db/utils.py", line 213, in __iter__ return iter(self.databases) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/db/utils.py", line 147, in databases self._databases = settings.DATABASES File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/opt/python/run/venv/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line β¦ -
How to get json data from another api or website with Django & REST
i'm developing a web app with Django which this website using NASA api (daily image, image library vs). NASA Api using REST and i get json data from NASA, i did like this; url = "https://api.nasa.gov/planetary/apod?api_key=apikey" response = urllib.request.urlopen(url) data = json.loads(response.read()) return render(request, 'home.html', {"apod": data}) And in image library search, gettin more than one page json data, it's very difficult for me to split this json data. Is there another way? like djangorestframework Thank you guys. -
Django two columns or composite foreign key in model
How i can declare composite constraint like this scheme in Django 3 model? I tried to declare foreign and primary key like this: class DiAttribute(models.Model): attribute_name = models.CharField(max_length=80, blank=True, null=True) attribute_id = models.IntegerField(max_length=10, blank=False, null=False, unique=True, related_name='attribute_id') object_type_id = models.CharField(max_length=50, blank=False, null=False, unique=True, related_name='object_type_id') class Meta: managed = False unique_together = (('object_id', 'attribute_no'),) db_table = 'di_attribute' class Attribute(models.Model): object_id = models.ForeignKey(RpObject, on_delete=models.DO_NOTHING, db_column='object_id') attribute_no = models.IntegerField(max_length=10, blank=False, null=False) attribute_id = models.ForeignKey(DiAttribute, on_delete=models.DO_NOTHING, db_column='attribute_id', to_field='attribute_id', unique=True, related_name='attribute_id') object_type_id = models.ForeignKey(DiAttribute, on_delete=models.DO_NOTHING, db_column='object_type_id', to_field='object_type_id', unique=True, related_name='object_type_id') class Meta: managed = False unique_together = (('object_id', 'attribute_no'),) db_table = 'attribute' but it's not working -
How in Djnago admin to allow adding only one object in Inline section?
I need allow user to add only one object. How to make it? How to remove button Add another ...? -
How to integrate react components to django
I have an existing django project. I want to be able to use react components with the existing django templates. This way, i will have the functionalities of django templates like template extending, while, i can use react for the dynamic updation of all the content. While this seems doable, i tried setting up a react app using create-react-app inside my django project and ran both react and django. Well, it didnt work. Django didn't render the react components. How can i render the react components ? -
Adding iddentifiable non-field errors
I am doing some custom validation in the clean method in a ModelForm. I want to add custom non-field error messages, but I need them to be identifiable by some kind of key, so this doesn't work: self.add_error(None, 'Custom error message 1') self.add_error(None, 'Custom error message 2') self.add_error(None, 'Custom error message 3') I need to be able to tell these apart to render them in an appropriate place in the invalid form template instead of having them all grouped as None non-field errors. How can I do that? -
Prefetch related extracted database rows?
I am using this query with DRF: def get(self, request, format=None): show = Show.objects.prefetch_related( Prefetch( 'posttitleimage_set', queryset=PostTitleImage.objects.filter(post__is_published=True), ) ).exclude(publication__isnull=False)[:5] This should, however, only fetch 5 shows from the DB. Also, I'll never run into the case that I will need all posttitleimages for one show. I only ever want the latest posttitleimage for one show. class ShowIndexSerializer(serializers.ModelSerializer): last_title_image = serializers.SerializerMethodField() class Meta: model = Show fields = ( .... 'last_title_image', ) def get_last_title_image(self, obj): last_published_image = obj.posttitleimage_set.all()[: 1] return ShallowPostTitleImageSerializer(last_published_image, many=True).data While my code manages to reduce the number of queries from 10 to only 4, I am now concerned about the number of rows this will query from the DB. Especially once the DB grows. Also, this seems to be a bit of a hacky solution to just get the latest posttitleimage from the DB. Are there some obvious flaws with this implementation. How could this be improved? I'd be super happy about suggestions. -
Signal firing twice when a user is mentioned in a reply
I have a single signal which is fired when a user comments on the post,replies or tags any user It works fine but when a user is tagging another user in reply the signal get's fired twice and the notification is created twice.I probably don't seem to get what is the actual error? Here's my signals.py def usernametags_receiever(sender,instance,created,*args,**kwargs): # Basically check if the instance is post or comment and the move ahead body = instance.body def extract_hash_tags(body): return set(part[1:] for part in body.split() if part.startswith('@')) users_tagged = list(extract_hash_tags(body)) model = "post" notification_sender = None if sender == Comment: notification_sender = instance.by notification_sender_username = notification_sender.user.username if instance.reply_to: message = f"{notification_sender_username} replied to your comment" notification_receiver = instance.reply_to.by model = "reply" else: model = "comment" notification_receiver = instance.post.profile message = f"{notification_sender_username} comment on your post" else: notification_sender = instance.profile notification_sender_username = notification_sender.user.username if notification_sender_username in users_tagged: users_tagged = users_tagged.remove(notification_sender_username) if notification_receiver.user.username not in users_tagged: data = {"comment_by_image":"/media/"+str(notification_sender.image),"comment_by_slug":notification_sender.slug,"comment_post_notification":True,"comment_by":notification_sender_username} if model == "reply": if notification_sender != notification_receiver: notification_comment(data,message,notification_receiver,notification_sender_username) else: notification_comment(data,message,notification_receiver,notification_sender_username) if users_tagged: for username in users_tagged: profile_tagged = Profile.objects.filter(user__username=username) if profile_tagged.exists(): profile_tagged = profile_tagged[0] message = f"Your were tagged by {notification_sender_username} on a {model}" notification = Notification.objects.create(message=message,to=profile_tagged,by=notification_sender_username) async_to_sync(channel_layer.group_send)( f"profile_{profile_tagged.pk}", { "type":"chat_message", "data":{"tagged_by_image":"/media/"+str(notification_sender.image),"tagged_by_created":notification.created_time, "tagged_on":model,"user_tagged":True,"message":message,"tagged_by_username":notification_sender_username} } β¦ -
Django redirect to another view in CreateView form_valid before Model.save()?
Is it possible to redirect to a different view before saving the model? -
Join two records from same model in django queryset
Been searching the web for a couple hours now looking for a solution but nothing quite fits what I am looking for. I have one model (simplified): class SimpleModel(Model): name = CharField('Name', unique=True) date = DateField() amount = FloatField() I have two dates; date_one and date_two. I would like a single queryset with a row for each name in the Model, with each row showing: {'name': name, 'date_one': date_one, 'date_two': date_two, 'amount_one': amount_one, 'amount_two': amount_two, 'change': amount_two - amount_one} Reason being I would like to be able to find the rank of amount_one, amount_two, and change, using sort or filters on that single queryset. I know I could create a list of dictionaries from two separate querysets then sort on that and get the ranks from the index values ... but perhaps nievely I feel like there should be a DB solution using one queryset that would be faster. union seemed promising but you cannot perform some simple operations like filter after that I think I could perhaps split name into its own Model and generate queryset with related fields, but I'd prefer not to change the schema at this stage. Also, I only have access to sqlite. appreciate any β¦ -
Django TinyMCE HTMLField
I'm using crispy_forms to help with loading my form fields. I'm using TinyMCE HTMLField, which doesn't resize automatically with window resizing, while other forms fields that I rendered with |as_crispy_field resize automatically. What should I do? Here's what it looks like Here's what I want it to look like -
manage.py: error: unrecognized arguments: runserver
import argparse parser = argparse.ArgumentParser() # set up training configuration. parser.add_argument('--gpu', default='', type=str) parser.add_argument('--aggregation_mode', default='gvlad', choices=['avg', 'vlad', 'gvlad'], type=str) # set up learning rate, training loss and optimizer. parser.add_argument('--loss', default='softmax', choices=['softmax', 'amsoftmax'], type=str) parser.add_argument('--test_type', default='normal', choices=['normal', 'hard', 'extend'], type=str) global args args = parser.parse_args() SAVED_MODEL_NAME = 'pretrained/saved_model.uisrnn_benchmark' I have a project in django and I am calling this model in views.py When you use django an error occurs: usage: manage.py [-h] [--gpu GPU] [--resume RESUME] [--data_path DATA_PATH] [--net {resnet34s,resnet34l}] [--ghost_cluster GHOST_CLUSTER] [--vlad_cluster VLAD_CLUSTER] [--bottleneck_dim BOTTLENECK_DIM] [--aggregation_mode {avg,vlad,gvlad}] [--loss {softmax,amsoftmax}] [--test_type {normal,hard,extend}] -
How to save blob object from JS in Django UpdateView?
I have blob object accessible in my JavaScript. How can I upload this to Django UpdateView? Models: class Item(models.Model): name = models.CharField(...) image = models.FileField(...) HTML <form method="post"> <input type="text" id="id_name" name="name"/> <!--<input type="file" id="id_image" name="image"/>--> -
In django, any user can block any user, if they are blocked they cant see the posts of the blocked users and cant find them too
in my django i have made so far a user can follow many users and he(the user) will get posts of the follower users too.so similarly i want to make a the vice versa of it.. so if any user block other users, the users who are blocked by the login user cant find or see the user and the login user cant see the posts of those blocked users. i don't know how to do it..please help me on this. this is my models.py: class post(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to='post_pics', null=True, blank=True) video = models.FileField(upload_to='post_videos', null=True, blank=True) content = models.TextField() likes = models.ManyToManyField(User, related_name='likes', blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) objects = postManager() def __str__(self): return self.title class Meta: ordering = ['-date_posted', 'title'] def get_absolute_url(self): return reverse ('blog-home') def total_likes(self): return self.likes.count() class UserProfileManager(models.Manager): use_for_related_fields = True def all(self): qs = self.get_queryset().all() try: if self.instance: qs = qs.exclude(user=self.instance) except: pass return qs def toggle_follow(self, user, to_toggle_user): user_profile, created = UserProfile.objects.get_or_create(user=user) if to_toggle_user in user_profile.following.all(): user_profile.following.remove(to_toggle_user) added = False else: user_profile.following.add(to_toggle_user) added = True return added def is_following(self, user, followed_by_user): user_profile, created = UserProfile.objects.get_or_create(user=user) if created: return False if followed_by_user in user_profile.following.all(): return True return False β¦ -
DJANGO ALL AUTHEMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL
I am trying to have two different redirects...one for normal login and another for redirect after email confirmation ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/profile' LOGIN_REDIRECT_URL = '/' But when I enable login, AUTHENTICATED REDIRECT goes to LOGIN_REDIRECT but when I disable Login it goes to the EMAIL_CONFIRMATION_REDIRECT route. When I try printing the adapter settings for email_confirmation redirect url below it shows only the LOGIN_REDIRECT def get_email_confirmation_redirect_url(self, request): """ The URL to return to after successful e-mail confirmation. """ if request.user.is_authenticated: if app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL: return \ app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL else: return self.get_login_redirect_url(request) else: return app_settings.EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL I tried overriding this get_email_confirmation_redirect_url in the adapter but still wont work. It is not picking the REDIRECT before I login and reverify. -
django channels not working after change in url
django - 2.2 django-channels - 2.4.0 I used django channels for notification functionallity. it was working fine. working code urls.py urlpatterns = [ path('notify', views.notify, name='notify'), ] routing.py websocket_urlpatterns = [ path('notify/', consumers.Notify), ] template 1(sending) var notifySocket = new ReconnectingWebSocket( 'ws://' + window.location.host + '/notify/'); document.querySelector('#talk_yes').onclick = function(e) { notifySocket.send(JSON.stringify({ 'talk_type': 'notification_yes', })); } template 2 (receiving) var notifySocket = new ReconnectingWebSocket( 'ws://' + window.location.host + '/notify/'); notifySocket.onmessage = function(e) { var data = JSON.parse(e.data) var talk_type = data['talk_type'] get_notification(talk_type) }; Everything was working fine. Problem For some reason, I changed notify to add_question. and this is casing error: [Failure instance: Traceback: <class 'ValueError'>: No route found for path 'notify/'. [Failure instance: Traceback: : No route found for path 'notify/'. D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\autobahn\websocket\protocol.py:2821:processHandshake D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\txaio\tx.py:429:as_future D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\twisted\internet\defer.py:151:maybeDeferred D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\daphne\ws_protocol.py:83:onConnect --- --- D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\twisted\internet\defer.py:151:maybeDeferred D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\daphne\server.py:201:create_application D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\channels\staticfiles.py:41:call D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\channels\routing.py:54:call D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\channels\sessions.py:47:call D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\channels\sessions.py:145:call D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\channels\sessions.py:169:init D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\channels\middleware.py:31:call D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\channels\routing.py:150:call ] Bigger Problem I changed back add_question to notify. Now this is causing error: [Failure instance: Traceback: <class 'ValueError'>: No route found for path 'add_question/'. [Failure instance: Traceback: : No route found for path 'add_question/'. D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\autobahn\websocket\protocol.py:2821:processHandshake D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\txaio\tx.py:429:as_future D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\twisted\internet\defer.py:151:maybeDeferred D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\daphne\ws_protocol.py:83:onConnect --- --- D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\twisted\internet\defer.py:151:maybeDeferred D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\daphne\server.py:201:create_application D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\channels\staticfiles.py:41:call D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\channels\routing.py:54:call D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\channels\sessions.py:47:call D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\channels\sessions.py:145:call D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\channels\sessions.py:169:init D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\channels\middleware.py:31:call D:\Django\NewProject\ChannelBot\project_venv\lib\site-packages\channels\routing.py:150:call ] Can anyone help. I don't know what happened here.