Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JSON local file retrieval with internationalization in django
I am making a website in django and have included internationalization. The internationalization works fine on other pages, except for when I am trying to retrieve a json file. The search takes in a word, then finds the corresponding JSON file in the javascript file (below). The search was working without issue until I added internationalization. Now I can see that when jquery goes to get the file, it includes the i18n abbreviation on the front, resulting in a 500 error. I have tried parsing the file location but the abbreviations are always added in getJSON. How do I fix this issue? The error specifically that shows in the console is: GET http://localhost:8000/en/static/assets/chowords/amo.json 500 (Internal Server Error) It makes sense that that is an error since the json file is actually at http://localhost:8000/static/assets/chowords/amo.json I tried storing the files in a directory "en" with static nested inside, but that did not resolve the issue. Code for reference: Javascript file new URLSearchParams(window.location.search).forEach((value,name)=>{ console.log(name) console.log(value) var fileword = value; var url = "./static/assets/chowords/" + fileword + ".json"; var xhr = new XMLHttpRequest(); xhr.open('HEAD', url, false); xhr.send(); console.log(xhr) document.getElementById("wordsearched").innerHTML =`<h1>${fileword} </h1>` if (xhr.status == "404") { //console.log("File doesn't exists"); let div = document.createElement('p') div.innerHTML … -
How to remove double quote from key value in dictionary
I have this payload: "cardType": "CHOICE", "step": 40, "title": {"en-GB": "YOUR REPORT"}, "description": {"en-GB": ""}, "options": [ {"optionId": 0, "text": {"en-GB": "Ask me"}}, {"optionId": 1, "text": {"en-GB": "Phone a nurse"}}, {"optionId": 2, "text": {"en-GB": "Download full report"}}, ], "_links": { "self": { "method": "GET", "href": "/assessments/898d915e-229f-48f2-9b98-cfd760ba8965", }, "report": { "method": "GET", "href": "/reports/17340f51604cb35bd2c6b7b9b16f3aec", }, }, } I then url encode it like so and redirect to a report view: url = reverse("my-reports") reverse_url = encodeurl(data, url) The urlencode output is returned as this: "/api/v2/ada/reports?cardType=CHOICE&step=40&title=" "%7B%27en-GB%27%3A+%27YOUR+REPORT%27%7D&description=" "%7B%27en-GB%27%3A+%27%27%7D&options=" "%5B%7B%27optionId%27%3A+0%2C+%27text%27%3A+%7B%27en-GB" "%27%3A+%27Ask+me%27%7D%7D%2C+%7B%27optionId%27%" "3A+1%2C+%27text%27%3A+%7B%27en-GB%27%3A+%27Phone+a+nurse" "%27%7D%7D%2C+%7B%27optionId%27%3A+2%2C+%27text%27%3A+%7B" "%27en-GB%27%3A+%27Download+full+report%27%7D%7D%5D&_links=" "%7B%27self%27%3A+%7B%27method%27%3A+%27GET%27%2C+%27href%27%" "3A+%27%2Fassessments%2F898d915e-229f-48f2-9b98-cfd760ba8965" "%27%7D%2C+%27report%27%3A+%7B%27method%27%3A+%27GET%27%" "2C+%27href%27%3A+%27%2Freports%2F" "17340f51604cb35bd2c6b7b9b16f3aec%27%7D%7D" In my report view I get the payload from the url query string: class Reports(generics.GenericAPIView): permission_classes = (permissions.AllowAny,) def get(self, request, *args, **kwargs): result = request.GET data = result.dict() print(data) Now the problem is that the output of the transferred data which is printed above has quotes for nested keys. { 'cardType': 'CHOICE', 'step': '40', 'title': "{'en-GB': 'YOUR REPORT'}", 'description': "{'en-GB': ''}", 'options': "[{'optionId': 0, 'text': {'en-GB': 'Ask me'}}, {'optionId': 1, 'text': {'en-GB': 'Phone a nurse'}}, {'optionId': 2, 'text': {'en-GB': 'Download full report'}}]", '_links': "{'self': {'method': 'GET', 'href': '/assessments/898d915e-229f-48f2-9b98-cfd760ba8965'}, 'report': {'method': 'GET', 'href': '/reports/17340f51604cb35bd2c6b7b9b16f3aec'}}" } Notice the double quote in the "description", "options" keys … -
Why empty response headers after ajax call?
I post to Django 4 from index.html ajax call function check() { $.ajax({ url: '{% url "cb" %}', type: 'POST', dataType: 'json', contentType: 'application/json', data: JSON.stringify({username: "{{request.user.username}}"}), headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': csrftoken, }, success: function (response) { if (response.balance == true) { message = 'OK' $('#customModal').attr('class', 'alert alert-success').html(message); // exit from func } else { message = 'Awaiting' $('#customModal').attr('class', 'alert alert-info').html(message); } }, error: function (response) { console.log(response); }, }); } $(document).ready(function(){ setInterval(check,60000); }); view.py def cb(request): print(request.headers) When ajax call from localhost , response headers is ok {'Content-Length': '32', 'Content-Type': 'application/json', 'Host': '127.0.0.1:8000', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:100.0) Gecko/20100101 Firefox/100.0', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Referer': 'http://127.0.0.1:8000/payment', 'X-Requested-With': 'XMLHttpRequest', 'X-Csrftoken': 'wNCgxlQH0L2KhDxUkZ9uDE5zGdnbhejyynbmBEhhsU7J4HXfcmztxY69Zr9A3jbe', 'Origin': 'http://127.0.0.1:8000', 'Dnt': '1', 'Connection': 'keep-alive', 'Cookie': 'csrftoken=yeNnsws4zk4UBKo7qJe5GrP92Vz5Gh7wbcTqHHDNZtTjPEdlu31I6T3dXIKi3w8S; sessionid=u448kfdu0dovpgad2aj2ig0fuitgrj7o', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-origin'} When I open index.html from server public ip, the result of response print(request.headers) HostConnectionContent-LengthUser-AgentAcceptAccept-LanguageAccept-EncodingContent-TypeCookieCache-Control -
I am facing Multiple dictionary key value error in djnago
Csv_file=request.files[‘csv’] i am getting multiple dictionary key values error Csv_file = request.files.get(‘csv’) If i use this one I couldn’t able to file validation Name=csv_file.name Size=csv_file.size Here i am getting no attribute name and size -
How to set foreign key default field type?
I have simple model: id type is int(10) class Client(models.Model): name = models.CharField(max_length=45) surname = models.CharField(max_length=45) And second model with foreign key referencing Client table. from django.contrib.auth.models import User class ExtendedUser(models.Model): user = models.OneToOneField(User, on_delete=models.DO_NOTHING) client = models.ForeignKey('Client', on_delete=models.DO_NOTHING, blank=True, null=False, default=1) class Meta: managed = True db_table = 'extended_user' When I run python manage.py makemigrations and python manage.py migrate y have: 1215, 'Cannot add foreign key constraint' SHOW ENGINE INNODB STATUS; -> FOREIGN KEY (client_id) REFERENCES client(id): Cannot find an index in the referenced table where the referenced columns appear as the first columns, or column types in the table and the referenced table do not match for constraint. SQL sentence python .\manage.py sqlmigrate principal 0136: ALTER TABLE extended_user ADD COLUMN client_id bigint DEFAULT 1 NOT NULL , ADD CONSTRAINT extended_user_client_id_e51a6e7c_fk_client_id FOREIGN KEY (client_id) REFERENCES client(id); ALTER TABLE extended_user ALTER COLUMN client_id DROP DEFAULT; I tried client = models.ForeignKey('Client', on_delete=models.DO_NOTHING, blank=True, null=True, default=1) but still same error. Why Django is using bigint when I have primary key Int? How can I specify foreign key field type? -
Create or update related model object using Django management command
I need to periodically check on the status of a list of urls and report on their status. I created 2 models, one that has the list of main urls and another that holds all the sublinks on the pages of the main url. Model 1 class Site(CreationModificationDateBase, SoftDeletionModel): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=250, unique=True) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) url = models.URLField(unique=True) status_code = models.CharField(max_length=3, blank=True, default="") status_message = models.CharField(max_length=255, blank=True, default="") def __str__(self): return f'{self.name}' Model 2 class Link(CreationModificationDateBase, SoftDeletionModel): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) site = models.ForeignKey(Site, on_delete=models.DO_NOTHING, blank=True, null=True) url = models.CharField(blank=True, max_length=250, default="") status_code = models.CharField('Site Status', max_length=3, blank=True, default="") status_message = models.CharField(max_length=255, blank=True, default="") def __str__(self): return f'{self.url}' class Meta: ordering = ('url',) verbose_name = "link" verbose_name_plural = "links" I have this method on Model1 that returns the status code and message from the ListView on load. def get_links(self): data = requests.get(self.url).text soup = BeautifulSoup(data, features="html.parser") anchors = soup.find_all("a") links = [] links_status = [] for link in anchors: link_href = link.get("href") if f"https" in link_href: links.append(link_href) elif f"http" in link_href: links.append(link_href) elif f"/" in link_href and len(link_href) > 1 and self.url not in link_href: links.append(self.url + link_href) for ll in links: … -
Django Rest nested serializers multiple model CRUD operations using mixins
I'm trying to implement CRUD operation with nested serializer with multiple data models so that I can write all field at once when I call the API endpoint. Should I use some sort of filtering or for loop ? I've not found similar post that is using mixins Django-Rest nested serialization OneToOne Django rest framework- writable(create,update) double nested serializer models.py class Student(models.Model): student_id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) firstName = models.CharField(max_length=20) age = models.IntegerField(default=18) class Course(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) courseName = models.CharField(max_length=20) courseYear = models.IntegerField(default=2021) student = models.ManyToManyField(Student, related_name='courses') class Homework(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) hwName = models.CharField(max_length=20) hwPossScore = models.IntegerField(default=100) course = models.ForeignKey(Course, related_name='homeworks', on_delete=models.CASCADE, null=True, blank=True) students = models.ManyToManyField(Student) Serializers.py class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = "__all__" class HomeworkSerializer(serializers.ModelSerializer): class Meta: model = Homework fields = __all__ class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = "__all__" class All_Serializer(serializers.ModelSerializer): students = serializers.SerializerMethodField() homeworks = serializers.SerializerMethodField() courses = serializers.SerializerMethodField() def get_students(self, obj): students = obj.student_set.all() serializer = StudentSerializer(students, many=True) return serializer.data def get_homeworks(self, obj): homeworks = obj.homework_set.all() serializer = HomeworkSerializer(homeworks, many=True, read_only=True) return serializer.data def get_coruses(self, obj): courses = obj.courses_set.all() serializer = CourseSerializer(courses, many=True, read_only=True) return serializer.data class Meta: model = Student fields = ('student_id','firstName','age','homeworks','courses') … -
customizing django shell, injecting variables from a script
(likely was answered before, but no luck finding it) Every time I open a Django shell, I execute the same sequence of commands to get the environment set up, mostly loading JSON files which represent API responses, then doing data transformations to get the objects. Naturally, I started looking for a way to pre-initialize the environment with a script. I got as far as writing the script, which can be manually executed in a shell. However, a custom admin command doing all these things eludes me. Specifically, the line run_command('shell') starts a new process, which doesn't have any of the objects I've prepared in the script (as it ran in another process, duh). -
Django Keyerror on runserver until many restarts
I hope you can help me, I have a project with Django 2.2.25 and docker, but suddenly this error is showing: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/local/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.8/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 387, in check all_issues = self._run_checks( File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.8/site-packages/debug_toolbar/apps.py", line 37, in check_middleware if is_middleware_class(GZipMiddleware, middleware): File "/usr/local/lib/python3.8/site-packages/debug_toolbar/apps.py", line 81, in is_middleware_class middleware_cls = import_string(middleware_path) File "/usr/local/lib/python3.8/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 843, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/app/shared/middleware.py", line 8, in <module> from shared.exceptions import JsonNotFound File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 682, in _load_unlocked KeyError: 'shared.exceptions' I believe … -
Drop down menu implementation
Im making a job searching website using django. I think a nice touch is to have a couple of options where when you press them a drop down menu comes down with more options. For example a salary option and when it is pressed you see a couple of different salaries and when one of them is pressed a new query is sent out to the database. Lets say we only want jobs that pay more than 50,000. What would a query like that look like -
How do I get django decouple to use my updated env vars?
I use DECOUPLE in my Django project and its awesome. However, I recently changed an env variable to a new key and after restarting the server, it still used the old env key. I used a print statement to see the key being used. Does it cache the old one and still use it ? If so, how do I clear it? My workaround for now is just to rename the key when i update the var. Any help would be greatly appreciated. Many thanks A. -
Django IntegerField min length numbers
MinValueValidator How can i define the min length of the IntegerField? nummer = models.IntegerField( unique=True, validators=[MaxValueValidator(99999999), MinValueValidator(00000001), ]) Error Message: SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers -
Recommendation for the creation of a complex web application
My goal is to create a complex and modern web application, however, it has been three years since I last developed. I was using Spring API REST for the backend and React for the frontend at the time. Are there any other more interesting choices for you to consider? I heard about Django for the backend, what do you think? I would like to have a frontend that allows me to create a lot of interaction with the user (React?). A backend that allows to provide APIs usable by the frontend. -
How can i get username througth queryset?
I have some model: class Comments(models.Model): user = models.ForeignKey(User, related_name='user_comment', on_delete=models.CASCADE) heading = models.CharField(max_length=100) score = models.IntegerField(default = 1, validators=[MinValueValidator(1), MaxValueValidator(5)]) text = models.CharField(max_length=1000) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created_at',] def __str__(self): return self.heading And i when make .get request in shell: Comments.objects.get(pk=1).user I get: <User: user9> But when i make that request: Comments.objects.filter(pk=1).values('user') I get: <QuerySet [{'user': 9}]> For some reason, in the queryset I get only id, but not username. Due to the peculiarities of my application, I need to use exactly .filter or .all (), so I must somehow get the username in the queryset. Please help me. -
How to use filter method for user model in another model (django)
I have a custom user model : # accounts > models.py > ... class MyUser(AbstractUser): ... fallowing_tags = models.ManyToManyField('posts.tag', blank=True) and i want to filter all users who fallowed a specefic tag: from accounts.models import MyUser as User # ---- or ----- from django.contrib.auth import get_user_model User = get_user_model() class Tag(models.Model): name = models.SlugField(max_length=50, unique=True) @property def fallowers(self): return User.objects.filter(fallowing_tags=self) But the program gives an error: File "~/path/to/blog/accounts/models.py", line 13, in <module> from posts.models import Tag, Post File "~/path/to/blog/posts/models.py", line 3, in <module> from accounts.models import MyUser as User ImportError: cannot import name 'MyUser' from partially initialized module 'accounts.models' (most likely due to a circular import) (~/path/to/blog/accounts/models.py) -
What are the default expiry time for Access Token and Refresh Token? (Django GraphQL JWT)
I use Django GraphQL JWT. Then, I could set the expiry time for Access Token and Refresh Token in "settings.py" as shown below: # "settings.py" from datetime import timedelta GRAPHQL_JWT = { "JWT_VERIFY_EXPIRATION": True, "JWT_LONG_RUNNING_REFRESH_TOKEN": True, "JWT_EXPIRATION_DELTA": timedelta(minutes=60), # For "Access Token" "JWT_REFRESH_EXPIRATION_DELTA": timedelta(days=180), # For "Refresh Token" } Now, I want to ask: What are the default expiry time for Access Token and Refresh Token in Django GraphQL JWT? -
How do I create range slider in django?
I want this type of slider in django I have searched a lot but I am not getting this particular slider, any help would be appreciated. -
django - nothing under added model
What i am trying to tackle is best shown in pics , enter image description here Whenever I try to click on View others to see everything in the Recently added genre it leads to the following page enter image description here What am i doing wrong? to make reading shorter for you guys - movie_category is what I am trying to access here movie\urls.py from django.urls import path from .views import MovieList, MovieDetail, MovieCategory, MovieLanguage, MovieSearch, MovieYear app_name = 'movie' urlpatterns = [ path('', MovieList.as_view(), name='movie_list'), path('category/<str:category>', MovieCategory.as_view(), name='movie_category'), path('language/<str:lang>', MovieLanguage.as_view(), name='movie_language'), path('search/', MovieSearch.as_view(), name='movie_search'), path('<slug:slug>', MovieDetail.as_view(), name='movie_detail'), path('year/<int:year>', MovieYear.as_view(), name='movie_year'), ] views.py from django.views.generic import ListView, DetailView from django.views.generic.dates import YearArchiveView from .models import Movie, MovieLinks # Create your views here. class HomeView(ListView): model = Movie template_name = 'movie/home.html' def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context['top_rated'] = Movie.objects.filter(status='TR') context['most_watched'] = Movie.objects.filter(status='MW') context['recently_added'] = Movie.objects.filter(status='RA') return context class MovieCategory(ListView): model = Movie paginate_by = 2 def get_queryset(self): self.category = self.kwargs['category'] return Movie.objects.filter(category=self.category) def get_context_data(self, **kwargs): context = super(MovieCategory, self).get_context_data(**kwargs) context['movie_category'] = self.category return context Models.py STATUS_CHOICES = ( ('RA', 'RECENTLY ADDED'), ('MW', 'MOST WATCHED'), ('TR', 'TOP RATED'), ) class Movie(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=1000) image = … -
django.core.exceptions.ValidationError: ['“None” is not a valid UUID.']
i'm trying to develop my app to heroku and i have this error: I'm trying to delete database, or connect with AWS RDS, but still this error stops me. I was trying some --fake migrations, or delete migrations files but there is other errors. Now i'm go back to first version and hope to find the solution. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=50, blank=True, null=True) username = models.CharField(max_length=50, blank=True, null=True, unique=True) location = models.CharField(max_length=50, blank=True, null=True) email = models.EmailField(max_length=50, blank=True, null=True) short_intro = models.CharField(max_length=250, blank=True, null=True) profile_image = models.ImageField( null=True, blank=True, upload_to="profile_images/", ) social_github = models.CharField(max_length=200, blank=True, null=True) social_twitter = models.CharField(max_length=200, blank=True, null=True) social_linkedin = models.CharField(max_length=200, blank=True, null=True) social_youtube = models.CharField(max_length=200, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) draft_teams = models.ManyToManyField("Team", blank=True, related_name="draft_teams") id = models.UUIDField( default=uuid.uuid4, unique=True, primary_key=True, editable=False ) def __str__(self): return str(self.username) class Meta: ordering = ["created"] And error: Operations to perform: Apply all migrations: admin, auth, contenttypes, fifa_draft, sessions, users Running migrations: Applying fifa_draft.0001_initial...Traceback (most recent call last): File "/home/x/Desktop/projekty/draft_fifa/venv/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 2614, in to_python return uuid.UUID(**{input_form: value}) File "/usr/lib/python3.8/uuid.py", line 168, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') AttributeError: 'Profile' object has no attribute 'replace' During handling of the above exception, another exception … -
Can't create Django superuser due to "TypeError: initializer for ctype 'wchar_t' must be a unicode string of length 1, not int"
I am trying to setup something with Django 2.0.7. I am following this [tutorial][1] and am trying to create a superuser in Django. This is what happened: (venv) PS C:\Users\testuser\Development\Projekte\diwa_portal2\src> python manage.py createsuperuser Username (leave blank to use 'testuser'): Email address: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\testuser\Development\Projekte\diwa_portal2\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\testuser\Development\Projekte\diwa_portal2\venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\testuser\Development\Projekte\diwa_portal2\venv\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\testuser\Development\Projekte\diwa_portal2\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 87, in execute return super().execute(*args, **options) File "C:\Users\testuser\Development\Projekte\diwa_portal2\venv\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) File "C:\Users\testuser\Development\Projekte\diwa_portal2\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 171, in handle password = getpass.getpass() File "C:\Users\testuser\Tools\WPy64-38120\pypy3.8-v7.3.7-win64\Lib\getpass.py", line 103, in win_getpass msvcrt.putwch(c) File "C:\Users\testuser\Tools\WPy64-38120\pypy3.8-v7.3.7-win64\Lib\msvcrt.py", line 112, in putwch _lib._putwch(ord(ch)) TypeError: initializer for ctype 'wchar_t' must be a unicode string of length 1, not int``` Thanks in advance! [1]: https://youtu.be/F5mRW0jo-U4 -
is there any way i can install Stack Overflow RichTextEditor for my Django project
Is there any way i can install Stack Overflow RichTextEditor for my django project. The Stack Overflow RichTextEditor is a mobile friendly and the visitors of my website are using their Mobile phones to add post. And they are complaining on my RichTextEditor for not being mobile friendly also or is there anyway i can style ckeditor to look like Stack Overflow RichTextEditor ?. my model: from ckeditor.fields import RichTextField class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=False, null=False) body = RichTextField(blank=False, null=False) category = models.CharField(max_length=50, blank=False, null=False) def __str__(self): return str(self.title) my settings.py file: CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'height': 100, 'width': 200, }, } my template: <div class="container"> <div class="row justify-content-center"> <div class="col-md-5"> {% load crispy_forms_tags %} <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} {{ form | crispy }} <br> <input type="submit" value="submit" class="btn btn-warning"> </div> </div> </form> </div> -
FieldError Cannot resolve keyword: Django blog likebutton dosent work
am having problems i implemented my like button it shows up on the blog post sites when you click in to read more, but when you click on like i get a error msg below: I want the like button to work to add a like and also remove the like after if you feel like it. I also want it to count the number of likes. Any help with this will be very appreciated! folder newsapp views.py from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from django.views import generic from .models import Post, Like from .forms import CommentForm class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' paginate_by = 6 def post_view(request): qs = Post.objects.all() user = request.user context = { 'qs': qs, 'user': user, } return render(request, 'main.html', context) @login_required def like_post(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() return redirect('newsapp:post-list') def post_detail(request, slug): template_name = 'post_detail.html' post = get_object_or_404(Post, slug=slug) comments = post.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': … -
Can't migrate models to MySQL
Makemigrations and migrate commands work fine and they create files in 'migrations' folder (migration commands). But MySQL db does not change(MySQL screen). 0001_initial.py Code: from django.db import models class Student(models.Model): student_id = models.AutoField(primary_key=True) student_name = models.CharField(max_length=100) grade = models.IntegerField() class Teacher(models.Model): teacher_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) -
No type registered for model:
When I start the server and go to the GraphQL API. It shows me the exception - Model type not registered: UserAgreementAssociation. Someone will advise? mutations.py from graphene_django.forms.mutation import DjangoModelFormMutation from agreement.forms import UserAgreementAssociationForm, class CreateUserAgreementAssociationMutation(DjangoModelFormMutation): class Meta: form_class = UserAgreementAssociationForm forms.py from django import forms from agreement.models import UserAgreementAssociation class UserAgreementAssociationForm(forms.ModelForm): class Meta: model = UserAgreementAssociation fields = ('user', 'agreement', 'active',) models.py class UserAgreementAssociation(models.Model): user = models.ForeignKey(CloudTowerBaseUser , related_name='user', on_delete=models.CASCADE) agreement = models.ForeignKey(BaseAgreement, related_name='agreement_associations', on_delete=models.CASCADE) active = models.BooleanField(default=True) date_create = models.DateTimeField(auto_now_add=True, editable=False, blank=True) def __str__(self): return f'{self.date_create}/{self.user}/{self.agreement}' -
Why am I sometimes logged out of Django Admin?
Since the deployment of my Django website on Digitalocean with Nginx and Gunicorn I have the problem that I either can not log in to the admin panel and he jumps on the registration form again and again or when I am logged in, then only very briefly and then he jumps back again. In between, he also shows the error "Too many redirects" Nginx Config