Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error Map Keys Must be unique while using YAML extension field in docker compose for django application
hi I have this in my YAML file , and I am getting error Map keys must be unique at <<: *common in django service. version: '3.4' x-common: &common restart: unless-stopped networks: docker_django x-django-build: &django-build build: context: . dockerfile: ./DockerFile.dev services: django: <<: *django-build <<: *common container_name: docker_django_dc01 command: bash -c "python manage.py runserver 0.0.0.0:8000" ports: - 8000:8000 volumes: - ./:/code depends_on: - postgres -
How to create custom login decorators in django
I am creating an app in django where all the authentication like login signup is done by using an exernal rest api so there is no database involved in it. This is why I am saving logged in user data in request.session now the issue is I don't want to show some of the pages if the user is not inside the sessions, what we usually do back in django apps is use @login_required decorator but now as there is no database so what will be the procedure of not showing those pages to not logged in users. thanks -
Read data from google sheets and dump into Postgres database using python and django
I have data on google sheets and I want to dump data into the Postgres database using python and Django. Note that each row in a google sheet contains information for different tables like it could be a foreign key etc. Am looking for any tutorial/blog to serve this purpose. -
Can't load JS static file, but style.css file still work
This is my error. The styles.css and index.js file in same folder name network. But the styles.css file is work, and index.js file doesn't work, it looking to my other project is Mail [20/Feb/2022 14:17:59] "GET / HTTP/1.1" 200 1804 [20/Feb/2022 14:17:59] "GET /static/network/styles.css HTTP/1.1" 304 0 [20/Feb/2022 14:18:01] "GET /static/mail/inbox.js HTTP/1.1" 404 1667 [20/Feb/2022 14:18:01] "GET / HTTP/1.1" 200 1804 setting.py STATIC_URL = '/static/' index.html {% extends "network/layout.html" %} {% load static %} {% block body %} <div id="allposts-view"> <h2>All Posts</h2> <div id="new-post"> <h5>New Post</h5> <form id="new-post-form"> <textarea id="post-content" class="form-control"></textarea> <input type="submit" class="btn btn-success"/> </form> </div> <div id="post-detail"></div> </div> {% endblock %} {% block script %} <script src="{% static 'network/index.js' %}" defer></script> {% endblock %} index.js console.log('OK'); -
Django user permission on generate specific view depending on user group
I am new to Django user permission and is setting it up for the first time. I need to generate different views after user has logged in. The views being generated depends on the group that the user belongs to. Say we have two users called user1 and user2 user1 belongs to group1 user2 belongs to group1 and group2 For user1 I will like to render a view that is specific for group1. For user2 the view rendered must be have both the content specific for group1 and group2 In my current views.py I am only able to decide if a user has logged in and if true the page staffLoginIndex.html will be rendered. from django.shortcuts import render from django.views import View from django.contrib.auth.mixins import LoginRequiredMixin # Create your views here. class StaffLoginIndexView(LoginRequiredMixin, View): login_url = '/accounts/login/' def get(self, request, *args, **kwargs): context = dict() context['user'] = request.user return render(request, template_name='staff/staffLoginIndex.html', context=context) -
product.Category: (models.E015) 'ordering' refers to the nonexistent field, related field, or lookup 'name'
I am following a tutorial on YT and I can't migrate my models. from django.db import models class Category(models.Model): name = models.CharField(max_length=255), slug = models.SlugField(), class Meta: ordering = ('name',) def __str__(self): return self.name def get_absolute_url(self): return f"/{self.slug}/" I've tried several potential solutions... typo issue? class Meta: ordering = ('-name',) tuple & typo? class Meta: ordering = ('-name') tuple issue? class Meta: ordering = ('name') ...but to no avail. I would love if someone could help me out with this -
NOT NULL constraint failed error for a not existing field in Django
I removed name_ko field in Category model but this error is consistently arising even after migration. My models.py is like below. class Brand(models.Model): name = models.CharField(max_length=20) category = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True) class Category(models.Model): name = models.CharField(max_length=10) It's also weird that I'm not getting this error in my computer but it's arising in all of my friends' computer. What should I do? I also cleared DB. -
Bootstrap 5 Dropdown Not Functioning
I am using Bootstrap 5 along Django to develop a website and I'm having issues getting a dropdown to function correctly. I have copied this code from w3schools exactly how it is and it is not working when I load the HTML. I've tried running it on the latest version of Chrome and Firefox and still no success. Does it have to do with the Bootstrap CDN? <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script> </head> <body> <div class="container mt-3"> <h2>Dropdowns</h2> <p>The .dropdown class is used to indicate a dropdown menu.</p> <p>Use the .dropdown-menu class to actually build the dropdown menu.</p> <p>To open the dropdown menu, use a button or a link with a class of .dropdown-toggle and data-toggle="dropdown".</p> <div class="dropdown"> <button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown"> Dropdown button </button> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Link 1</a></li> <li><a class="dropdown-item" href="#">Link 2</a></li> <li><a class="dropdown-item" href="#">Link 3</a></li> </ul> </div> </div> </body> </html> -
How to I override dj-rest-auth Registrations' SocialLoginSerializer? Error "non_field_errors": [ "Incorrect value" ] while running of postman
my system uses a custom user entity and I need to create this entity inside SocialLoginSerializer. It is not seemed to be mentioned here: https://dj-rest-auth.readthedocs.io/en/latest/configuration.html I tried adding in settings.py REST_AUTH_SERIALIZERS = { 'LOGIN_SERIALIZER': 'BackendApp.auth_serializers.LoginSerializer', 'TOKEN_SERIALIZER': 'dj_rest_auth.serializers.TokenSerializer', "PASSWORD_RESET_SERIALIZER": "BackendApp.auth_serializers.PasswordResetSerializer", } REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER':'BackendApp.auth_serializers.RegisterSerializer', 'SOCIAL_LOGIN_SERIALIZER' :"BackendApp.auth_serializers.SocialLoginSerializer" } I ran the following on command line POST 'http://localhost:8000/dj-rest-auth/google/' and JSON: { "access_token": "ya29.A0ARrdaM_u-mk71-yQia3Kx2NpKe8PTlMixeVuXUB_CsjnWhOT-mb4TdG9FyED7iPWHQskQ1kyjJ8jqsdNwv7XY5-6-G36gwwAIS3tEVCKMwzUXdUB26OH7rqqcUfUfdskTdN85M04ljq0m0DYFOudfwdHMxNwjAOjF-3m-EjTBXFhtp6rrzhXBIwZVVE58Pghy28x0YNu0wE0Iu-J5NbcGlSIF_NmevLQ6QSNdpTglmZfKQOc06MKddlW-kRlE4pSpMSSOA", "code": "", "id_token": "", "endUserType":"Refashionee" } but I have gotten "non_field_errors": [ "Incorrect value" ] and POST /dj-rest-auth/google/ HTTP/1.1" 400 40 Any help is greatly appreciated My customised SocialLoginSerializer.py (Original source code from dj-rest-auth) class SocialLoginSerializer(serializers.Serializer): access_token = serializers.CharField(required=False, allow_blank=True) code = serializers.CharField(required=False, allow_blank=True) id_token = serializers.CharField(required=False, allow_blank=True) endUserType = serializers.CharField(required=True, write_only=True) .... def get_cleaned_data(self): return { 'endUserType': self.validated_data.get('endUserType', '') } def validate(self, attrs): .... if not login.is_existing: # We have an account already signed up in a different flow # with the same email address: raise an exception. # This needs to be handled in the frontend. We can not just # link up the accounts due to security constraints if allauth_settings.UNIQUE_EMAIL: # Do we have an account already with this email address? account_exists = get_user_model().objects.filter( email=login.user.email, ).exists() if account_exists: raise serializers.ValidationError( _('User is already registered with this … -
How to integrate django with existing Postgres database
To use an existing database in Django, you need to have a model for each table. But creating models for existing tables manually is just too much work. However, there's no need to do that, since Django has a builtin tool to solve this exact problem. Reference article linked here: how-to-integrate-django-with-existing-database -
Custom error message not being raised during model validation
I have created a custom max_length error message on my Question model title field. Yet when the QuestionForm is validated, it raises the default max_length error message: 'Ensure this value has at most 55 characters (it has 60).'. Why is the default error message being used when the form is validated? AssertionError: ValidationError(['Ensure this value has at most 55 characters (it has 60).']) != 'The title of your question is too long' class TestQuestionSubmissionTitleField(TestCase): """Verify that an error is raised when the title exceeds the maximum character limit.""" @classmethod def setUpTestData(cls): user = get_user_model().objects.create_user("TestUser") profile = Profile.objects.create(user=user) msg = "This is a very very very very very very very very long title" data = { 'title': msg, 'body': "The context to this post doesn't explain alot does it" } cls.form = QuestionForm(data) def test_invalid_question_title_length(self): import pdb; pdb.set_trace() self.assertFalse(self.form.is_valid()) self.assertTrue(self.form.has_error("title")) self.assertEqual( self.form.errors.as_data()['title'][0], "The title of your question is too long" ) from django.forms import ModelForm, CharField from django.forms.widgets import TextInput, Textarea from .models import Question class QuestionForm(ModelForm): body = CharField( widget=Textarea(attrs={"class": "question_input_field"}), min_length=50, help_text="Clarify your question with as much detail as possible", error_messages={ 'required': "Elaborate on your question", 'min_length': "Add more info to your question" } ) tags = CharField(widget=TextInput( attrs={"class": … -
csv reader opening files differently in Django and Apache
I need to parse a csv file inside my Django application. The csv file could have some non-ascii characters that I need to remove before processing. Here's what my code looks like with open(inputFile, newline='') as f: reader = csv.reader(f) row1 = next(reader) for element in row1: columnHeader = element.encode("ascii","ignore").decode("ascii").strip() It works perfectly fine in Django standalone. But I get "'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)" when I run it in production (Apache, mod_wsgi, Django). I have tried a slightly different formulation, but no luck. columnHeader = element.encode("ascii","ignore").decode() I am new to Apache, Django and Python - so kind of running out of ideas. (Both environments are on the same machine - Ubuntu). -
How to let the last object in the modals be the first iteration in Django for loop template
I am having issues, displaying my images and I believe if I can let the last object in the models to be the first iteration, it will fix my problem. Instead of going 1, 2, 3, 4... I want to go 4, 3, 2, 1. Is there any way to manipulate {% for x in img %}? profile.html <div class="album-section"> <h2>Albums</h2> {% for x in img %} {% if forloop.first %}<div class="row ">{% endif %} <div class="col-4 col-4 col-4" > <div class="text-center mt-2"> <a href="{% url 'single_page' x.id %}" ><img src="{{x.file.url}}" href="{% url 'single_page' x.id %}" height="100%" width="100%" class="myImg"></a> </div> </div> {% if forloop.counter|divisibleby:3 %} </div> <div class=row>{% endif %} {% if forloop.last %} </div>{% endif %} {% endfor %} </div> views.py def profile(request, user): img = Uploads.objects.filter(profile_id = request.user.profile) profile = Profile.objects.filter(user = request.user).first() context = {"profile": profile, "img": img} return render(request, "main/profile.html", context) -
ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value
I have a Django cookiecutter template. After performing all the required actions given on cookiecutter docs when I run python manage.py migrate I get this error Traceback (most recent call last): File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\task_manager_app\manage.py", line 31, in <module> execute_from_command_line(sys.argv) File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle self.check(databases=[database]) File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\checks\model_checks.py", line 34, in check_all_models errors.extend(model.check(**kwargs)) File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\models\base.py", line 1303, in check *cls._check_indexes(databases), File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\models\base.py", line 1695, in _check_indexes connection.features.supports_covering_indexes or File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\postgresql\features.py", line 93, in is_postgresql_11 return self.connection.pg_version >= 110000 File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\postgresql\base.py", line 329, in pg_version with self.temporary_connection(): File "C:\Python310\lib\contextlib.py", line 135, in __enter__ return next(self.gen) File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\base\base.py", line 603, in temporary_connection with … -
Django cant load static files - 404 error
I've looked on stackoverflow for info and tried to fix it but it didn't work! I've been trying to search for the past 2 weeks but I'm still getting 404 static files. Under local, everything still loads normally The server I use is: Django + Gunicorn + Nginx Here is the file I loaded and configured! Please take a look and see where I went wrong! Thanks everyone! /staticfiles /apps /templates /includes scripts.html /static /assets /vendor /jquery /dist jquery.min.js /home /core templates: {% load static %} <script src="{%static 'assets/vendor/jquery/dist/jquery.min.js' %}"></script> setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'resultSaved', 'channels', 'apps.home', 'apps.templates' ] WSGI_APPLICATION = 'core.wsgi.application' ASGI_APPLICATION = 'core.asgi.application' STATIC_ROOT = os.path.join(CORE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(CORE_DIR, 'apps/static'), ) Ngnix config server { server_name *******; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/django/magi/src/staticfiles; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_pass *******:8001; } }server { if ($host = *******;) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = *******;) { return 301 https://$host$request_uri; } # managed by Certbot server_name *******; listen … -
Redis on Heroku not recognizing Django celery migrations
I have a basic Django app deployed on Heroku with a Redis addon and postgres addon, and my tasks are running fine locally. However, on the deployed app, the worker is not recognizing the celery tables/migrations. I've checked that all migrations have been run on the deployed app (heroku run python3 ./manage.py showmigrations -a {my-app}). My Procfile command: celery -A my_app worker --beat -S django -l info Running this command locally works fine and correctly receives the tasks. I have the DATABASE_URL env variable on heroku set from the postgres addon, and additionally I have added POSTGRES_USER, POSTGRES_DB, and POSTGRES_PASSWORD env variables for the same postgres database. The REDIS_URL is set as well as an env variable, from the Redis addon. Here are the logs from my heroku app's worker, which is successfully connected to redis: [2022-02-20 03:29:59,235: INFO/MainProcess] Connected to redis://:**@ec2-3-224-115-109.compute-1.amazonaws.com:12849// 2022-02-20T03:29:59.250151+00:00 app[worker.1]: [2022-02-20 03:29:59,249: INFO/Beat] beat: Starting... 2022-02-20T03:29:59.257880+00:00 app[worker.1]: [2022-02-20 03:29:59,257: INFO/MainProcess] mingle: searching for neighbors 2022-02-20T03:29:59.299601+00:00 app[worker.1]: [2022-02-20 03:29:59,297: ERROR/Beat] Process Beat 2022-02-20T03:29:59.299605+00:00 app[worker.1]: Traceback (most recent call last): 2022-02-20T03:29:59.299607+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute 2022-02-20T03:29:59.299607+00:00 app[worker.1]: return self.cursor.execute(sql, params) 2022-02-20T03:29:59.299608+00:00 app[worker.1]: psycopg2.errors.UndefinedTable: relation "django_celery_beat_periodictask" does not exist 2022-02-20T03:29:59.299608+00:00 app[worker.1]: LINE 1: ...ango_celery_beat_periodictask"."description" FROM "django_ce... … -
How can i Use Django with Docker?
So I have a basic django blog application. Which i want to dockerise into django. And one more thing. I am writing my question here because there are live people to answer. -
Bokeh: Generate graph server side, update graph from JS client side (change data source, axes ...)
I just took Bokeh for a spin on a Django site. Lot of fine tutorials out there and really easy to get a quick example running. For example, I have a Django view that offers something like: ... # This is part of a broader Django view, simply adding a graph to it. # Fetch the x and y data for a histogram using a custom function. # It takes a queryset, a field in that queryset and returns, two lists one # containing the unique values that some field took on and the second containing # the count of times it took on that value. (values, frequency) = FrequencyData(some_queryset, "some field") p = figure(height=350, x_axis_label="Count of Players", y_axis_label="Number of Events", background_fill_alpha=0, border_fill_alpha=0, tools="pan,wheel_zoom,box_zoom,save,reset") p.xaxis.ticker = values p.yaxis.ticker = list(range(max(frequency) + 1)) p.toolbar.logo = None p.vbar(x=values, top=frequency, width=0.9) p.y_range.start = 0 graph_script, graph_div = components(p) context.update({"graph_script": graph_script,"graph_div": graph_div}) ... Then in the Django template I simply have: {{ graph_div | safe }} {{ graph_script| safe }} And I have a lovely histogram of data that is otherwise presented in a table on that view. I like it. Now the same view, like many, has a pile of settings for filtering … -
How to get list of all objects associated with a foreign key in Django
Not super experienced with Django so I apologize if this is trivial. Say I had a category instance and I wanted to get access to all of the content objects that I have previously added to my foreign key. How would I do so? class Organization(models.Model): id = models.CharField(primary_key=True, max_length=200, default=uuid4, editable=False, unique=True) name=models.CharField(max_length=200,unique=True) phoneNumber=models.CharField(max_length=20) logo=models.CharField(max_length=100000) # storing this as base 64 encoded location=models.CharField(max_length=200) class Category(models.Model): categoryName=models.CharField(max_length=300, unique=True, primary_key=True) associatedOrganizations=models.ForeignKey(Organization,on_delete=models.CASCADE,related_name='associatedOrgs',null=True,blank=True) associatedContent=models.ForeignKey(Content, on_delete=models.CASCADE,related_name='associatedContent',null=True,blank=True) associatedMeetingNotices=models.ForeignKey(MeetingNotice,on_delete=models.CASCADE,related_name='associatedMeetingNotices',null=True,blank=True) For example: say I had the following healthcareCategory=models.Category.objects.get(pk="healthcare") and I wanted to access all Organizations related to healthcare, what should I do? This? healthcareCategory.associatedOrganizations.all() -
Django query: Calculate average monthly spend per user
Given a Django model which stores all transactions made by users, how can I create a query that returns the average monthly spend for each user? My current solution queries all the transactions then manually calculates the averages for each user however I am aware that there is a more pythonic way to do this using Django annotations but unsure how to write it. models.py Class Transactions(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey('User', on_delete=models.CASCADE) amount = models.DecimalField(max_digits=100, decimal_places=2, blank=True, null=True) date = models.DateField() -
Positioning Django objects, with template for loop tags *Struggling to replicate Instagram push and pop of photo location *
I am having difficulty positioning the photo location after a user posts a photo, where the (Purple Gameboy Photo) goes where the (Mansion Photo) is, and where the (American Football Player Photo) goes where the (Purple Gameboy Photo) is, just like Instagram's profile. Where the most recent go to the top left of the photos, and the last posted photos get pushed down to the bottom right The function checks the first iteration of the for loop and creates a row and column for the first photo, the American Football Player Phot is the first photo posted, then moves along until the fourth photo comes in. Rather than poping the oldest photo to a new row and pushing the newest photo to the front of the existing row. It keeps the location of the first photo and creates a new row for the latest photo. Profile_Page.html <!-- -----------------------------------------ALBUM SECTION---------------------------------------- --> <div class="album-section"> <h2>Albums</h2> {% for x in img %} {% if forloop.first %} <div class="row ">{% endif %} <div class="col-4 col-4 col-4" > <div class="text-center mt-2"> <a href="{% url 'single_page' x.id %}" ><img src="{{x.file.url}}" href="{% url 'single_page' x.id %}" height="100%" width="100%" class="myImg"></a> </div> </div> {% if forloop.counter|divisibleby:3 %} </div> <div … -
User oriented dynamic URL not loading - Django
I'm having this issue where I can register and login users but when I go to view the data (as the signed in user) nothing will load. I've been struggling with it quite a bit and just can't figure it out. When I look at the Django error page it shows it is pulling the correct user but won't show it. Dynamic URL per user issue - Django error page Here is the urls.py: from django.urls import path from.import views urlpatterns = [ path('',views.HomePage, name='HomePage'), path('category/<slug:slug>', views.CategoryPage, name='image-date'), path('<slug:slug_customer>/',views.Customer), Here is the models.py: from django.db import models from django.template.defaultfilters import slugify from django_resized import ResizedImageField from django.utils import timezone from uuid import uuid4 from django.urls import reverse class User(models.Model): user_name = models.CharField(max_length=100) #insert way to have user specific .csv link class Category(models.Model): title = models.CharField(null=True, blank=True, max_length=200) class Image(models.Model): description = models.TextField(null=True, blank=True) altText = models.TextField(null=True, blank=True) #ImageFields squareImage = ResizedImageField(size=[1000, 1000], crop=['middle', 'center'], default='default_square.jpg', upload_to='DB Pictures') #Related Fields category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) Here is my views.py: from django.shortcuts import render from .models import * # Create your views here. def HomePage(request): categories = Category.objects.all() context = {} context['categories'] = categories return render(request, 'HomePage.html', context) def CategoryPage(request): categories … -
Can We Implement Flask-JWT In Django?
1). Guys I need to implement jwt in my Django Rest Framework Application 2). but I want to implement jwt without a database like Flask https://pythonhosted.org/Flask-JWT/ like these. 3). Can You Please help me with this I like this flask jwt please help me with this. -
How Do I Convert This Function Based View To An UpdateView?
I've been staring at code for too long...but I can't figure this out for the life of me... I am trying to convert a function based view to a class based view....I've done it with the CreateView but the UpdateView is giving me grief. It won't take my update....I can get the view to take my update...but it doesn't save it....I don't get it... Here's my function based view... def update_task_update_view(request, pk): task = Task.objects.get(id=pk) form = TaskForm(request.POST or None, instance=task) if request.method == "POST": if form.is_valid(): form.save() return redirect("MyTasks:task_detail", pk=task.id) context = { "form": form, "task": task } return render(request, "partials/task_form.html", context) And here was my attempt at a Class Based View.... class UpdateTaskUpdateView(LoginRequiredMixin,UpdateView): model = Task form_class = TaskForm template_name = 'partials/task_form.html' def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): task = form.save() task.save() return redirect("MyTasks:task_detail", pk=task.id) else: return render(request, "partials/task_form.html", { "form":form }) This function based view is working fine...no issues with it. Thanks in advance for any thoughts. -
How to custom save login information in django
I am creating an app where I am dealing with an external REST API, I am sending my login credentials along with JWT token if they are correct I get a success status along with phone number and id, Now I dont know how to save this data to set persmissions to disaplay pages, like in normal app we sigply use login(request, user) to save the user but here we dont have database. Now I want to show some of the pages if the user is authenticated.I tried using reuqest.session['user_id] but deleting the session when user clicks on logout but this does't seems to be a good idea.