Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migrate error : TypeError expected string or bytes-like
I'm trying to learn django and can't do migrate **Internal Server Error: / Traceback (most recent call last): File "C:\Users\DEAR\Envs\test\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\DEAR\Envs\test\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: apps_blog_one.date The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\DEAR\Envs\test\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\DEAR\Envs\test\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\DEAR\Envs\test\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\DEAR\test_me\start\apps\views.py", line 7, in blog return render(request, 'index.html', {'bloger':bloger}) File "C:\Users\DEAR\Envs\test\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\DEAR\Envs\test\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\DEAR\Envs\test\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\DEAR\Envs\test\lib\site-packages\django\template\base.py", line 171, in render return self._render(context) File "C:\Users\DEAR\Envs\test\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\Users\DEAR\Envs\test\lib\site-packages\django\template\base.py", line 936, in render bit = node.render_annotated(context) File "C:\Users\DEAR\Envs\test\lib\site-packages\django\template\base.py", line 903, in render_annotated return self.render(context) File "C:\Users\DEAR\Envs\test\lib\site-packages\django\template\defaulttags.py", line 166, in render len_values = len(values) File "C:\Users\DEAR\Envs\test\lib\site-packages\django\db\models\query.py", line 258, in __len__ self._fetch_all() File "C:\Users\DEAR\Envs\test\lib\site-packages\django\db\models\query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\DEAR\Envs\test\lib\site-packages\django\db\models\query.py", line 57, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "C:\Users\DEAR\Envs\test\lib\site-packages\django\db\models\sql\compiler.py", line 1151, in … -
Make success messages disappear after few second :(
it is my layout.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <title>Mikayıl`ın Bloğu</title> </head> <body> {% include "includes/navbar.html" %} <div style = "margin-top : 100px; margin-bottom:100px;" class = "container"> {% include "includes/messages.html" %} {% block body %} {% endblock body %} </div> <script src="{% static 'js/jquery-3.2.1.min.js'%} "></script> <script src="{% static 'js/bootstrap.min.js'%} "></script> <script> $(document).ready(function() { // messages timeout for 10 sec setTimeout(function() { $('.message').fadeOut('slow'); }, 10000); // <-- time in milliseconds, 1000 = 1 sec // delete message $('.del-msg').live('click',function(){ $('.del-msg').parent().attr('style', 'display:none;'); }) }); </script> </body> </html> and it is my message.html this file is intor the folder in templates/includes but i added this into layout.html to {% if messages %} {% for message in messages %} {% if message.tags == "info" %} <div class="alert alert-danger">{{ message }}</div> {% else %} <div class="alert alert-{{ message.tags }}">{{ message }}</div> {% endif %} {% endfor %} {% endif %} i looked stackoverflow there was topic same as me i tried but i couldnt reach my goal but i cant make succes message which one disappear after 5 second who can help me :) -
Single Sign on Wordpress in Django project
I have a Wordpress account and a Django project. I want to login to the Wordpress when I log in to my Django project. I looked up this article. Single sign-on between WordPress and Django but I am not able to understand how to authenticate it once I get the token, so if I redirect to any of the WordPress links, I am automatically logged in. -
when i tried to put two forms at the seem time i cant i don't know why everything is good and true
ValueError at /update_profile/ The Profile could not be changed because the data didn't validate. Request Method: POST Request URL: http://127.0.0.1:8000/update_profile/ Django Version: 3.0.5 Exception Type: ValueError Exception Value: The Profile could not be changed because the data didn't validate. Exception Location: D:\project_4\my_project\lib\site-packages\django\forms\models.py in save, line 454 Python Executable: D:\project_4\my_project\Scripts\python.exe Python Version: 3.7.6 Python Path: ['C:\Users\pc\Desktop\template\project_4\my_project\src\project', 'D:\project_4\my_project\Scripts\python37.zip', 'c:\users\pc\appdata\local\programs\python\python37-32\DLLs', 'c:\users\pc\appdata\local\programs\python\python37-32\lib', 'c:\users\pc\appdata\local\programs\python\python37-32', 'D:\project_4\my_project', 'D:\project_4\my_project\lib\site-packages'] Server time: Sat, 16 May 2020 14:51:34 +0000 Traceback Switch to copy-and-paste view and this is my view : @login_required() def update_profile(request): if request.method == 'POST': user_form = UpdateUserForm(request.POST, instance=request.user) profile_form = UpdateProfileForm(request.POST, request.FILES, instance=request.user.profile) if user_form.is_valid and profile_form.is_valid: user_form.save() profile_form.save() return redirect('/') else: user_form = UpdateUserForm(instance=request.user) profile_form = UpdateProfileForm(instance=request.user.profile) context = { 'user_form': user_form, 'profile_form': profile_form, } return render(request, 'Update_profile.html', context) -
Connecting Django to Microsoft SQL Database
I want to connect my django application to MS-SQL server 2014 database. I wrote this code for making connections. DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST':'DESKTOP-6UNRAN0', 'PORT':'1433', 'NAME': 'MOVIE', 'COLLATION' : '', } } I have installed sql_server.pyodbc pip install django-pyodbc-azure as mentioned in the documentation https://pypi.org/project/django-pyodbc-azure/. I am still getting error django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') -
python manage.py runserver not working in pycharm
manage.py not working Django not opening how to fix it? In pycharm not working on django -
How to add Django template to pycharm?
I need to add a Django Template in Rub/Debug Configurtions section in my PyCharm Community. How can I do it? -
Application error in heroku django app deployment
can anyone help me why my app is giving the error? Application error An error occurred in the application and your page could not be served. ERROR (heroku logs) 2020-05-16T15:43:07.360568+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=algopediaapp.herokuapp.com request_id=74a12a50-a9cc-4269-8349-41fcb027be10 fwd="139.167.146.100" dyno= connect= service= status=503 bytes= protocol=https 2020-05-16T15:43:09.138262+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=algopediaapp.herokuapp.com request_id=bdb6134c-31c6-457c-8bc2-3490610da6cf fwd="139.167.146.100" dyno= connect= service= status=503 bytes= protocol=https 2020-05-16T16:32:14.255438+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=algopediaapp.herokuapp.com request_id=3bbecde1-6c5b-4dc2-9bc0-a05757fb2594 fwd="139.167.146.100" dyno= connect= service= status=503 bytes= protocol=https 2020-05-16T16:32:16.489639+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=algopediaapp.herokuapp.com request_id=5cb98de5-14a7-4780-aa69-de1de72e7604 fwd="139.167.146.100" dyno= connect= service= status=503 bytes= protocol=https I created profile , runtime and requirement file Procfile release: python manage.py migrate web: gunicorn Loginproject.wsgi --log-file - installed whitenoise and added it to settings file and also specified static root in settings.py -
Django Admin sending email after post
So I'm familiar with sending emails using django, but I'd want to send an email to all those that subscribed to my newsletter if I were to use the admin panel instead of the one I have on the site itself. How would I go about doing this? For my current view on the user site version, it is something like: def form_valid(self, form): message = 'A new article has been released...' subject = 'New Article!' to = Email.objects.values_list('email', flat=True).distinct() from_email = settings.EMAIL_HOST_USER send_mail(subject, message, from_email, to, fail_silently=True) return super().form_valid(form) -
Not able to connect Django with mongoDb
I am using djongo to connect my mongodb with django. the mongodb i use is atlas service.my password and username are correct even though its showing auth failed. System check identified some issues: sock_info.check_auth(all_credentials) File "C:\Users\rupek\AppData\Local\Programs\Python\Python38\lib\site-packages\pymongo\pool.py", line 712, in check_auth auth.authenticate(credentials, self) File "C:\Users\rupek\AppData\Local\Programs\Python\Python38\lib\site-packages\pymongo\auth.py", line 564, in authenticate auth_func(credentials, sock_info) File "C:\Users\rupek\AppData\Local\Programs\Python\Python38\lib\site-packages\pymongo\auth.py", line 263, in _authenticate_scram res = sock_info.command(source, cmd) File "C:\Users\rupek\AppData\Local\Programs\Python\Python38\lib\site-packages\pymongo\pool.py", line 603, in command return command(self.sock, dbname, spec, slave_ok, File "C:\Users\rupek\AppData\Local\Programs\Python\Python38\lib\site-packages\pymongo\network.py", line 165, in command helpers._check_command_response( File "C:\Users\rupek\AppData\Local\Programs\Python\Python38\lib\site-packages\pymongo\helpers.py", line 159, in _check_command_response raise OperationFailure(msg % errmsg, code, response) pymongo.errors.OperationFailure: Authentication failed. My setting.py file 'ENGINE': 'djongo', 'NAME': 'first', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'mongodb+srv://user:pass@cluster0-omtoq.mongodb.net/test?retryWrites=true&w=majority', 'port': 27017, 'username': 'user', 'password': 'pass', 'authSource': 'first', 'authMechanism': 'SCRAM-SHA-1' }, thanks in advance -
Django with apache2 Not Found The requested resource was not found on this server
I've just moved my django project on a LAN based apache server, however, I've encountered a problem when toggling the DEBUG modes from True to False in settings.py. With debug set to True I can access the default django landing page,but with debug set to false I get "Not Found The requested resource was not found on this server.". I have tried the Allowed Hosts settings as follow, but with no change: ALLOWED_HOSTS = ['192.168.88.101','localhost','127.0.0.1'] ALLOWED_HOSTS = ['*'] Thank you in advance. -
How to retrieve the session while calling from an iframe in Django
I am trying to login from an iframe in Django to mysite.com domain. I can save sessions to the database successfully. Here is the view from the mysql database. And here is the source code in the index function in the views.py file. As I said, I can save the session to the db. @xframe_options_exempt def index(request): # if a social auth, then close the pop up window and set a session is_close = request.GET.get('close') if is_close and request.user.is_authenticated: request.session['user_name'] = request.user.username request.session.modified = True response = render(request, "my_folder/close.html", {}) return response # this is used when an external page with an iframe calls if request.session.has_key('user_name'): user_name = request.session['user_name'] if not user_name == "": user = User.objects.get(username=user_name) request.user = user # if the user has already authenticated then get into the system if request.user.is_authenticated: ........ ........ ........ After closing the social authentication successfully, it makes another request from that iframe on a different domain and I loose the session. I don't loose it if I access the login page from the same origin (mysite.com). if request.session.has_key('user_name'): user_name = request.session['user_name'] The request object is losing the session variable. Again, it is working if I use the iframe the same origin (mysite.com). … -
Why is Django (3.0.6) looking in the wrong directory for admin static files?
I have restructured my django project, and for some reason the django admin loads with no css applied and looking at the log it shows: Django version 3.0.6, using settings 'config.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [16/May/2020 16:48:33] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1910 Not Found: /admin/login/static/admin/css/login.css Not Found: /admin/login/static/admin/css/responsive.css Not Found: /admin/login/static/admin/css/base.css [16/May/2020 16:48:33] "GET /admin/login/static/admin/css/login.css HTTP/1.1" 404 4875 [16/May/2020 16:48:33] "GET /admin/login/static/admin/css/responsive.css HTTP/1.1" 404 4890 [16/May/2020 16:48:33] "GET /admin/login/static/admin/css/base.css HTTP/1.1" 404 4872 [16/May/2020 16:48:34] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1910 Not Found: /admin/login/static/admin/css/login.css Not Found: /admin/login/static/admin/css/base.css Not Found: /admin/login/static/admin/css/responsive.css [16/May/2020 16:48:34] "GET /admin/login/static/admin/css/base.css HTTP/1.1" 404 4872 [16/May/2020 16:48:34] "GET /admin/login/static/admin/css/login.css HTTP/1.1" 404 4875 [16/May/2020 16:48:34] "GET /admin/login/static/admin/css/responsive.css HTTP/1.1" 404 4890 "/admin/login/static/admin/css/" is not a directory and I am confused. Project structure and settings files below. <repository root> │ │db.sqlite3 │ │manage.py │ │ ├───config │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ ├───docs └───project ├───media ├───products │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ 0001_initial.py │ │ __init__.py │ │ │ │ ├───static │ └───admin │ … -
Django:Child Model Fields Not Rendering
All Foreign Keys,Booleans and Choices fields are not rendering on the form template.But their label tags are rendering. For example: This is a "Generated TimeTable" model of a school system. The model class GT(models.Model): timetable_id = models.CharField(primary_key=True,max_length=200) period_number = models.ForeignKey(Ref_Period,on_delete=models.CASCADE) scheduled_date_and_time = models.ForeignKey(Ref_Calendar,on_delete=models.CASCADE) schedule_id = models.ForeignKey(Planned_Timetable,on_delete=models.CASCADE) subject = models.ForeignKey(Ref_Subject,on_delete=models.CASCADE) teacher_id = models.ForeignKey(Teacher,on_delete=models.CASCADE) def __str__(self): return str(self.teacher_id) I already imported the in the forms.py file forms.py class GTForm(ModelForm): class Meta: model = GT fields = '__all__' View: @login_required(login_url = 'main:loginPage') @allowed_users(allowed_roles=['admin']) def dalltt(request): gtform = GTForm() if request.method == "POST": gtform = GTForm(request.POST) print(gtform) if gtform.is_valid(): gtform.save() print("saved") return redirect('/') else: print(gtform.errors) print(gtform) context = {'gtform':gtform} return render(request=request,template_name="main/dalltimetable.html",context=context) The template(dalltimetable.html): <form enctype="multipart/form-data" action="" method="POST" > {% csrf_token %} <table> <tr> <th>ID</th> <th>Time</th> <th>Day</th> <th>Subject</th> <th>{{ gtform.teacher_id.label_tag }} </th> </tr> <tr> <td>{{ gtform.teacher_id }} </td> <td>{{ gtform.teacher_id }}</td> </tr> </table> <input class="btn btn-warning" type="submit" value="Update"> {{ form.name.errors }} {{ form.non_field_errors }} </form> -
adding default strings to textarea by clicking a button
I'm trying to add "@username" to my textarea. I think I'm missing something fundamental so I'd appreciate if you could help me find out what it is. js function: function insertText(text){ var elem = document.getElementById("id_content") elem.innerHTML += text; } button: <button onclick="insertText('@username')" type="button" class=text-edit-but onmousedown="event.preventDefault()"><img class=link src="{% static 'icons\yazar.png' %}" alt='link'></button> textarea: <textarea name="content" cols="40" rows="10" maxlength="10000" class="entry-content" placeholder="sen ne diyorsun?" onfocus="window.scrollBy(0,233)" spellcheck="false" required="" id="id_content"></textarea> onmousedown="preventDefault" is not the problem as I tried to press it by turning it into a submit button and it worked. It's there because I don't want the button to get the focus. -
Django - Creating a comment system for different pages, using one Comment model
I'm trying to create a website with a page for information about different cities. At the bottom of each page, I want there to be a comment section. My idea is to have a Comment model, which stores all the comments in one place, with each comment object having a field called 'page' which tells me the page they should be displayed on. Then I can just filter through the comments so only the ones for the right page are displayed. So far I have created a City model which is used by a detail view, CityDetailView, to create a page for each of the cities. This works well and uses a slug for the URLs. I've made a Comment model which accepts: 'content' (describing the city), 'date_posted', 'author' and 'page' which I've connected to the City model through a foreign key. It's my thinking that this 'page' field can be used to store what page the comment was written on, so that I can use {{ if comments.page == cites.name}} or something in my city.html template to display the comments only to the correct page. Going with this thinking, I'm guessing I would need to make a ListView inside … -
URL parameter in Django RESTApi
Thank you in advance, I'm new to Django REST Framework. when i use get() method with id parameter, it is working fine Below is url.py urlpatterns = [ path('admin/', admin.site.urls), url(r'api/userList/$', UserList.as_view(), name="userList"), url(r'^api/userList/(?P<id>\d+)/$', UserDetails.as_view(), name="userDetails") ] Below is api.py: class UserDetails(APIView): def get(self, request, id): model = Users.objects.get(id=id) serializer = UsersSerializers(model) return Response(serializer.data) above code is fine When i try to get user details by using emailID, i'm not able to get the details, showing below error: Using the URLconf defined in myProject.urls, Django tried these URL patterns, in this order: 1. admin/ 2. api/userList/$ [name='userList'] 3. ^api/userList/(?P<emailID>\d+)/$ [name='userDetails'] The current path, api/userList/sannila1527@gmail.com/, didn't match any of these. Below is api.py: class UserDetails(APIView): def get(self, request, emailID): model = Users.objects.get(emailID=emailID) serializer = UsersSerializers(model) return Response(serializer.data) Can you please help me on this. -
Login anonymous behaviour even though the user exist it shows invalid user
views.py ' def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("inactive") else: return HttpResponse("Someone tried to login and failed") else: return render(request, 'basic_app/login.html', {}) login.html {% extends 'basic_app/base.html' %} {% block content %} <div class="jumbotron"> <form action="{% url 'basic_app:user_login' %}" method="POST"> {% csrf_token %} <label for="username">USERNAME</label> <input type = "text" name="Username" placeholder="enter"> <label for="password">Password</label> <input type = "password" name="password" placeholder="PASSWORD"> <input type = "submit" name ="" value = "LOGIN"> </form> </div> {% endblock %} In django admin the users are registered and are in database but when i login it shows Someone tried to login and failed . I have to submit this by midnight need help noob here. -
Getting error in django at the time of migration
from django.db import models class Note(models.Model): subject=models.CharField(max_length = 100) My_Thought= models.TextField(blank = False) at time of migration i am getting the following error: I execute this command=>python manage.py makemigrations You are trying to add a non-nullable field 'id' to note without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: =>As you know i am not adding id ,because it is automatically generated by django, then why i am getting this? -
@admin.register decorator causing (admin.###) errors in Django
Using the @admin.register decorator is producing (admin.###) errors. I initially suspected it to be relevant to this question but when fiddling around with this. I found that simply switching to using admin.site.register fixes it. When to use @admin.register and when to use admin.site.register then? I have these models ### models.py from django.db import models from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter( status='published' ) class Post(models.Model): objects = models.Manager() #default manager published = PublishedManager() # custom manager STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[ self.publish.year, self.publish.month, self.publish.day, self.slug ]) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return f'Comment by {self.name} on {self.post}' and these ### admin.py from django.contrib import admin from .models import Post, Comment # Register your models here. … -
Manager isn't available; 'auth.User' has been swapped for 'diabetes.UserSignupModel'
I have made a custom user model using AbstractBaseUser, BaseUserManager and a signup form using that model. but whenever I try to load the signup form it gives me an error. my app name is diabetes. I have added the app is installed app in settings.py also added the AUTH_USER_MODEL='diabetes.UserSignupModel'. i can manually add data in the database. models.py from django.db import models from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class SignUpManager(BaseUserManager): def create_user(self, email, username, age, name, password=None): if not email: raise ValueError("insert user") if not username: raise ValueError("insert username") if not name: raise ValueError("insert name") if not age: raise ValueError("insert age") user = self.model( email=self.normalize_email(email), username=username, age=age, name=name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, age, name, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, age=age, name=name, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class UserSignupModel(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) age = models.CharField(max_length=15) name = models.CharField(max_length=15) username = models.CharField(max_length=15, unique=True) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = "username" REQUIRED_FIELDS = ["email", "name", "age"] objects = SignUpManager() def __str__(self): return self.email def … -
Key is still referenced from table "old_table"
I am developing and rest api with Django rest_framework. For notifications, I used fcm_django package. But after a while, I removed that package and used another package for notifications. Then, when I try to delete a user that created when I have fcm_django models. I got this error in terminal. New users does not give that error. I cannot remove old users. But there is nothing to do with fcm_django of any models now. I am already created new migrations after remove that fcm model. What can I do? Thanks. Error: update or delete on table "user_user" violates foreign key constraint "fcm_django_fcmdevice_user_id_6cdfc0a2_fk_user_user_id" on table "fcm_django_fcmdevice" DETAIL: Key (id)=(25) is still referenced from table "fcm_django_fcmdevice". -
Asynchronous Django, Ajax, Jquery Information
So big news! Async Django. I have some confusions and will like to clear them by asking some questions. 1. Async Views will require 'NO' need for AJAX? According to info I have, (don't know what AJAX is but many Django tutorials mention it so it was on my learning wishlist) Ajax is a set of web development techniques using many web technologies on the client side to create asynchronous web applications. With Ajax, web applications can send and retrieve data from a server asynchronously without interfering with the display and behavior of the existing page. Isn't this is what asynchronous views in Django will do too? 1A. If Async Django will not completely replace AJAX, Is it worth learning? 2. What does this mean for Channels? Channels is a project that takes Django and extends its abilities beyond HTTP - to handle WebSockets, chat protocols, IoT protocols, and more. It's built on a Python specification called ASGI. Can async django replace channels too? Suggest me anything related to these topics with reasoning. e.g. Use AJAX with JSON (just an example) I know that converting Django to async will take time so have this in mind when answering -
Dropdown element from mobile menu not opening
I have a mobile dropdown menu in a Django website which is opening correctly but two dropdowns from it are not opening as expected. The dropdowns have an anchor then should display the hidden dropdown. I couldn't figure it out why, so I'm pasting the code here hoping someone will have a suggestion. In browser view, the dropdown menu is a css dropdown and gets displayed on mouseover but mobile menu is a different story. Thanks for any help! jQuery code for mobile menu is: website_settings.mobileMenu = function() { var mobile_str = ""; $(".menu-ul").each(function() { mobile_str += $(this).html(); }); $(".menu-mobile ul.menu").html(mobile_str); $(".menu-toggle").on('click', function() { $(".menu-mobile.cssmenu").toggleClass("open"); $(this).toggleClass("mdi-menu mdi-close"); }); $('.menu-mobile.cssmenu li.has-sub a').on('click', function(e) { $(this).parent().children("ul").toggleClass("open"); $(this).find("i").toggleClass("open"); e.stopPropagation(); }); $('.menu-mobile.cssmenu li a').on('click', function(e) { $(".menu-mobile.cssmenu").toggleClass("open"); $(".menu-toggle").toggleClass("mdi-menu mdi-close"); }); } The HTML part: <div class="menu-mobile col-xs-10 pull-right cssmenu open"> <i class="mdi menu-toggle mdi-close"></i> <ul class="menu" id="parallax-mobile-menu"> <li class="homelink"><a class="" href="/#header">Home</a></li> <li class="serviceslink"><a class="" href="/#services">Services <span class="caret"></span></a> <ul class="dropdown"> <li class="productslink"><a class="" href="/products/#products">Products</a></li> </ul> </li> <li class="aboutlink"><a class="" href="/#about">About us <span class="caret"></span></a> <ul class="dropdown"> <li class="team"><a class="" href="/team/#team">Team</a></li> </ul> </li> <li class="clients"><a class="" href="/#clients">Customers</a></li> <li class="partners"><a class="" href="/#partners">Partners</a></li> <li class="bloglink"><a class="" href="/#blog">Blog</a></li> <li class="contact"><a class="" href="/#contact">Contact</a></li> <li class="careers"><a class="" href="/#careers">Careers</a></li> </ul> </div> The HTML … -
truncate text in django
I have a blog made by django. I want django to be able to read my post content and after django reaches to a specific word which I have already specified for Django, truncate the content. for example this is a post content : *Once upon a time, there lived a shepherd boy who was bored watching his flock of sheep on the hill. To amuse himself, he shouted, “Wolf! Wolf! The sheep are being chased by the wolf!” The villagers came running to help the boy and save the sheep. They found nothing and the boy just laughed looking at their angry faces. [django_Truncate] “Don’t cry ‘wolf’ when there’s no wolf boy!”, they said angrily and left. The boy just laughed at them. After a while, he got bored and cried ‘wolf!’ again, fooling the villagers a second time. The angry villagers warned the boy a second time and left. The boy continued watching the flock. After a while, he saw a real wolf and cried loudly, “Wolf! Please help! The wolf is chasing the sheep. Help!”* I want django to read it and when it reaches to [django_Truncate], truncate it. so, the paragraph before [django_Truncate] will be displayed …