Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Is this solution DRY or is there a better way to model these profile classes and subclasses?
Basically, I have the following requirements: A user has a personal user profile An organisation can have a staff profile The staff profile can be independent or link to a user The organisation can edit the staff profile without changing the users' personal user profile A user changing their personal user profile wouldn't affect an organisations staff profile of the user A user can be staff at multiple organisations (and hence have multiple staff profiles) A user doesn't have to be staff Currently I have the following classes (Irrelevant fields removed for simplicity) profiles.models.py class Profile(TimeStampMixin): title = models.CharField(max_length=6, choices=Title.choices, blank=True) forename = models.CharField(max_length=50, blank=True) surname = models.CharField(max_length=50, blank=True) class UserProfile(Profile): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name="profile", on_delete=models.CASCADE) class StaffProfile(Profile): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, db_index=True, related_name="staff_profiles") organisations.models.py class Organisation(TimeStampMixin): staff = models.ManyToManyField('profiles.StaffProfile', blank=True, related_name="organisations") What I'm wondering is whether this solution is DRY and whether it's the best way of dealing with the requirements? The reason I'm not sure is because I've contemplated having StaffProfile extend UserProfile instead of Profile and changing the OneToOneField in UserProfile to a ForeignKey Field however this seems like it would complicate finding a User's personal profile from their staff profile. Unless I change the related_name … -
Postgres procedure not updating selected row
I'm working on a Django application that uses Stored Procedures on a PostgreSQL database. I'm stuck in a very strange (for me, at least) problem. I have the following SP code: create procedure inbound_550(p_operation_id integer) language plpgsql as $$ declare file_operation record; ... begin select oo.id, oo.file_id, ot.transaction_type_id, ot.code into file_operation from operations_operation oo join operations_type ot on ot.id = oo.type_id where oo.id = p_operation_id; for line in # select some records from other tables using parameter p_operation_id on some FKs loop # business logic here with some calculations and some inserts sum_tax_day = X # some value end loop; operation_avg_year_tax = ((1 + (sum_tax_day / 100)) ^ 252) - 1; update operations_operation set avg_year_tax = operation_avg_year_tax where id = p_operation_id; end $$; The problem is, when I call this procedure from the console it runs fine and the field avg_year_tax gets updated with the operation_avg_year_tax value but, when I call the procedure from my application using Python and psycopg2 the field is not updated, it seems that the update statement is ignored. Here is the Python code used to call the procedure: from django.db import connection class Inbound: def __init__(self, operation): self.operation = operation def main(self): conn = connection … -
please someone should help me out... this gives me error
views.py @login_required def edit_entry(request, entry_id): """ edit exiting entry """ entry = Entry.objects.get(id=entry_id) blogpost = entry.blogpost check_blog_owner(request, blogpost_id) if request.method != 'POST': # initial request, pre-fill with entry data form = EntryForm(instance= entry) else: form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('blogs:blogpost', args=[blogpost.id])) context = {'entry':entry, 'blogpost':blogpost, 'form':form} return render(request, 'blogs/edit_entry.html', context) def check_blog_owner(request, blogpost_id): """check if the blog owner is logged it""" blog = BlogPost.objects.get(id=blogpost_id) if blog.owner != request.user: raise Http404 Traceback (most recent call last): File "C:\Users\MUHDYE~1\DOWNLO~1\PROGRA~1\FULL-S~1\Blog\bb_env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\MUHDYE~1\DOWNLO~1\PROGRA~1\FULL-S~1\Blog\bb_env\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\MUHDYE~1\DOWNLO~1\PROGRA~1\FULL-S~1\Blog\bb_env\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\Muhd Yekini\Downloads\programming\FULL-STACK projects\Blog\blogs\views.py", line 72, in edit_entry check_blog_owner(request, blogpost_id) Exception Type: NameError at /edit_entry/13/ Exception Value: name 'blogpost_id' is not defined -
SMTPAuthenticationError at /
my django app is not being able to send email. On my email less secure apps is turned on and i have unlocked captcha. am stuck i dont know what am missing. any help will be appreciated. Traceback Environment: Request Method: POST Request URL: http://localhost:8000/ Django Version: 3.0.9 Python Version: 3.8.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shield_sec'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/apple/projects/Django/ingabo_sec/shield_sec/views.py", line 17, in contact send_mail ( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/mail/__init__.py", line 60, in send_mail return mail.send() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 69, in open self.connection.login(self.username, self.password) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 734, in login raise last_exception File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 723, in login (code, resp) = self.auth( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 646, in auth raise SMTPAuthenticationError(code, resp) Exception Type: SMTPAuthenticationError at / Exception Value: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials l188sm1732224lfd.127 - gsmtp') settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ … -
How to import django allauth.account when already having an app module named 'account'?
settings.py INSTALLED_APPS = [ 'apps.account', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.linkedin_oauth2', ] error shows : Application labels aren't unique, duplicates: account I cannot change my project app named 'account' also i need to use allauth.account .How can I solve this issue ? -
How to deploy a django-react app to docker container and run it?
I have a Django-backend React-frontend small application and I need it to run on Docker container so I can start both servers with one button/file, I don't have any Docker experience except for understanding core concepts, can someone point me out to a good modern tutorial or just give some instructions on how to do it? -
How can my translation be shown in my website
I am currently working on my website, which is a translator which you input a phrase and it gets translated into an invented language. Here's the code of the translator function: def translator(phrase): translation = "" for letter in phrase: if letter.lower() in "a": if letter.isupper: translation = translation + "U" else: translation = translation + "u" elif letter.lower() in "t": if letter.isupper: translation = translation + "A" else: translation = translation + "a" elif letter.lower() in "c": if letter.isupper: translation = translation + "G" else: translation = translation + "g" elif letter.lower() in "g": if letter.isupper: translation = translation + "C" else: translation = translation + "c" return translation However, I am stuck in showing this funcion in my web, here's the code in views.py: from .translate import translator def translated_view(request): text = request.GET.get('text') print('text:', text) translate = translator dt = translator.detect(text) tr = translated.text context = { 'translated': tr } return render(request, context, 'main/translated.html') Here's the template that should would show the translation. {% extends "base.html"%} {% block content%} <div > <center><h2 class = "display-4">DNA TRANSLATED SUCCESFULLY INTO</h2></center> <br> <br> <br> <h3> {{ translated }} </h3> </div> {% endblock content%} -
I can not access to mount directory from Django when using docker
I run Django in docker and I want to read a file from host. I mount a path in host to container using following command in my docker-compose file: volumes: - /path/on/host/sharedV:/var/www/project/src/sharedV Then I execute mongodump and export a collection into sharedV on host. After that, I inspect web container and go to the sharedV directory in container and I can see the backup file. However, when I run os.listdir(path) in django, the result is empty list. In the other word, I can access to sharedV directory in Django but I can not see its contents! Is there any idea that how can I access to host from a running container? thanks -
send metatags through Google Cloud Signed URL with Django
I'm using signed url to get or post/put video fileq on my google storage. My modules refers on signed_url V4 and it's working quite well. I wanted to add some metadata tags to my requests in order to manage more efficiently the charges related to GCS. But since I added those headers, the requests failed returning a cors policy error : (I have shortened the signature in the block above to make it more readable) Access to XMLHttpRequest at 'https://test-dev-slotll.storage.googleapis.com/uploads/dave/FR/eaa678c9/2020/9/785f/f45d3d82-785f_full.mp4?X- Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=dev-storage%40brilliant-tower-264412.iam.gserviceaccount.com%2F20200926%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20200926T093102Z&X-Goog-Expires=3600&X-Goog-SignedHeaders=host%3Bx-goog-meta-account&x-goog-signature=6fbb27e[...]bd0891d21' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. and the detailed message: <Error> <Code>MalformedSecurityHeader</Code> <Message>Your request has a malformed header.</Message> <ParameterName>x-goog-meta-account</ParameterName> <Details>Header was included in signedheaders, but not in the request.</Details> </Error> The cors are conigured to allow almost everything on my bucket : [{"maxAgeSeconds": 3600, "method": ["*"], "origin": ["*"], "responseHeader": ["*"]}] and here is the Python/Django function def _get_signed_url(self, http_method="GET"): """' create a signed url with google storage create a 'GET' request by default, add method='w' or 'put' to create a 'PUT' request get_signed_url('w')->PUT / get_signed_url()->GET """ if http_method.lower() in ["w", "put", "post"]: http_method = "PUT" else: http_method = "GET" signed_url = generate_signed_url( settings.GS_BUCKET_NAME, self.file.name, subresource=None, expiration=3600, http_method=http_method, … -
Django simple captcha and ajax sometimes not workings
I'm used Django-simple-captcha in my Django project. The user submits the wrong captcha while showing error but sometimes the user submit the wrong captcha and show us the account is created successfully (account isn't created). I can't figure out that issue. I thought the problem with ajax. I want --> user submit her details with valid captcha then account created but the user submits the wrong captcha then shows an error message and the page not load. how can I solve this issue? this is my details. views file @is_user_logged_in @find_and_assign_anonymous_cart() def signup(request): if request.region.code.upper() == settings.DEFAULT_LOCAL_COUNTRY: form = LocalSignupForm(request.POST or None) else: form = SignupForm(request.POST or None) if form.is_valid(): human = True form.save() password = form.cleaned_data.get('password') confirm_password = form.cleaned_data.get('confirm_password') email = form.cleaned_data.get('email') _group = Group.objects.get(name='customer') user = auth.authenticate( request=request, email=email, password=password) _group.user_set.add(user) if user: # Get Client IP Address current_user = user client_ip = get_client_ip(request) current_user.last_login_user_ip = client_ip current_user.last_login_user_country = get_country_by_ip(client_ip) current_user.save() if user.groups.filter(name='customer').exists(): request.session['is_customer'] = True # send welcome email, with four featured products # featured_products = products_for_homepage() domain = request.site scheme = request.is_secure() and "https" or "http" domain = "{}://{}".format(scheme, domain) email_tpl_context = { "request": request, "customer_name": email, "domain": domain, # it will be changed to customer … -
Django view-function for personal page of "author"
How to pass information about a specific user and his messages to the view function. For example, I write the following URL: http://127.0.0.1:8000/leo. Leo is the author of posts. I already have a template to display all posts for a specific author. Here is my view function: def profile(request, username): user = posts = return render(request, 'profile.html', {'user': user, 'posts': posts}) Thank's guys -
Server error after deploy a Django project with MediumEditor
I built a blog-like site in Django, and deployed it on Linode. Everything works well if I don't use the Django MediumEditor, but with this app. included I get a server error 500 when trying to get a page that uses such editor. I blindly followed all the instructions on how to use Medium editor with Django; here below all the files that call the editor. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mediumeditor', 'blog.apps.BlogConfig' ] ... MEDIUM_EDITOR_OPTIONS = { 'toolbar': { 'buttons': [ 'bold', 'italic', 'underline', 'strikethrough', 'subscript', 'superscript', 'link', 'quote' ] }, 'placeholder': {'text': 'insert text'} } blog/admin.py from django.contrib import admin from .models import Post, Comment from mediumeditor.admin import MediumEditorAdmin @admin.register(Post) class PostAdmin(MediumEditorAdmin, admin.ModelAdmin): mediumeditor_fields = ('title', 'content') search_fields = ['title', 'content'] list_display = ['title', 'content', 'date'] list_filter = ['title'] list_editable = ['content'] @admin.register(Comment) class CommentAdmin(MediumEditorAdmin, admin.ModelAdmin): mediumeditor_fields = ('content') blog/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.utils.safestring import mark_safe from .models import Post, Comment from mediumeditor.widgets import MediumEditorTextarea class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=50, required=True) last_name = forms.CharField(max_length=50, required=True) email = forms.EmailField(max_length=100, required=False, help_text="Optional") class Meta: model = User fields = ('username', 'password1', 'password2', 'first_name', 'last_name', 'email') … -
Django set CreateView field programmatically with foreign key SELECT FROM WHERE clause
class Contest(TimeStampedModel): is_open = models.BooleanField(default=False) name = models.CharField(max_length=200) class ContestEntry(TimeStampedModel): name = models.CharField("Track name", max_length = 255) artist = models.CharField("Artist", max_length = 255) url = EmbedVideoField(); description = models.TextField("Description*", blank=True) slug = models.SlugField(max_length=200, unique=True, null=True) contest = models.ForeignKey(Contest, on_delete=models.CASCADE, null=True) and a view: class EntryCreateView(LoginRequiredMixin, CreateView): model = ContestEntry fields = ['name', 'artist', 'url', 'description'] def form_valid(self, form): form.instance.poster = self.request.user return super().form_valid(form) I want to enter the field Contest in my EntryCreateView programmatically with the first entry from the query SELECT id FROM Contests WHERE is_open ORDER BY created desc -
How to add comments functionality to a django web app?
I want to add the functionality of adding comments in the same html page with post details starting from this class based view. I also have left below the model and the html template that I want to use. Please help me The class based view that I want to use as a starting point : class PostDetailView(DetailView): model = Post The model: class Comments(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField() date_added = models.DateTimeField(default=timezone.now) def __str__(self): return self.content The html template: <div id="comments"> <h3>{{ comments.total }}</h3> <ol class="commentlist"> {% for comment in comments %} <li class="depth-1"> <div class="avatar"> <img width="50" height="50" alt="" src="{{ comment.user.profile.image.url }}" class="avatar"> </div> <div class="comment-content"> <div class="comment-info"> <cite>{{ comment.user }}</cite> <div class="comment-meta"> <time datetime="2014-07-12T23:05" class="comment-time">{{ comment.date_added|date:"F d, Y" }}</time> </div> </div> <div class="comment-text"> <p>{{ comment.content }}</p> </div> </div> </li> {% endfor %} </ol> <!-- /commentlist --> <!-- respond --> <div class="respond"> <h3>Leave a Comment</h3> <!-- form --> <form action="" method="POST"> {% csrf_token %} <fieldset> <div class="group"> {{ form|crispy }} <button class="submit full-width" type="submit">Add Comment</button> </div> </fieldset> </form> <!-- /contactForm --> </div> <!-- /respond --> </div> <!-- /comments --> -
Django makemigrations Segmentation fault
I am trying to run a Django rest api in Docker-compose on a raspberry pi 3B with 1gb of RAM. The postgresql database and the nodejs frontend run without any problem. But for the django backend the output of docker-compose up is a segmentation fault: backend | + python3 manage.py makemigrations restapi backend | No changes detected in app 'restapi' backend | scripts/start_server.sh: line 29: 13 Segmentation fault (core dumped) python3 manage.py makemigrations restapi line 29 in start_server.sh refers to: python3 manage.py makemigrations restapi Any ideas where the segfault is coming from or how I could find out what's the problem? Might this be a memory issue? I configured a 8GB swap alongside the 1GB RAM. Would this prevent python to run out of memory? The exact same configuration runs fine on my PC with 8GB RAM so I suppose there isn't a problem with my django models. Edit: if i skip the makemigrations and jump to migrate I also get a segfault: backend | Applying restapi.0001_initial... OK backend | Applying sessions.0001_initial... OK backend | scripts/start_server.sh: line 31: 13 Segmentation fault (core dumped) python3 manage.py migrate -
Tried scheduling a function in django with celery beats but giving error
Tried to schedule a function print_hello() in Django. But code seems not working. Here is the Django project layout. Only celery related files are given. - celery_test - celery_test - __init__.py - celery.py - tasks.py _init_.py code: from .celery import app as celery_app __all__ = ('celery_app',) celery.py code: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'celery_test.settings') app = Celery('celery_test') app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.schedule_beat = { 'print-hello-every-2-seconds': { 'task': 'tasks.print_hello', 'schedule': 2, }, } app.autodiscover_tasks() tasks.py code: from celery import shared_task @shared_task def print_hello(): print("Hello celery...") After running celery -A celery_test worker -l info, prompt is showing following error. -------------- celery@########## v4.4.7 (cliffs) --- ***** ----- -- ******* ---- Windows-10-10.0.18362-SP0 2020-09-26 19:03:12 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: celery_test:0x2c34a320eb0 - ** ---------- .> transport: amqp://guest:**@localhost:5672// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] [2020-09-26 19:03:13,202: INFO/SpawnPoolWorker-1] child process 4856 calling self.run() [2020-09-26 19:03:13,202: INFO/SpawnPoolWorker-3] child process 784 calling self.run() [2020-09-26 19:03:13,211: INFO/SpawnPoolWorker-2] child process 8868 calling self.run() [2020-09-26 19:03:13,220: INFO/SpawnPoolWorker-4] child process … -
-----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz Push failed
C:\Users\Admin\projects\ParasnathCorporation>git push heroku master Enumerating objects: 796, done. Counting objects: 100% (796/796), done. Delta compression using up to 8 threads Compressing objects: 100% (795/795), done. Writing objects: 100% (796/796), 41.57 MiB | 735.00 KiB/s, done. Total 796 (delta 162), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> App not compatible with buildpack: https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: af4699d8483bd3539d1c5fab804dab8dc114987 remote: ! We have detected that you have triggered a build from source code with version af4699d8483bd3539d1c5fab804dab8dc114987 remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! If you are developing on a branch and deploying via git you must run: remote: ! remote: ! git push heroku <branchname>:main remote: ! remote: ! This article goes into details on the behavior: remote: ! https://devcenter.heroku.com/articles/duplicate-build-version remote: remote: Verifying deploy... remote: remote: ! Push rejected to parasnathcorporation. remote: To https://git.heroku.com/parasnathcorporation.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/parasnathcorporation.git' This shows when I … -
Django - reload template after post request
My template does not reload immediately after hitting button for post request. But I know the request worked fine because if I load the page manually (with link) I can see it changed correctly. Any ideas? I understand the problem is in the render of post method... def profile(request, user): this_user = request.user profileuser = get_object_or_404(User, username=user) posts = Post.objects.filter(user=profileuser).order_by('id').reverse() followed = Follow.objects.filter(followed=profileuser) following = Follow.objects.filter(following=profileuser) all_followed = len(followed) all_following = len(following) paginator = Paginator(posts, 10) if request.GET.get("page") != None: try: posts = paginator.page(request.GET.get("page")) except: posts = paginator.page(1) else: posts = paginator.page(1) try: both_follow = Follow.objects.filter(followed=profileuser, following=request.user) except: both_follow == False context = { "posts": posts, "profileuser": profileuser, "all_followed": all_followed, "all_following": all_following, "both_follow": both_follow, "this_user": this_user, } if request.method == "GET": return render(request, "network/profile.html", context) if request.method == "POST": if both_follow: both_follow.delete() both_follow == False else: f = Follow() f.followed = profileuser f.following = request.user f.save() both_follow == True return render(request, "network/profile.html", context) And the html is: <p> <button type="button" class="btn btn-success" data-toggle="modal" data-target="#followed">{{ all_followed }} Followers </button> <button type="button" class="btn btn-success" data-toggle="modal" data-target="#following">{{ all_following }} Following </button> </p> {% if profileuser != this_user %} {% if both_follow %} <form action="{% url 'profile' profileuser %}" method="POST"> {% csrf_token %} <button … -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte in django
I want to get the list of posts api through the get request.But after writing the code, I sent the get request and the following error appears. Traceback Traceback (most recent call last): File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response response = response.render() File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\renderers.py", line 100, in render ret = json.dumps( File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\utils\json.py", line 25, in dumps return json.dumps(*args, **kwargs) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 234, in dumps return cls( File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\utils\encoders.py", line 50, in default return obj.decode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte In the previous code, we received it normally without any decoding errors, and this problem occurs after modification. What's the problem? Here's my code. views.py class CreateReadPostView (ModelViewSet) : serializer_class = PostSerializer permission_classes = [IsAuthenticated] queryset = Post.objects.all() def perform_create (self, serializer) : serializer.save(author=self.request.user) def list (self, request) : posts = Post.objects.all() data … -
Django-haystack & solr : Increase the number of results
I have this function : def search_books(request): search_text = request.POST.get('search_text') if search_text: books = SearchQuerySet().filter(content=search_text).filter(quantite__gte=0) else: books = [] return render_to_response("search/search.html", {'books': books}) By default it returns only 20 results, is there a way to increase that number? Thanks. -
Have a django reverse to a url with PK <int:pk>
I was following This Tutorial to set up payment with PayPal my problem is with the paypal_dict as it contains this paypal_dict = { ... 'return_url': 'http://{}{}/{}'.format(host, reverse('payment_done')), ... } and my payment_done URL needs to have an id for the trade itself, I'm not sure how can i have a pk within this Here is my full URLs.py ... # Payment path('payment/process/<int:trade_id>/', payment_views.payment_process, name="payment_process"), path('payment/done/<int:trade_id>/', payment_views.payment_done, name="payment_done"), ... My full process_paypal def payment_process(request, trade_id): trade = get_object_or_404(Trade, id=trade_id) host = request.get_host() paypal_dict = { 'business': settings.PAYPAL_RECEIVER_EMAIL, # todo WHO TO PAY 'amount': Decimal(trade.price), 'item_name': trade.filename, 'invoice': str(trade.id), 'currency_code': 'USD', 'notify_url': 'http://{}{}'.format(host, reverse('paypal-ipn')), 'return_url': 'http://{}{}/{}'.format(host, reverse('payment_done')), 'cancel_return': 'http://{}{}'.format(host, reverse('home')), } form = PayPalPaymentsForm(initial=paypal_dict) return render(request, 'payment/payment_process.html', {'trade': trade, 'form': form}) -
Django Tweepy API.friends clarification
I have an app that fetches friends and followers from a logged user then serves them on an html table. I had the the following code checking for entries that were neither on update and deleted them. # Setup Twitter API instance of logged User api = get_api(user) me = api.me() # Fetch logged User's friends user_friends = api.friends(me.screen_name, count=200) # Fetch logged User's followers user_followers = api.followers(me.screen_name, count=200) # Check for excess entries and delete them if any existing_contacts = Contact.objects.filter(user=user) for contact in existing_contacts: if contact not in user_friends and contact not in user_followers: contact.delete() I decided to use cursor method in order to provide scalability but after changes current code is deleting all contacts. Probably cause it doesn't find the object in any of the lists. Any ideas? # Setup Twitter API instance of logged User api = get_api(user) me = api.me() # Fetch logged User's friends user_friends = tweepy.Cursor(api.friends, me.screen_name, count=200).items() # Fetch logged User's followers user_followers = tweepy.Cursor(api.followers, me.screen_name, count=200).items() # Check for excess entries and delete them if any existing_contacts = Contact.objects.filter(user=user) for contact in existing_contacts: if contact not in user_friends and contact not in user_followers: contact.delete() models.py class Contact(models.Model): twitter_id = models.CharField(max_length=30) profile_image_url … -
ConnectionError(<urllib3.connection.HTTPConnection object at 0x7f70f408b3c8>: Failed to establish a new connection
I am trying to build a social network with django. Every thing was working perfectly. then I changed some code in two views. one in post like_unlike_post view and profile detail view. I added SingleObjectMixin and formviwe with detail view so that people can like and comment on post when visiting others profile. after that I notice this error occurs everytime I try to login or update something. I have no idea what causing this error. Can anyone help me with this. here is my profile detail and update view from django.http import HttpResponseRedirect from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse from django.shortcuts import get_object_or_404, redirect, render from django.utils.translation import gettext_lazy as _ from django.views import View from django.views.generic import DetailView, RedirectView, UpdateView, FormView from django.views.generic.detail import SingleObjectMixin from .models import Profile from posts.forms import PostModelForm, CommentModelForm from posts.models import Post from relationships.models import Relationship User = get_user_model() class ProfileDetailView(LoginRequiredMixin, DetailView): model = Profile slug_field = "slug" slug_url_kwarg = "slug" form_class = CommentModelForm queryset = Profile.objects.prefetch_related('posts__likes', 'friends', 'posts__comment_posted', 'posts__comment_posted__user') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) sender_profile = get_object_or_404(Profile, id=self.request.user.id) receiver_profile = get_object_or_404(Profile, id=self.object.id) frnd_btn_state = Relationship.objects.relation_status( sender=sender_profile, receiver=receiver_profile, ) context['frnd_btn_state'] = frnd_btn_state context['frnd_req_rcvd'] = Relationship.objects.invitation_recieved( … -
Is theirany way to view the hashed password from Django
I have a an application developed in Django and using BaseUserManger model. When I looking to my database and admin panel password has been hashed. But I want to know what exactly in the password field. Is there any way to know the password? Please try to answer this question if anyone knows..! -
Django related_name not working while using self reference in many-to-many field
I'm currently trying to create following relationship between users, so I used a many-to-many field in the User model to reference itself. class User(AbstractUser): followers = models.ManyToManyField('self', related_name='following') def __str__(self): return self.username However, when I tested this model using shell and trying to access the related_name, it reported error has occurred. >>> u1 = User.objects.get(pk=1) >>> u1.following.all() Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'User' object has no attribute 'following' Now I'm really confused, and really need help or alternative ways of doing this.