Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django vote system failing
I am Confused. I am trying to set a vote system for a post in a blog. But Django always sums on the vote posive side, /blog/models.py class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') post_pos = models.IntegerField(default=0) post_neg = models.IntegerField(default=0) objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) /blog/urls.py urlpatterns = [ path('', views.PostListView.as_view(), name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'), path('<int:post_id>/share/',views.post_share, name='post_share'), path('<int:post_id>/',views.positive_post, name='positive_post'), path('<int:post_id>/',views.negative_post, name='negative_post'), ] blog/views.py def positive_post(request,post_id): obj = Post.objects.get(pk=post_id) obj.post_pos += 1 obj.save() print ('positive') return redirect(obj.get_absolute_url()) def negative_post(request,post_id): obj = Post.objects.get(pk=post_id) obj.post_neg += 1 obj.save() print ('negative') return redirect(obj.get_absolute_url()) template: <p> <a href="{% url 'blog:positive_post' post.id %}"> VOTE UP {{ post.post_pos}} </p> <p> <a href="{% url 'blog:negative_post' post.id %}"> VOTE DOWN {{ post.post_neg}} </p> no matter if I click vote up or vote down always sums in obj.post_pos ???????? thanks to those print('positive), and print('negative') of views.py I know it is always … -
XML-RPC API with Django
I'm trying to create an API with Django using xml-rpc protocol. I actually created some basic examples on Python but when implementing them on Django I started to get lots of issues. I'm following this code, I think it's pretty old but I couldn't find any better tutorial My urls.py: urlpatterns = [ path('xml_rpc', views.rpc_handler), ] This is my django views.py: from xmlrpc.server import SimpleXMLRPCDispatcher from django.http import HttpResponse # Create a Dispatcher; this handles the calls and translates info to function maps #dispatcher = SimpleXMLRPCDispatcher() # Python 2.4 dispatcher = SimpleXMLRPCDispatcher() # Python 2.5 @csrf_exempt def rpc_handler(request): if len(request.POST): response = HttpResponse(mimetype="application/xml") response.write(dispatcher._marshaled_dispatch(request.raw_post_data)) else: response = HttpResponse() response.write("<b>This is an XML-RPC Service.</b><br>") response.write("You need to invoke it using an XML-RPC Client!<br>") response.write("The following methods are available:<ul>") methods = dispatcher.system_listMethods() for method in methods: sig = dispatcher.system_methodSignature(method) help = dispatcher.system_methodHelp(method) response.write("<li><b>%s</b>: [%s] %s" % (method, sig, help)) response.write("</ul>") response.write('<a href="http://www.djangoproject.com/"> <img src="http://media.djangoproject.com/img/badges/djangomade124x25_grey.gif" border="0" alt="Made with Django." title="Made with Django."></a>') response['Content-length'] = str(len(response.content)) return response def multiply(a, b): return a*b dispatcher.register_function(multiply, 'multiply') This code actually 'works', I mean, I can access the view if I run the server and I can send the Api request from Python with this code: import … -
Django: Pillow seems to install but is not showing in pip freeze
I'm having problems installing Pillow in a venv on AWS Linux. Pillow seems to install correctly but pip freeze doesn't list it and Django runserver fails claiming that PIL is missing. The following console output shows the problem: [root@ip-172-31-25-228 ichiba]# source venv/bin/activate (venv) [root@ip-172-31-25-228 ichiba]# pip freeze asgiref==3.2.10 Django==3.1.1 django-bootstrap-form==3.4 django-crispy-forms==1.9.2 django-filter==2.3.0 django-rest-framework==0.1.0 djangorestframework==3.11.1 pytz==2020.1 sqlparse==0.3.1 (venv) [root@ip-172-31-25-228 ichiba]# pip install Pillow Collecting Pillow Using cached Pillow-7.2.0-cp36-cp36m-manylinux1_x86_64.whl (2.2 MB) Installing collected packages: Pillow Successfully installed Pillow-7.2.0 (venv) [root@ip-172-31-25-228 ichiba]# pip freeze asgiref==3.2.10 Django==3.1.1 django-bootstrap-form==3.4 django-crispy-forms==1.9.2 django-filter==2.3.0 django-rest-framework==0.1.0 djangorestframework==3.11.1 pytz==2020.1 sqlparse==0.3.1 (venv) [root@ip-172-31-25-228 ichiba]# What am I doing wrong? Thanks and regards...Paul -
How to read a file form a Django model FileField
I have the following model in Django: class Batch(CustomModel): product = models.ForeignKey(Product, verbose_name=_("Producto"), on_delete=models.PROTECT, related_name='batchs') start_date = models.DateField(_("Fecha de Inicio"), auto_now=False, auto_now_add=False) due_date = models.DateField(_("Fecha de Vencimiento"), auto_now=False, auto_now_add=False) states = models.ManyToManyField(State, verbose_name=_("Estados")) source_file = models.FileField(_("Archivo de origen"), upload_to=None, max_length=100) class Meta: verbose_name = _("Lote") verbose_name_plural = _("Lotes") def __str__(self): return "[{}]{}/{}/{}".format(self.id, self.product.id, self.start_date, self.due_date) def save(self, *args, **kwargs): super().save(*args, **kwargs) tokens_string = self.source_file.open() tokens = tokens_string.split('\n') print(tokens) As you can see, in method save() I try to print the content of the file being uploaded to field ' source_file`. This is the file being uploaded: file.txt 867670000460 867670000693 867670001445 867670001519 867670001597 When I do print(tokens), I get a single long string: b'867670000460\r\n867670000693\r\n867670001445\r\n867670001519\r\n867670001597\r\n867670002554' I tried to split the string using tokens_string.split('\n'), but I get this error: File "/Users/hugovillalobos/Documents/Code/cinetogoproject/backend/cinetogo/inventory/models.py", line 37, in save tokens = tokens_string.split('\n') TypeError: a bytes-like object is required, not 'str' How can I get each line of the file separated? -
How to rebuild index in elasticsearch for low-memory instance
I'm trying to run python3 manage.py search_index --rebuild -f on my EC2 small instance (+500,000 documents) but the process gets killed as soon as it starts. I tried changing chunk_size, query_pagination, and parallel_indexing but I always get the same error "Killed" or sometimes I get "Memory Error". My question is how can I run this command in small chunks so it doesn't cause this error? -
How do you link form action to a view method?
In my rendered index.html, I have: <form action="???" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> In my views.py, I have: class weather(base.TemplateView): # Generates the above html def get_hours(request): # do something with request.Post return shortcuts.render(request, "index.html", {"form": form}) How do I make the form action call the get_hours? I want to post to the same page the form is on so the page won't refresh and will display the results on the same page. -
Django request header not in preflight response
my application uses angular for frontend and Django for the backend. The front end is sending data in a custom header called mobile. This are the request-headers from the frontend. Accept: application/json, text/plain, */* code: +1 Content-Type: application/json mobile: 1234678901 Referer: http://localhost:4200/ User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36 But I am getting an error like this. from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field mobile is not allowed by Access-Control-Allow-Headers in preflight response. I have also added the header to the CORS_ALLOW_HEADERS in my settings.py file. My settings.py file has something like this. from corsheaders.defaults import default_headers CORS_ALLOW_HEADERS = default_headers + ( 'mobile' ) But still I am getting the CORS error. What am I missing? Thanks in advance. -
I am trying to save attendance in my Django attendance app but keep getting TypeError, expected string or bytes-like object
I have tried everything. Checked several solutions on this platform, none have worked. Please help!! The error looks like this TypeError at /attendance/student/ expected string or bytes-like object Request Method: POST Request URL: http://127.0.0.1:8000/attendance/student/?reg_class=1 Django Version: 3.1 Exception Type: TypeError Exception Value: expected string or bytes-like object Exception Location: line 75, in parse_date Python Executable: C:\Users\Mrs Onajide\Desktop\school_management_system.venv\Scripts\python.exe Python Version: 3.8.3 My View from django.shortcuts import render, redirect from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .forms import SearchEnrolledStudentForm, AttendanceForm, DateForm from student.models import EnrolledStudent from academic.models import ClassRegistration from .models import StudentAttendance from django.forms.formsets import formset_factory def student_attendance(request): forms = SearchEnrolledStudentForm() class_name = request.GET.get('reg_class', None) if request.method == 'POST': class_info = ClassRegistration.objects.get(id=class_name) student = EnrolledStudent.objects.filter(class_name=class_name) count = student.count() attendance_formset = formset_factory(AttendanceForm, extra=count) formset = attendance_formset(request.POST) date = DateForm(request.POST) list = zip(student,formset) if formset.is_valid(): for form, student in zip(formset,student): mark = form.cleaned_data['mark_attendance'] StudentAttendance.objects.create_attendance(class_info.name, student.roll, mark, date) return redirect('home') My Model from django.db import models from academic.models import ClassRegistration from student.models import EnrolledStudent from django.utils import timezone class AttendanceManager(models.Manager): def create_attendance(self, std_class, std_roll, std_id, datel): std_cls = ClassRegistration.objects.get(name=std_class) std = EnrolledStudent.objects.get(roll=std_roll, class_name=std_cls) std_att = StudentAttendance.objects.create( class_name=std_cls, student = std, status = std_id, date = datel ) return … -
Speed of the django website after deploying it on heroku
I have deployed a django website on herokuapp (using free tier without having to pay anything) for testing.Currently when the site opens it takes a bit more time to open than the time it takes to open on localhost(127.0.0.1:8000).Also the images take a bit more time to load.My concern is that if I upload it on a platform such as digital ocean or linode or aws will I get the website to load in the same time as it is loading on heroku or there will be a better performance . Or is it the problem with the coding that is making it load slower. If that is the case please tell me ways so that I can get my website to load faster. -
I am unable to update two models at the same time in Django Views.py
I already ask questions related to this at How can I update first_name, last_name & email of Django model User and update other field in separate models But I'm not getting a proper solution. That's why I make this question similar to that one. I have pages.views.py: from django.shortcuts import render, redirect from .forms import CreateUserForm from accounts.models import Account from django.contrib import messages def signupPage(request): if request.user.is_authenticated: return redirect('/') else: form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() # focus on this line Account.objects.create(user=user) messages.success(request, 'Signup success. Now, you can login.') return redirect('login') else: messages.warning(request, 'Signup failed. Please, try again.') context = {'form':form} return render(request, 'signup.html', context) Also, I have accounts.models.py: from django.db import models from django.contrib.auth.models import User class Account(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) # This field is used for to update django model User first_name=models.CharField(max_length=30, null=True, blank=False) last_name=models.CharField(max_length=30, null=True, blank=False) email = models.EmailField(max_length=30, null=True, blank=True) profile_photo = models.ImageField(upload_to='profile', null=True) mobile_number = models.PositiveBigIntegerField(null=True) date_of_birth = models.DateField(auto_now_add=False, auto_now=False, null= True) zip_code = models.IntegerField(null=True) address = models.CharField(max_length=225, null=True) website = models.URLField(max_length=100, null=True) bio = models.CharField(max_length=225, null=True) In Accounts.view.py: from django.shortcuts import render, redirect from .forms import AccountForm from .models import Account from … -
Django primary key prefix and length
I am looking to add a custom primary key to my models. Here is what i have so far. ticket_id = models.CharField(max_length=10, primary_key=True, editable=False) I basically want the primary key for each record to look like this, auto-incrementing from 001. AB001 AB002 AB003 AB004 How would I accomplish this? Many Thanks -
Django Session isn't getting updated appropriately
Stumbled upon the error message - The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example. This error is popping up when rendering a django template (narrowed down the error to the line - return render(request, {})). This process involves uploading a file, running view logic, and presenting the results to the user. It worked for a good many files and is throwing this error for one specific file. The view logic involves a bunch of django session updates. Suspected that this error could be due to the huge session size. Ironically though, the size of the session as I checked in the DB is 120 MB, which sounds reasonable. Can you walk me through the possible issues that could have led to this error? Thanks in advance! -
Can't send API Requests from python code hosted on AWS Lightsail instance
I have a django website that is hosted on an AWS Lightsail. I am trying to add in a Speech to text tool in it. I have tried Google Cloud Speech to text as well as Microsoft Azure Speech to text APIs for this purpose and have used sample code from their websites. The code works fine when i'm running it on my localhost, but the same code does not work when hosted on that AWS Lightsail instance. There is no error, the reponse just never comes and the status stays on "pending.." Is there any log i can check for an error? Or is there any additional step required? Thank you in advance. -
Dynamic inheritance from Model
I have a Photo-Model that helps me achieve storing each image as a thumbnail aswell: class Photo(models.Model): image = models.ImageField(upload_to=upload_path, default=default_image) thumbnail = models.ImageField(upload_to=upload_path_2, editable=False, default=default_image_2) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Now I have another Model, lets call it User, which inherits from Photo: class User(Photo): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Now lets say there are multiple classes inheriting from Photo and depending on the inheriting class, I want to set another upload_path and default_image. How Do I achieve that? Can I somehow use the constructor? Thanks in Advance! -
How can I solve this problem in update crud in Django?
Well, I've been trying to solve this problem for days, at the time of performing the update crud, the form doesn't make me valid and the modified records aren't saved. Next I will show you how my code is in each module: views.py def modificarcurso(request,id): curso = Curso.objects.get(id=id) curso = CursoForm(request.POST, instance=curso) if curso.is_valid(): curso.save() return redirect("/mostrarcursos") return render(request, 'mostrarcursos.html', {'curso': curso}) forms.py class CursoForm(forms.ModelForm): class Meta: model = Curso fields=['docente','anio','paralelo','jornada'] models.py class Curso(models.Model): docente= models.ForeignKey(Docente,on_delete=models.CASCADE) anio = models.IntegerField(default=1) paralelo = models.CharField(max_length=1) jornada = models.CharField(max_length=20) user = models.CharField(max_length=100) user_mod = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) estado = models.IntegerField(default=1) # 1 es activo y 2 es eliminado class Meta: db_table ="Cursos" verbose_name ="Curso" verbose_name_plural ="Cursos" def __str__(self): return self.paralelo + ' ' + self.jornada Well, and in the html code the form is created where the records are entered with the name of each field. -
Not Found: /style.css/ , django
I'm trying to create my own website on Django, but some problems stop me and I can't solve them myself. I want to create a sidebar. I found a website with css and HTML code for it. style.css: @import url('https://fonts.googleapis.com/css?family=Montserrat:600|Open+Sans:600&display=swap'); *{ margin: 0; padding: 0; text-decoration: none; } .sidebar{ position: fixed; width: 240px; left: -240px; height: 100%; background: #1e1e1e; transition: all .5s ease; } .sidebar header{ font-size: 28px; color: white; line-height: 70px; text-align: center; background: #1b1b1b; user-select: none; font-family: 'Montserrat', sans-serif; } .sidebar a{ display: block; height: 65px; width: 100%; color: white; line-height: 65px; padding-left: 30px; box-sizing: border-box; border-bottom: 1px solid black; border-top: 1px solid rgba(255,255,255,.1); border-left: 5px solid transparent; font-family: 'Open Sans', sans-serif; transition: all .5s ease; } a.active,a:hover{ border-left: 5px solid #b93632; color: #b93632; } .sidebar a i{ font-size: 23px; margin-right: 16px; } .sidebar a span{ letter-spacing: 1px; text-transform: uppercase; } #check{ display: none; } label #btn,label #cancel{ position: absolute; cursor: pointer; color: white; border-radius: 5px; border: 1px solid #262626; margin: 15px 30px; font-size: 29px; background: #262626; height: 45px; width: 45px; text-align: center; line-height: 45px; transition: all .5s ease; } label #cancel{ opacity: 0; visibility: hidden; } #check:checked ~ .sidebar{ left: 0; } #check:checked ~ label #btn{ margin-left: … -
Why boto3 dose not recognize my AWS_ACCESS_KEY_ID in Django on EC2?
I was connecting the S3 to Django on EC2. I confirmed that it works on the my computer (window), but when I uploaded it to AWS EC2 Ubuntu and ran it, I saw the following message. when i ran python manage.py commands File "/home/ubuntu/django/e/lib/python3.6/site-packages/botocore/session.py", line 821, in create_client aws_secret_access_key)) **botocore.exceptions.PartialCredentialsError: Partial credentials found in explicit, missing: aws_secret_access_key** But I think I set it up correctly. in my settings.py AWS_S3_HOST = 's3.me-south-1.amazonaws.com' AWS_S3_REGION_NAME= config('AWS_S3_REGION_NAME') AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_kEY = config('AWS_SECRET_ACCESS_kEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') I tried Give IAM permission on EC2 Delete EC2 retry set env var via export throw away virtualenv and try install awscli and configure it s3 bucket policy configure tried to write it inline because it might not be able to refer to the .env file, but it gave me same message. I struggled with this problem all day today. When it comes to AWS Config, I think I've tried everything I can. If you have any guesses about the cause of this problem, please give me a hint. And I only think boto3 looks up keys in a peculiar way on EC2 -
django what is best way to handle Exception in views
I have like 15 views , I dont want to add try, except for every view . Should I create a middleware or decorator or mixins or something else for error handling ? -
alternative option of blank=True in django model
I want to have a ForeignField that can be null some times depending on a BooleanField. so is this necessary to make it blank=true. Explaning the requirement: I have in models.py class InfaUsers(models.Model): first_name = models.CharField(max_length=30, default=None, null=True) last_name = models.CharField(max_length=30, default=None, null=True) ...[some more fields]... class DisputeUserRole(models.Model): corporate_party = models.ForeignKey(CorporatePartyNames, on_delete=models.CASCADE, default=None, null=True) party_name = models.CharField(max_length=100, default=None, null=True) is_individual = models.BooleanField(default=True) infa_user = models.ForeignKey(InfaUsers, on_delete=models.CASCADE) role = models.ForeignKey(UserRoles, on_delete=models.CASCADE) dispute = models.ForeignKey(Disputes, on_delete=models.CASCADE) ...[some more fields]... class CorporatePartyNames(models.Model): name = models.CharField(max_length=100, default=None, null=True) is_added_by_infa_user = models.BooleanField(default=True) ...[some more fields]... class DisputeUserRole(models.Model): corporate_party = models.ForeignKey(CorporatePartyNames, on_delete=models.CASCADE, default=None, null=True) # can not make it blank=True because of some api, which may go in fault. party_name = models.CharField(max_length=100, default=None, null=True) is_individual = models.BooleanField(default=True) infa_user = models.ForeignKey(InfaUsers, on_delete=models.CASCADE) ...[some more fields]... in admin.py: class DisputeUserRoleInline(admin.TabularInline): model = DisputeUserRole form = DisputeUserRoleForm # fields = ['corporate_party', 'is_individual', 'address', 'nationality', # 'infa_user', 'is_added_by_infa_user', ] @admin.register(Disputes) class DisputesAdmin(admin.ModelAdmin): list_display = ('id', 'case_id', 'status', 'created_at') inlines = [ DisputeUserRoleInline, ] fields = ['is_new_case', 'case_id', 'claim_amount', 'type_of_dispute'] # list_filter = ('group', 'collection_type') form = DisputesForm class Meta: model = Disputes in forms.py: class DisputesForm(forms.ModelForm): class Meta: model = Disputes exclude = [] class DisputeUserRoleForm(forms.ModelForm): full_name = forms.CharField(required=False) # … -
Gunicorn , no module named mysite.wsgi
I tried to configure gunicorn but i'm an error i can't solve. I looked around to see, but no issue ... I think it's a simple trick , if you can help me I based my configuration on this tutorial here I started on a brand new installation , so folder are standard: -tripplanner | -my_env/ | -mysite/ | mysite/ | firstapp/ | manage.py when I'm on the Step 7 — Testing Socket Activation i got this error for sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2020-09-14 14:38:46 UTC; 10s ago Process: 7946 ExecStart=/home/debian/.local/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock mysite.wsgi:application Main PID: 7946 (code=exited, status=3) Sep 14 14:38:46 vps-06a05efe gunicorn[7946]: return _bootstrap._gcd_import(name[level:], package, level) Sep 14 14:38:46 vps-06a05efe gunicorn[7946]: File "<frozen importlib._bootstrap>", line 1006, in _gcd_import Sep 14 14:38:46 vps-06a05efe gunicorn[7946]: File "<frozen importlib._bootstrap>", line 983, in _find_and_load Sep 14 14:38:46 vps-06a05efe gunicorn[7946]: File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked Sep 14 14:38:46 vps-06a05efe gunicorn[7946]: ModuleNotFoundError: No module named 'mysite.wsgi' Sep 14 14:38:46 vps-06a05efe gunicorn[7946]: [2020-09-14 14:38:46 +0000] [7950] [INFO] Worker exiting (pid: 7950) Sep 14 14:38:46 vps-06a05efe gunicorn[7946]: [2020-09-14 14:38:46 +0000] [7946] [INFO] … -
Django data migration fails unless it's run separately
I've run into this a couple other times and can't figure out why it happens. When I run the migrations all together through ./manage.py migrate then the last migration (a data migration) fails. The solution is to run the data migration on it's own after the other migrations have been completed. How can I run them all automatically with no errors? I have a series of migrations: fulfillment/0001.py order/0041.py (dependency: fulfillment/0001.py) order/0042.py order/0043.py I followed this RealPython article to move a model to a new app which which works perfectly and is covered by migrations #1 to #3. Migration #3 also adds a GenericForeignKey field. Migration #4 is a data migration that simply populates the GenericForeignKey field from the existing ForeignKey field. from django.db import migrations, models def copy_to_generic_fk(apps, schema_editor): ContentType = apps.get_model('contenttypes.ContentType') Order = apps.get_model('order.Order') pickup_point_type = ContentType.objects.get( app_label='fulfillment', model='pickuppoint' ) Order.objects.filter(pickup_point__isnull=False).update( content_type=pickup_point_type, object_id=models.F('pickup_point_id') ) class Migration(migrations.Migration): dependencies = [ ('order', '0042'), ] operations = [ migrations.RunPython(copy_to_generic_fk, reverse_code=migrations.RunPython.noop) ] Running the sequence together I get an error: fake.DoesNotExist: ContentType matching query does not exist. If I run the migration to order/0042.py then run order/0043.py everything works properly. How can I get them to run in sequence with no errors? -
import OAuth2Authentication ImportError: No module named 'oauth2_provider.ext'
I'm trying to login by Facebook in my python projcet .it keeps telling me that ImportError: No module named 'oauth2_provider.ext' whenever I migrate it using terminal my installed using pip freeze : certifi==2020.6.20 cffi==1.14.2 chardet==3.0.4 cryptography==3.1 defusedxml==0.7.0rc1 dj-database-url==0.5.0 Django==2.2.16 django-braces==1.14.0 django-oauth-toolkit==1.3.2 django-oauth2==3.0 django-rest-framework-social-oauth2==1.0.4 djangorestframework==3.11.1 gunicorn==19.6.0 idna==2.10 oauthlib==3.1.0 Pillow==3.3.0 pycparser==2.20 PyJWT==1.7.1 python-social-auth==0.3.6 python3-openid==3.2.0 pytz==2020.1 requests==2.24.0 requests-oauthlib==1.3.0 shortuuid==1.0.1 six==1.15.0 social-auth-app-django==1.1.0 social-auth-core==3.3.3 sqlparse==0.3.1 urllib3==1.25.10 whitenoise==3.2.1 and requirements.txt file contains: Django==1.10 gunicorn==19.6.0 Pillow==3.3.0 whitenoise==3.2.1 dj-database-url==0.5.0 psycopg2==2.7.5 django-rest-framework-social-oauth2==1.0.4 and my runtime.txt file : python-3.5.2 and the code I used to login by Facebook from the site I used in settings.py in INSTALLED_APPS = [.., 'oauth2_provider', 'social_django', 'rest_framework_social_oauth2', ] TEMPLATES = [ ..., 'OPTIONS': {..., 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', 'rest_framework_social_oauth2.backends.DjangoOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_FACEBOOK_KEY = '355645928947054' SOCIAL_AUTH_FACEBOOK_SECRET = 'c606775c70e7dc01626ee41cbf95a0b8' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id, name, email' } and in urls.py : in urlpatterns = [... , .., url(r'^api/social/', include('rest_framework_social_oauth2.urls')), ] -
Form in django not saving in Psql
Sorry I am learning Django and this is my first project. I want to allow the user to up/down vote others users post. I have a model. I am using postgresql as database, and I am able to create users, and was even able to create posts for each users, but when I added in my model Django the following vote fields: upVote = models.ManyToManyField(User, related_name="upvote") downVote = models.ManyToManyField(User, related_name="downvote") it just stopped saving users post in the database. It does not display any errors nothing, it just does not save. model.py from django.db import models from django.contrib.auth.models import User # Create your models here. from django.conf import settings class UserPost(models.Model): user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL ) title = models.CharField(max_length=250, blank=False) description = models.CharField(max_length=500, blank=False) images = models.ImageField( upload_to='post_pictures/', null=True, blank=True) videos = models.FileField(upload_to='post_videos/', null=True, blank=True) upVote = models.ManyToManyField(User, related_name="upvote") downVote = models.ManyToManyField(User, related_name="downvote") In the view.py the login and the registering works, but since I want to display all the post in the index I see nothing. Bc the DB is empty. @login_required(login_url='/login-page/') def personalPage(request): form = FormPost(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() messages.success(request, "Successfully created") return render(request, 'accounts/personal-page.html', … -
Upload a CSV file using AJAX in djngo
I want to upload a CSV file using ajax query. template: <form id="attendance-form" method="POST" enctype="multipart/form-data"> <input type="file" id="upload-attendance" name="employee-attendance-file"> </form> AJAX: $("#upload-attendance").change(function(e) { e.preventDefault(); // disables submit's default action var input = $("#upload-attendance")[0]; var employeeAttendanceFile = new FormData(); employeeAttendanceFile.append("attendance-file", $('#upload-attendance')[0].files[0]); console.log(employeeAttendanceFile); $.ajax({ url: '{% url "attendance:employee-attendance-upload" %}', type: 'POST', headers:{ "X-CSRFToken": '{{ csrf_token }}' }, data: { "employee_attendance_file": employeeAttendanceFile, }, dataType: "json", success: function(data) { data = JSON.parse(data); // converts string of json to object }, cache: false, processData: false, contentType: false, }); }); after uploading a CSV file, when I console.log the file(console.log(employeeAttendanceFile);) variable nothing return. When I fetch ajax request from django view, it(print(csv_file)) also returns None. views.py: class ImportEmployeeAttendanceAJAX( View): def post(self, request): csv_file = request.FILES.get("employee_attendance_file") print(csv_file) Where am I doing wrong? -
Django Private Channel - two users
I'm trying to build a channel. I'd like to restrict the detail views to consumer and seller. I don't want the other users have an access to the detail views. The thing is I can make it accessible to one but I don't know how to make it accessible for both consumer & seller? class Group(models.Model): consumer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="", blank=True, null=True) name = models.CharField(max_length=10) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="") ... def __str__(self): return self.name #Detail channel @method_decorator(login_required(login_url='/cooker/login'),name="dispatch") class CheckoutDetail(generic.DetailView): ... def get(self,request,*args,**kwargs): self.object = self.get_object() if self.object.consumer or self.object.seller != request.user: #it's redirect me to home page return HttpResponseRedirect('/') return super(CheckoutDetail, self).get(request,*args,**kwargs)