Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ERROR in src\containers\Login.js Line 35:5: Parsing error: Unexpected token (35:5)
Hello guys I'm new in React while watching a tutorial I'm getting this error and I checked it multiple times and compared it with the one in tutorial and can't find any difference. I'm trying to create a user authentication with Django and React. I'm using sublime text 3 as an editor and I have also Visual Studio Code installed. Should I install any extension to handle this problem? Can you help me with this parsing error? import React, { useState } from 'react'; import { Link, Redirect } from 'react-router-dom'; import { connect } from 'react-redux'; const Login = () => { const [formData, setFormData] = useState({ email: '', password: '' }); const { email, password } = formData; const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value }); const onSubmit = e => { e.preventDefault(); // login(email, password) }; // Is the user Authenticated? // Redirect them to the home page return ( <div className='container mt-5'> <h1> Sign in </h1> <p> Sign into your account </p> <form onSubmit={e => onSubmit(e)}> <div className='form-group' <input className='form-control' type='email' placeholder='Email' name='email' value={email} onChange={e => onChange(e)} required /> </div> <div className='form-group' <input className='form-control' type='password' placeholder='Password' name='password' value={password} onChange={e => onChange(e)} minLength='6' required /> … -
Django and Iyzco Integration
I am trying build e-commerce back-end system with Django. But I don't have any idea about the payment system. I researched for Iyzco tutorial for Django but couldn't find any halber things. So Can anybody suggest to me any tutorial or website or any course? -
'float' object is not iterable in django queryset
class TransactionHistoryListSerializer(serializers.BaseSerializer): class Meta: model = CustomerVisit def to_representation(self, instance): price = 0 package_price = booking_models.TestBooking.objects.filter(customer_visit=instance).values_list("package__test__test_mrp", flat=True)[0] for price in package_price: pass return{ 'visit_id':instance.id, 'customer_name':{ 'salutation':instance.customer.salutation, 'first_name':instance.customer.first_name, 'middle_name':instance.customer.middle_name, 'last_name':instance.customer.last_name}, 'dob':instance.customer.date_of_birth, 'amount':sum([k.amount for k in booking_models.TestBooking.objects.filter(customer_visit=instance)]) + (price if price else 0), 'discount': sum([k.discount for k in booking_models.TestBooking.objects.filter(customer_visit=instance)]), 'paid_amount': sum([k.amount for k in payment_models.Payment.objects.filter(customer_visit=instance)]) } here tes_mrp is float type. I searched and got solution to use list comprehension but still not working. I tried [[price] for price in package_price], for price in package_price: a = list(str(price)) but still getting float object is not iterable. Surely i am doing something wrong. Can somebody help. Thank you !! -
Accessing dictionary values in a list of dicts django
I have this code that translates my queryset into a list of dict groupmembers = GroupUser.objects.filter(group_id=group_id) memberlist = [] for member in groupmembers: user = User.objects.get(username=member.username) entry = { "username":user.username, "first_name":user.first_name, "last_name":user.last_name } memberlist.append(entry) How can I access each individual value in the list of dict? I tried to use: <ul> {% for key, value in memberlist.member %} <li>{{ member.username }} {{ member.first_name }} {{ member.last_name }}</li> {% endfor %} </ul> But it was raising an error, what's the appropriate code to use -
simpleJWT user has no 'id' attribute
I'm trying to use the simplejwt package for my django rest framework project. And I get an AttributeError saying my user model doesn't have a 'id' field which is true, because I have a userID field myself and I have set that to be the primary key. But I'm not referencing the 'id' field anywhere in my code and I would like to know how I could get this fixed. This is my code: #Serializers.py class UserTokenSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) token['userID'] = user.userID token['username'] = user.username token['email'] = user.email token['name'] = user.name token['balance'] = user.balance token['email_activation'] = user.emailActivation return token #Views.py class UserTokenView(TokenObtainPairView): serializer_class = UserTokenSerializer #models.py class User(AbstractBaseUser, PermissionsMixin): userID = models.AutoField(primary_key=True) username = models.CharField(max_length=100, unique=True, validators=[RegexValidator(regex="^(?=[a-z0-9._]{5,20}$)(?!.*[_.]{2})[^_.].*[^_.]$")]) email= models.EmailField(max_length=100, unique=True, validators=[EmailValidator()]) name = models.CharField(max_length=100) isSuspended = models.BooleanField(default=False) isAdmin = models.BooleanField(default=False) emailActivation = models.BooleanField(default=False) balance = models.IntegerField(default=0) objects = UserManager() USERNAME_FIELD = 'username' And this is the error I get when I user the token api: Internal Server Error: /api/token/ Traceback (most recent call last): File "C:\Users\Mohsen\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Mohsen\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Mohsen\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\Mohsen\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", … -
Django i18n issue for the post api urls
I am using i18n language URLs for one of my Django app and those URLs contain both post and get methods. before implementing i18n it was working fine and now started behaving strangely. I have an endpoint to which I post data but now when I try to post data into it I am getting response like Method \"GET\" not allowed. but when I try with default language It is working fine like when I append the language code it works. Ideally, it should take the default language if not specified in the URL right? -
Show only not None values in Django template
I have a Model with numerous attributes; in the template rendered by my DetailView I want to show only the attributes that are not None. This can be easily done with an if template tag that checks if the value of the attribute is not None, tho I should add an if condition for every attribute in my model, and there's a lot of them. I would like to iterate through all the attributes and if not None display them. In pseudo code it would look like this: {% for attribute in my_instance.all_attributes %} {% if attribute.value is not None %} {{attribute.value}} I can get a tuple of concrete attributes both through the class or the instance: cls._meta.concrete_fields or self._meta.concrete_fields Now that I have the my_instance.all_attributes in my pseudo code example, I can iterate it but I don't know how to get the actual value of the instance's attribute. -
How to create a custom serializer for a DRF APIView to retrieve list of entries instead of ids
I am creating an API for a picture labeling program. A picture (resource) can have labels or verified_labels - if more than one user entered a label for the same resource. I am trying to extend the program by adding taboo input. Taboo input means that these labels have been entered most frequently for a specific resource. Currently, my models are Resource, Label and VerifiedLabel. models.py class Resource(models.Model): id = models.PositiveIntegerField(null=False, primary_key=True) hash_id = models.CharField(max_length=256) creators = models.ManyToManyField(Creator) titles = models.ManyToManyField(Title) created_start = models.DateField(null=True) created_end = models.DateField(null=True) location = models.CharField(max_length=512, null=True) institution_source = models.CharField(max_length=512, blank=True) institution = models.CharField(max_length=512, blank=True) origin = models.URLField(max_length=256, null=True) enabled = models.BooleanField(default=True) media_type = models.CharField(max_length=256, default='picture') objects = models.Manager() def __str__(self): return self.hash_id or '' @property def verified_labels(self): verified_labels = self.labels.values('verified_label').annotate(count=Count('label')) return verified_labels.values('verified_label_id', 'verified_label__name', 'verified_label__language', 'count') class VerifiedLabel(models.Model): name = models.CharField(max_length=256) language = models.CharField(max_length=256) objects = models.Manager() def __str__(self): return self.name or '' class Label(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True) gameround = models.ForeignKey(Gameround, on_delete=models.CASCADE) resource = models.ForeignKey(Resource, on_delete=models.CASCADE, related_name='labels') verified_label = models.ForeignKey(VerifiedLabel, on_delete=models.CASCADE) created = models.DateTimeField(editable=False) score = models.PositiveIntegerField(default=0) origin = models.URLField(max_length=256, blank=True, default='') objects = models.Manager() def __str__(self): return str(self.verified_label) or '' def save(self, *args, **kwargs): if not self.id: self.created = timezone.now() return super().save(*args, **kwargs) … -
How To Used Freeradius Exiting Django Project?
I am Try to used Free Radius For My Project I Want To used FreeRadius In exiting Django Project I all ready config > Freeradius app in setting.py and also add url in url.py when i type > python manage.py in terminal i got this type of error how can i fiext > it please help me if any one know that.....*** [This Is The image][1] INSTALLED_APPS = [ 'django_freeradius', 'django_filters', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] DJANGO_FREERADIUS_API_TOKEN = 'L@x!nKh@TriJ@nveeKcJ@naki*&$' urlpatterns = [ path('admin/', admin.site.urls), path(r'^', include('django_freeradius.urls', namespace='freeradius')), ] -
Django error "serviceworker" must be a dictionary in your web app manifest
I have done razorpay payment integration and when I click the payment procced button it throws an console error "serviceworker" must be a dictionary in your web app manifest. pay.html <html> <head> <title>Pay</title> </head> <body> <button id="rzp-button1">Pay</button> <script src="https://checkout.razorpay.com/v1/checkout.js"></script> <script> var options = { "key": "{{key_id}}", // Enter the Key ID generated from the Dashboard "amount":"{{amount}}", // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise "currency": "INR", "name": "Acme Corp", "description": "Test Transaction", "image": "https://example.com/your_logo", "order_id": "{{order_id}}", //This is a sample Order ID. Pass the `id` obtained in the response of Step 2 "handler": function (response){ alert(response.razorpay_payment_id); alert(response.razorpay_order_id); alert(response.razorpay_signature) }, "prefill": { "name": "Gaurav Kumar", "email": "gaurav.kumar@example.com", "contact": "9999999999" }, "notes": { "address": "Razorpay Corporate Office" }, "theme": { "color": "#3399cc" } }; var rzp1 = new Razorpay(options); rzp1.on('payment.failed', function (response){ alert(response.error.code); alert(response.error.description); alert(response.error.source); alert(response.error.step); alert(response.error.reason); alert(response.error.metadata.order_id); alert(response.error.metadata.payment_id); }); document.getElementById('rzp-button1').onclick = function(e){ rzp1.open(); e.preventDefault(); } </script> </body> </html> I have attached an image below. image for reference I know this question been asked before but none of the solutions have helped me solve the problem. -
How to prevent your fields name in your form.py, to display on your form after using 'as_cripsy_field' on your template
How do i stop my fields name in my form.py, from displaying as a label on my form after using as_cripsy_field on my template in an input field. example: {{form.fieldname|as_cripsy_field}} -
Can't get Cronjob to work on Elastic beanstalk in Django project
I have been trying for couple of days. Gone through lots of articles and many StackOverflow posts but nothing worked. I have deployed a django project on elastic beanstalk. I have a command that I want to run every hour. I have 3 .config files in .ebextensions dir django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: project/wsgi.py db-migrate.config container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate" leader_only: true 02_process_cron: command: "cat .ebextensions/crontab.txt > /etc/cron.d/crontab && chmod 644 /etc/cron.d/crontab" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: project.settings crontab.txt * * * * * source /opt/python/run/venv/bin/activate && cd /opt/python/current/app/ && source /opt/python/current/env && python3 manage.py my_process >> /var/log/myjob.log 2>&1 For testing purpose I have cronjob for every minute I am not finding any myjob.log file when downloaded the full logs from elastic beanstalk. My application is always on Degraded status. and it just saying Following services are not running: release.. I don't even have anything with name release Why does AWS have to make simple processes harder to do. I mean on heroku running a django cronjob is just one adding a command and that's it. would appreciate any help. thanks in advanced. -
Create URL for detailview using DRF Modelviewset
i'm using DRF modelviewset to create an api for users model. Can anyone explain or help how can I pass a url in react-native for the detailview of user. Right now i'm getting the detailview in this manner 127.0.0.1:8000/users/users/2/. But everytime i don't want to pass the id in the url. models.py class User(AbstractUser): """This Class is used to extend the in-build user model """ ROLE_CHOICES = (('CREATOR','CREATOR'),('MODERATOR','MODERATOR'),('USERS','USERS')) GENDER_CHOICES = (('MALE','MALE'),('FEMALE',"FEMALE"),('OTHER','OTHER')) date_of_birth = models.DateField(verbose_name='Date of Birth', null=True) profile_image = models.ImageField(upload_to='media/profile_images', verbose_name='Profile Image', default='media/profile_images/default.webp', blank=True) bio = models.TextField(verbose_name='Bio') role = models.CharField(max_length=10, verbose_name='Role', choices=ROLE_CHOICES, default='USERS') gender = models.CharField(max_length=6, verbose_name='Gender', choices=GENDER_CHOICES) serializers.py class UserSerializer(serializers.ModelSerializer): following = serializers.SerializerMethodField(read_only=True) followers = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ('first_name','last_name','username','password','email','date_of_birth', 'profile_image','bio','role','gender', 'following','followers') extra_kwargs = {'is_active':{'write_only':True}, 'password':{'write_only':True}} def create(self, validated_data): logger.info('Information Stored!') return User.objects.create_user(**validated_data) def update(self, *args, **kwargs): user = super().update( *args, **kwargs) p = user.password user.set_password(p) user.save() return user views.py class UserAPI(viewsets.ModelViewSet): serializer_class = UserSerializer # permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] def get_queryset(self): users = User.objects.all() return users urls.py router = DefaultRouter() router.register('users', views.UserAPI, basename='users'), router.register('following', views.FollowingAPI, basename='following'), urlpatterns = router.urls How can i solve this. Need your help please. Thank you -
Displaying different content depending on which title it has
I am creating a django application with classed based views. In the detail view, I want depending on the title the object has, show different content. I don't understand why the if statement does not work. The data in the example is just dummy data right now because it is in the production stage. This shows the detail view I have created. {% extends 'main.html' %} {% block content %} <div class="container px-5"> {{object.title}} {% if object.title == 'hello' %} {% include 'x/y.html' %} {% endif %} </div> {% endblock content %} Does anybody know how I can fix this? -
How to attach a file from an url with django weasyprint?
I'm trying to attach a file from an url with django and weasyprint, django-weasyprint The pdf view: class OrdineDetailView(LoginRequiredMixin, DetailView): model = Ordine def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["merce"] = OrdineMerce.objects.filter(ordine=kwargs.get("object")) return context class OrdinePrintView(WeasyTemplateResponseMixin, OrdineDetailView): # output of MyDetailView rendered as PDF with hardcoded CSS pdf_stylesheets = [ settings.STATIC_ROOT / "ordini/ordine.css", ] # show pdf in-line (default: True, show download dialog) pdf_attachment = True Then I have an api endpoint that when hit it sends an email. class InviaOrdineView(APIView): def get(self, request, pk): pdf_url = f"{settings.PROTOCOL}gestione.{settings.PARENT_HOST}/ordini/{pk}/pdf/" url = urllib.request.urlopen(pdf_url) pdf = url.read() mail = EmailMessage( "Ordine merce", "Con questa vi ordiniamo la merce che trovate in allegato a questa email.", settings.DEFAULT_FROM_EMAIL, [settings.DEFAULT_FROM_EMAIL, email_fornitore], ) mail.attach("ordine.pdf", pdf, "application/pdf") mail.send() The email is sent but the attachment cannot be read. How to attach a file via url? -
Retrieve data from external api and show in django admin panel
How to display data from external service in Django admin?Rather than querying a local database I would like to use an external API to retrieve the data to display in the django admin class Order(models.Model): service = models.ForeignKey('Service', on_delete=models.CASCADE, related_name='orders') number = models.CharField(...) creation_date = models.DateTimeField(...) ... @register(Order,site=admin_site) class OrderAdmin(ImportExportMixin, SimpleHistoryAdmin): Perform the API call instead of the database lookup and show data from API in orders model in admin panel. Is there any way to achieve this -
Python add when entries have the same name
I have a model with the registered sales of a publishing house.with the following code, I can get the name of the book and the quantity the client bought: a=Sale.objects.all() for b in a: print(str(b.book) + ' ' + str(b.quantity)) So I get something like this: Del mismo modo en el sentido contrario 15 Sobre el horror 1 Del mismo modo en el sentido contrario 5 Del mismo modo en el sentido contrario 2 Un lápiz labial para una momia 1 La cólera en los tiempos del amor 3 La cólera en los tiempos del amor 1 La cólera en los tiempos del amor 1 El tambor encantado 1 What I need now is a loop so every entry that has the same book name, sum or add that quantity number. Any ideas on how to accomplish this? -
How to override the default wagtail page slug
I'm trying to make a wagtail pages for the astrologer based on category, country and city. And my url's are: https//localhost:8080/<category> https//localhost:8080/<category>/<country> https//localhost:8080/<category><country>/<city> If I am trying to save the url with '/' forward slash then it removing the '/' form the slug and saving it as a string. Ex: <category><country>/<city> to categorycountrycity So Is it possible to override the wagtail default page slug type 'SlugField' to 'CharField'. or is there any other solution ? -
Django with GDAL throwing error when deploying on Heroku
When I deploy my Django app with Heroku there seems to be some problem with GDAL. When I run heroku logs --tail I get the following: [...] 2022-01-14T11:20:56.792392+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/base.py", line 6, in <module> 2022-01-14T11:20:56.792393+00:00 app[web.1]: from .features import DatabaseFeatures 2022-01-14T11:20:56.792393+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/features.py", line 1, in <module> 2022-01-14T11:20:56.792394+00:00 app[web.1]: from django.contrib.gis.db.backends.base.features import BaseSpatialFeatures 2022-01-14T11:20:56.792394+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/gis/db/backends/base/features.py", line 3, in <module> 2022-01-14T11:20:56.792394+00:00 app[web.1]: from django.contrib.gis.db import models 2022-01-14T11:20:56.792395+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/gis/db/models/__init__.py", line 3, in <module> 2022-01-14T11:20:56.792395+00:00 app[web.1]: import django.contrib.gis.db.models.functions # NOQA 2022-01-14T11:20:56.792395+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/gis/db/models/functions.py", line 3, in <module> 2022-01-14T11:20:56.792396+00:00 app[web.1]: from django.contrib.gis.db.models.fields import BaseSpatialField, GeometryField 2022-01-14T11:20:56.792401+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/gis/db/models/fields.py", line 3, in <module> 2022-01-14T11:20:56.792401+00:00 app[web.1]: from django.contrib.gis import forms, gdal 2022-01-14T11:20:56.792402+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/gis/forms/__init__.py", line 3, in <module> 2022-01-14T11:20:56.792402+00:00 app[web.1]: from .fields import ( # NOQA 2022-01-14T11:20:56.792402+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/gis/forms/fields.py", line 2, in <module> 2022-01-14T11:20:56.792402+00:00 app[web.1]: from django.contrib.gis.gdal import GDALException 2022-01-14T11:20:56.792403+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/gis/gdal/__init__.py", line 28, in <module> 2022-01-14T11:20:56.792406+00:00 app[web.1]: from django.contrib.gis.gdal.datasource import DataSource 2022-01-14T11:20:56.792407+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/gis/gdal/datasource.py", line 40, in <module> 2022-01-14T11:20:56.792407+00:00 app[web.1]: from django.contrib.gis.gdal.driver import Driver 2022-01-14T11:20:56.792407+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/gis/gdal/driver.py", line 5, in <module> 2022-01-14T11:20:56.792407+00:00 app[web.1]: from django.contrib.gis.gdal.prototypes import ds as vcapi, raster as rcapi 2022-01-14T11:20:56.792408+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/gis/gdal/prototypes/ds.py", line 9, in <module> 2022-01-14T11:20:56.792408+00:00 app[web.1]: … -
How to hide specific field by User Group on a django admin
i want to hide a specific line of my Django Admin Model by permission or Group My models.py Model My django admin page Django admin page If someone has an idea -
Why am I getting "ValueError: The following fields do not exist in this model or are m2m fields: last_login" this error
I am writing a unit test for a website, the website has many permissions. Here is the code of my unit test from django.test import TestCase from accounts.models import Address, User, Business, Employment class Test_Cases(TestCase): def setUp(self): self.user = User.objects.create_superuser( birth_year=1996, birth_month= 8, birth_day = 15, marital_status= "married", \ confirmation_token = "55zr2xYflgSiz18dhBAk1Qqswb70ckmZ", email= "testuser1234@example.com", \ username = "testusera11123", password= "abc123") self.address = Address.objects.create(city="oslo", state="Norway", street_1="112 Main", street_2="113 Main", zip="54000") self.business = Business.objects.create(address=self.address, name="NoorLimited", contact_email="work@bitspro.com", \ contact_first_name= "Business", contact_last_name= "Admin") self.employer= Employment.objects.create(role="ADMIN", user=self.user, business=self.business, active=True) def test_get_business(self): self.client.force_login(self.employer) API_LOGIN_URL = '/business/1/roster/' response= self.client.get(API_LOGIN_URL) self.assertEquals(response.status_code, 200) the "Get_business" code has "Business_admin" permission Here is the code def needs_business_admin(wrapped): @wraps(wrapped) def decorator(*args, **kwargs): business = kwargs.get("business") request = [a for a in args if hasattr(a, 'user')][0] try: Employment.objects.get( role=ADMIN, user=request.user, business=business, active=True) except Employment.DoesNotExist: return BaseView(request).forbidden() return wrapped(*args, **kwargs) return decorator here is url that I am testing url(r'^business/(?P<business>[^/]+)/roster/?$', BusinessRosterController()), and I am getting this error PS C:\Users\Lenovo\web> docker-compose run --rm api sh -c "python manage.py test accounts" Creating encastweb_api_run ... done Creating test database for alias 'default'... System check identified some issues: ====================================================================== ERROR: test_get_business (accounts.tests.Test_Cases) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/src/app/web/accounts/tests.py", line 24, in test_get_business self.client.force_login(self.employer) File "/usr/local/lib/python3.8/site-packages/django/test/client.py", line … -
How can I Set Video Durations And Video Type in python
I created an app where user can post a video, how can I set the video durations ? I mean: I don't a user to post a video that are more than 3 minutes and i want a video type to be .mp4 if it's not an .mp4 i want to throw the error message saying: ('we accepts only .mp4 file'). How can I do this in django. does that possible in django or should I go for JavaScripts to archive that ? this is my addvideo views: def addvideo(request): if request.method == 'POST': file = request.FILES.get('video') videos = Video.objects.create( file=file ) return redirect('home') return render(request, 'addvideo.html') this is my home views: def home(request): videos = Video.objects.all() return render(request, 'home.html', {'videos': videos}) this is my addvideo template: <div class="container"> <div class="row justify-content-center"> <div class="col-md-5"> <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="card"> <div class="form-group m-3"> <label>Upload Your Video</label><br><br> <input required name="video" type="file" class="form-control-file"> </div> <button type="submit" class="btn btn-primary">Post</button> </div> </form> </div> </div> </div> this is my home templates: <div class="container"> {% for video in videos %} <div class="row justify-content-center"> <video controls src="{{video.file.url}}"></video> </div> {% endfor %} </div> this is my models.py: class Video(models.Model): file = models.FileField(upload_to='file', null=False, blank=False) -
How to properly set up Viber bot in Python (Django)
I'm an absolute beginner in Viber bot, and I can't make my bot send a Welcome (or any other) message to the user, even if he has subscribed to my Viber bot account. I have tried all of the tutorials that I have found on the internet, read Viber Bot Python and REST documentation, some tutorials that I've found on github like this and this and every code possibility that has come to my mind - but I still couldn't make it to work. I have a website domain with SSL (Let's Encrypt) and everything should be fine. Also, I have used Postman to set a Webhook and received status 0 (ok), so users now can connect to my bot and message him. Here is what I've got so far views.py (django) from viberbot import Api from viberbot.api.bot_configuration import BotConfiguration from viberbot.api.messages.text_message import TextMessage from viberbot.api.messages.data_types.contact import Contact from viberbot.api.viber_requests import ViberConversationStartedRequest from viberbot.api.viber_requests import ViberFailedRequest from viberbot.api.viber_requests import ViberMessageRequest from viberbot.api.viber_requests import ViberSubscribedRequest from viberbot.api.viber_requests import ViberUnsubscribedRequest from django.views.decorators.csrf import csrf_exempt logger = logging.getLogger() logger.setLevel(logging.DEBUG) handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) viber = Api(BotConfiguration( name='MyBotName', avatar='https://someavatar.com/avatar.jpg', auth_token='mytoken' )) def hook(request): logger.debug("received … -
how to share user session between subdomains?
i have 1 website on auth.mydomain.com and another as home.mydomain.com i want to use auth.mydomain.com for authentication only and after authentication user will get redirect to home.mydomain.com with auth.mydomain.com session cookie . the whole idea is i want to use auth.mydomain.com to authenticate users from my all subdomains *.mydomain.com in Django documentation i found SESSION_COOKIE_DOMAIN but i am not sure how to use it documentation shows it shares cookie only if its authenticated with base domain like mydomain.com anyone got idea how to solve this ?? -
How to get Images from AJAX and save it to Django
I'm trying to get an image with AJAX and save it to my django model. However, I can not see 'photo' variable that AJAX returns in the terminal although other variables (csrf, name...) are in there. So I can not process with 'photo' field and save it. there is the querydict that I received from AJAX. csrf and name is in there but no 'photo' variable. *** request.POST: <QueryDict: {'csrfmiddlewaretoken': ['krnIBkcYUb1breFjMyoReCwXeH9DLFc1Pvg2x1U2SGZSxPxQSLOwOxs1aSMrvBkf'], 'name': ['fgdfdsfsdf']}> js script var clientCreateForm = document.getElementById('client-create-form') var csrf = document.getElementsByName('csrfmiddlewaretoken') var client_name = document.getElementById('name') var image = document.getElementById('photo') clientCreateForm.addEventListener('submit', e => { e.preventDefault() console.log('submitted') var resim = image.files[0] console.log(resim) var fd = new FormData() fd.append('csrfmiddlewaretoken', csrf[0].value) fd.append('name', client_name.value) fd.append('photo', resim) $.ajax({ type:'POST', url:'/clients/', enctype: 'multipart/form-data', data: fd, contentType: false, processData: false, success: function (response) { window.location.replace(response.instance_url) }, error: function (error) { console.log("An error occurred") } }) }) views.py def post(self, request, *args, **kwargs): if is_ajax(request=request): # if request.method == "POST": print("*** request.POST: ", request.POST) my_name = request.POST.get('name') my_foto = request.POST.get('photo') new_client = models.Client.objects.create(owner=self.request.user, name=my_name, sector=my_sector, foto=my_foto) new_client.save() slug = new_client.slug return JsonResponse({'instance_url': slug}) return redirect('action-listview')