Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
GenericAPIView' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method
class GenericAPIView(generics.GenericAPIView,mixins.ListModelMixin): queryset = Article.objects.all() serilizer_class = ArticleSerializer def get (self,request): return self.list(request) -
ModuleNotFoundError: No Module Named cant figure out why
going to retrieve a simple httpresponse from view at nested app, but some how having this error which cant figure out what the problem. project url.py from django.contrib import admin from django.urls import path, include from django.http import HttpResponse, HttpRequest # from .corex import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('corex.urls')), ] app[corex] url.py from django.urls import path, include from . import views urlpatterns = [ path('', views.testcorex, name='testcorex'), ] app views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def testcorex(request): return HttpResponse('module passed') traceback error File "/home/differentmonster/App/x_house_project/x_house_backend/x_house_cms/urls.py", line 11, in <module> path('', include('corex.urls')), File "/root/.cache/pypoetry/virtualenvs/x-house-cms-p6EwdKv_-py3.8/lib/python3.8/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'corex the installedApp should be no problem cause, if i import corex.views directly into root urls.py, the response works. but after i added the url.py into app, … -
How to use AJAX spinner in django(prefer to use some library) while waiting until file is processed in backend
The Form I want that after I click the submit button a spinner/progressbar(preferred) should pop up on the screen while the uploaded file is being processed in the backend. A csv file will be processed and based on number of rows processed the width of the progressbar should change. I don't know how that signal to change the width dynamically can be tuned.It would be better if the progressbar hides the form for the duration the file is being processed. Once the file is processed then the /success/ template will be loaded where I would show some stats of the files like number of rows failed to process. I saw this package but 'm too noob to use it. I know javascript and so please don't hesisate to talk about that if required. https://pypi.org/project/django-lazy-tags/ Thanks, class EmailView(FormView): template_name = 'Email/index.html' form_class = forms.EmailForm success_url = '/success/' def form_valid(self, form): # form.send_email() # return super().form_valid(form) print(form) index.html {% extends 'Base/index.html' %} {% load static %} {% load crispy_forms_tags %} {% load bootstrap4 %} {% load lazy_tags %} {% bootstrap_css %} {% block main %} <link rel="stylesheet" href="{% static 'Email/index.css' %}"> {% crispy form %} {% endblock main %} form.py class EmailForm(forms.Form): … -
I've installed the django-cors-headers but still get No 'Access-Control-Allow-Origin' header error
I use a simple JS code to get data from an API, but I encountered No 'Access-Control-Allow-Origin' error, I installed django-cors-headers and configured settings.py according to the tutorial, but still got the same error.Am I missing something here? I use Google Chrome and have not tested other browsers yet. part of my settings.py ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sde.apps.SdeConfig', 'mptt', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True and my js code <script> var x = new XMLHttpRequest(); x.open("GET","https://www.ceve-market.org/api/marketstat?typeid={{i.typeid}}&regionlimit=10000002",true); x.onreadystatechange = function() { if (x.readyState==4 && x.status==200){ var doc = x.responseXML; console.log(doc); } }; x.send(null); </script> error messages on console Access to XMLHttpRequest at 'https://www.***.org/api/' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. VM2118:10 GET https://www.***.org/api/ net::ERR_FAILED -
ajax succes function not worked
i' trying to send data from ajax to django. here is my script: $(document).ready(function(){ $('#accept_all').click(function(){ var id_list = []; $('#table input:checked').each(function() { id_list.push($(this).attr('value')); }); $.ajax({ url: "/myurl", type: "post", data: { 'id_list': id_list, }, headers: {'X-CSRFToken': '{{ csrf_token }}'}, success: function(data) { window.location.reload(); }}); }); }); and in my django views.py: @csrf_exempt def mydef(request): if request.method == 'POST': if request.is_ajax(): id_list=request.POST.getlist('id_list[]') for item in id_list: obj=models.users.objects.get(id=item) obj.Status='1' obj.save() return HttpResponse('done!') this function works correctly and changes to obj done! but in success function of ajax that should reload page not worked -
How to send email in post_save without asking user to wait in form submission?
Here is my post_save method: from asgiref.sync import sync_to_async @receiver(post_save, sender=SubmissionDetails) def create_submission_email(sender, instance, created, **kwargs): if created: data = sync_to_async(call_submssion_email(instance)) def call_manuscript_submssion_email(instance): print("Hi") message = '''Submitted with the title, <br> {0}'''.format(instance.title) subject = 'Article Submitted' to_address = 'example@gmail.com' from_address = "from@mail.example.com" msg = EmailMessage( subject, message,from_address,[to_address] ) msg.content_subtype = "html" msg.send() The problem is while submitting the form, the user has to wait till email is sent to see the results. I am using django 3.0 with some async support. -
Customized location choices in Django/JS/Paypal Buttons Integration
Below I have my Payal Checkout setup. User can input any address they want but I want to limit the country, State/Province, and City choices they have with a dropdown menu. Does anyone know how to do that? or any alternate options for this? -
how to implement csrf without csrf token in django
In django, if I want to use csrf token, I need to imbed a form with csrf token in django template. However as a backend-engineer I am co-working with a front-end engineer whose code is not available for me. So I caanot use the template. In this case, if I want still the csrf function. what should I do? -
Page not found in django, pycharm?
i am working with django project to create a website when i set the first url it works properly but when i add new url after products/new/ then it shows page not found Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/products/new/ Using the URLconf defined in pyshop.urls, Django tried these URL patterns, in this order: admin/ products/ products/ new The current path, products/new/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. please help me!!! -
What Django model field should I use for WYSIWYG data from React?
I am creating a blog application and want to use a text editor/ WYSIWYG editor for individual posts. Since I will be using React for the frontend, the data will be received through an API (using DRF for that). So in my model, what field should I create that will accept the WYSIWYG data? eg. model: class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() unit = models.DecimalField() I want the content field to be accepting that data -
Error while creating a SignUp view in django
I tried to create a signup page in Django and whenever I tried o access the admin page it showing RelatedObjectDoesNotExist at /admin/login/ User has no profile. views.py: if request.method=='POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() # user.profile.first_name = form.cleaned_data.get('first_name') # user.profile.last_name = form.cleaned_data.get('last_name') user.profile.email = form.cleaned_data.get('email') user.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) return redirect('blog-home') else: form = SignUpForm() context = {'form':form} return render(request, 'user/signup.html', context=context) forms.py: from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=200) class meta: model = User fields = ['first_name', 'last_name', 'email', 'password1', 'password2'] models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') # img = date_of_birth = models.DateField(blank=True, null=True) bio = models.CharField(blank=True, max_length=500) location = models.CharField(blank=True, max_length=50) email = models.EmailField(unique=True, max_length=200) def __str__(self): return f'Profile for {self.user.username}' @receiver(post_save, sender=User) def update_profile_signal(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() And I am not able to create any user via SignUp Page. -
How to set sender mail name in mail from section?
When i send a mail by django send_mail, the smtp show the email is sent by sender: "EMAIL_HOST_USER mail name". But i want to changed it sender mail name. here is my mail seating: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = 'mntushar.p.d@gmail.com' EMAIL_HOST_PASSWORD = '*******' EMAIL_USE_TLS = True EMAIL_USE_SSL = False here is my views.py: def contact_mail(request): forms = ContactForms() to_mail = settings.EMAIL_HOST_USER if request.method == 'POST': forms = ContactForms(request.POST) if forms.is_valid(): subject = forms.cleaned_data['subject'] message = forms.cleaned_data['message'] from_email = forms.cleaned_data['email'] send_mail( subject, message, from_email, [to_mail] ) Mail reply is: from: mntushar.p.d@gmail.com to: mntushar.p.d@gmail.com date: May 30, 2020, 10:11 AM subject: Test mailed-by: gmail.com But i want to change from name by user send mail name. How to do it -
Loaded: error (Reason: Invalid argument) : Gunicorn
while i am trying to run sudo systemctl start gunicorn then it's showing me error that Failed to start gunicorn.service: Unit gunicorn.service is not loaded properly: Invalid argument. In my case, gunicorn has already been installed: /home/ubuntu/Big-Commerce/bigcommerce-backend/uenv/bin/gunicorn /etc/systemd/system/gunicorn.service: [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/Big-Commerce/bigcommerce-backend/ ExecStart=/home/ubuntu/Big-Commerce/bigcommerce-backend/uenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/Big-Commerce/bigcommerce-backend /bigcommerce.sock bigcommerce.wsgi:application [Install] WantedBy=multi-user.target -
Getting error while posting a message to slack user through an api call when hosted in pythonanywhere
I am having an html page which consists all the slack users list and there if I click one user it will have a messaging tab with the user id and the input text area and then I wrote an ajax call for getting the userid and msg onclick of send button so I get those details from ajax call into my views.py and there I wrote an api call for posting message my ajax call: $(document).ready(function() { $("#msg_send_btn").click(function() { var msg=$("#write_msg").val() var id=$("#insertName").html() $.ajax({ url: 'target_view/', data: { 'id': id, 'msg':msg },///Users/azky/Desktop/img_1.jpeg' success:function (data) { alert("Successfully sent the message"); }, error:function () { } }) }) }) urls.py: path('target_view/',views.chat1, name='chat1'), views.py: def chat1(request): value1 = request.GET.get('id') value2 = request.GET.get('msg') print(value1,value2) client = WebClient(os.getenv('API')) try: response = client.chat_postMessage(channel=value1,text=value2) assert response["message"]["text"] == value2 except SlackApiError as e: assert e.response["ok"] is False assert e.response["error"] # str like 'invalid_auth', 'channel_not_found' print(f"Got an error: {e.response['error']}") return HttpResponse("OK") The same when running in my local machine I am able to post messages but when deployed in pythonanywhere I am not able to post a message getting error traceback: -
Django Error: Didn't return an HttpResponse, returned None instead
Yesterday my view was working just fine after testing it. Today I tested the view again and now it keeps returning HTTP response error. I'm returning a response for every case I thought. I've been trying to debug this for a couple of hours now and I honestly not sure where the error is being thrown. I tried printing to the console but nothing prints so I'm not sure where in the view is failing. View: def getAvaliability(request): if request.user.is_authenticated: if request.method == 'POST': lot = request.POST.get('lot') start = request.POST.get('checkin') end = request.POST.get('checkout') print('hello') try: Customer.objects.get(site=lot) except ObjectDoesNotExist: messages.success(request, 'Avaliable.') return redirect('home') except MultipleObjectsReturned: reservations = Customer.objects.filter(site=lot).all() reservationList = list(reservations) overlap = [] for res in reservationList: if parser.parse(start) < timezone.make_naive(res.start, timezone=None) or parser.parse(start) > timezone.make_naive(res.end, timezone=None): if parser.parse(end) < timezone.make_naive(res.start, timezone=None) or parser.parse(end) > timezone.make_naive(res.end, timezone=None): overlap.append(False) else: overlap.append(True) else: overlap.append(True) if True in overlap: messages.error(request, 'Unavaliable.') return redirect('home') else: messages.success(request, 'Avaliable.') return redirect('home') else: # For Debugging messages.error(request, 'Not Post') return redirect('home') else: return redirect('loginuser') -
How to populate my Django Model 'updated_by' field with logged in User automatically using a formset?
I am a beginner with Django and I have been enjoying it so far. I figured out how to use model formsets, but I cannot figure out how to make my form automatically use logged in User as the 'updated_by' field. models.py class Inventory(models.Model): item = models.CharField(max_length=50, unique=True) stock = models.IntegerField() par = models.IntegerField() date_updated = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey(User, on_delete=models.PROTECT) def __str__(self): return self.item class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') phone = PhoneField(blank='True', help_text='Contact Phone Number') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() -
Wagtail: menu item opens in new window but appends main domain to external url?
I'm creating a menu using snipets. The menu items have the option to have a internal page as destination, or an external page (e.g. google.com). The internal option works great, but the external option opens in a new tag, with the hostname attached to the external link: http://127.0.0.1:8000/google.com Not sure if something is wrong with my Orderable model or what's going on. Code: class MenuItem(Orderable): link_title = models.CharField( blank=True, null=True, max_length=50 ) link_url = models.CharField( max_length=500, blank=True, ) link_page = models.ForeignKey( "wagtailcore.Page", #app y modelo de tu proyecto blank=True, null=True, related_name="+", on_delete=models.CASCADE, ) open_in_new_tab = models.BooleanField(default=False, blank=True,) page = ParentalKey("Menu", related_name="menu_items") panels = [ FieldPanel("link_title"), FieldPanel("link_url"), PageChooserPanel("link_page"), FieldPanel("open_in_new_tab"), ] # @tood add properties # link @property def link(self): if self.link_page: return self.link_page.url elif self.link_url: return self.link_url return "#" @property def title(self): if self.link_page and not self.link_title: return self.link_page.title elif self.link_title: return self.link_title return 'Missing title' @register_snippet class Menu(ClusterableModel): title = models.CharField(max_length=100) slug = AutoSlugField(populate_from="title", editable=True) panels = [ MultiFieldPanel([ FieldPanel("title"), FieldPanel("slug") ], heading="Menu"), InlinePanel("menu_items", label="Menu item") ] def __str__(self): return self.title html: <div class="collapse navbar-collapse" id="navbarCollapse"> <ul> <li> <a href="/">Home</a> </li> {% for item in navigation.menu_items.all %} <li> <a href="{{ item.link }}" class="nav-link" {% if item.open_in_new_tab %} target="_blank" {% endif … -
how do I make an element not work as href in an entire href card
So I have this card that works as an entire link but inside that, I have an icon under a span tag and I don't want it to work as the card's link rather just act like an icon, Ik I can solve this if I don't make the entire card href but then I'd have to manually turn all the required elements present inside the card into href which I feel like isn't efficient and neat. So any suggestions on how do I go from here? {% for m in mlist %} <div class="card"> <a href="http://www.google.com/search?q={{m.Name}}" target="_blank"> <div class="top"> <div class="year">{{m.Year}}</div> <span class="span-bookmark"><i class="material-icons bookmark" id="bookmark-style">bookmark</i></span> </div> <div class="middle"> <div class="img-container"><img src="{{ m.Image.url }}"></div> </div> <div class="bottom"> <div class="title">{{m.Name}}</div> <div class="target_id">{{m.targetid}}</div> </div> </a> </div> {% endfor %} -
Should I be using the django.contrib.auth.models User model? Or is it better to create my own User model?
I'm still a beginner, and for some reason using a built in model such as User seems bugs me a bit. Should I create my own User model to become a more independent programmer, or will the User model do just as fine if not better for my project? Please tell me about the pros and cons about the User model. Any help is much appreciated. -
Getting a Error 400: redirect_uri_mismatch when trying to use OAuth2 with Google Sheets from a Django view
I am trying to connect to Google Sheets' API from a Django view. The bulk of the code I have taken from this link: https://developers.google.com/sheets/api/quickstart/python Anyway, here are the codes: sheets.py (Copy pasted from the link above, function renamed) from __future__ import print_function import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'] # The ID and range of a sample spreadsheet. SAMPLE_SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms' SAMPLE_RANGE_NAME = 'Class Data!A2:E' def test(): """Shows basic usage of the Sheets API. Prints values from a sample spreadsheet. """ creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('sheets', 'v4', credentials=creds) # Call the … -
Upload File to Django Admin, Process it, and Deliver to Template
I would like to upload a file object in the admin, run a process on this to convert it to html, and deliver the result to a template. I cannot figure out how to access the file object in order to run the handler, but the file itself is .json (jupyter notebook). Here is a basic model: #blog/models.py class FileUploader(models.Model): title = models.CharField(max_length = 200) notebook = models.FileField(upload_to='./notebooks/') In my views I have a notebook converter function: #blog/views.py def upload_file(request): notebook_html = converter(request.FILES['notebook']) return render(request, 'test.html', context={'html': notebook_html}) then, in my urls I have: #blog/urls.py urlpatterns = [ path('', views.upload_file, name = 'notebook_page') ] When I go to view the page, I get a MultiValueDictKeyError at /blog/ 'notebook' error. I'm not sure how to access the notebook file itself to run the conversion process on, not sure where in the MultiValueDict object this is or how it works. Big idea is to upload the file, convert it to html, inject in template. -
Is there a way to merge an airtable database and an SQLite database in Django?
So, what i have basically, is a table on airtable that is loading all the products on my api. I'm also loading other similar table with SQL. Is there a way of merging both? -
Trying to Use Gulp to Run Sass
It used to be you couldn't trust answers over five years old. Now it seems to be just down to months. I'm trying to set up Gulp to watch and compile my sass file in my Django project I followed the app doc to install gulp. The sample task worked. Every answer I saw to run sass was different. This version seemed to run the best: 'use strict'; // function defaultTask(cb) { // // place code for your default task here // cb(); // } // // exports.default = defaultTask var gulp = require('gulp'); var sass = require('gulp-sass'); sass.compiler = require('node-sass'); gulp.task('watch', function () { gulp.watch('./base/static/base/css/stylesheets/main.scss', gulp.series('sass')); }); gulp.task('default', gulp.series('sass', 'watch')); The commented out code was from the install and it worked. The error I get is "Task never defined: sass" gulp version 4.0.2 on MacOS. I also can't see where it plans to put the output css file. The correct location is one directory out from the input. I'm giving the path from where I'm running gulp, which is the root of the project. When I run sass manually, I use this command: /usr/local/bin/sass main.scss:../main.css I run it in the stylesheets directory. I have to specify the version because … -
Order Objects using an associated model and timedelta
I have a puzzle on my hands. As an exercise, I am trying to write a queryset that helps me visualize which of my professional contacts I should prioritize corresponding with. To this end I have a couple of models: class Person(models.Model): name = models.CharField(max_length=256) email = models.EmailField(blank=True, null=True) target_contact_interval = models.IntegerField(default=45) class ContactInstance(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='contacts') date = models.DateField() notes = models.TextField(blank=True, null=True) The column target_contact_interval on the Person model generally specifies the maximum amount of days that should pass before I reach out to this person again. A ContactInstance reflects a single point of contact with a Person. A Person can have a reverse relationship with many ContactInstance objects. So, the first Person in the queryset should own the greatest difference between the date of the most recent ContactInstance related to it and its own target_contact_interval So my dream function would look something like: Person.objects.order_by(contact__latest__date__day - timedelta(days=F(target_contact_interval)) but of course that won't work for a variety of reasons. I'm sure someone could write up some raw PostgreSQL for this, but I am really curious to know if there is a way to accomplish it using only the Django ORM. Here are the pieces I've found so … -
Django DRF adds double quotes around response even though it shouldn't
I'm trying to get some data from another API and return it on my local setup. It's a very simple script that calls the API and should just return the exact identical response to me. I'm using Django DRF btw. @api_view(['GET',]) def onlinenodes(request): """ Show Online nodes """ if request.method == 'GET': response = requests.get("https://stats.golem.network/v1/nodes") return Response(response.text) My issue is that, when I return my response.text and query my own API it returns the data but with double quotes around the JSON object, which I don't want. I literally just want to return the data received from the external API that has no double quotes around the JSON object. Issue visualized from my returned response: "[ { ... } ]" But I just want to return the following as i'm getting from the external API: [ { ... } ] If I try to print(response.text) it doesn't contain any double quotes either. It simply just happens in my response. What do I do to remove them?