Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
For a MySQL database, several queries of smaller bytes or few queries of very long string, which one causes more load on server?
In a MySQL database, having several queries of few bytes and having very few query of very big string, which one causes more pressure on server? Based on this I'm going to decide whether I should split tables having few common things or use single table with lengthy rows. -
django : arrayfield with custom model as base field
I have custom model class customModel(models.Model): contents = models.TextField(null=True) and another customModel with ArrayField from django.contrib.postgres.fields import ArrayField class customModel2(models.Model): ArrayField(customModel()): but it raised errors AttributeError: 'customModel' object has no attribute 'set_attributes_from_name' ArrayField(customModel) also raised similar errors. What are the proper method to define an arrayfield with custom model as base field ? -
How to count choices in django
I'm working on a blog in Django, each blog post have a 'status' and i want to have 3 fields in the profile, so each fild can count the total status. For example: Not started: 4 In progress: 8 Complete: 2 Models.py class Post(models.Model): NS= 'NOT STARTED' STATUS_CHOICES = ( ('NOT STARTED','NOT STARTED'), ('IN PROGRESS','IN PROGRESS'), ('COMPLETE','COMPLETE'), ) status=models.CharField(max_length=40, choices = STATUS_CHOICES,default=NS) views.py where it says "context['postns']" i was writting the code, but is not working. class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name='posts' paginate_by = 15 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') def get_context_data(self, **kwargs): context = super(UserPostListView, self).get_context_data(**kwargs) user = get_object_or_404(User, username=self.kwargs.get('username')) context['postuser'] = Post.objects.filter(author=user).order_by('-date_posted')[:1] context['posts'] = Post.objects.filter(author=user).order_by('-date_posted') context['postns'] = Post.objects.filter(author=user).values('status').annotate(num_status=Count('status')).order_by('status') return context -
DRF Simple JWT does not log in user?
I try to use simpleJWT in my project. I have created a CustomUser in my profiles app and later added to settings.py AUTH_USER_MODEL = "profiles.User" # django-allauth ACCOUNT_EMAIL_VERIFICATION = "none" ACCOUNT_EMAIL_REQUIRED = (True) CORS_ORIGIN_ALLOW_ALL = True #CSRF_COOKIE_NAME = "csrftoken" CORS_ALLOW_CREDENTIALS = True REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly', 'rest_framework.permissions.AllowAny', ), } REST_AUTH_SERIALIZERS = { 'PASSWORD_RESET_SERIALIZER': 'yogavidya.apps.profiles.api.serializers.PasswordResetSerializer', 'USER_DETAILS_SERIALIZER': 'yogavidya.apps.profiles.api.serializers.UserSerializer', } ACCOUNT_AUTHENTICATION_METHOD = 'username' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' OLD_PASSWORD_FIELD_ENABLED = True LOGOUT_ON_PASSWORD_CHANGE = False AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` "django.contrib.auth.backends.ModelBackend", # `allauth` specific authentication methods, such as login by e-mail "allauth.account.auth_backends.AuthenticationBackend", 'yogavidya.emailbackend.EmailOrUsernameModelBackend', ) SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'AUTH_HEADER_TYPES': ('Bearer',), 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } When I try to login using Django REST Framework view, I get an answer but no user is logged in. HTTP 200 OK Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTU5MDI2Njk2OCwianRpIjoiODhjN2FmOWZhZDBlNGIyYWFiYTRlMDA3YmVjNjY0YzciLCJ1c2VyX2lkIjoxfQ.YSluUaCU0r5WBlLmKmju1_HqrQjAxEDj5jONiv0U_mA", "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkwMTgwODY4LCJqdGkiOiJlNjI1ZjI5NjJjYTQ0OGM3YWQ2MWM2OTZhMWU5NWRkYyIsInVzZXJfaWQiOjF9.1A1ZTcxXRMQj5cBG631dwVeFQqG1FJVcKbjlrxRCcwE" } I have read the docs and in … -
How to resolve duplicate applications issue when running Django server
I created a Django app called session_booker and added an app called sessions. When I try to run my Django server I get this error: $ python manage.py migrate Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/me/.local/share/virtualenvs/SessionBooker-fBhCDalc/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/me/.local/share/virtualenvs/SessionBooker-fBhCDalc/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/Users/me/.local/share/virtualenvs/SessionBooker-fBhCDalc/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/me/.local/share/virtualenvs/SessionBooker-fBhCDalc/lib/python3.8/site-packages/django/apps/registry.py", line 93, in populate raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: sessions I'm not even sure where to begin with this one. I guess I've unknowingly created two sessions apps. If that's the case is there somewhere I could just delete one? Can anybody tell me how I might fix this? -
Get the value in a dict from a QuerySet to use it in url tag django3
I'm new to django3, and when I do the QuerySet in DB of a model to use it in a template using the url tag, I get a dictionary, but I can't get the value of that dictionary in order to get the desired url. These are my main files models.py from django.db import models from django.utils.timezone import now from django.apps import apps # Create your models here. class Section(models.Model): section = models.CharField(max_length=80, verbose_name="Sección") created = models.DateTimeField(auto_now_add=True, verbose_name="Fecha de creación") updated = models.DateTimeField(auto_now=True, verbose_name="Fecha de creación") class Meta: verbose_name="sección" verbose_name_plural="secciones" ordering=['-created'] def __str__(self): return self.section class Post(models.Model): title = models.TextField(verbose_name="Titular") subtitle = models.TextField(verbose_name="Subtitular") content = models.TextField(verbose_name="Noticia") published = models.DateTimeField(default=now, verbose_name="Fecha de publicación") link = models.URLField(verbose_name = "Dirección web", null=False, blank=False) secciones = models.ManyToManyField(Section, verbose_name="Sección") journals = models.ManyToManyField(Journal, verbose_name="Diario") tags = models.ManyToManyField(Tag, verbose_name="Etiquetas") created = models.DateTimeField(auto_now_add=True, verbose_name="Fecha de creación") updated = models.DateTimeField(auto_now=True, verbose_name="Fecha de creación") class Meta: verbose_name="noticia" verbose_name_plural="noticias" ordering=['-created'] def __str__(self): return self.title This is url.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('section/<str:section_section>/', views.section, name="section"), ] This is views.py from django.shortcuts import render, HttpResponse, get_object_or_404 from .models import Post, Section # Create your views here. def home(request): posts = Post.objects.all() return render(request, … -
Django REST - Incorrect type. Expected pk value, received str (pk is a CharField)
I have a ModelSerializer which I'm using to create new posts. It has a field book, of type PrimaryKeyRelatedField(queryset=Book.objects.all(), pk_field=serializers.CharField(max_length=255)). When I post to this endpoint I get the error: { "book": ["Incorrect type. Expected pk value, received str."] } How can this be, as my Primary Key is a CharField. The thing that really throws me off is, that I tried circumventing this with a SlugRelatedField, but when I do this, I get a really long and weird error: DataError at /api/content/posts/ value "9780241470466" is out of range for type integer LINE 1: ...020-05-22T20:14:17.615205+00:00'::timestamptz, 1, '978024147..., I don't understand it at all, as I am not setting an integer. Serializer Code: class PostCreationSerializer(serializers.ModelSerializer): book = serializers.PrimaryKeyRelatedField(queryset=Book.objects.all(), pk_field=serializers.CharField(max_length=255)) class Meta: model = Post fields = ['content', 'book', 'page', 'date_posted', 'user', 'id'] read_only_fields = ['date_posted', 'user', 'id'] Model Code: class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) pages = models.PositiveSmallIntegerField(null=True, blank=True) image = models.URLField(null=True, blank=True) date_published = models.CharField(max_length=4, null=True, blank=True) publisher = models.CharField(max_length=140, null=True, blank=True) isbn13 = models.CharField(max_length=13, primary_key=True) objects = AutomaticISBNDBManager def __str__(self): return self.title View Code: class PostListCreate(UseAuthenticatedUserMixin, generics.ListCreateAPIView): serializer_class = PostSerializer queryset = Post.objects.order_by('-date_posted') def get_serializer_class(self): if self.request.method == 'POST': return PostCreationSerializer else: return PostSerializer -
After changing password don't redirect my desired page in django
path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(template_name='registration/password_change_done.html'), name='password_change_done'), path('password_change/', auth_views.PasswordChangeView.as_view(template_name='registration/password_change.html'), name='password_change'), Here is my two url path. After changing password the new url should be 'password_change/done/' and should show some thing that is in template. but when I change my password it goes to 'password_change/done/' url but shows something that is default in django saying password change succesful does not show login link that is in template. How can I fix this? here is my template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div class="container"> <div class="d-flex flex-column"> <p class="m-auto">Your password has been set. You may go ahead and <a href="{% url 'loginuser' %}">Login in</a> now.</p> </div> </div> </body> </html> -
How would I create an ACL like model structure in Django?
I'm currently working on a project whereby I need to create quite a complicated database schema. We're tracking the requirements for Vendors in order to withhold our partnership status. For the most part this is fairly straightforward as generally we just need X amount of people accredited with any of [x,y] certifications. However, one company has an incredibly complicated set of requirements. Essentially they require X users to hold either any of [x,y] certifications AND any of [a,b] certifications. My idea was to create a "Rule" model which will have a foreignkey of the requirement (simplified slighty for explanation purposes): class Certificate(models.Model): name = models.CharField(max_length=256) class UserCertificate(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) certificate = models.ForeignKey(Certificate, on_delete=models.CASCADE) class Vendor(models.Model): name = models.CharField(max_length=256) class Requirement(models.Model): name = models.CharField(max_length=256) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) required_users = models.IntegerField() class RequirementRule(models.Model): requirement = models.ForeignKey(Requirement, on_delete=models.CASCADE) certs_required_1 = models.ManyToManyField(Certificate, on_delete=models.CASCADE, related_name="x") certs_required_2 = models.ManyToManyField(Certificate, on_delete=models.CASCADE, related_name="y") However, this seems very "static" and wouldn't allow for any requirements such as X users to hold either any of [x,y] certifications AND any of [a,b] certifications AND any of [c,d] certifications for example without me needing to add another field to the database. Any help would be massively appreciated as I'm … -
Front-End Developer Environment for Python Flask/Django Projects [closed]
I am at a point where I need to hire a couple front-end devs for my Flask project and I'm looking for suggestions on best practice without hampering their productivity. I don't want them to need to setup the entire project locally as that will incur a bunch of additional licensing costs (plus, deploying an entire project locally for just front-end work seems overkill). So, I have a development server which is being served up by apache/wsgi. I supposed I can give them access to that and add them to the wsgi group (owner of the www project files) but they won't be able to mount that in any way. What do people normally do while maintaining security of their servers? -
Import CSV into Django Models that has user name (OnetoOne) field
I am trying to import the csv file into "Player User Model" using Django import-export widgets. When I upload the CSV file, it is giving me an error of "Line number: 1 - (1048, "Column 'user_id' cannot be null") 1, Player 1, Saint Eds, 0, PG, 6'1", 185, 9". How can I use the import-export functionality and add the user from the Player models? I found how to add a foreign key object but I cannot figure out how to import the csv and create the user for the Player Model also? csv data models.py class Player(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) player_name = models.CharField(max_length=100, default='') team = models.ForeignKey(Team, on_delete=models.CASCADE) jersey_number = models.CharField(max_length=100, default='') position = models.CharField(max_length=100, default='') height = models.CharField(max_length=100, default='') weight = models.CharField(max_length=100, default='') grade = models.CharField(max_length=100, default='') headshot = models.ImageField(upload_to='profile_image', blank=True) status = models.CharField(max_length=100, choices=STATUS_CHOICES) def __str__(self): return self.player_name admin.py class PlayerResource(resources.ModelResource): team = fields.Field( column_name='team', attribute='team', widget=ForeignKeyWidget(Team, 'team_name')) class Meta: model = Player skip_unchanged = True report_skipped = False fields = ('id', 'player_name', 'team', 'jersey_number', 'position', 'height', 'weight', 'grade',) Django Admin Error -
Django model forms able to save to db but unable to display in template
I'm trying to save the inputs from my model form and it only saves the inputs to the db and doesn't display it on the template until I go to the db and click the save button. My form and the location where I display the submitted inputs are on the same HTML page. Why does this happen? I can't seem to find the reason. Please bear with me as I'm new to Django. Thanks in advance. views.py: def detail(request, pk): prof = get_object_or_404(Prof, pk=pk) ratings = Rating.objects.filter(slug=pk) paginator = Paginator(ratings, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) new_rating = None # rating posted if request.method == 'POST': rating_form = RatingForm(data=request.POST) if rating_form.is_valid(): # Create Rating object but don't save to database yet new_rating = rating_form.save(commit=False) # Assign the current prof to the rating new_rating.name = prof # Save the rating to the database new_rating.save() else: rating_form = RatingForm() return render(request, 'rating/detail.html', {'prof': prof, 'ratings': ratings, 'new_rating': new_rating, 'rating_form': rating_form, 'page_obj': page_obj}) template: ... <p class="centerize mt-4">{{ ratings.count }} {% if ratings.count > 1 or ratings.count == 0 %} ratings {% else %} rating {% endif %}</p> {% for rating in page_obj %} <div class="rating-container-detail"> <div class="card border-secondary"> <div class="card-header">{{ … -
How to make Django use an offset SQL query?
How do you make Django's ORM wrap queries like SELECT * FROM (<sql> OFFSET 0) ORDER BY <sort> LIMIT <n>? This is an optimization trick to forcing PostgreSQL to not do expensive scans. I have a Django admin interface wrapping an especially large table with millions of records. When it tries to do simple queries for the changelist page, it can take minutes to run, even if there are few or no filters being used, regardless of how many indexes I've made. However, if I run a raw SQL query from the command line or pgAdmin4 against it, like: SELECT * FROM mybigtable WHERE active=true AND cat_id IN (1,2,3) ORDER BY last_checked; it runs fine, in just 3 seconds and appears to use indexes correctly. But yet if I add a small LIMIT, which you'd think would improve performance by requiring fewer records, and run: SELECT * FROM mybigtable WHERE active=true AND cat_id IN (1,2,3) ORDER BY last_checked LIMIT 10; this somehow prevents the planner from using indexes and it takes an astonishingly long 5 minutes. If run EXPLAIN on it, I get: "Limit (cost=0.56..11040.78 rows=10 width=1552)" " -> Index Scan Backward using mybigtable_index on mybigtable (cost=0.56..36844505.94 rows=33373 width=1552)" " … -
Rendering a template inside a django view?
So I'm designing a website with Django that does some heavy scraping based on user input. This can take up to 5-6 secs and while I am working on cutting that down I would like for some kind of a loader to show up while the backend is scraping. I have put a loader as you normally would using CSS and JavaScript inside the template but that only pops up when the template is actually loading and not when the view is scraping to gather data for the template Literally my first project so if I sound like a rookie, I am Tried this in Django: def scrape(request): render(request,'loader.html') *do scraping* return render(request,'results.html',scraped_data) -
Wagtail API v2 django.template.exceptions.TemplateDoesNotExist
I have configured Wagtail API as prescribed in the docs and it works nicely when using curl: $ curl -LsD- http://127.0.0.1:8080/rest/p/ HTTP/1.1 200 OK Date: Fri, 22 May 2020 17:33:58 GMT Server: WSGIServer/0.2 CPython/3.8.2 Content-Type: application/json Vary: Accept, Cookie Allow: GET, HEAD, OPTIONS X-Frame-Options: DENY Content-Length: 433 X-Content-Type-Options: nosniff { "meta": { "total_count": 1 }, "items": [ { "id": 2, "meta": { "type": "wagtailcore.Page", "detail_url": "http://localhost/rest/p/2/", "html_url": "http://localhost/", "slug": "home", "first_published_at": null }, "title": "Welcome to your new Wagtail site!" } ] } Wagtail doc state the following: Optionally, you may also want to add rest_framework to INSTALLED_APPS. This would make the API browsable when viewed from a web browser but is not required for basic JSON-formatted output. This is kind of true, because API works fine via curl, however if I do not add rest_framework to the INSTALLED_APPS and then try to access the same url via browser I do get http 500, namely because application throws an exception: Internal Server Error: /rest/p/ Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/usr/local/lib/python3.8/site-packages/django/template/response.py", line … -
How can I implement the views and forms of the genericrelation Django...here is what i have
I have this for my models..how can I implement it in the views/url/template...what i want is for a user to click a button[toggle] that will save the post as favourite from django.db import models from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import User from django.contrib.contenttypes.fields import GenericRelation from django.contrib import admin class Activity(models.Model): FAVORITE = 'F' ACTIVITY_TYPES = ( (FAVORITE, 'Favorite'), ) activity_type = models.CharField(max_length=1, choices=ACTIVITY_TYPES) date = models.DateTimeField(auto_now_add=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE,default=None) object_id = models.PositiveIntegerField(default=None) content_object = GenericForeignKey() user = models.ForeignKey(User,on_delete=models.CASCADE,default=None) def __str__(self): return self.title for my job post I have the following in the same model class Job(models.Model): thumb = models.ImageField(upload_to='images/career/job/', default='default_image.jpg') title = models.CharField(max_length=100) discription = models.TextField(default="job discription") averageIncome = models.DecimalField(max_digits=10, decimal_places=2) slug = models.SlugField() pub_date = models.DateTimeField(auto_now_add=True) last_update = models.DateTimeField(auto_now=True) category = models.ForeignKey(Category,on_delete=models.CASCADE,related_name='job' ,default= None ) favorites = GenericRelation(Activity,related_query_name="job") is_favourite = models.BooleanField(default=False) author = models.ForeignKey(User,on_delete=models.PROTECT,default=None) #plan B #is_fav = medels.BooleanField(default=False) def __str__(self): return self.title def snippet(self): return self.discription[:100] -
Django on Elastic Beanstalk, How can I save output files of edited videos into S3 bucket
For starters, I am running the Django service on AWS Elastic Beanstalk and I am trying to trim a video's length with moviepy's ffmpeg_extract_subclip method then save it into the linked S3 bucket. media_storage = S3Boto3Storage() #used for targetname subclip_url = "temp/" + str(asset.id) + "-" + str(i) + ".mp4" #get url of file asset_url = media_storage.url(str(asset.asset_url)) self.create_clip(asset_url, subclip_url) if not media_storage.exists(subclip_url): curr_clip = open(settings.MEDIA_ROOT + "/" + subclip_url) object_file = files.File(curr_clip) media_storage.save(subclip_url,object_file) I split the ffmpeg_extract_subclip into another method below def create_clip(self, asset_url, subclip_url): url = settings.MEDIA_ROOT + "/" + subclip_url ffmpeg_extract_subclip(asset_url, 0, 5, targetname=url) My idea is to save the edited clip into the local directory, then open it and then send it to the S3 bucket. However, in this case, I have permission denied in EB when ffmpeg_extract_subclip attempts to save the file in the EB system (Which makes sense). Should I attempt to find a solution to override these permissions or is there perhaps a better way to edit a clip and send it to S3 through EB? Most of the methods I have found online requires Python to save the edited file to an output file. P.S. Sorry If I am not clear enough in … -
Django, Docker, collectstatic, UnicodeEncodeError: 'utf-8' codec can't encode characters in position 0-1: surrogates not allowed
I hope you can help me here. I run a Django project in containers (Docker version 18.03.1-ce) and recently upgraded to Django 3.0.6. Also, in the process, moved to Python 3.6 from Python 2.7. The container is built "FROM python:3.6". Everything works except collectstatic. The static files are stored in an S3 bucket and was all working fine before the upgrade (I had to fix a number of Django things due to the Python upgrade, but all predictable and documented). The locale settings in the container (with error messages) are: root# locale locale: Cannot set LC_CTYPE to default locale: No such file or directory locale: Cannot set LC_MESSAGES to default locale: No such file or directory locale: Cannot set LC_ALL to default locale: No such file or directory LANG=en_US.UTF-8 LANGUAGE=en_US:en LC_CTYPE="en_US.UTF-8" LC_NUMERIC="en_US.UTF-8" LC_TIME="en_US.UTF-8" LC_COLLATE="en_US.UTF-8" LC_MONETARY="en_US.UTF-8" LC_MESSAGES="en_US.UTF-8" LC_PAPER="en_US.UTF-8" LC_NAME="en_US.UTF-8" LC_ADDRESS="en_US.UTF-8" LC_TELEPHONE="en_US.UTF-8" LC_MEASUREMENT="en_US.UTF-8" LC_IDENTIFICATION="en_US.UTF-8" LC_ALL=en_US.UTF-8 And the message when running collectstatic (from within the container): root# python manage.py collectstatic You have requested to collect static files at the destination location as specified in your settings. This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Traceback (most recent call last): … -
Python integration for users to withdraw money from app wallet
I am working on an app that lets users play games and win prizes which they can withdraw to their bank accounts. Using paypal is not an option. Does anyone know of an integration that I can use to let users withdraw their winnings from their wallet into a bankcard? The app uses django for the backend and react for the frontend. -
form not showing in django
I want to create form in Django There is no error in the source code and the program is running but when the signup page is run the form does not appear and there appears "RegestrationonData object (None)" this source code models.py from django.db import models class RegestrationonData(models.Model): username = models.CharField(max_length=100) password = models.CharField(max_length=100) email = models.CharField(max_length=100) phone = models.CharField(max_length=100) form.py from django import forms class RegestrationonForm (forms.Form): username = forms.CharField(max_length=100) password = forms.CharField(max_length=100) email = forms.CharField(max_length=100) phone = forms.CharField(max_length=100) views.py from django.shortcuts import HttpResponse, render, redirect from .models import News from .models import RegestrationonData def Index(request): context = { "name": "Ali" } return render(request, "index.html", context) def Home(request): obj = News.objects.filter() context = { "list": ["Django", "Flask", "Oddo"], "data": obj } return render(request, "home.html", context) def Contact(request): return render(request, "contact.html") def NewsDate(request, year): article_list = News.objects.filter(pub_date__year=year) context = { 'year': year, 'article_list': article_list } return render(request, "NDate.html", context) def SignUp(request): context = { "form": RegestrationonData } return render(request, "signup.html", context) signup.html {% extends 'base.html' %} {% block title %} Sign Up {% endblock %} {% block body %} <div class="container"> <h1>This is sign up page</h1> <form> {{form}} </form> </div> {% endblock %} when running the application any solution? -
Django AWS S3 Files Not Showing Up on Site
When I check the page source, the link is linking to the correct AWS links but no images/css or media files are showing up. The bucket policy and CORS are configured as it should according to the tutorials I've followed. The bucket has the mdeia and static folders inserted as well. STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( (os.path.join(BASE_DIR, 'static')), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' AWS_ACCESS_KEY_ID = 'XXX' AWS_SECRET_ACCESS_KEY = 'XXX' AWS_STORAGE_BUCKET_NAME = 'XXX' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog.apps.BlogConfig', 'crispy_forms', 'ckeditor', 'django_cleanup', 'storages', ] -
Python cannot load project module Django Mod_WSGI
I am trying to deploy a test Django project onto an Apache2 server running under Debian 10. Django is running in a virtual environment under Python 3.7. After about 3 days of going in circles, I have got something to load upon connecting to the Apache server, but now I get the following Python error: My Django project is called myproject (how creative), and has 3 apps underneath it. I originally had it running in a virtual environment created using Pipenv, which was located in /home/dj/, and I entered into that virtual environment using 'pipenv shell' in that folder. I then had issues with the Python executable path and libraries, and discovered on day 2 that pipenv doesn't use shared libraries and is a lot more difficult to work with. I was mostly getting errors about Python failing to initiate. So I exited that virtual environment and created a new one using python3-venv (python3 -m venv venv). This new virtual environment is in /home/dj/venv/. I successfully linked the Python-home in the Apache site config (under sites-available) and Apache starts correctly. Upon connecting to the server, it serves the following page: **Internal Server Error** The server encountered an internal error or … -
save() method is not working in django after receiveing all the data?
The data are coming from a filed where i want to update only specific data that comes other wise left the model data as previous. So in my views the code is like this: views.py def set_product_detail(request, id): id = int(id) keys = [ "name", "price", "digital", "image", "image1", "image2", "image3", "seller", "stock", "size", "color", "search_tags", "description", ] if request.method == "POST": real_keys = [] for each in keys: if each.startswith("image"): if request.FILES.get(each) is not None: real_keys.append(each) else: if request.POST[each] is not None: real_keys.append(each) print(real_keys) product = Product.objects.get(id=id) print(product) for keys in real_keys: if keys.startswith("image"): product.keys = request.FILES.get(keys) print(keys, product.keys) else: product.keys = request.POST[keys] print(keys, product.keys) product.save() return redirect("view_product_in_table") models.py class Product(models.Model): name = models.CharField(max_length=200) price = models.FloatField() digital = models.BooleanField(default=False, null=True, blank=True) image = models.ImageField(null=True, blank=True) image1 = models.ImageField(null=True, blank=True) image2 = models.ImageField(null=True, blank=True) image3 = models.ImageField(null=True, blank=True) seller = models.CharField(max_length=100, null=True) distance = models.CharField(max_length=5, null=True) stock = models.IntegerField(default=0) color = models.CharField(max_length=100, null=True) description = models.CharField(max_length=200, null=True) size = models.CharField(max_length=100, null=True) search_tags = models.CharField(max_length=100, null=True) created_at = models.DateTimeField(auto_now_add=True) The provided keys are the fields in Product table! The print method print these after saving the form! ['name', 'price', 'digital', 'image', 'seller', 'stock', 'size', 'color', 'search_tags', 'description'] Facewash name Facewash … -
Django ORM annotate Sum calculation wrong and its multiplying by number of entry, it's wired
I am going through a wired situation in Django ORM. It is returning a wrong calculation of sum and unexpectedly it is multiplied by the number of entries which I don't want, it's behave completely wired. These are my models class Person(models.Model): name = models.CharField(max_length=100) class Purchase(models.Model): person = models.ForeignKey( Person, on_delete=models.CASCADE, related_name='person_purchase' ) amount = models.DecimalField(decimal_places=2, max_digits=5) class Consumption(models.Model): person = models.ForeignKey( Person, on_delete=models.CASCADE, related_name='person_consumption' ) amount = models.DecimalField(decimal_places=2, max_digits=5) This is my query: person_wise_payable = Person.objects.annotate( difference=ExpressionWrapper( Coalesce(Sum('person_purchase__amount'), Value(0)) - Coalesce(Sum('person_consumption__amount'), Value(0)), output_field=FloatField() ), ) for i in person_wise_payable: print(i.difference, i.name) I am trying to find out the difference between person wise Purchase and Consumption. For example, i have 3 person, foo, doe, jhon and these are their entry Purchase models entries: foo = 5 doe = 2 doe = 3 doe = 3 Consumption models entries: foo = 1 foo = 2 foo = 2 doe = 1 doe = 1 jhon = 2 So you see above, foo total purchase is 5 doe total purchase is 8 jhon total purchase is 0 (coz, no entry of him) and foo total consumption is 5 doe total consumption is 2 jhon total consumption is 2 So expected output/difference … -
check_password() in django always returning false
I am making a custom reset password module. I am checking the old password with django auth User model. But check_password is always returning false. Please help if there is mistake in my logic. views.py def user_pass_change(request): pass_old = request.POST.get('old_pass') hash_pass_new = make_password(request.POST.get('new_pass')) username = request.POST.get('username') user = User.objects.get(username=username) if user: check = check_password(user.password,pass_old) if check: User.objects.filter(username=username).update(password=hash_pass_new) messages.success(request, 'Password changed !') return redirect('/login') else: messages.warning(request, 'Wrong old password') return redirect('/login') else: messages.warning(request, 'Invalid Username !') return redirect('/login') I have tried including these hashers in setting.py PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.Argon2PasswordHasher', ] Thanks in advance