Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get user's phone number from python social auth(google-oauth2)
I use python social auth and django rest framework. I want to fetch the user phone number. Settings SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = config('GOOGLE_ID') SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = config('GOOGLE_SECRET') SOCIAL_AUTH_RAISE_EXCEPTIONS = False SOCIAL_AUTH_USER_MODEL = 'users.TransUser' SOCIAL_AUTH_GOOGLE_OAUTH2_USER_FIELDS = ['email', 'firstname', 'lastname', 'phone_number'] SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/user.phonenumbers.read', 'profile', 'email', ] Ouput {'access_token': 'xxxxxxxx', 'email': 'xxxxxxxx, 'email_verified': True, 'expires_in': 3582, 'family_name': 'xxxxxxx', 'given_name': 'xxxxx', 'id_token': 'xxxxxx', 'locale': 'es', 'name': 'xxxxxxx', 'picture': 'xxxxx', 'scope': 'https://www.googleapis.com/auth/userinfo.email ' 'https://www.googleapis.com/auth/user.phonenumbers.read ' 'https://www.googleapis.com/auth/userinfo.profile openid', 'sub': 'xxxxxx', 'token_type': 'Bearer'} but never phone number. I use user's phone number to registration it. I activated people APi in google console. Thx you -
django with postfix doesn't send email and doesn't raise an error
i have configured postfix as a null client on my machine and the configuration also seems to be working, as $ echo "test" | mail -s "test" -r "sender@domain.com" recipient@domain.com successfully delivers the email. however if i try to use it with django with the following settings: EMAIL_HOST = "localhost" EMAIL_PORT = 25 EMAIL_HOST_USER = "" EMAIL_HOST_PASSWORD = "" DEFAULT_FROM_EMAIL = "sender@domain.com" SERVER_EMAIL = "sender@domain.com" the process get's stuck without an error being raised: from django.core.mail import send_mail from django.conf import settings send_mail(subject="test", message="test", from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=["recipient@domain.com"]) i can't figure out why this function get's stuck, the /var/log/mail.log file is also empty. Edit: Note, that sender@domain.com and recipient@domain.com are both valid adresses but i replaced them in this question. -
How to test if user can register and is redirected to home page?
I am writing tests in order to see if a user can register and if successful, is redirected to home page. I have created a class RegisterPageViewtest(TestCase): def setUp(self): self.register_url=reverse('register') self.user={ 'username':'username', 'password':'password', 'password2':'password', 'first_name':'first_name', 'last_name':'last_name', 'email':'email@gmail.com' } with a function: def test_user_can_register(self): response = self.client.post(self.register_url,self.user,format='text/html') self.assertEqual(response.status_code,302) However, when I run tests I get a response in a console: AssertionError: 200 != 302 How can I fix it? -
How To Make Every Fifth Post An Ad Post In Django
I am trying to allow users to sponsor a post to bring more clicks to there posts. I want to make every fifth post a post that is a sponsored post but if i try to just use divisible by in the templates and loop through ads then it will post all of the ads after the fifth post here is some code i have tried models: class Ad(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True) views: def home(request, pk): context = { 'products': Post.objects.all(), 'ads': Ads.objects.all(), } return render(request, 'new.html', context) templates i have tried but don't work: {% for item in products %} //prints products {% if forloop.counter|divisibleby:4 %} {% for i in ads %} {% with it = forloop.parent.loop.counter|div:4 %}//this will give error //prints ad post {% endwith %} {% endfor %} {% endif %} {% endfor %} -
I have a Validation error in my Django models.py file
I am making a table in Django with the models.py file and when I run the code it gives a validation error which goes like this: django.core.exceptions.ValidationError: ['“null” value must be either True or False.'] this is my models.py file from django.db import models class Users: id = models.IntegerField(primary_key=True) first_name = models.CharField(max_length=250) last_name = models.CharField(max_length=250) username = models.CharField(max_length=50) password = models.CharField(max_length=300) birthday = models.DateField(auto_now_add=False) date_created = models.DateTimeField(auto_now_add=True) terms_confirmed = models.BooleanField(default=False) I have tried commenting out the fields with boolean values along with singling out each line to see if it produces the error -
How to open bash_profile in windows 10
Can anyone please help me with this error bash: /c/Users/ADMIN/.bash_profile: No such file or directory I am doing this for the first time so need help to resolve this error. -
Django how to customize upload_to function
I created a system with Django. In this system a user has more than one customers. There is a customer list. A user can upload files to a customer's page. What I want to is the file should save in a file and path of this file should be customer_customername (For example: customer_Emily). But in my code created a file that name as customer_None. How can i fix it? file upload model and customer model are 2 different models that connecetd with a foreign key owner Pdf/models.py def customer_directory_path(instance, filename): return 'customer_{0}/{1}'.format(instance.id, filename) class Pdf(models.Model): CHOICES = [ ... ] STAT = [ ... ] id = models.AutoField(primary_key=True) title = models.CharField(max_length=200) pdf = models.FileField(upload_to=customer_directory_path) owner = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) customer/models.py class Customer(models.Model): customer_name = models.CharField(max_length=20) ... id = models.AutoField(primary_key=True) -
Set Selected Value In Html Dropdown List Option With Django Jinja Or Python
I want to set the default selected value from for loop in for loop using python or a jinja code with the if-else statement. {% for product in product %} <label>Supplier Name<span class="text-danger">*</span></label> <select class="form-control" name="fk_supplier"> <option>-- Select Supplier Name --</option> {% for supplier in supplier %} {% if supplier.supplier_name == product.fk_supplier %} <option value="{{supplier.pk}}" selected>{{supplier.supplier_name}}</option> {% else %} <option value="{{supplier.pk}}">{{supplier.supplier_name}} {{product.fk_supplier}} </option> {% endif %} {% endfor %} </select> {% endfor %} -
avoid html button being clicked again before it disapears (django)
I'm working in a Django project which has events that can be joined by users (adding the user_id and event_id to a model attend), In my event I have a join button form that when clicked adds the attend, after clicking the button disappears and appears a new button called leave event and the opposite. All this works, when the user joins or leaves the event page reloads. The problem I'm having is that I'm able to click the button 2 times in a row before the button disappears getting an error because it is trying to add an attend object that already exists or delete an object that does not exist. So my question is if there is a way to avoid the user clicking two times the button so it is not sending a POST request 2 times, or at least if he clicks it again before it disappears not sending a request. Here the javascript to show the join or leave button which is executed when the page is loaded or either button is clicked (I first looked in the list of attendants if the logged user is attending, because I didn't find a way to query … -
Comments are not saving from frontend in django
Hi everyone the comments are not working with CBV my form not even saving the comment. here is my code i will love if anyone help me with this.my models.py is class Product(models.Model): title = models.CharField(max_length=110) slug = models.SlugField(blank=True, unique=True) price = models.DecimalField(decimal_places=2, max_digits=6) discount_price=models.FloatField(blank=True, null=True) size = models.CharField(choices=SIZE_CHOICES, max_length=20) color = models.CharField(max_length=20, blank=True, null=True) image = models.ImageField(upload_to=upload_image_path) description = models.CharField(max_length=1000) featured = models.BooleanField(default=False) author = models.ForeignKey(User, on_delete=models.CASCADE) time_stamp = models.DateTimeField(auto_now_add=True) objects=ProductManager() def get_absolute_url(self):#i use this in product_list.html to go to detail page #return "/product/{slug}".format(slug=self.slug) return reverse("products:detail", kwargs={"slug" : self.slug}) def __str__(self): return str(self.title) @property def name(self): #sometime in html i say name istead of title so to make it work i wrote this return self.title def product_pre_save_reciever(sender, instance, *args, **kwargs):#i inherit unique slug generator from utils to here so when i create aa new instance it slug automatically generate. and i i create two t shirts it give a random straing to tshirt 2nd slug if not instance.slug: instance.slug=unique_slug_generator(instance) pre_save.connect(product_pre_save_reciever, sender=Product) class Comment(models.Model): product=models.ForeignKey(Product , related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=255) body=models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s'%(self.product.title, self.name) my forms.py is: from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment … -
Django button in admin
On user form view, add button "Login As", that button will execute functionality that we login as that user. Only admins can see/execute this functionality. This is my question, how this to make? -
How to create breadcrumb in my view function BY mptt
How to create breadcrumb in my view function? class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') slug = models.SlugField( null=True, blank=True) description = models.TextField(null=True, blank=True) image = models.ImageField( upload_to=user_directory_path, default='posts/default.jpg') def get_absolute_url(self): return reverse('Category:post_single', args=[self.slug]) class Meta: ordering = ('-name',) def __str__(self): return self.name class Post(models.Model): class NewManager(models.Manager): def get_queryset(self): return super().get_queryset() .filter(status='published') options = ( ('draft', 'Draft'), ('published', 'Published'), ) category = TreeForeignKey('Category', on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=250) excerpt = models.TextField(null=True) image = models.ImageField( upload_to='uploads/', default='posts/default.jpg') image_caption = models.CharField(max_length=100, default='Photo by Blog') slug = models.SlugField(max_length=250, unique_for_date='publish') publish = models.DateTimeField(default=timezone.now) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='blog_posts') content = models.TextField() status = models.CharField( max_length=10, choices=options, default='published') favourites = models.ManyToManyField( User, related_name='favourite', default=None, blank=True) likes = models.ManyToManyField( User, related_name='like', default=None, blank=True) like_count = models.BigIntegerField(default='0') views = models.PositiveIntegerField(default=0) thumbsup = models.IntegerField(default='0') thumbsdown = models.IntegerField(default='0') thumbs = models.ManyToManyField(User, related_name='thumbs', default=None, blank=True) objects = models.Manager() # default manager newmanager = NewManager() # custom manager def get_absolute_url(self): return reverse('blog:post_single', args=[self.slug]) class Meta: ordering = ('-publish',) def __str__(self): return self.title #views def post_single(request, post): post = get_object_or_404(Post, slug=post, status='published') postcat = Post.objects.filter(category=post.category) fav = bool if post.favourites.filter(id=request.user.id).exists(): fav = True allcomments = post.comments.filter(status=True) page = request.GET.get('page', 1) paginator = Paginator(allcomments, 10) … -
Django SearchVector postgres searchvector not saving correct strings
The postgres SearchVector in Django seems to be shortening my strings, I dont understand why. Ive shortened the code below to show what is happening. I am querying a person object with a lastname that is added to the SearchVector. from django.contrib.postgres.search import SearchVector self.model.objects.annotate( search=SearchVector( "last_name" ) ).filter(search__icontains="hjer").first().search reults in: "'hjerp':1" But the last_name is actually: self.model.objects.annotate( search=SearchVector( "last_name" ) ).filter(search__icontains="hjer").first().last_name 'Hjerpe' Why is the e not present in the search string? I would expect search above to show: "'hjerpe:1'" -
How to correctly migrate a Django application from SQL Lite to MySql database?
I am very new in Python and Django (I came from Java and Angular) and I am starting working on a Django project made by someone else. I studied Python and Django byt I have the following doubt about what could be a good approach to solve the following problem. This Django application it is using SQL Lite as database. First thing that I have to do is to change RDBMS in order to use MySql instead SQL Lite. I know that, after the MySql installation, I have to change these lines form the settings.py file in order to point to my MySql installation: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } And now my doubt. At the moment my SQL Lite database contains some tables that came from the classes defined into my models.py file. I know that in theory these tables can be automatically generated on the new MySQL database using the migrations (the data are not important because these tables derived from the models at the moment are empty). But my SQL Lite database contains also some Django tables related to users, groups and permissions and some other tables automatically generated by Django. … -
How to Create custom permission classes?
models: class DoctorProfile(AbstractBaseUser, PermissionsMixin): id=models.AutoField(primary_key=True) name = models.CharField(_('name'), max_length=50, blank=True) mobile = models.CharField(_('mobile'), unique=True, max_length=10, blank=False) # mobile= models.CharField(primary_key=True , max_length=10, validators=[RegexValidator(r'^\d{1,10}$')]) # mobile= models.IntegerField(validators=[MinValueValidator(10),MaxValueValidator(10)]) email = models.EmailField(_('email address'), blank=True) password = models.CharField(_('password'),max_length=25,blank=False) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_verified=models.BooleanField(default=False) is_active = models.BooleanField(_('active'), default=False) is_doctor = models.BooleanField(_('active'), default=False) otp = models.IntegerField(null=True, blank=True) dob=models.DateField() GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) How to Create custom permission for creating tasks ? eg: class ClinicRegistrationView(generics.ListCreateAPIView): serializer_class = ClinicSerializer queryset = Doctor_clinic.objects.all() permission_classes = (permissions.IsAuthenticated,)#token user can create How to give is_doctor permission ,only create task ?? -
Pylint does not ignore migrations
I use Pylint and run it via pre-commit hook. It doesn't ignore my migrations folders. What should I add to configuration? repos: - repo: https://github.com/PyCQA/pylint rev: pylint-2.5.2 hooks: - id: pylint name: pylint entry: pylint language: system types: [python] args: - --rcfile=./backend/.pylintrc - --load-plugins=pylint_django And .pylintrc [MASTER] init-hook='import sys; sys.path.append("./backend")' max-line-length=120 disable= missing-module-docstring, missing-function-docstring, missing-class-docstring, too-few-public-methods, no-self-use, fixme, ignore=migrations -
Chart.js - Multiple bar Charts - Only Show Last Chart
Chart.js - Multiple Bar Charts - Only Show Last Chart.Basically data comes from django and is rendered in the template.Data is proper but only one of 2 charts are being rendered. I also tried changing ctx but it did not worked HTML Code <div class="container"> <div id="container" class="col-6"> <canvas id="indiacanvas"></canvas> </div> <div id="container" class="col-6"> <canvas id="usacanvas"></canvas> </div> </div> Basically data comes from django and is rendered in the template.Data is proper but only one of 2 charts are being rendered. I also tried changing ctx but it did not worked Script.js //BAR CHART USD var barChartData = { labels: [{% for item in listyear1 %}'{{item| date:"Y"}}', {% endfor %}], datasets: [ { label: "Total amount", backgroundColor: "lightblue", borderColor: "blue", borderWidth: 1, data: [{% for inr in USATOTAL %}'{{inr}}', {% endfor %}], }, { label: "Amount Recieved", backgroundColor: "lightgreen", borderColor: "green", borderWidth: 1, data: [{% for rinr in RUSDS %} '{{rinr}}', {% endfor %}], }, { label: "Amount Left", backgroundColor: "pink", borderColor: "red", borderWidth: 1, data: [{% for linr in LUSDS %} '{{linr}}', {% endfor %}], }, ], }; var chartOptions = { responsive: true, legend: { position: "top", }, title: { display: true, text: "YearWise Summary USD", }, scales: { … -
Cheapest Python / Django Web Hosting in UK? [closed]
Where is the cheapest Python / Django Web Hosting in UK? Preferably shared hosting (which is usually cheapest). Any recommendation? -
What is the best data structure for this sensordata?
I'm currently working on a project to store sensordata in a database using the Django framework. I'm receiving a data object that has 19 data fields, which can be interpreted differently depending on the type of measurement. For the sake of this question, I'm going to simplify the data fields to five fields. The received data looks like the following example: { "data type": 1 "values":[12, 18.4, 14, 15, 1] } The data values can be interpreted depending on the data type. So for example, the lookup table might look something like this: Data type 1: Climate control | field | description | unit | | --- | --- | --- | | 1 | Room temperature | C | | 2 | Desired temperature | C | | 3 | Cooler power percentage | % | | 4 | Valve position | % | | 5 | Power supply | kWh | Each of these data types might have a different interpretation of the given data. The question How would I go about storing this data in the best way possible? Do I: Store the raw values in the database, and define the context of the values in the … -
Alter data in django tables via views.py
I am creating an eCommerce site and need to reduce the stock of products available when a user purchases them. This is done via views.py and without any forms involved. I am currently doing... product = ProductItem.objects.filter(id=4).first() product.quantity_available -= items.get('quantity') product.save() Where items.get('quantity') shows the quantity of the number of items that a user has bought of that product. However, for some reason, this code doesn't seem to work. Is there any error in this? Any help would be greatly appreciated. Thanks! -
Djano: How to query on json field to get string values stored as json
I have a JSONField column in a data model like this one: class SomeModel(models.Model): extra_data = JSONField(null=True, blank=True) records in the database contain values of mixed types: actual objects and strings. Like this one: id extra_data 1 '{"a":1}' 2 {"a": 1} Notice the extra quotation marks on the first row. I want to query only those string records. How can I achieve this? I tried to find out how can I achieve this within postgres too, looking at this postgres page I could not find any means. -
Django-SES: InvalidClientTokenId - The security token included in the request is invalid
I have been trying to set up django-ses for my Django application, but I keep getting the following error: Error: unable to send email BotoServerError: 403 Forbidden <ErrorResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/"> <Error> <Type>Sender</Type> <Code>InvalidClientTokenId</Code> <Message>The security token included in the request is invalid.</Message> </Error> <RequestId>c59883a9-c3fd-48c1-ada5-0a97d607a83e</RequestId> </ErrorResponse> Here are parts of my code that may help in decoding the issue: Environment Variables AWS_ACCESS_KEY_ID='<Key from My Security Credentials in AWS (root user)>' AWS_SECRET_ACCESS_KEY='<Secret from My Security Credentials in AWS (root user)>' AWS_SES_REGION_NAME=ap-south-1 AWS_SES_REGION_ENDPOINT=email.ap-south-1.amazonaws.com I have also set up my custom send_email function which I am using in my views: def send_email(receiver, email_message, subject, reply_to=None, **kwargs): sender = "noreply@xxx.com". # Verified email ID by AWS if type(receiver) == list or type(receiver) == tuple: receivers = list(receiver) else: receivers = [receiver] init = time.time() try: # smtp_server.sendmail(sender, receivers, msg.as_string()) for rec in receivers: recipient = [rec] msgtoUser = EmailMultiAlternatives(subject=subject, body=email_message, from_email=sender, to=recipient, reply_to=reply_to) msgtoUser.attach_alternative(email_message, "text/html") msgtoUser.send() print("Successfully sent email") except Exception as e: print("Error: unable to send email", e) finally: pass print("send email took " + str(time.time() - init) + " secs") Even after going through the steps in the way that the documentation of django-ses recommends, I end up with the same error about the … -
Add filed to serializer if user is admin django rest
I have following Serializer class PersonSerializer(serializers.ModelSerializer): comments = serializers.SerializerMethodField('paginated_comments') images = ImageSerializer(source='image_set', many=True) class Meta: model = Person exclude = ('paid', 'status', 'register_date', 'paid_date') def paginated_comments(self, obj): page_size = self.context['request'].query_params.get('size') or 12 paginator = Paginator(obj.comment_set.all(), page_size) page_number = self.context['request'].query_params.get('page') or 1 comments = paginator.page(page_number) serializer = CommentSerializer(comments, many=True) return OrderedDict( [ ('count', len(serializer.data) if serializer.data else 0), ('next', comments.has_next()), ('previous', comments.has_previous()), ('results', serializer.data) ] ) Which return info about user id": "718b309c-864d-4c26-a80e-2e744ac3102a", "comments": {}, "images": [], "name": "piwщ", "city": "piwщ", } I want to add to result field is_admin:True if user is admin, but i not, i don't want to add this field to result -
can you help me, why my {% extends %} command in django project doesnt work
I tried to redirect my todolist.html to base.html on higher directory using line {% extends 'base.html' %} and I've got the following error: *Request Method: GET Request URL: http://127.0.0.1:8000/todolist/ Django Version: 2.1.7 Python Version: 3.8.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todolist_app'] 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'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.filesystem.Loader: C:\Users\cypri\pydjango\django-project\taskmate\templates\base.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\cypri\pydjango\tmenv\lib\site-packages\django\contrib\admin\templates\base.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\cypri\pydjango\tmenv\lib\site-packages\django\contrib\auth\templates\base.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\cypri\pydjango\django-project\taskmate\todolist_app\templates\base.html (Source does not exist) Template error: In template C:\Users\cypri\pydjango\django-project\taskmate\todolist_app\templates\todolist.html, error at line 1 base.html 1 : {% extends 'base.html' %} 2 : Exception Type: TemplateDoesNotExist at /todolist/ Exception Value: base.html* -
Inherit from parent class and form, then i want a listview
//i have a modelform class Parrent(forms.ModelForm): someTest = forms.CharField(max_length=20) // i have a child form class Child(Parrent): someTestChild = forms.CharField(max_length=20) // i want a listview for the child form, this is my url.py path('Testing/', views.Child.as_view(),name="child"), //but i get an error saying that this class has no .as_view possibility. Is it possible to create an list and detailview on the child form.