Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I choose the social authentication plugin for Django?
I am a beginner for Django, and I want to create social login. but there are plenty of Django-social-plugin, and I don't know which one is the best for me (I only need login with google and others is optional), I want to pick one from below: (I want to know their futures. if there have comments for the pros and cons will be better) django-allauth tutorial social-app-django (pip install social-auth-app-django) tutorial-1 tutorial-2 The reason why I list above is just they have more stars than others. I don't know if it's appropriate to use the number of stars as a standard. If you think there are better choices than above, I still welcome you to share the link. I know my question may be too broad and is opinion-based, but I really have no idea how I can get started. I am confident that I can complete it from the tutorial, but I don't want the library that I choose that is out fashioned. And I don't know why there exist a lot of similar plugins on PyPI. It's helpful if you can show me a little light on how to get started to complete it by myself. I … -
Can I run Django application in both local server and Ubuntu server?
So I've deployed my Django project with AWS EC2, which uses Ubuntu server. Also, I'm using Posgtres as the DB engine. Then I've made some small changes to the code, and wanted to check if it was properly made but in my local computer so only I can check at the moment. However when I used python manage.py runserver command, it gave me an error saying "Is the server running on host "##MyDBInstanceID##.ap-northeast-2.rds.amazonaws.com" and accepting TCP/IP connections on port 5432?". It's my first time deploying a project, and I have no idea what went wrong. Do I have to turn the Ubuntu server off while I try to access with my local computer? If that's the case, will I have to do it every time I make small changes and want to check on my own? Thanks. -
why does my data not appear whenever i reload the page
i made a search function for getting date from my data in django, but when i refreshed, all the data from my table is gone this is my views.py def index(request): info = Info.objects.all() query = request.GET.get("q") if query: info = info.filter( Q(Fname__icontains=query) | Q(Diagnosis__icontains=query) ).distinct() return render(request, 'index.html', {'info': info}) else: return render(request, 'index.html', {'info': info}) this is what is showing in my website can anyone help huhuhu -
Django 'collectstatic': is it a bad practice to automate it?
I have a Django project as a webserver (Apache2) on a Linux machine. The server needs to periodically analyze some files outside the Django project folder, so I'm running python3 manage.py collectstatic to gather all files into my static directory. I couldn't find anything related to this, so I would like to know if is this a Bad practice or if already exist a better way to do this... Should I add a cronjob or systemd service to automatically execute python3 manage.py collectstatic --noinput to automate this process? Is there a better alternative? -
Adding a Post Context to Home List View
I am going to be as descriptive as possible as I have a minor issue and I am stuck about how to fix it. I am trying to add a Post to a list view, the Home list view has already an Item context. In my project, a user can add a post and add an item each is a different app with different models. So In my Home list view, I have my items looped and in each item, it is showing the user related to it. What I am trying to do is check if this item.user has a post existing related to the user and if it does exist a button show appears in the page linking to another page with these posts. In order words if there are Zero posts related to the user the button should not appear but if there is 1 or more the button should appear. I have tried to add a condition to the template but it is not working correctly and I think there might be another easier way to do it through the views Here is the post model: class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) here … -
Django Stripe Subscription
I'm trying to create a subscription payment method in Django with basic subscription recurring model and user define recurring time frame. I have created three products in stripe monthly, quarterly, and half-yearly. But I don't know how to implement a subscription model in Django. The direct payment method is working fine though. from django.shortcuts import render, redirect from django.urls import reverse from django.http import JsonResponse import stripe stripe.api_key = " " # Create your views here. def index(request): return render(request, 'index.html') def charge(request): if request.method == 'POST': print('Data:', request.POST) amount = int(request.POST['amount']) customer = stripe.Customer.create( email=request.user.email, name=request.user.first_name, source=request.POST['stripeToken'] ) charge = stripe.Charge.create( customer=customer, amount=amount*100, currency='usd', description="subscription" ) return redirect(reverse('success', args=[amount])) def successMsg(request, args): amount = args return render(request, 'success.html', {'amount':amount}) <form action="{% url 'charge' %}" method="post" id="payment-form"> {% csrf_token %} <select required name="amount" id="amount"> <option selected value="50"> Monthly $50 </option> <option selected value ="250"> quaterly $250 </option> <option selected value ="450"> half yearly $450</option> </select> </select> <div class="form-row"> <label for="card-element"> Credit or debit card </label> <div id="card-element"> <!-- A Stripe Element will be inserted here. --> </div> <!-- Used to display form errors. --> <div id="card-errors" role="alert"></div> </div> <button>Submit Payment</button> </form> -
Is saving user's id and login token in local storage a good idea?
I am developing Django + React project and I'm caught with this security approach concerning login and managing views for the logged in user. I am using django-rest-framework or DRF for my RESTful API. And I'm using django-rest-knox for authenticating user logins since I am implementing Token-based authentication (instead of session-based which uses CSRF). Question: Is it a good idea to save user's id and token in local storage? Currently, I have a /auth/login/ API endpoint that handles the backend logic of logging in user and returns JSON response of login details upon successful login (including user id and token). In my frontend, I use redux and redux-persist so the user's login details are kept even when the site is refreshed. The way redux-persist do it is that it saves the response in local storage. This means that the user id and token can be accessed and changed anytime thru dev tools. If user will then make a POST request to an API that requires a Token authentication header, the frontend will look into that local storage for the token value to be supplied to the request header. If user will then make a POST request to an API where … -
How to Ordering Django SerializerMethodField with ManytoManyField Count
I want to make blog web , I want to order on a computed SerializerMethodField, such as likes_count. Here are my Code models.py class Post(models.Model): title = models.CharField(max_length=255, unique=True) content = models.TextField() like = models.models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='likes', blank=True) serializer.py class PostSerializer(serializers.ModelSerializer): likes_count = serializer.SerializerMethodField() class Meta: model = Post fields = 'title, content, likes' def likes_count(self, obj): return obj.like.count() views class PostGenericAPIView(generics.GenericAPIView): queryset = Post.objects.all() serializer_class = PostSerializer filter_backends = (filters.OrderingFilter) -
Django rest framework CORS error only on localhost, not 127.0.0.1
I am attempting to enable CORS for my Django api. I have followed the documentation provided by the django-cors-headers package, in that I've installed the package with pip and added: INSTALLED_APPS = [ ... "corsheaders", ] MIDDLEWARE = [ ... "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", ... ] and CORS_ORIGIN_ALLOW_ALL = True to my settings.py. This works if I use 127.0.0.1:3000 to request the resource from the django server but not if I request it from localhost:3000. My frontend application requests the data like this: componentDidMount() { RecipeAPI.get(this.props.router.query.recipeId).then( ({ data }) => { console.log(data); this.setState({ recipe: data, loading: false }); }, (err) => { console.log(err); this.setState({ error: err.response, loading: false }); } ); } Where RecipeAPI is const RecipeAPI = { get: async (id) => axios.get(`${SERVER_URL}/recipes/${id}`), } I am confused why it works on 127.0.0.1 but not localhost. The error I get from localhost is the standard Access to XMLHttpRequest at 'http://localhost:8000/recipes/3' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I also noted that Django does not log any requests from localhost in the terminal prompt (i.e. it appears to me that the request does not even get recieved by Django). Any assistance is … -
Elements stuck in the same container
I am trying to create an slider with dynamic data on my django project, but first I have to make the elements slide horizontally from left to right. When I try to do this, the elements get stuck on a single container making the elements look bad, How can this error be solved? html <div class="mates-container"> <div class="mates-grid"> </div> {% for content in contents %} {% if content %} <div class="mates-grid-content"> <div class="mates-grid-1-1-container"> <div class="mates-grid-1-1-content"> <div class="mates-grid-2-content"> <button type="button" id="prev-button">prev</button> </div> <div class="mates-grid-1-container"> <div class="mates-grid-1-content"> <div class="mates-item-content"> <img class="mate-pic" src="{{ user.profile.profile_pic.url }}" > </div> <div class="mates-item-content"> <a href="{% url 'profile' username=content.user.username %}" style="float: left">{{ content.user }}</a> </div> <div class="mates-item-content"> <div class="responses"> <div class="response-item-img"> <img class="mates-image" src="{{ content.req_image.url }}" width="400px"> </div> <div class="response-item-bio"> <p>{{ content.req_bio }}</p> </div> <div class="response-item-button"> <button type="submit">Submit</button> </div> </div> </div> </div> </div> <div class="mates-grid-3-content"> <button type="button" id="next-button">next</button> </div> </div> </div> </div> {% endif %} {% endfor %} <div class="mates-grid"> </div> </div> css .mates-container { display: grid; grid-template-columns: 60%; grid-template-rows: 1fr 18fr 1fr; justify-content: center; height: 100%; align-content: space-evenly; grid-gap: .3rem; } .mates-grid-content { display: flex; text-align: center; justify-content: center; align-items: center; grid-column: 1; grid-row: 1; } .mates-grid-1-1-content { display: grid; text-align: center; justify-content: center; align-self: center; grid-column: … -
Ajax: SyntaxError: Unexpected token < in JSON at position 2
I am trying to use ajax to update my database when a user clicks a checkbox. I'm getting the following error msg SyntaxError: Unexpected token < in JSON at position 2 From what I've read this is happening because it's getting a html response rather than a json response. However it's not even executing my post_form_api view (it doesn't run my print statement) so I don't know where it's getting this response from. I am not using a form as I don't see the need, though I did try it with a form and got the same error. urls.py path('/api/post_form/', post_form_api, name="post_form_api"), javascript.js /* get the csrftoken token */ function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); /* checkbox */ $("task_complete").click(function(){ var csrfToken = $("input[name='csrfmiddlewaretoken']"); var form_field1 = 'test' $.ajax({ url: "{% url 'post_form_api' %}", type: "POST", dataType: "json", … -
Django JWT authentication with Apache
I have an architecture that I want to protect using json web tokens. My architecture is composed of 3 parts: Authentication backend made with Django, based on JWT (Json Web Tokens) using Simple JWT. Node.JS backend that I want to protect with Django JWT authentication. Apache Web Server which uses reverse proxy for communication with both backends. I have almost everything ready. But there's something I don't know how to do. The problem: I don't know how to integrate Django authentication with Apache to protect the path to the Node.js service I'm not a specialist in Apache and I only know the basics of how it works. I've been reading a lot for 2 days but I have no idea how to do this. -
Django: Using Raw SQL Queries to create models in models.py?
We're doing a school project that needs us to create data tables and a UI. We're considering using Django but we were also asked specifically to avoid ORM for creating the data models. So my question is -- Is there any way we can using raw SQL instead of ORM in models.py in Django? -
Why 'Model_name' object is not iterable?
Why I got the error { TypeError at /4 'Model_name' object is not iterable } for this code in my index.html {% for dest in dests %} <a href="{% url 'destinations' dest.id %}>{{dest.name}}</a> {% endfor %} urls.py I don't know what have I mistaken urlpatterns=[ path('',views.index,name='index'), path('<int:destinations_id>', views.destinations, name='destinations'), ] views.py when I was fetching all rows of Model on template by "dests=Destination.objects.all()" than there was no error for same "index.html", but I want only row of perticular id on template so I'm using "get_object_or_404". from django.shortcuts import get_object_or_404, render from .models import Destination def destinations(request, destinations_id): dests = get_object_or_404(Destination, pk=destinations_id) return render(request, 'destinations.html', {'dests':dests}) -
Adding Ajax to Django
I am a simple messaging system built in my Django project. Currently, a user needs to refresh the page to see the new messages. How do I add Ajax to load the messages asynchronously? View: def user_messages(request): time_now = datetime.datetime.now() user = request.user if request.method == "POST": sender = request.user receiver_name = request.POST.get('msg_receiver') receiver = User.objects.get(username=receiver_name) msg_content = request.POST.get('msg_content') Messages.objects.create(sender=sender, receiver=receiver, msg_content=msg_content) inbox = Messages.objects.filter(receiver=user).order_by('-timestamp') outbox = Messages.objects.filter(sender=user).order_by('-timestamp') context = {'inbox': inbox, 'outbox': outbox, 'time_now': time_now} return render(request, 'accounts/messages.html', context) Messages.html: <h6>Inbox</h6> {% for message in inbox %} <ul> <li title="{{ message.sender.username }}">{{ message.sender.first_name }}: {{ message.msg_content }} <button onclick="myFunction()">Reply</button> </li> <small>-{{ message.timestamp }}</small> <hr> </ul> {% endfor %} -
How to create a pathlib relative path with a dot starting point?
I needed to create a relative path starting with the current directory as a "." dot For example, in windows ".\envs\.some.env" or "./envs/.some.env" elsewhere I wanted to do this using pathlib. A solution was found, but it has a kludgy replace statement. Is there a better way to do this using pathlib? The usage was django-environ, and the goal was to support multiple env files. The working folder contained an envs folder with the multiple env files within that folder. import environ from pathlib import Path import os domain_env = Path.cwd() dotdot = Path("../") some_env = dotdot / "envs" / ".some.env" envsome = environ.Env() envsome.read_env(envsome.str(str(domain_env), str(some_env).replace("..", "."))) print(str(some_env)) print(str(some_env).replace("..", ".")) dot = Path("./") some_env = dot / "envs" / ".some.env" print(str(some_env)) On windows gives: ..\envs\.some.env .\envs\.some.env envs\.some.env -
Django ProgrammgError: relation does not exist when interacting with postgres db
I have been working on a project using Django 3 and recently began working toward migrating to a PostgreSQL database instead of the SQLite solution that is used in development. Whenever I try to run any command that effects the DB, I always get the following error. django.db.utils.ProgrammingError: relation "users_customuser" does not exist LINE 1: ...aims", "users_customuser"."firstFailedClaim" FROM "users_cus... Most solutions I see revolve around running makemigrations and then migrate, but unfortunately both of those also cause this error so that does not work. I've also attempted to delete the migrations folder altogether and start from scratch but that also has not worked so far. Here is my models.py file. from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.utils.translation import gettext_lazy as _ from django.utils import timezone from django.db.models import ObjectDoesNotExist from django.contrib.auth import get_user_model from .managers import CustomUserManager # Secrets import for keygen from secrets import token_urlsafe # TODO: Work on this def keygen(): genKey = True while genKey: key = token_urlsafe(8) key = key[:8] # genKey = False try: possibleObject = CustomUser.objects.get(id=key) except ObjectDoesNotExist: genKey = False return key class CustomUser(AbstractBaseUser, PermissionsMixin): id = models.CharField(primary_key=True, max_length=8, default=keygen) email = models.EmailField(_('email address'), unique=True) is_staff … -
One To One relationsship in Django
I need to make a profile for each user with address and city, and more... with OneToOne relationship in Django models, So I don't know how I can do it, I want to inheritance class Profile from Class User. and I'v got this error : django.core.exceptions.FieldError: Unknown field(s) (address) specified for User this is my model: #models.py from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) from phonenumber_field.modelfields import PhoneNumberField class UserManager(BaseUserManager): def create_user(self, email, fav_color, lastname, password=None, is_active=True, is_staff=False, is_admin=False,): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') # if not phone_number: # raise ValueError('user must have phone number') user = self.model( email=self.normalize_email(email), fav_color=fav_color, lastname=lastname, city=profile.city, address=profile.address, ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, password, fav_color, lastname,): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( email, password=password, fav_color=fav_color, lastname=lastname, ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = … -
How can I get data from another function in views.py?
So I'm doing an project with github API and I already successful called an user API here is my views.py: def user(req, username): username = str.lower(username) with urlopen(f'https://api.github.com/users/{username}/repos') as response: source = response.read() sorted_by_stars = json.loads(source) def sort_user_repo_by_stars(sorted_by_stars): return sorted_by_stars['stargazers_count'] sorted_by_stars.sort(key=sort_user_repo_by_stars, reverse=True) context = { 'username': username, 'sorted_by_stars': sorted_by_stars[:8], } return render(req, 'user.html', context) class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): labels = ["Blue", "Yellow", "Green", "Purple", "Orange"] default_items = [ DATA HERE ] data = { "labels": labels, "default": default_items, } return Response(data) How can I get 'sorted_by_stars': sorted_by_stars[:8] to Class ChartData ? -
Relation does not exist on postgresql database with Django
I made a model in my Django DB. I did migrations and now I am getting this error. I removed everything I did, deleted the migration files, and it is fine. But now when I add the model back, I get the same error. ProgrammingError at /admin/omegavalidator/bugscenario/ relation "omegavalidator_bugscenario" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "omegavalidator_bugscenari... The above exception (relation "omegavalidator_bugscenario" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "omegavalidator_bugscenari... ^ ) was the direct cause of the following exception: I am looking at the table to my database and I see no references to omegavalidator_bugscenario. I removed the only reference in it in my code as well. Right now it is just a model that is not being used. I am not sure what to do from here. -
How to add a Context to a ListView Class Based View
I am having trouble fixing a minor issue related to my comments section, I have created a comment section for my Item detail view which is working fine and showing the no. of comments an Item have. I have another List view which I want to reflect the no. of comments each item has. Here is the models.py class Comment(models.Model): STATUS = ( ('New', 'New'), ('True', 'True'), ('False', 'False'), ) item = models.ForeignKey(Item, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ItemComments") comment = models.CharField(max_length=250, blank=True) status = models.CharField(max_length=10, choices=STATUS, default='New') create_at = models.DateTimeField(auto_now_add=True) def __str__(self): return '{} by {}'.format(self.subject, str(self.user.username)) def total_comments(self): return self.comment.count() Here is the item detail view.py class ItemDetailView(DetailView): model = Item template_name = "product.html" def get_context_data(self, **kwargs): comments = Comment.objects.filter(item=self.object, status='New').order_by('-create_at') context = super().get_context_data(**kwargs) context["comments"] = comments context["total_comments"] = comments.count() return context Here is the list view which I am working on the add the count as well. I have written the code but it is not reflecting the correct count is reflecting the total count of comments for all items, I want to show the no. of comments for each item separately. class DesignerOnlyPostListView(ListView): model = Item template_name = "designer_only_posts.html" context_object_name = 'items' paginate_by = 6 def … -
How to get just the decimal values from query
I have a m2m field: class Example(models.Model): example = models.CharField(max_length=30, blank=True) Val1 = models.DecimalField(blank=True, null=True, max_digits=20, decimal_places=10) Val2 = models.DecimalField(blank=True, null=True, max_digits=20, decimal_places=10) class Group example = models.ManyToManyField(example) I would like to return the decimal values of Val1 and Val2 from Example. The closest I've gotten so far is: ValExample = self.example.values_list('Val1', 'Val2').all() for example in ValExample: return example return ValExample This gives me: (Decimal('60.1234500000'), Decimal('-123.5567000000')). I would like just 60.1234500000, -123.556700000 Any idea on how to do this? Thank you for any suggestions. -
Django tracking user's activity
I'm working on the e-comm website in Django. For now, I had all the basic e-comm website functions such as shopping cart, check out, user login logout, register..etc. I'm planning to do the tracking user activity such as user clicked on which product and then show on my admin page but there are some bugs and user activity didn't show up on my admin page. Models.py class History(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL, null= True) #product object_id = models.PositiveIntegerField() # slug content_object = GenericForeignKey('content_type', 'object_id') #actual object viewed_on = models.DateTimeField(auto_now_add=True) def __str__(self): return "%s viewed on %s" %(self.content_object, self.viewed_on) def object_viewed_receiver(sender, instance, request, *args, **kwargs): new_history = History.objects.create( user = request.user, content_type = ContentType.objects.get_for_model(sender), object_id = isntance.id, ) object_viewed_signal.connect(object_viewed_receiver) mixins.py from .signals import object_viewed_signal class ObjectViewMixin: def dispatch(self, request, *args, **kwargs): try: instance = self.get_object() except self.model.DoesNotExist: instance = 'None' if request.user.is_authenticated and instance is not None: object_viewed_signal.send(instance.__class__, instance=instance, request=request) return super(ObjectViewMixin, self).dispatch(request, *args,**kwargs) singal.py from django.dispatch import Signal object_viewed_signal = Signal(providing_args=['instance', 'request']) -
{{ request.META.HTTP_HOST }} Django tag doesn't seem to work in development
If I include this code in a Django template: <script src="http://{{ request.META.HTTP_HOST }}/static/adminbsb/plugins/jquery-datatable/jquery.dataTables.js"></script> Pycharm highlights the reference from http up to .js and the yellow bulb indicates: "There is no locally stored library for the http link" and offers me to download the content. The content already exists, but anyway, the download fails. This addressing way does not fail for images, that is, when used in, for example: <img src="http://{{ request.META.HTTP_HOST }}/static/logos/Minion-Girl-icon.png" alt="Minion Girl"> By inspection and intuition, I have determined that I can recode the first fragment as: <script src="{% static '/adminbsb/plugins/jquery-datatable/jquery.dataTables.js' %}" ></script> I suppose it is because I have these settings coded: STATIC_URL = '/static/' STATIC_ROOT = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') But I do not like the idea that I would need to change every thing if I went into production and wanted static components on a faster server. I am thoroughly new to this environment. Can you please help me?. Feel free to assume I am an absolute ignoramus. It is a full development environment, with Django 3.0.7, Python 3.8, PyCharm 2020.1 -
Is there an AWS inbound policy that interferes with "Authorization: Bearer {token}" data?
The question above is the thread associated with these links. Link 1, Link 2 It's like this when I understand my current situation. Request.user cannot be identified from EC2 instance created via AWS EB. The reason is that the Authorization: Bearer {token} provided during data communication is not being delivered to the EC2 instance. However, this issue only occurs within AWS instances. With the same code, Authorization data is correctly passed in local, and it is also correctly passed in GCP Compute instance. I think it's an environmental issue in AWS, but is there something I should look at?