Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to give start time to django-apscheduler?
I want to create a scheduler that will start counting the interval from the time that I give as starting time. I know that this is the format: from apscheduler.schedulers.background import BackgroundScheduler def start(): scheduler = BackgroundScheduler() scheduler.add_job(schedule_api, 'interval', minutes=5) scheduler.start() I want this scheduler to count minutes from the datettime that I give, is there a way to do that? -
Datatble datetime field is sorted as string
I have a Datatble for my django web app, the backend sends date for the field updated as 'Feb. 14, 2023, 3:58 p.m.'. when I use the sorting feature, it always sorts as alphabetical order, where 'April 24, 2023, 10:04 a.m.' comes before Feb because A is bigger than F in alphabetical order, so how to solve this? I tries some from datatble jquery documentation and some StackOverflow answers but it didn't gave me the desired output -
Django POST API id become null when password hashed
Hi im new to django and python, i want to make API to add user and it worked but when i try login with it but the result is i cant login, seems like it must hash password for system can read the user, and i try to hash my password in model. heres my model : from django.contrib.auth.hashers import make_password class MyUser(AbstractUser): pass password = models.CharField(max_length=128, null=False) def save(self, *args, **kwargs): self.password = make_password(self.password) but its make id become null heres the screenshot of result when i use make_passwod and not: screenshot when make_password not added screenshot when make_password added im following this tutorial with a bit modification heres the link django-rest-framework-create-api cause the id null the data not saved to database. So the question how to add the id ? why the id become null when i add make_password ? or maybe i am missing something ? thank you in advance -
Unable to authenticate my login details with custom backend authentication
For some reason, even when I enter the right details, it does not refer me to the home page and instead just acts like i keyed in wrong details. Would appreciate some help, thanks! views.py def login_view(request): if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) return redirect('index.html') else: return render(request, 'login.html', {'error': 'Invalid credentials'}) else: return render(request, 'login.html') auth_backend.py class EmailAuthBackend: def authenticate(self, request, username=None, password=None): try: user = User.objects.get(email=username) if user.check_password(password): return user return None except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None -
Problem on Python Django Application When I execute a Number of Input Values
I'm developing an application using Python Django, these app there are some codes in JavaScript because it needs to run in a web browser. When I execute the application with a certain number of input values Django's terminal (I'm using PyCharm) shows these things: Signal received: -250068120, errno: 32607 ################################################################################ Stack trace: ################################################################################ /usr/local/lib/python3.8/dist-packages/_awscrt.cpython-38-x86_64-linux-gnu.so(aws_backtrace_print+0x4f) [0x7f5ff65c392f] /usr/local/lib/python3.8/dist-packages/_awscrt.cpython-38-x86_64-linux-gnu.so(+0x726c3) [0x7f5ff65316c3] /lib/x86_64-linux-gnu/libc.so.6(+0x43090) [0x7f6046e9b090] /usr/local/lib/python3.8/dist-packages/dwave_qbsolv/qbsolv_binding.cpython-38-x86_64-linux-gnu.so(tabu_search+0x475) [0x7f5ff1cc8c35] /usr/local/lib/python3.8/dist-packages/dwave_qbsolv/qbsolv_binding.cpython-38-x86_64-linux-gnu.so(solve+0x990) [0x7f5ff1cca4b0] /usr/local/lib/python3.8/dist-packages/dwave_qbsolv/qbsolv_binding.cpython-38-x86_64-linux-gnu.so(+0x17915) [0x7f5ff1cd6915] /usr/local/lib/python3.8/dist-packages/dwave_qbsolv/qbsolv_binding.cpython-38-x86_64-linux-gnu.so(+0x1af96) [0x7f5ff1cd9f96] /usr/bin/python3(PyCFunction_Call+0x59) [0x5f5b39] /usr/bin/python3(_PyObject_MakeTpCall+0x296) [0x5f6706] /usr/bin/python3(_PyEval_EvalFrameDefault+0x62cd) [0x57165d] /usr/bin/python3(_PyEval_EvalCodeWithName+0x26a) [0x569d8a] /usr/bin/python3(_PyFunction_Vectorcall+0x393) [0x5f60c3] /usr/bin/python3(PyObject_Call+0x62) [0x5f52b2] /usr/bin/python3(_PyEval_EvalFrameDefault+0x1f2c) [0x56d2bc] /usr/bin/python3(_PyEval_EvalCodeWithName+0x26a) [0x569d8a] /usr/bin/python3(_PyFunction_Vectorcall+0x393) [0x5f60c3] /usr/bin/python3() [0x50b32c] /usr/bin/python3(PyObject_Call+0x62) [0x5f52b2] /usr/bin/python3(_PyEval_EvalFrameDefault+0x1f2c) [0x56d2bc] /usr/bin/python3(_PyEval_EvalCodeWithName+0x26a) [0x569d8a] /usr/bin/python3(_PyFunction_Vectorcall+0x393) [0x5f60c3] /usr/bin/python3(_PyEval_EvalFrameDefault+0x851) [0x56bbe1] /usr/bin/python3(_PyFunction_Vectorcall+0x1b6) [0x5f5ee6] /usr/bin/python3(_PyEval_EvalFrameDefault+0x726) [0x56bab6] /usr/bin/python3(_PyFunction_Vectorcall+0x1b6) [0x5f5ee6] /usr/bin/python3(PyObject_Call+0x62) [0x5f52b2] /usr/bin/python3(_PyEval_EvalFrameDefault+0x1f2c) [0x56d2bc] /usr/bin/python3() [0x50b22e] /usr/bin/python3(_PyEval_EvalFrameDefault+0x726) [0x56bab6] /usr/bin/python3(_PyEval_EvalCodeWithName+0x26a) [0x569d8a] /usr/bin/python3(_PyFunction_Vectorcall+0x393) [0x5f60c3] /usr/bin/python3(_PyEval_EvalFrameDefault+0x57f2) [0x570b82] /usr/bin/python3(_PyFunction_Vectorcall+0x1b6) [0x5f5ee6] /usr/bin/python3() [0x59cb2e] /usr/bin/python3(_PyObject_MakeTpCall+0x296) [0x5f6706] /usr/bin/python3(_PyEval_EvalFrameDefault+0x59a4) [0x570d34] /usr/bin/python3(_PyEval_EvalCodeWithName+0x26a) [0x569d8a] /usr/bin/python3(_PyFunction_Vectorcall+0x393) [0x5f60c3] /usr/bin/python3(_PyEval_EvalFrameDefault+0x57f2) [0x570b82] /usr/bin/python3(_PyFunction_Vectorcall+0x1b6) [0x5f5ee6] /usr/bin/python3() [0x59cb2e] /usr/bin/python3(_PyObject_MakeTpCall+0x296) [0x5f6706] /usr/bin/python3(_PyEval_EvalFrameDefault+0x59a4) [0x570d34] /usr/bin/python3(_PyEval_EvalCodeWithName+0x26a) [0x569d8a] /usr/bin/python3(_PyFunction_Vectorcall+0x393) [0x5f60c3] /usr/bin/python3(_PyEval_EvalFrameDefault+0x57f2) [0x570b82] /usr/bin/python3(_PyFunction_Vectorcall+0x1b6) [0x5f5ee6] /usr/bin/python3() [0x59cb2e] /usr/bin/python3(_PyObject_MakeTpCall+0x296) [0x5f6706] /usr/bin/python3(_PyEval_EvalFrameDefault+0x59a4) [0x570d34] /usr/bin/python3(_PyEval_EvalCodeWithName+0x26a) [0x569d8a] /usr/bin/python3(_PyFunction_Vectorcall+0x393) [0x5f60c3] /usr/bin/python3(_PyEval_EvalFrameDefault+0x57f2) [0x570b82] /usr/bin/python3(_PyFunction_Vectorcall+0x1b6) [0x5f5ee6] /usr/bin/python3() [0x59cb2e] /usr/bin/python3(_PyObject_MakeTpCall+0x296) [0x5f6706] /usr/bin/python3(_PyEval_EvalFrameDefault+0x59a4) [0x570d34] /usr/bin/python3(_PyEval_EvalCodeWithName+0x26a) [0x569d8a] /usr/bin/python3(_PyFunction_Vectorcall+0x393) [0x5f60c3] /usr/bin/python3(_PyEval_EvalFrameDefault+0x57f2) [0x570b82] /usr/bin/python3(_PyFunction_Vectorcall+0x1b6) [0x5f5ee6] /usr/bin/python3() [0x59cb2e] /usr/bin/python3(_PyObject_MakeTpCall+0x296) [0x5f6706] /usr/bin/python3(_PyEval_EvalFrameDefault+0x59a4) [0x570d34] /usr/bin/python3(_PyEval_EvalCodeWithName+0x26a) [0x569d8a] /usr/bin/python3(_PyFunction_Vectorcall+0x393) [0x5f60c3] /usr/bin/python3(_PyEval_EvalFrameDefault+0x57f2) [0x570b82] /usr/bin/python3(_PyFunction_Vectorcall+0x1b6) [0x5f5ee6] /usr/bin/python3() [0x59cb2e] /usr/bin/python3(_PyObject_MakeTpCall+0x296) [0x5f6706] /usr/bin/python3(_PyEval_EvalFrameDefault+0x59a4) [0x570d34] /usr/bin/python3(_PyEval_EvalCodeWithName+0x26a) [0x569d8a] /usr/bin/python3(_PyFunction_Vectorcall+0x393) [0x5f60c3] /usr/bin/python3(_PyEval_EvalFrameDefault+0x57f2) … -
Include additional details in Django error log for improved debugging?
Let's say I have a simple django view like so # views.py def view1(request): val = 5 / 0 return JsonResponse({"val": val}) and I have the following config for logging with debugging intentionally set to False # settings.py DEBUG = False LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': f'{BASE_DIR}/logs/debug.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } If I were to call the view, I would see the following statement in my logs Internal Server Error: /view1/ Traceback (most recent call last): File "/opt/pyenv/versions/3.10.8/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/opt/pyenv/versions/3.10.8/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/code/app1/views.py", line 14, in view1 val = 5 / 0 ZeroDivisionError: division by zero I can easily enable monitoring alerts to be notified of such errors like these when they occur. And I can inspect the log to see what line failed with what exception. But I am lacking other vital information in order to fully debug the issue. How can I include additional details into this log? Details such as the URL that was called, query parameters, the incoming payload, … -
Getting 500 Internal Server Error when Deploying Django Project in Linux Server using ubunto 18.04 Apache
I have deployed a Django Project using 18.04 and before using Apache I was testing using Portal:8000 and it worked perfectly fine when I added Apache and made the required changes I am getting 500 Internal Server Error and in the log I am getting the following error [Fri Feb 24 02:22:13.453312 2023] [wsgi:error] [pid 7610:tid 140621178033920] Traceback (most recent call last): [Fri Feb 24 02:22:13.453355 2023] [wsgi:error] [pid 7610:tid 140621178033920] File "/home/user/project/project/wsgi.py", line 12, in <module> [Fri Feb 24 02:22:13.453364 2023] [wsgi:error] [pid 7610:tid 140621178033920] from django.core.wsgi import get_wsgi_application [Fri Feb 24 02:22:13.453388 2023] [wsgi:error] [pid 7610:tid 140621178033920] ModuleNotFoundError: No module named 'django' [Fri Feb 24 02:25:31.905130 2023] [wsgi:error] [pid 7610:tid 140621161248512] mod_wsgi (pid=7610): Target WSGI script '/home/user/project/project/wsgi.py' cannot be loaded as Python module. [Fri Feb 24 02:25:31.906124 2023] [wsgi:error] [pid 7610:tid 140621161248512] mod_wsgi (pid=7610): Exception occurred processing WSGI script '/home/user/project/project/wsgi.py'. [Fri Feb 24 02:25:31.906647 2023] [wsgi:error] [pid 7610:tid 140621161248512] Traceback (most recent call last): [Fri Feb 24 02:25:31.906871 2023] [wsgi:error] [pid 7610:tid 140621161248512] File "/home/user/project/project/wsgi.py", line 12, in <module> [Fri Feb 24 02:25:31.906979 2023] [wsgi:error] [pid 7610:tid 140621161248512] from django.core.wsgi import get_wsgi_application [Fri Feb 24 02:25:31.907098 2023] [wsgi:error] [pid 7610:tid 140621161248512] ModuleNotFoundError: No module named 'django' Here is … -
Why am I getting an attribute error with object has no attribute get, in django?
Models.py: class WeeklyPlan(models.Model): title = models.CharField(max_length=255, verbose_name="Weekly Plan Name") monday = models.ForeignKey(Meal, on_delete=models.PROTECT, related_name="monday_plans") tuesday = models.ForeignKey(Meal, on_delete=models.PROTECT, related_name="tuesday_plans") wednesday = models.ForeignKey(Meal, on_delete=models.PROTECT, related_name="wednesday_plans") thursday = models.ForeignKey(Meal, on_delete=models.PROTECT, related_name="thursday_plans") friday = models.ForeignKey(Meal, on_delete=models.PROTECT, related_name="friday_plans") def __str__(self): return self.title Views.py: from django.shortcuts import render from .models import WeeklyPlan, Extra, Meal # Create your views here. def homepage(request): plans = WeeklyPlan.objects.all() print(plans) context = {"plans": plans} return render(request, template_name='food/index.html', context=context) I would've expected this to output all the weekly plan objects but instead got the error: Internal Server Error: / Traceback (most recent call last): File "C:\Users\Rayyan Admin\Documents\GitHub\food_delivery\venv\lib\site-packages\django\core\handlers\exception.py", line 56, in inner response = get_response(request) File "C:\Users\Rayyan Admin\Documents\GitHub\food_delivery\venv\lib\site-packages\django\utils\deprecation.py", line 138, in __call__ response = self.process_response(request, response) File "C:\Users\Rayyan Admin\Documents\GitHub\food_delivery\venv\lib\site-packages\django\middleware\clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: AttributeError: 'WeeklyPlan' object has no attribute 'get' Can anyone assist me on this? -
Using django_tables2, tables.A() is only returning the passed string rather than an object
I'm creating a templateColumn in django_tables, and in order to populate a dropdown menu with Vendors related to a particular Job, I'm trying to use tables.A('job') to filter my queryset. However, tables.A('job') gives me the error ValueError: Field 'id' expected a number but got 'job'. No matter what I set as the argument, it just returns that string. I've tried "cost__job", "job__id", other field names etc., but it only ever returns the string I pass in. Code below: tables.py import django_tables2 as tables from .models import Job, Cost, Vendor class CostTable(tables.Table): vendor = tables.TemplateColumn(template_name="main_app/tables_costsheet_vendor_column.html", extra_context={ 'vendors':[(vendor.unique_id, vendor.full_name) for vendor in Vendor.objects.filter(jobs_rel=tables.A("job"))] }) edit = tables.TemplateColumn(verbose_name='', template_name="main_app/tables_costsheet_edit_column.html") job = tables.Column(accessor='job.vendors.all') #just for debug, correctly shows the vendors for the job class Meta: model = Cost order_by = 'vendor_initials' template_name = "django_tables2/bootstrap5.html" fields = ("job", "vendor", "description", "amount", "invoice", "PO_number", "edit") Here's how my Cost and Job objects are related: class Cost(models.Model): ... vendor = models.ForeignKey(Vendor, on_delete=models.SET_NULL, null=True, blank=True,) job = models.ForeignKey('Job', on_delete=models.CASCADE, related_name='cost_rel', null=True) ... class Job(models.Model): ... vendors = models.ManyToManyField(Vendor, verbose_name='vendors involved', blank=True, related_name = 'jobs_rel') ... Note the dropdown populates if I use 'vendors':[(vendor.unique_id, vendor.full_name) for vendor in Vendor.objects.all())] in the context, but I only want it to show … -
Why don't the options for my cascading dropdown form appear?
I am building a car repair estimator and need to create a dependent dropdown that will allow users to select from a variety of Models that depend on the Make that they've chosen. I'm able to see and select different Makes, but I am unable to see the different Models. I am using Django framework and have stored the Makes, and Models in a Postgresql database Here is what is happening with my app right now: Ford models are supposed to be here Here is a snapshot of my working director of my app, AutoBuddy: Working Directory Here is the code from my ABDjango/templates/models/home.html file: <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Dependent Dropdown in Django</title> </head> <body> <h2>Car Form</h2> <form method="post" id="modelForm" data-models-url="{% url 'ajax_load_models' %}"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_model").change(function () { const url = $("#modelForm").attr("data-models-url"); // get the url of the `load_cities` view const modelId = $(this).val(); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: url, // set the url of the request (= /persons/ajax/load-cities/ ) data: { 'model_id': … -
Writeable Nested Serializer, overriding .create() - Django
I have AttendanceSlot model which has a foreign key to Course model, I want my endpoint to return the actual course code, not just the primary key.but I'm getting the below error when I try to override the .create() please, I don't know where i'm getting it wrong. TypeError at /attendance/attendance-slot/ Field 'id' expected a number but got OrderedDict([('course_code', 'COM411')]). models.py class Course(models.Model): course_code = models.CharField(_("Course Code"), max_length=50) course_title = models.CharField(_("Course Title"), max_length=100) def __str__(self): return '{0}'.format(self.course_code) class AttendanceSlot(models.Model): department_id = models.ForeignKey("students.Department", verbose_name=_("department id"), on_delete=models.CASCADE) course_id = models.ForeignKey("students.Course", verbose_name=_("course id"), related_name= 'course', on_delete=models.CASCADE) lecturer_id = models.ForeignKey("lecturers.Lecturer", on_delete=models.CASCADE) date = models.DateField(_("attendance date"), auto_now=False, auto_now_add=True) start_time = models.TimeField(_("start time"), auto_now=False, auto_now_add=False) end_time = models.TimeField(auto_now=False, auto_now_add=False) def __str__(self): return '{0}'.format(self.course_id.course_code) below is my serializers.py class CourseMini(serializers.ModelSerializer): class Meta: model = Course fields = ['id','course_code'] class AttendanceSlotSerializer(serializers.ModelSerializer): course_id = CourseMini() class Meta: model = AttendanceSlot fields = '__all__' def create(self, validated_data): course = Course.objects.get(pk = validated_data.pop('course_id')) instance = AttendanceSlot.objects.create(**validated_data) instance.course_id = course instance.save() return instance def to_representation(self, instance): representation = super(AttendanceSlotSerializer, self).to_representation(instance) return representation views.py class AttendanceSlotView(ListCreateAPIView): queryset = AttendanceSlot.objects.all() serializer_class = AttendanceSlotSerializer def perform_create(self, serializer): serializer.save(lecturer_id=self.request.user.lecturer) return super().perform_create(serializer) what am i missing? -
Python / Django - Safest way to normalize relative paths cross-platform?
Please note this question is about relative paths and must account for cross-platform functionality. When a user uploads a file, I want to generate a timestamped path to it: def get_filepath(instance, filename) -> str: """ Returns a timestamped directory path to deposit files into. i.e. "evidence/2023/02/23/96672aa5-94d9-4289-8531-d7a8dc8f060d/data.jpg" """ dt = timezone.now() YYYY = dt.year MM = str(dt.month).zfill(2) DD = str(dt.day).zfill(2) UID = str(uuid.uuid4()) # settings.MEDIA_URL = 'media/', I just checked path = (str(x) for x in ( settings.MEDIA_URL, 'evidence', YYYY, MM, DD, UID, filename )) path = os.path.join(*path) # dubious return path This is raising SuspiciousFileOperation, which is not at all surprising: raise SuspiciousFileOperation( django.core.exceptions.SuspiciousFileOperation: Detected path traversal attempt in '/media/evidence\2023\02\23\1cfa40b9-b522-4c70-b59b-fd270d722ab2\templeos.txt' I'm at a loss as to how to normalize this though. pathlib.PurePath -- didn't work, Django FileField doesn't like the Path object, which want to treat the string as an absolute path by sticking C:\ in front. os.path.normpath -- didn't work either (SuspiciousFileOperation: The joined path (C:\media\evidence\2023\02\23\cc32be4a-76d8-47c5-a274-9783707844b3\templeos.txt) is located outside of the base path component (C:\Users\...) This does appear to work if I do str(x).strip('/\\') when defining the path, but this is hacky and the sort of thing I'd expect a proper library to handle... What am I "supposed" to … -
Django 4.1 Google Social Auth does not authenticate
I am not sure what happened as this was working fine before. Now, when I use google authentication with social-auth, and when I check request.user.is_authenticated, it is always False. I will provide my setup, I checked it hundreds of times, I just can't seem to see the error: Here are the variable to my key files. I verified the keys, I can confirm I am using the correct ones, I changed the URI and got an error. Here are all my settings. I use the login_view to create a userProfile and to send out emails. All this was working fine, and I have no idea why it would just stop. This is all happening on a local Dev server I have on an Ubuntu VM. Please, if you have any suggestions at all, I would be so very happy. # social auth configs for google SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.environ.get('SOCIAL_AUTH_GOOGLE_OAUTH2_KEY') SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.environ.get( 'SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET') SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile' ] #installed apps: 'social_django', #middleware: 'social_django.middleware.SocialAuthExceptionMiddleware', #templates: 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', LOGIN_REDIRECT_URL = "login_view" SOCIAL_AUTH_LOGIN_REDIRECT_URL = "login_view" SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'Quiz.pipeline.redirect_to_login_view', # custom pipeline function 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) pipeline.py: from django.shortcuts import redirect … -
Turn 'Like' to 'Unlike' if button is already liked by user
I have the 'Like' button working which adds the currently logged in user to database once button is pressed, but the button doesn't turn to 'Unlike'. If the button is pressed a second time the 'Like' is removed from the database. So the key issue is getting the button to change. I'm thinking I would need a variable for liked_status some where possibly? But wouldn't know how to implement this. Views def BlogLike (request, slug): post_id = request.POST.get('blog-id') post = BlogPost.objects.get(slug=post_id) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse('viewblog', args=[post_id])) html <form action="{% url 'likepost' blog.slug %}" method="POST"> {% csrf_token %} {% if blog.liked is True %} <button class="btn btn-outline-secondary rounded-0 custom-button" id="like" type="sumbit" name="blog-id" value="{{ blog.slug }}">Unlike<i class="fa-solid fa-heart-crack"></i></button> - {{ blog.total_likes }} Likes {% else %} <button class="btn btn-outline-secondary rounded-0 custom-button" id="like" type="sumbit" name="blog-id" value="{{ blog.slug }}">Like<i class="fa-solid fa-heart"></i></button> - {{ blog.total_likes }} Likes {% endif %} </form> -
How can I render my Django variable and tags from my custom html code that is coming from sql database
I am using GrapesJS and Django together when I save GrapesJS html it doesn't save my dynamic variable for instance "Copyright {% now "Y" %}" it wants to save "Copyright 2023" instead. So before I save to database I do a re.sub and change "2023" back to {% now "Y" %} and save to database. Problem now is that when I get the html back from the database and put it into django template as "{{ page.html }}" it doesn't read the Django Tag because it has already did its magic and read "{{ page.html }}" so what it shows on webpage instead of seeing "Copyright 2023" I see "Copyright {% now "Y" %}". How can I get Django to read the variables and tags from the databases when rendering into template. I have tried to use engines['django'].from_string and couldn't get it to work. -
DJANGO: How to turn re_path into path
I am trying to understand how can I modify urlpatterns written with re_path to use path instead here's an example: re_path( r'^(?P<pk>[-\w]+)/$', views.SchoolDetailView.as_view(), name='detail') How can I write the same thing using path instead? here's the html that when clicked takes you to the detail page of a school {% for school in school_list %} <h2><li><a href="{{school.id}}">{{school.name}}</a></li></h2> {% endfor %} here's what I tried: path('<int:school_id>/', views.SchoolDetailView.as_view(), name='detail') what I got is the following error: Generic detail view must be called with either an object pk or a slug in the URLconf. -
DRF web interface doesn't work as Postman
I'am creating a blog app where only authenticate users can add blogs. I'm using JWT token and on Postman it work's well and I can add blog's after I logged in. I want to do it on DRF web interface also but it always tell me that I'm not logged in - I think. Exception Value: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x0000021035CA1C50>": "Blog.author" must be a "User" instance. My views.py class BlogList(generics.ListCreateAPIView): queryset = Blog.objects.all() serializer_class = BlogSerializer authentication_classes = [JWTAuthentication] #permission_classes = [IsAuthenticated] permission_classes = [IsOwnerOrReadOnly] filter_backends = [SearchFilter] search_fields = ["title", "content", "author__username", "author__first_name", "author__last_name"] def perform_create(self, serializer): serializer.save(author=self.request.user) Serializer.py class BlogSerializer(serializers.ModelSerializer): author = serializers.ReadOnlyField(source="author.username") author_first_name = serializers.ReadOnlyField(source="author.first_name") author_last_name = serializers.ReadOnlyField(source="author.last_name") slug = serializers.ReadOnlyField() comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True) read_only_fields = ["author", "first_name", "last_name"] class Meta: model = Blog fields = ["id", "title", "content", "status", "author", "comments", "image", "created_on", "updated_on", "author_first_name", "author_last_name", "slug"] def to_representation(self, instance): data = super().to_representation(instance) user = self.context["request"].user if not user.is_authenticated: data.pop("slug") return data def save_author(self, **kwargs): if "author" not in self.validated_data: self.validated_data["author"] = self.context["request"].user return super().save(**kwargs) def save(self,**kwargs): self.validated_data["slug"] = slugify(self.validated_data.get("title")) return super().save(**kwargs) I don't know what else I should post here. I tried somehow to DRF web interface add some button like "Authenticate" … -
Deploying a Django application to Elastic Beanstalk: Advantages and disadvantages of adding the VENV (Virtual Environment) folder
I've seen that some people have a virtual environment/venv folder in a project, or app folder. They are zipping that and deploying with Elastic Beanstalk. Is it a good or bad idea to do so? Official docs don't mention that directly, but in the example, there is no venv folder in the set for zipping. Quote: I don't have such an approach - I prefer to stick to the documentation. But I wonder if this approach that some use results from the case or is intentional. -
Like button not recording likes in the back end
Button successfully links back to current blog page but the likes are recording in the back end, what am I doing wrong here? views def BlogLike (request, slug): post = get_object_or_404(BlogPost, id=request.POST.get(slug)) post.likes.add(request.user) return render(request, 'viewblog', {'post': post}) urls path('view-blog/<slug:slug>/', views.ViewBlog, name='viewblog'), path('like/<slug:slug>', views.BlogLike, name='likepost'), html <form action="{% url 'viewblog' blog.slug %}" method="POST"> {% csrf_token %} <button class="btn btn-outline-secondary rounded-0 custom-button" id="like" type="sumbit" name="blog_id" value="{{ blog.slug }}">Like</button> </form> EDIT class BlogPost(models.Model): title = models.CharField(max_length=100, null=False, blank=False, default="",) text = RichTextUploadingField(null=True, blank=True, default="text") featured_text = models.TextField(max_length=550, null=True, blank=True, default="text") image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") date = models.DateField(auto_now_add=True) published = models.BooleanField(default=False) featured = models.BooleanField(default=False) slug = models.SlugField() likes = models.ManyToManyField(User, related_name='likes') def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.title) super().save(*args, **kwargs) def __str__(self): return self.title -
Django: How to use post data in DetailView
I would like to use detailview instead of the current view and process post data in it. However, I don't know how to download them to the view, is it even possible? If not then please give me some advice if leaving it as it is also looks good? views.py class ProductDetailView(View): def get(self, request, pk): product = Product.objects.get(id=pk) context = {'object': product} return render(request, "products/detailview.html", context) def post(self, request, pk): if not request.user.is_authenticated: messages.success(request, "You must be logged in") return redirect('Login') cart, created = Cart.objects.get_or_create( user=request.user, ) cart.save() added_item = Product.objects.get(id=pk) item_in_cart = CartItem.objects.filter(cart=cart) for item in item_in_cart: if item.product.title == added_item.title: messages.success(request, "It's already in the basket") return redirect('ProductDetail', pk=pk) new_item_in_cart = CartItem.objects.create( product=added_item, cart=cart, ) new_item_in_cart.save() added_item.quantity -= 1 if added_item.quantity == 0: added_item.is_available = False added_item.save() messages.success(request, "Add to cart") return redirect('home') pk captures from url detail.html {% extends 'base.html' %} {% load static %} {% block content %} <div class="container"> {% if messages %} {% for message in messages %} <div class="alert alert-success text-center" role="alert">{{ message }}</div> {% endfor %} {% endif %} <div class="col-md-3 mx-auto"> <div class="card card-product-grid"> <img src="{{ object.image.url }}"> {% if object.model_name == 'book' %} <div class="text-center">{{ object.author }}: {{ object.title … -
Django Database Router allow_migrate method
I'm trying to setup a database router to route my models to postgresql and redshift. I have an app within my project with multiple models. The database router should route the 1 model to redshift and all others to postgresql, however, I get the below errors when I run migrations. "python manage.py migrate --database redshift" SyntaxError: multiple default values specified for column "id" of table "django_migrations" ProgrammingError: multiple default values specified for column "id" of table "django_migrations" MigrationSchemaMissing: Unable to create the django_migrations table (multiple default values specified for column "id" of table "django_migrations" ) =============================================================== I'm confused by this as I do not have a django_migrations table in redshfit yet, which leads me to believe that my router is not working correctly and my logic for allow_migrate method is not correct. I'm new to django and this has me at my wits end. If anyone can provide any clarifying information or point me in the right direction, I would greatly appreciate it. NOTE: I've looked at the django documentation and built my router based off the examples they provided. Thanks! Below is my router, model Meta class example and database config. routers.py class DbRouter: def db_for_read(self, model, **hints): if … -
Django, rest api post ForeignKey
I am writing REST API in Django, I create model Member where is ForeignKey from User table (auth_user)... method GET work perfectly but with post I have problem... every time I saw error message that fk_id cannot be null. models.py class Member(models.Model): valid_from = models.DateTimeField(null=True, blank=True) valid_to = models.DateTimeField(null=True, blank=True) online = models.IntegerField() vpn_ip = models.CharField(max_length=20, unique=True) created = models.DateTimeField(auto_now_add=True) fk = models.ForeignKey(User, on_delete=models.CASCADE) @property def username(self): return self.fk.username @property def password(self): return self.fk.password @property def email(self): return self.fk.email @property def status(self): return self.fk.is_active @property def admin(self): return self.fk.is_staff @property def fk_id(self): return self.fk.id def __str__(self): return self.username views.py class MemberData(APIView): serializer_class = MemberDataSerializer permission_classes = [IsAuthenticated] def get(self, request, format=None): ''' Retrieves all Member from database ''' data = Member.objects.all() serializer = MemberDataSerializer(data, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): ''' Put new member to database ''' data = { "fk_id": request.data.get('fk_id'), "valid_from": request.data.get('valid_from'), "valid_to": request.data.get('valid_to'), "online": request.data.get('online'), "vpn_ip": request.data.get('vpn_ip'), } serializer = MemberDataSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class MemberDataSerializer(serializers.ModelSerializer): class Meta: model = Member fields = ["id", "fk_id", "username", "password", "email", "status", "admin", "valid_from", "valid_to", "online", "vpn_ip", "created"] and If I try post data as application/json then I saw this error... … -
Django .exclude everyone except object owner
I've got two models: Animal and Pet. Pet has fields 'owner' and 'public'. owner connects object to user who creates it, public is BooleanField type sending information whether object should be visible to others or not. I want my website to show all of current user pets whether their attribute is set to True or False, and to show public pets of other users. My models.py from django.db import models from django.contrib.auth.models import User class Animal(models.Model): spec = models.CharField(max_length=50,) type = models.CharField(max_length=50) cute = models.BooleanField(default=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.spec class Pet(models.Model): animal = models.ForeignKey(Animal, on_delete=models.CASCADE) name = models.CharField(max_length=50) color = models.CharField(max_length=50) age = models.DecimalField(max_digits=3, decimal_places=0) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) public = models.BooleanField(default=False) def __str__(self): return self.name and function in views.py @login_required def animal(request, animal_id): animal = Animal.objects.get(id=animal_id) pets = animal.pet_set.filter(owner=request.user).order_by('-date_added') # <----- context = { 'animal': animal, 'pets': pets, } return render(request, 'animals/animal.html', context) I've tried this: for pet in pets: if pet.owner != request.user and pet.public == False: pets = pets.exclude(pet) but it messed up my list. Could you help me figuring it out? -
Deploying Django Web API to AWS Elastic Beanstalk server issue
I am trying to create venv and application in Elastic Beanstalk, but getting some error, so it is not finishing to deploy. To fix the issue, I tried downgrading my Django version from 4.0 to 3.2. Also did same with Python. In order to understand and find the issue, I'll provide here: .ebextensions/django.config my_site/settings.py requirements.txt logs from server deployment platform settings I also collected all static files using python3 manage.py collectstatic and added all environment variables needed django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: my_site.wsgi:application settings.py Django settings for my_site project. Generated by 'django-admin startproject' using Django 4.1.5. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path from os import getenv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = getenv("DJANGOPASS") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = getenv("IS_DEVELOPMENT", True) ALLOWED_HOSTS = [getenv('APP_HOST')] # Application definition INSTALLED_APPS = [ 'blog', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
err too many redirects.this page isnt working now on django
i was trying to create a registration form html page for my django project.but i ended up in a "too many redirects error".can anyone help me with this? iam new to django. here's my code : from . import views from django.urls import path app_name = 'credentials' urlpatterns = [ path('register/', views.register, name='register'), path('login/', views.login, name='login'), path('logout/', views.logout, name='logout') ]``` ` def register(request): if request.method == 'POST': username = request.POST['username'] firstname = request.POST['first_name'] lastname = request.POST['last_name'] email = request.POST['email'] password = request.POST['password'] confirmpassword = request.POST['password2'] ``if password == confirmpassword: if User.objects.filter(username=username).exists(): messages.info(request, 'Username Taken') return redirect('register') elif User.objects.filter(email=email).exists(): messages.info(request, 'Email Taken') return redirect('register')` ` user = User.objects.create_user(username=username, first_name=firstname, last_name=lastname, email=email, password=password) user.save() messages.info(request, 'USER REGISTERED') print('USER REGISTERED') else: messages.info(request, 'password did not match!!') return redirect('credentials:register') return redirect('/') return render(request, 'register.html')