Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Debug Toolbar not showing
I installed: pip install django-debug-toolbar I have DEBUG=True in my settings I have django.contrib.staticfiles and debug_toolbar in INSTALLED_APPS i have STATIC_URL = '/static/' in STATIC_URL I have 'debug_toolbar.middleware.DebugToolbarMiddleware' high up in MIDDLEWARE_CLASSES I have INTERNAL_IPS = ['127.0.0.1'] in my settings I have urlpatterns = [ ... path('debug/', include(debug_toolbar.urls)) ] and Import debug_toolbar in URLConfig of project. I have run python manage.py collectstatic and Debug Toolbar not showing in my browser How can I fix it? -
Flask Unique SQLAlchemy with Flask-LImiter
I want to make a project with flask where you sign up and sign in and then you can make new posts. I use flask-limiter to prevent users from making new posts. Also, I want the title of the post to be unique because there is an edit page too. Here is the code of flask: def ifonly(): if current_user.name == 'admin': return False else: try: if request.method == 'POST': title1 = request.form['title'] content2 = request.form['content'] post70 = Post.query.filter_by(title=title1).first() if post70: return redirect('/home') else: if len(title1) > 5 and len(title1) < 50 and len(content2) > 5: global post1 post1 = Post(title=title1,content=content2,name=current_user.name,author=current_user.id) db.session.add(post1) db.session.commit() return True except: flash("nooo") else: return False @app.route('/makepost/',methods=['POST','GET']) @limiter.limit('10 per 10 minutes',cost=ifonly) def makepost(): allposts = Post.query.all() sear = 1 if not current_user.is_authenticated: return redirect('/login') poster = Users.query.filter_by(name=current_user.name).first() try: if request.method == 'POST': title = request.form['title'] content = request.form['content'] if len(title) < 5: flash("Title must be at least 5") if len(title) > 50: flash("Title must be 50 characters max") if len(content) < 5: flash('Content must be at least 5 letters') if len(title) > 5 and len(title) < 50 and len(content) > 5: sear = 2 post69 = Post.query.filter_by(title=title).first() if sear == 2: global post1 post1 = Post(title=title,content=content,name=current_user.name,author=current_user.id) … -
Django com DetailView E ModelForm
Estou tentando utilizar o FormView com DetailView mas não estou obtendo o comportamento esperado. O que estou procurando é que ao clicar no nome do cliente na minha ListView, quero que o campo cliente da servico/models.py já seja associado a este nome e gere um formulário com os outros campos. restantes. servico/views.py class AssociarServicoDetail(FormView, DetailView): model = Clientes template_name = 'servico/associar_detail.html' form_class = ServicoForms success_url = reverse_lazy('pages:home') cliente/models.py class Clientes(models.Model): nome_cliente = models.CharField(max_length=70, verbose_name='Nome Completo') telefone = models.CharField(max_length=15, verbose_name='Telefone') email = models.EmailField(unique=True, blank=True, verbose_name='E-mail') data_criacao = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.nome_cliente def get_absolute_url(self): return reverse('servico:associar_detail', kwargs={'pk': self.pk}) servico/models.py class servico(models.Model): choices_services = [('1', 'Tatuagem'), ('2', 'Piercing')] cliente = models.ForeignKey(Clientes, on_delete=models.CASCADE) lista_servico = models.CharField(max_length=1, choices=choices_services, blank=False, null=False) tatuador = models.ForeignKey(User, on_delete=models.CASCADE) marcar_servico = models.BooleanField(default=True) servico/forms.py class ServicoForms(forms.ModelForm): class Meta: model = servico fields = '__all__' -
Graph not being displayed on django framework
I want to display a graph using C3 Javascript library which displays future prices of textile raw materials on django framework. When I run the code it does not display the graph and when I inspected it gave the following error : Failed to load resource:allpredicted.js:1 the server responded with a status of 500 (Internal Server Error). Can anyone tell what could be the problem? I tried changing location of static and template folders but nothing worked. This is the javascript file which creates graph allpredicted.js /* * Parse the data and create a graph with the data. */ function parseData(createGraph) { Papa.parse("201222-yarn-market-price-china--034.csv1.csv", { download: true, complete: function(results) { createGraph(results.data); } }); } function createGraph(data) { var years = ['x']; var pred_appended = ["Cotton Yarn1"]; for (var i = 1; i < data.length; i++) { if (data[i][0] === undefined) { years.push (null); } else { years.push (data[i][0]); } if (data[i][2] === undefined) { pred_appended.push (null); } else { pred_appended.push (data[i][2]); } } console.log(years); console.log(pred_appended); var chart = c3.generate({ data: { x: 'x', //xFormat: '%d/%m/%Y', // 'xFormat' can be used as custom format of 'x' columns: [ years, // ['x', '20130101', '20130102', '20130103', '20130104', '20130105', '20130106'], pred_appended ] }, axis: { … -
Upload file from html when block public access is true
I am using django-s3direct to file upload https://github.com/bradleyg/django-s3direct Using IAM role setting because I upload the file from the server on ECS container. Now I set the blockPublicAccess of S3 false. When uploading images from html, there comes error. https://s3.ap-northeast-1.amazonaws.com/static-resource-v/images/c64d6e593de44aa5b10dcf1766582547/_origin.jpg?uploads (403 (Forbidden) ) initiate error: static-resource-v/line-assets/images/c64d6e593de44aa5b10dcf1766582547/_origin.jpg AWS Code: AccessDenied, Message:Access Deniedstatus:403 OK, it is understandable. Browser try to access the for initiation. However there is any way to upload file from browser when blockPublicAccess is true?? -
Test a decorated fucntion in Python
I have a python function which is decorated. @retry_if_access_token_expired(app_id) def add_something( self, *, argument1, argument1 = None, ): """adding something""" I've written tests for the given as below. @patch("other inside function to mock") @patch("other insdie function to mock 2") def test_add_something( self, mock_1, mock_2 ): """ some logic to test the add something method """ But I am getting this error that says add_somehthing takes 1 positional argument. TypeError: add_something() takes 1 positional argument but 3 were given Any help would be appreciated. -
how to pass null value to just one specific key of the one object using same DRF serializer
I'm just passing the same object 2 times in the same serializer but I want to pass key: "retweet": null in one object and in another object I want to pass some values like some many-to-many field values because key "retweet" is many-to-many field and having data Thanks in advance! -
wkhtmltopdf-django dynamic template to render
Is there any way to generate a PDF dynamically, with content being fetched from the database? My goal is to allow my users to generate their own PDF design from a wysiwyg editor. This is my model class DocumentService(models.Model): name = models.CharField(max_length=60, blank=True) html_content = models.TextField(blank=True) I use django-wkhtmltopdf to render html to PDF. response = PDFTemplateResponse( request=request, template="document.html", filename=filename, context=data, show_content_in_browser=True, cmd_options=cmd_options, ) How can I render the content of this record into my PDF? document = DocumentService.objects.get(pk=1) document.html_content # <-- this content The HTML content should be something like this <html> <body> <p> <strong>Date: </strong> {{date}} <strong>User: </strong> {{user.name}} <strong>Email: </strong> {{user.email}} <strong>Info: </strong> {{user.info}} ... </p> </body> </html> -
Can't set default image django
I was create a profile for user. I done set up all the Media and Static. But when I set default and upload_to in image field, it error not found image. I had try all the different Path image but it doesn't work either. Can someone check the path for me. Thank a lot ! path in setting: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media/images') MEDIA_URL = '/media/' url project: urlpatterns = [ path('admin/', admin.site.urls), path('',views.IndexPage.as_view(),name='index'), path('welcome/',views.WelcomePage.as_view(),name='welcome'), path('bye/',views.ByePage.as_view(),name='bye'), path('about/',views.AboutPage.as_view(),name='about'), path('profile/', include('accounts.urls')) ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) model: class UserInfoCnc(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to = 'profile_pics', default='profile_pics/xinlacho.JPG' ,blank=True show image in html: <img class='img-thumbnail' src="{{ userinfocnc.profile_pic.url }}" alt="Error load image"> file media and static in project: -
Move HTML variable through views to python script in Django
While working in Django I am trying to take a variable from HTML input, pass it to views.py for some decision making, then pass it from views.py to a separate python script in my project. Here is my upload form in my HTML file, this step works fine: <form method="POST" enctype="multipart/form-data" action="{% url 'upload' %}"> {% csrf_token %} <input type='file' name='document' accept='.csv' required><br> <label for='axis'>Which column is the x-axis?<label> <input type='number' name='axis' id='axis' required><br> <button type='submit' name='csvreader'>Bar Graph</button> <button type='submit' name='line_plot'>Line Graph</button> <button type='submit' name='scatter_plot'>Scatter Plot</button> </form> Then in my views.py, I use it to check if the value is valid before calling the python script, also works fine: def upload(request): if request.method == 'POST': form = UploadFileForm(request.POST.get, request.FILES) file=request.FILES['document'] df = pd.read_csv(file,header=None) data = pd.DataFrame(df) length = len(data.columns) item = Item() item.text = request.POST.get('axis', '') item.save() request.session['item.text'] = item.text if ((int(item.text) < 0)) | ((int(item.text) >= length)): HttpResponse("Your axis is not valid") if 'csvreader' in request.POST: csv = CSV.objects.create(doc=file) os.system('python csvreader2.py') if 'line_plot' in request.POST: csv = CSV.objects.create(doc=file) os.system('python line_plot.py') if 'scatter_plot' in request.POST: csv = CSV.objects.create(doc=file) os.system('python scatter_plot.py') return render(request, 'uploaded.html') And finally, I want to use it to define which line of the csv file will be … -
The transaction has been cancelled, but our business server can still receive the webhook with successful payment
This is one of the customers who failed to pay and cancelled the Recurring payment However, my business server receives a Payment sale completed Webhook notification set up on paypal, I'm very confused -
Redirect inside async function
I have a function for creating a Stripe.com checkout session: @csrf_exempt def create_checkout_session(request): if request.method == 'GET': domain_url = 'https://example.com/' stripe.api_key = settings.STRIPE_SECRET_KEY try: order = request.user.profile.order_set.get(ordered=False) all_in_stock = True for orderitem in order.orderitem_set.all(): if orderitem.item.in_stock >= orderitem.quantity: pass else: all_in_stock = False break if all_in_stock: line_items = [] for orderitem in order.orderitem_set.all(): line_item = { 'name': orderitem.item.item_name, 'quantity': orderitem.quantity, 'currency': 'usd', 'amount': int(orderitem.item.price * 100), } line_items.append(line_item) orderitem.item.in_stock -= orderitem.quantity orderitem.item.save(update_fields=['in_stock']) if order.shipping_address.state == 'IL': line_item = { 'name': 'Sales tax', 'quantity': 1, 'currency': 'usd', 'amount': int(order.get_sales_tax() * 100), } line_items.append(line_item) checkout_session = stripe.checkout.Session.create( client_reference_id=request.user.profile.id, success_url=domain_url + 'store/success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'store/cancelled/', payment_method_types=['card'], mode='payment', line_items=line_items, customer_email=request.user.email, expires_at=int(time.time() + 3600), ) return JsonResponse({'sessionId': checkout_session['id']}) else: messages.error(request, "Not enough items in stock to fulfill the order") return redirect("store:order-summary") except Exception as e: return JsonResponse({'error': str(e)}) It is executed with this script: fetch("/store/config/") .then((result) => { return result.json(); }) .then((data) => { const stripe = Stripe(data.publicKey); document.querySelector("#stripeSubmitBtn").addEventListener("click", () => { fetch("/store/create-checkout-session/") .then((result) => { return result.json(); }) .then((data) => { console.log(data); return stripe.redirectToCheckout({sessionId: data.sessionId}) }) .then((res) => { console.log(res); }); }); }); I want to add the functionality to check that all items are still in stock, and if not abort the session. … -
django if user.is_authenticated not working but login user
my problem is that the login operation is done correctly and the session is set up correctly, but user.is_authenticated does not work. The point is that it works when I log in through the admin, but not like this, what can I do to fix it? my code : views.py class LoginView(View): def get(self, request): login_form = LoginForm() context = { 'login_form': login_form } return render(request, 'account/login.html', context) def post(self, request: HttpRequest): login_form = LoginForm(request.POST) if login_form.is_valid(): user_email = login_form.cleaned_data.get('email') user_password = login_form.cleaned_data.get('password') user: User = User.objects.filter(email__iexact=user_email).first() if user is not None: check_password = user.check_password(user_password) if check_password: login(request, user) return redirect('home') else: login_form.add_error('password', 'password is not correct !') else: login_form.add_error('email', 'email dose not exists !') context = { 'login_form': login_form } return render(request, 'account/login.html', context) header_component.html <div class="navbar__list"> <ul class="navbar__links"> {% for link in links %} <li class="navbar__link"><a href="{{ link.url }}">{{ link.name|capfirst }}</a></li> {% endfor %} {% if user.is_authenticated %} <li class="navbar__link"><a href="#">welcome</a></li> <li class="navbar__link"><a href="{% url 'logout' %}">Log out</a></li> {% else %} <li class="navbar__link"><a href="{% url 'login' %}">Login</a></li> <li class="navbar__link"><a href="{% url 'register' %}">Register</a></li> {% endif %} </ul> </div> -
How to Override get_absolute_url in Django for different Fields?
I want to make the method get_absolute_url to be dynamic with different class based views. So if in a template where it displays a list of all the articles in the database I call the function for the attribute as {{ instance.get_absolute_url }}, that link will take me to blog/article/title. But then I want to have a page that displays all the authors in the database and when I click in an author, the next page would display all the articles of that author, so the url would be blog/author/authorname. The problem is that I overrode the method in the Article class as follows: reverse(blog:article-detail, kwargs={'title': self.title}) What do I have to do to implement a conditional that checks whether I am looking for the author or the title. I've tried overriding the method inside the AuthorArticleListView class that I created to render the template where the author's articles will be displayed but when calling the get_absolute_url method in the template, the link would just not work and stays in the same page, does not even give me an error but when called for the articles to go into the DetailView of each article from the ListView, it works just … -
TemplateDoesNotExist at /home/
I'm following a video tutorial but Im getting an error. The only differance is that author uses Subline Text, while i use VSCode what is causing the error? enter image description here here's my views code: from django.http import HttpResponse from django.shortcuts import render def about(request): return HttpResponse("Inforamation about") def home(request): return render(request, 'home.html') here's my urls code: from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('about/', views.about), path('home/', views.home), ] and my settings code: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
update model field when events occurs in django
I have a patient model and one dateTimeField field, i need to update this data when an event occurs patient.py class Patient(Tenantable): lastVisitDateTime = models.DateTimeField(null=True) and event.py class Event(Tenantable): patient = models.ForeignKey( Patient, related_name="events", on_delete=models.CASCADE ) what i should do? -
Getting bytes written to SQL database for integer column, want integer to be written
I am writing data from a dash app to a SQL database setup by Django and then reading back the table in a callback. I have a column that the value should either be 1 or 2 but the value is as below in the SQL database: SQL Database view of column that should contain 1 or 2 When this is read back to a pandas dataframe it appears as b'\00x\01x... or something along those lines, which then gets read wrong when it needs to be used. The django code for the column is: selected = models.IntegerField(default=1, null=True) I am writing and reading the data using SQLAlchemy. Number appeared perfectly in pandas dataframe before involving SQL. Read and write code: select = pd.read_sql_table('temp_sel', con=engine) select.to_sql('temp_sel', con=engine, if_exists='append', index=False) Any help would be appreciated. -
Django form validation based on custom function that calls api to validate form input value
I've been trying to look around for resources on how to do this, but no luck so far. Any direction would be appreciated! I'm attempting to run a custom function on a Django form as validation. So, how it would work is: User submits form Within the validation, there is a function that calls an external API with the input value If the API returns a valid response, the form submission completes successfully If the API returns an error, the form validation is failed and a notification is returned to frontend with error. Any direction on how this could be accomplished would be appreciated! -
Can't get the Profile instance that have logged user as field
So i have here a 'create_project' view where l’m trying to assigne to the 'owner' field of project instance created a 'profile of the current user logged . so it's show a error says: DoesNotExist at /projects/create-project/ Profile matching query does not exist. create_project view : def create_project(request): # create operation form = projectForm() if (request.method == "POST"): form = projectForm(request.POST,request.FILES) if form.is_valid(): # check if it valid project = form.save(commit=False) project.owner = Profile.objects.get(user=request.user) project.save() return redirect("home") context = {'form':form} return render(request, 'projects/project_form.html',context) Project Model Class: class project(models.Model): owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL) Profile Model Class: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) -
Flask SQLAlchemy Columns
I want to make a blog where a user can make posts. And I want the title of the post to be unique. But when I try to make a post and the post already exists returns an error. But when I write a try it still returns an error. Why does this happen? @app.route('/makepost/',methods=['POST','GET']) @limiter.limit('10 per 10 minutes',cost=ifonly) def makepost(): try: allposts = Post.query.all() sear = 1 if not current_user.is_authenticated: return redirect('/login') poster = Users.query.filter_by(name=current_user.name).first() if request.method == 'POST': title = request.form['title'] content = request.form['content'] if len(title) < 5: flash("Title must be at least 5") if len(title) > 50: flash("Title must be 50 characters max") if len(content) < 5: flash('Content must be at least 5 letters') if len(title) > 5 and len(title) < 50 and len(content) > 5: sear = 2 if sear == 2: global post1 post1 = Post(title=title,content=content,name=current_user.name,author=current_user.id) post2 = Post.query.all() db.session.add(post1) db.session.commit() # error, there already is a user using this bank address or other # constraint failed if sear != 2: flash('We couldnt make your post') except: flash('Error') return render_template('posts.html') class Users(UserMixin,db.Model): id = db.Column(db.Integer,primary_key=True) name = db.Column(db.String(200),unique=True,nullable=False) password = db.Column(db.String(200),unique=False,nullable=False) role = db.Column(db.String(200),unique=False,nullable=False) missions = db.Column(db.String(200),unique=False,nullable=True) waiter = db.Column(db.String(200),unique=False,nullable=False) posts = db.relationship('Post',backref='user') class Post(db.Model): … -
Decorator @property on ASP net core like in django
The thing is that like in Django which you can add model properties without changing the model class using the @property decorator. I'm trying to achieve same with aspnetcore I mean I want to add some functions to the model class which will return some string/int in order to access to them from the razor view(ex: model.extraProperty) Someone could help me to address this? -
Exempt Django Cross Domain Password Reset from CSRF token
I have a separate front end and backend site and am trying to enable users on the front end to reset their password. I have created an endpoint for them to do so which works when accessed via the backend site. But when I try to access the endpoint via Insomnia I get a 403 CSRF verification failed. Request aborted. error. I have added my front end ddomain to the CORS_ORIGIN_WHITELIST class PasswordResetView(auth_views.PasswordResetView): template_name = 'users/reset_password.html' @method_decorator(csrf_exempt) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) Is there some other method that I must also make csrf_exempt? -
How to use exchanged token with OAuth2 - social-auth-app-django
I'm trying to implement OAuth2 authentifications using social-auth-app-django. My backend can exchange an authorization token that I get from a frontend using providers SDK, I will give Apple as an example: My iOS app gets an authorization token from the user using "Sign in with Apple". I then sends this token to the backend so I can exchange it using this view: @api_view(http_method_names=['POST']) @permission_classes([AllowAny]) @psa() def exchange_token_view(request, backend): serializer = SocialSerializer(data=request.data) if serializer.is_valid(raise_exception=True): print("Backend:", backend) print("Token:", serializer.validated_data['access_token']) # set up non-field errors key # http://www.django-rest-framework.org/api-guide/exceptions/#exception-handling-in-rest-framework-views try: nfe = "non_field_errors" except AttributeError: nfe = 'non_field_errors' try: # this line, plus the psa decorator above, are all that's necessary to # get and populate a user object for any properly enabled/configured backend # which python-social-auth can handle. user = request.backend.do_auth(serializer.validated_data['access_token']) except HTTPError as e: # An HTTPError bubbled up from the request to the social auth provider. # This happens, at least in Google's case, every time you send a malformed # or incorrect access key. return Response( {'errors': { 'token': 'Invalid token', 'detail': str(e), }}, status=status.HTTP_400_BAD_REQUEST, ) if user: if user.is_active: token, _ = Token.objects.get_or_create(user=user) print() return Response({'token': token.key}) else: # user is not active; at some point they deleted their … -
PostgreSQL or Firebase Firestore DB for Django E-Commerce Web App (and Android & iOS App)
I am building an e-commerce website with customers and sellers with Django (as well as iOS and Android apps with React Native). I want to use the Firebase Firestore Database but I can't get it to work with Django (there are also almost no tutorials online..). For PostgreSQL there are a lot of tutorials online and I've already once used it in another Django project. Which is better for a Django e-commerce website (and React Native mobile apps)? -
Django Limit the Number of objects in a model
i am working on a django-cms project and (i have to make a image model which can only make 3 objects not more than that if someone tries there should be a message: Max Objects Have been Created) so, how can i limit the number of objects in a model ? Thank you, I will Really appreciate you feedback.