Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using non-AWS S3 storage with Django?
I have an S3 storage which is not hosted by AWS. I tried my AWS account as a file-storage, which worked fine, however, when I switch the credentials to the non-AWS provider I get: botocore.exceptions.ClientError: An error occurred (403) when calling the HeadObject operation: Forbidden in the django logs, and ClientError at /admin/api/metabolomicsmzxml/add/ An error occurred (403) when calling the HeadObject operation: Forbidden displayed in the browser. I use django-storages with the following configuration:q : AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWSS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_REGION_NAME = 'ca-central-1' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_S3_VERIFY = True AWS_ENDPOINT_URL = 'example.com:443' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Is it possible to use django-storages and boto3 with a non-AWS provider? Are there other packages that I should try? -
Var inside of object attribute [duplicate]
i got these code `{%for number in List %} <div class="top"> <h3> <a href="/my-blog-post">{{songs.history.0.Song}}</a> </h3> <section> <p>{{number}}Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec viverra nec nulla vitae mollis.</p> </section> <footer> <small> Posted on <time datetime="2017-04-29T19:00">Apr 29</time> in <a href="/category/code">Code</a> </small> </footer> </div> i want that the number of the {{songs.history.0.Song}} change with the var of the loop but when i change it to {{songs.history.number.Song}} the element a dont appear the thing is that i want that the number change automatic -
Update databate when user click at a checkbox
I made a model to control the existence of a specific list of customer documents. models.py class PersonalDocumentation(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, verbose_name='Project') cnd = models.BooleanField(default=False, verbose_name='CND proponente') producer_registration = models.BooleanField(default=False, verbose_name='Inscrição de produtor rural') sales_invoices_agriculture = models.BooleanField(default=False, verbose_name='Notas de comercialização agrícolas (3 anos)') sales_invoices_livestock = models.BooleanField(default=False, verbose_name='Notas de comercialização pecuária (5 anos)') rg = models.BooleanField(default=False,verbose_name="RG") cpf = models.BooleanField(default=False, verbose_name='CPF') wedding_certificate = models.BooleanField(default=False, verbose_name='Certidão de casamento') rg_spouse = models.BooleanField(default=False, verbose_name='RG conjuge') cpf_spouse = models.BooleanField(default=False, verbose_name='CPF conjuge') I would like to show this data in checkbox format and for the database to be updated when user check/uncheck some item. The only way I encontered to do this is making one url for each document I started to think that maybe the model I created is not the best option. And maybe making just one field with a list of documents owned by the client is better. -
What is MyModel.objects in Django?
I am following a beginner's Django course in which I am up to the level of creating models and inserting data into the tables. I have created the following model: from django.db import models # Create your models here. class Names(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) In the shell I do: elvis = Names.objects.create(first_name="elvis", last_name="prestley") This successfully creates a database record. I want to know the logic behind Names.object.create() - "Names" is a class I have created which inherits the Models class but I am not sure where the ".object.create()" part comes from? -
How to solve "'int' object is not subscriptable" in Django from a Kraken API
I was wondering what the correct way is to save a number in Django SQLite coming from a Kraken API, when there is an Array of Array of strings or integers (https://docs.kraken.com/rest/#operation/getOHLCData). my views.py from rest_framework import generics from .serializers import KrakenSerializer from krakenohlc.models import Krak import requests class KrakenList(generics.RetrieveAPIView): serializer_class = KrakenSerializer queryset = Krak.objects.all() def get_object(request): url = 'https://api.kraken.com/0/public/OHLC?pair=XBTEUR' response = requests.get(url) data = response.json() for i in data['result'].values(): kraken_data = Krak( time_0=(i[0][0]), ) kraken_data.save() my models.py from django.db import models class Krak(models.Model): time_0 = models.IntegerField(blank=True, null=True) def __str__(self): return self.time_0 This is the error that i get in the browser: The SQLite response is actually saving the API number in the database: I researched and tried thoroughly many similar cases here, but none had the example of an API response with this error message. -
Adding external javascript snippet to a Wagtail page field
My current Wagtail project has a very simple structure with some generic pages that have just a body RichTextField. These are just basic CMS type pages where an editor will edit some content in the rich text editor and publish. One of the pages (and probably more in time) is a "Help Wanted" page and uses an external javascript snippet from a third-party service that lists current job openings with links to the applications that are hosted by them. Since adding a <script> tag to the rich text editor simply escapes it and displays only the text value, I added an additional extra_scripts = models.TextField() to my page model along with a corresponding FieldPanel('extra_scripts') to the content panels. This lets a user paste in some arbitrary javascript snippets. If I include this field value in my template with {{page.extra_scripts}} it just displays the content and does not execute the javascript. Looking through the available wagtailcore_tags I'm not seeing a filter that I should use to execute the content, and when it's used with a {{}} tag, I presume the template engine handles it so that it doesn't execute. How can I include this field in a template so that the … -
WebSocket like grouping for SSE in Django
I have a Django website and I have a real-time "game" on it. Multiple people connect and play it. Every x seconds the users in the specific game will be getting updates. I have done this using WebSockets and it works, I would say, pretty good. The things I think that using WebSocket-s is an overkill, plus I'm not utilising the Bi-directional part of it, rather using it to get the updates from the server and using AJAX to send the data. I'm considering switching over to Server Sent Events. I've used it a bit and read about it online and have decided that it would be a good fit for my project (using it instead of WS). The "problem" that I have is that I'm not sure how to (I assume its possible) to use something like a groups in ws. I've searched online and the best solution that I could find is doing the client side filtering, which although its totally fine, I do not prefer as I think it's a waste of resources. The way that I have it set up is that based on the url for the game, the users that are connecting would be … -
Django-allauth - is there a way to automatically send an email after account is verified
We recently took over a project that was developed in Django, which uses allauth. We are hoping to send out some additional information to users once they have signed up and confirmed their email address, is there a default/native way to do this in django-allauth? At the moment the system uses email_confirmation_message.txt to configure the email for users to confirm their email address, but we couldn't find something similar once the account is confirmed. -
How to effectively count multiple nested children in a Django model?
I have the following data model (the database backend is PostGres): class User(models.Model): ... teams = models.ManyToManyField('Team', blank=True, related_name='all_users') ... class Team(models.Model): ... parent_team = models.ForeignKey('self', blank=True, null=True, related_name='child_teams') ... So a User can belong to multiple Teams, and the Teams can be nested in each other to varying degrees of depth. I'd like to count all Users within a given team and all its children, including nested children. Right now, I am doing it recursively, which doesn't seem like the most efficient way to go. Is there a better way to go about it? -
Cant login to created user after using custom model
from django.db import models from django.contrib.auth.models import AbstractUser,User from django.utils.html import escape,mark_safe # Create your models here. class user(AbstractUser): is_admin = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_student = models.BooleanField(default=False) def login_view(request): form = AuthenticationForm() if request.method=='POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username,password=password) if user.is_admin==True: login(request,user) return HttpResponse(f"Welcome {username}") else: return HttpResponse('failled') return render(request, 'login.html', {'form': form}) cant login using the user created by superuser. the user is creating but while calling it or using it shows created a user with staff and superuser authorization still cant login -
How can I get Followed/unfollowed count of a user last 24 hours from Twitter using Tweepy with python
How can I get user followed/unfollowed count of last 24 hours from Twitter using Tweepy with python. I have essential access of twitter api v2. I have read the tweepy documentation but there is no query of filter follow/unfollow count from last 24 hours. -
How can I create a user in Django?
I am trying to create a user in my Django and React application (full-stack), but my views.py fails to save the form I give it. Below the code. # Form folder def Registration(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] User.objects.create( email = email , username = username, password = password, ) user = form.save() login(request,user) return redirect('/profile/') else: context = {"Error" : "Error during form loading"} return render(request,'accounts/registration.html',context=context) return render(request,'accounts/registration.html',context=context) And that's my Forms.py class UserForm(UserCreationForm): username = forms.TextInput() email = forms.EmailField() password = forms.TextInput() password2 = forms.TextInput() class Meta: model = User fields = ("username", "email", "password", "password2") def save(self, commit=True): user = super(UserForm, self).save(commit=False) if self.password != self.password2: raise forms.ValidationError('Input unvalid') elif commit: user.save() return user -
Django NameError: name ' ' is not defined
I am trying to create a view that filters blog posts by topic, to I added a field in my post form called "topic" and, I created a view: And I defined the path in urls.py: I get this error in Terminal: model = Post template_name = 'blog/political_posts.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(topic=Political).order_by('date_posted') ``` ``` path('politics/', PoliticalPostListView.as_view(), name='political-posts'), ``` I used a template from a working user_posts.html to test: ``` {% extends "blog/base.html" %} {% block content %} <h1 class="md-3"> Posts by {{ view.kwargs.username }} ({{ page_obj.paginator.count }})</h1> {% for post in posts %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> <small class="text-muted">{{ post.topic }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} ``` File "/Users/leaghbranner/Desktop/django_project/blog/urls.py", line 21, in <module> path('politics/', PoliticalPostListView.as_view(), name='political-posts'), NameError: name 'PoliticalPostListView' is not defined And "This Site Cannot Be Reached." pagein my browser. Any thoughts? -
How to create a super user in Django using react signup application
I am trying to create a superuser or regular user by creating react signup application and I want to know the correct way to do this. -
How to prevent different user types to view each other dashboard in django
I have a website with 3 user types, admin, instructor and students, I used login mixing to redirect each of them to their respective dashboard but if the student modify their url to /instructor or /admin ; it will give them access to the page; I want to restrict student to only student page and admin to only admin page. I tried writing the function If user.student.is_authenticated: class Student_dashboard(): ...... However it's not restricting them -
Using Ajax to update a table on a page in django
I am trying to the table in my all-reviews whenever someone checks one of the filters at the top using ajax. However, when a filter is checked it is getting the entire page back including things like the navbar and then updating the table with the entire page data instead of just the filtered reviews. The issue I believe is with my view since its rendering the all-reviews.html page but I cannot figure out how to do it properly where the returned data doesn't include the navbar and other unneeded information that is imported into my base.html. Lastly, I am trying to make it so that if they click a filter, it loads the new data, but then if they uncheck the filter, or check a different one the data is refreshed again. Currently after the first time a filter is checked nothing happens if subsequent filters are checked or unchecked. base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>{% block title %}{% endblock %}</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="{% static "app.css" %}" /> {% block … -
Use login tables created by Django from NestJS/NodeJS service
We have the secrets and the source code from Django project (this is not a hack topic) this is a topic about the posibility of use Django generated tables for Users Login BUT from NodeJS/NestJS service. The goal is kickout Django, and keep existing users to generate same JWT tokens from encrypted password coming from users table generated by Django. -
E TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use subjects.set() instead
I am writing a test to some api calls, the issue that I am getting is that I can't figure out how to assign a many-to-many variable(subjects) in Django. models.py class Subject(BaseModel): id = models.AutoField(primary_key=True) name = models.TextField(null=False, blank=False) answers = models.ManyToManyField("registration.Answer", through="AnswerSubject") class Answer(BaseModel): id = models.AutoField(primary_key=True) text = models.TextField(null=False, blank=False) subjects = models.ManyToManyField("subjects.Subject", through="subjects.AnswerSubject") test.py def tets_get_answer: Answer.objects.create( text=f'{"test answer"}', subjects = f{"test subject"} # the error is here, how do I assign subjects? ), ........ this is the error that I am getting: E TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use subjects.set() instead. Any help is appreciated -
TypeError: __init__() got an unexpected keyword argument 'export_job'
I am implementing an export function with django-import-export-celery and the instructions are only three steps. I followed all of them, and when I try to do an export, it gives me an error on the celery process: This is what my code looks like: class Issuer(models.Model): name = models.CharField(max_length=200, null=False, blank=False,) @classmethod def export_resource_classes(cls): return { "Issuers": ("Issuers resource", IssuerResource), } class IssuerResource(ModelResource): def ready(self): class Meta: model = apps.get_model('crowdfunding.Issuer') Any help is appreciated. -
How to assign variable to JSON in Django Views.py context
I'm Getting Data from an external API, in which i convert to JSON then i add the data in context to use in my Template. the problem is that the different variables in the API have a specific assigned number. i want to store that number in my database so i can assign them to specific objects on my website. here is the code models.py = api_text = models.CharField(max_length=100, blank=True, null=True,) Views.py def projectdetails(request, pk): url = 'XXX' parameters = { 'slug': 'bitcoin', 'convert': 'USD', } headers = { 'Accepts': 'application/json', 'X-CMC_PRO_API_KEY': 'XXX' } session = Session() session.headers.update(headers) response = session.get(url, params=parameters) api_price = response.json() coin = Coin.objects.get(id=pk) context = {'coin':coin, 'gimmeprice':api_price['data']['1']['quote']['USD']['price'], } return render(request, 'blog/project_details_coin.html', context) the [1] in the context is where i want to use a variable that i assign to "api_text" im having troubles figuring out with Django Model Query to use and how -
After creating a custom model for custom roles now if create a user and give him 'admin' authentication i cant login to admin page
from django.db import models from django.contrib.auth.models import AbstractUser,User from django.utils.html import escape,mark_safe # Create your models here. class user(AbstractUser): is_admin = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_student = models.BooleanField(default=False) now if i create a user and give him any of these privilege and then call the user anywhere it shows 'NoneType' object has no attribute 'is_admin' -
How to filter and add multiple datasets using Django and Chart.js
I've been scratching my head for quite a while on this so any help is much appreciated. Let's say I have a model called Transaction. class Transaction(models.Model): time = models.DateTimeField(auto_now_add=True, blank=True) client = models.ForeignKey(User , on_delete=models.Cascade) value = models.IntegerField() I want to generate a chart using chart.js. So far i am able to do this for all the objects using this JS: <script> $(function () { var $xChart = $("#xChart"); $.ajax({ url: $xChart.data("url"), success: function (data) { var ctx = $xChart[0].getContext("2d"); new Chart(ctx, { type: 'line', data: data, options: { responsive: true, legend: { position: 'top', }, title: { display: true, text: 'xChart' } } }); } }); }); </script> And this FBV for the ajax call: def x_chart(request): def random_color(): return "#"+''.join([choice('ABCDEF0123456789') for i in range(6)]) labels=[] data=[] enddate = datetime.now() startdate = datetime.now().date() - relativedelta(days=3) transactions = Transaction.objects.filter(time__range=[startdate,enddate]) grouped_transactions = transactions.values("time__day").annotate(total=Sum('value')) for key in grouped_transactions: labels.append(key['time__day']) data.append(key['total']) return JsonResponse( data={ 'labels': labels, 'datasets': [ { 'label': 'All Transactions, 'backgroundColor': str(random_color()), 'data': data, } ], } ) I want to create a dataset from each Transaction.client field and then pass it as Json to the ajax request. How would i be able to do that since the lables are … -
Does the form to add data have to contain all the fields of models.py to be able to save?
I have a question, what happens is that I have a model called "Clientes" inside an app that has the same name, right there I have a form with all the fields of my model, the form saves quite well. I also have an app called "Presupuestos" that inherits "Clientes", that app serves as a shortcut for "Clientes". That is to say that this shortcut is the reduced version of the "Clientes form", I mean that the "clientes-add.html"(form) has 10 fields and in "presupuestos-add.html" (form) it has 5 fields. The problem is that the "Presupuestos" one does not save anything. Is it because it is not calling all the "Clientes" fields and it only saves 5? And tried also to put the form errors but it doesn't work models.py class Clientes(models.Model): tipo = models.CharField(max_length=200) TITLE = ( ('Mrs.', 'Mrs.'), ('Miss', 'Miss'), ('Mr.', 'Mr.'), ) corporacion=models.CharField(max_length=200) titulo = models.CharField(max_length=200, null=True, choices=TITLE,default='Mr.') nombre = models.CharField(max_length=200) apellido = models.CharField(max_length=200) telefono = models.IntegerField() tel = models.IntegerField() fax = models.IntegerField() correo = models.EmailField(max_length=200) website=models.URLField(max_length=200) pais = models.CharField(max_length=200) direccion=models.CharField(max_length=200) ciudad=models.CharField(max_length=255) estado=models.CharField(max_length=255) zip=models.CharField(max_length=255) fecha_registro = models.DateTimeField(default=datetime.now) def __str__(self): return f'{self.nombre} {self.apellido}' views.py class step1(CreateView): model=Clientes form_class = ClientesForm template_name='Presupuestos/new-estimate-1-customer-details.html' success_url=reverse_lazy('Presupuestos:step2') presupuestos-add.html <form method="post"> {% csrf_token %} <div … -
Save multiple Django formsets into a single database field
Acutal situation I have a db table called "invoice" where all Django formsets are being saved successfully. So, table looks like this: item_id|quantity|description|price|taxes|total|customer_id|invoice_id| 56 1 apple 100 0 100 567 1766 12 1 banana 40 0 40 567 1766 The problem If, for example, invoice has 100 items, I will have 100 rows inside invoice db table. Question I think there's a better and more efficient way to do the same without making the db heavier. So, I would like to save these items coming from the formsets into a single field as a list of tuples of invoice items? For example the new table will look like this: | items |customer_id|invoice_id| ["fruit", [apple,banana], "price", [100,40]] 567 1766 -
ReportLab page break in python
I have a view for creating from a Pandas dataframe and then turns it into a PDF file and returns the file response. Everything works fine except for (see code below for comment:) @login_required() def download_pdf(request, location_name): current = CurrentInfo() pdf_data = current.detail_employees_by_location(location_name) # this gives me the list of people buf = io.BytesIO() canv = canvas.Canvas(buf, pagesize=letter, bottomup=0) textob = canv.beginText() textob.setTextOrigin(inch, inch) textob.setFont("Helvetica", 10) pf = pd.DataFrame.from_dict(pdf_data, orient='index', columns=['EmployeeNumber', 'LastFirst']) data = pf.drop_duplicates() count = data.count() data = data.to_records() line_break = "|"+"-"*150+"|" textob.textLine(f"Employees in: {location_name} total in site: {count['EmployeeNumber']}") textob.textLine(line_break) textob.textLine("{0:^10}{1:^30} {2:^50}".format("#", "Employees Number", "Name")) textob.textLine(line_break) for index, line in enumerate(data, start=1): textob.textLine(f"{index:^10}{line['EmployeeNumber']:^30} {line['LastFirst']:^50}") textob.textLine(line_break) #when i add this space after each line it causes the page #to never break and just stay on the resulting in lines #not showing canv.drawText(textob) canv.showPage() canv.save() buf.seek(0) return FileResponse(buf, as_attachment=True, filename='employees.pdf') When I add an additional space after each line the for loop for additional spacing it causes the pages not to break and returns a PDF with bad formatting.