Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My REST API data is not saving into database but it is returning the correct data
I am very new to Django. I want to store my data to my MYSQL database using a POST request and retrieve the data. However, for some reason, it is not storing to the database but retrieving the correct data. I am assuming cust = UserSerializer(data = user_req_data) line is not valid. How do I fix my code? class UserSerializer(serializers.ModelSerializer): def get_serializer_context(self): return self.context['request'].data def create(self, validatedData): request_data = dict(self.get_serializer_context()) user_req_data = { 'username':request_data['username'][0], 'password': make_password(request_data['password'][0]), 'email':request_data['email'][0] } cust = UserSerializer(data = user_req_data) if cust.is_valid(): cust.save() return user_req_data -
How to use other URLs in CRUD API using Django Rest Framework
I am trying to make a CRUD API using the Django Rest Framework. Here is my urls.py router = routers.DefaultRouter() router.register('products', ProductView) # router.register('products/delete/<id>', ProductView) (This is not working) urlpatterns = [ path('', include(router.urls)), ] Here is my views.py class ProductView(viewsets.ModelViewSet): queryset = Products.objects.all() serializer_class = ProductSerializer By using the above code I can fetch a list of all products --- 1) localhost/products (This gives a list of all products) 2) localhost/products/1 (This gives a product with id 1) How to use other URLs for operations such as Delete, Update etc. This above code is working. Nothing is wrong. I Just want to know how to use other routes from the client. -
Django view AttributeError: 'str' object has no attribute 'get'
This is communication between ajax operation and django view. I have a form, and if I click submit button of the form the Ajax code excuted. Ajax code: function makeEvent(event){ event.preventDefault(); var year = event.target.childNodes[3].children[0].value.slice(0,4); var month = event.target.childNodes[3].children[0].value.slice(5,7); var day = event.target.childNodes[3].children[0].value.slice(8,10); $.ajax({ type: "POST", url: "{% url 'makeevent' %}", data: {'form': $("#makeEventForm").serialize(), 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", success: function(response){ console.log(response); refreshCalendarAjax(year, month); listevent(year, month, day); document.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Create new event successful." ); }, error: function(request,status,error){ if (status == 599) { $("#sidebar").html = error; } else { console.log(error); } }, }); } View Code: def makeevent(request): if request.method == "POST": form = EventForm(request.POST.get('form', None)) if form.is_valid(): form.save() return HttpResponse("Successful", status=200) else: return HttpResponse(form.errors, status=599) else: print("NOT POST"); And if I try to submit a data through form, 500 error comes out and the error message is: Internal Server Error: /makeevent Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/workspace/CalendarProject/cencal/views.py", line 42, in makeevent if form.is_valid(): File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 185, in is_valid return self.is_bound and not self.errors File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 180, … -
Issue in accessing the local host
When working in django, upon opening localhost:8000, an empty file named 'download' is getting downloaded but the browser informs that the site cant be reached. But, I get a 200 response from the cmd (refer screenshot). Why this empty file is getting downloaded and how can I view the response in local host? Thanks in advanceenter image description here -
Django send_mail not working for smtp.google.com
The send_mail function run successfully and it displays everything in the console but the mail is not reaching the recipients. I think the settings.py has some missing variables which causes the error. Is the email is blocked by gmail security? I have turned on less secure app access in my gmail account so why gmail is blocking it? My settings.py EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'my_email' EMAIL_HOST_PASSWORD = 'my_pass' my models.py class Mails(models.Model): email = models.EmailField() subject = models.CharField(max_length=1000) message = models.CharField(max_length=2000) def __str__(self): return self.email forms.py class SendEmail(forms.ModelForm): email = forms.EmailField(max_length=200, widget=forms.TextInput(attrs={'class': "form-control", 'id': "clientemail"})) message = forms.CharField(widget=forms.Textarea(attrs={'class': "form-control"})) subject = forms.CharField(widget=forms.TextInput(attrs={'class': "form-control"})) class Meta: model = Mails fields = ('email', 'subject', 'message',) my views.py def send_email(request): if request.method == "POST": form = SendEmail(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.published_date = timezone.now() post.save() email = request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('message') email_from = settings.EMAIL_HOST_USER recipient_list = [email] print("Sending ...") # email = EmailMessage(subject, message, email_from, recipient_list) # email.send() send_mail(subject, message, email_from, recipient_list, fail_silently=False) HttpResponse("Message sent") else: form = SendEmail() return render(request, 'send_email.html', {'form': form}) template.html {% load static %} {% load crispy_forms_filters %} {% block content %} <form … -
How to return the model's xxx_set in Django Rest Framework?
I have two models like this: class ProductImageDetailScene(models.Model): ... class ProductImageDetailScene(models.Model): ... product_image_big_scene = models.ForeignKey( to=ProductImageBigScene, on_delete=models.DO_NOTHING, related_name="productimagedetailscene_set", ) class Meta: verbose_name = "ProductImageDetailScene" verbose_name_plural = "ProductImageDetailScenes" I want to use a API to return the ProductImageBigWithDetailScene, I mean return like this: [ big_scene1: { name: ... detail_scenes: [detail_scene1: {...}, detail_scene2: {...}] }, ... ] Bit how to write the Serializer? class ProductImageBigWithDetailSceneSerializer(ModelSerializer): # product_image_detail_scenes = ProductImageDetailScene(many=True, read_only=True) # I tried to add this param, but I will get error: raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: ProductImageDetailScene() got an unexpected keyword argument 'read_only' class Meta: model = ProductImageBigScene fields = "__all__" -
django 404 page not found error http://localhost:8000/static/feed.html
django is adding the /static/ url to my path and i don't know why Page not found (404) Request Method: GET Request URL: http://localhost:8000/static/feed.html 'feed.html' could not be found Page not found (404) Request Method: GET Request URL: http://localhost:8000/static/messages.html 'messages.html' could not be found Page not found (404) Request Method: GET Request URL: http://localhost:8000/static/upload.html 'upload.html' could not be found here is my views.py from django.shortcuts import render from django.views.generic import TemplateView, ListView, CreateView from app.models import SendSMS from app.forms import SendSMSForm from django.urls import reverse_lazy from app.utils import send_twilio_message from django.conf import settings import datetime # Create your views here. # Create your models here. def index(request): return render(request, 'index.html') def feed(request): return render(request, 'feed.html') def upload(request): return render(request, 'upload.html') def messages(request): return render(request, 'messages.html') def statistics(request): return render(request, 'statistics.html') class SendSmsCreateView(CreateView): model = SendSMS form_class = SendSMSForm template_name = 'messages.html' success_url = reverse_lazy('send_sms') def form_valid(self, form): number = form.cleaned_data['to_number'] body = form.cleaned_data['body'] # call twilio sent = send_twilio_message(number, body) # save form send_sms = form.save(commit=False) send_sms.from_number = settings.TWILIO_PHONE_NUMBER send_sms.sms_sid = sent.sid send_sms.account_sid = sent.account_sid send_sms.status = sent.status send_sms.sent_at = datetime.datetime.now() if sent.price: send_sms.price_unit = sent.price_unit send_sms.save() return super(SendSmsCreateView, self).form_valid(form) here is my app urls.py from . import views from … -
Error: Multiple Settings in Django & Heroku
I'm having some issues with "Internal Server Error" in Heroku. This happened after I tried to create multiple settings (base, local and production) as you can see below: ──/ ── home/ ── settings/ ├── __init__.py ├── base.py ├── local.py └── production.py local.py from home.settings.base import * import os # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'some_key_here' DEBUG = True # Media settings MEDIA_DIR = os.path.abspath(os.path.join(BASE_DIR, '..', 'media')) MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' production.py from home.settings.base import * import django_heroku from decouple import config DEBUG = False SECRET_KEY = os.environ['SECURE_KEY'] django_heroku.settings(locals()) # is this path correctly? # AWS settings AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_LOCATION = 'media' wsgi.py and manage.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'home.settings') I tried to change both files above (wsgi and manage) to os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'home.settings.production') but it didn't work. I've also created the DJANGO_SETTINGS_MODULE in Heroku: Any help, guys? -
DEBUG = False causing 500 errors and unable to force logging everything to console in Django
I am trying to troubleshoot a 500 error, as whenever I set DEBUG = False in Django, I receive a 500 error. I attempted to set ALLOWED_HOSTS = ['*'] I attempted to setup LOGGING to debug and force logging to console with a loop. However, it does not work, so there is a good chance it is not doing what I think it should be doing. I have attached a snippet from my settings file: settings.py: DEBUG = False LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), }, }, } for logger in LOGGING['loggers']: LOGGING['loggers'][logger]['handlers'] = ['console'] ALLOWED_HOSTS = ['*'] -
Images in django's email are not displayed
I used EmailMultiAlternatives and django template to create email and send. I can receive the email in gmail but the images are not shown. In the template I set <img src="https://[my image url]"> In the email in gmail the img src turns out to be https://ci3.googleusercontent.com/proxy/...#[my image http url] but the image is not found I can access the image by the image's http url from browser. What should I do to fix it? -
Strange server outages when using Django Channels
I’m trying to write multiplayer chat using Django Channels. I followed the tutorial on https://channels.readthedocs.io/en/latest/index.html. Everything works okey on my local server, I continued with deploying but then I got some strange bug. When I tried to test to chat with other users with the help of my friends programmers (on real server), I ran into this thing: sometimes(!) when there are more than 8-9 users, messages stop coming back: they reach server, being saved the Database, being send to channels, BUT actually do not come from channels back to consumers and that’s why aren’t sent back to users of the chat! I have no idea what to do :(( Could anybody please help me with this? -
Attach A ReportLab Pdf To A Model
After logging in, my users complete a four forms and a pdf is generated containing the data from the forms. I can successfully do this and save the pdf, but dont know how to attach the generated pdf to the user. I usually save form data in an if request.method == 'POST': statement in the view.py file, but the pdf isnt being sent through POST, it is instead generated and saved within a function called after if request.method == 'POST': so I guess i need a way to attach it to the users pdf model within that function? Also, the questionnaire is quite large so I broke it into four separate forms and four seperate models each with a one-to-one relationship with the user. Is this good practice or should I create one large model and break it up using four separate forms? utils.py def generate_questionnaire_pdf(request): # get user user = request.user # create pdf pdf = SimpleDocTemplate(settings.MEDIA_ROOT+'\pdfs\\questionnaire_pdfs\\user_%s.pdf' %user.id) [..cont..] pdf.build(elems, onFirstPage=partial(pageSetup, title=title, user=user), onLaterPages=pageSetup) form.py class QuestionnairePdfForm(forms.ModelForm): class Meta: model = QuestionnairePdf fields = ['questionnaire_pdf'] model.py class QuestionnairePdf(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) questionnaire_pdf = models.FileField(upload_to='pdfs\\questionnaire_pdfs') view.py def final_question(request): if request.method == 'POST': form = FinalQuestionForm(request.POST, request.FILES, instance=request.user.finalquestion) if form.is_valid(): … -
Django: Where does this zip file create to?
For some context, I have a django-rest-framework project. This particular endpoint takes a json blob, and zips it before saving it to a FileField. My question is– where exactly is this zip file I'm creating saving to? Just the root directory? Will these regularly need to be cleaned up? class MyModel(models.Model): ... def create_zip(self, user, jsondata): filename = "data" + ".zip" with gzip.GzipFile(filename, "w") as fout: fout.write(jsondata.encode("utf-8")) my_model = MyModel.objects.create( user=user, animation_file=filename ) -
TypeError at /signup object of type 'NoneType' has no len()
class RegistrationView(View): def get(self,request): return render(request, 'accounts/signup.html') def post(self, request): context={ 'data':request.POST, 'has_error':False } name = request.POST.get('name') username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') password1 = request.POST.get('password1') username = request.POST.get('username') if len(password)<8: messages.add_message(request,messages.ERROR, 'Password should be atleast 8 characters long !!!') context['has_error']=True -
How to add app_label in Custom Auth User Model in Django?
Following code snippet I have tried but did not work for me class User(AbstractBaseUser): class Meta: app_label = 'apis' -
combine django-filter with an ajax call
I am using a package called django-filter it's basically a filtering system but i want to improve it and filter my product model without refreshing the page filter.py class ProductFilter(django_filters.FilterSet): category = django_filters.MultipleChoiceFilter(field_name='category', choices=CATEGORY_CHOICES, widget=forms.CheckboxSelectMultiple()) Type = django_filters.MultipleChoiceFilter(field_name='Type', choices=TYPE_CHOICES, widget=forms.CheckboxSelectMultiple()) class Meta: model = Product fields = { 'price': ['lt', 'gt'], } views.py : def ProductList(request): products = Product.objects.all() f = ProductFilter(request.GET, queryset=products) context={ 'products' :products, 'filter' :f, } return render(request,'ProductList.html',context) the filtering form is automatically generated with the template tag filter.form , when the form is submitted the product model is filtered based on the parameters inside the request.Get but if i prevent the form submission to make an Ajax request that request.GET does not exist so how do i send that same data inside an ajax request ?? -
Django Autocomplete light Value error for dependent chained dropdown menu from two different tables
I have been going over the DAL tutorial and now trying to implement it to my project but keep getting "ValueError: too many values to unpack (expected 2) [25/May/2020 18:42:17] "GET /wellsurfer/ajax/load_casing_weights?forward=%7B%7D HTTP/1.1" 500 17744 " the form looks like following and as you can see i can not make the form to filter the results down so the weight menu populates enter image description here forms.py class NewCasingDesignForm(forms.ModelForm): od = forms.ModelChoiceField(queryset=CasingCatalogue.objects.order_by().distinct().values_list('size', flat=True)) class Meta: model = CasingDesign fields = ( 'well', 'od', 'weight', 'pipeyield', 'connection','inner_diameter', 'set_depth', 'top_depth', 'type_csg_lnr',) help_texts = { 'well': 'Select a well', 'od': 'unit, inches', 'weight': 'unit, lbs', 'pipeyield': 'unit, psi', 'connection': 'Type', 'inner_diameter': 'unit, inches', 'set_depth': 'What depth (feet) the pipe is set (shoe depth)', 'top_depth': '0 feet to indicate casing or a depth greater than 0 for liner', 'type_csg_lnr': 'Confirm if string is a casing or liner', } widgets = { 'well': forms.Select(attrs={ 'class': 'form-control', }), 'od': forms.Select(attrs={ 'class': 'form-control', }), 'weight': autocomplete.ListSelect2(url='wellsurfer:ajax_load_casing_weight', forward=['od']), 'inner_diameter': forms.NumberInput(attrs={ 'class': 'form-control', 'placeholder': '8.835' }), 'set_depth': forms.NumberInput(attrs={ 'class': 'form-control', 'placeholder': '5000' }), 'top_depth': forms.NumberInput(attrs={ 'class': 'form-control', 'placeholder': '0' }), 'type_csg_lnr': forms.Select(attrs={ 'class': 'form-control', }), } views.py def new_casing_design(request): if request.method == 'POST': form = NewCasingDesignForm(request.POST) if form.is_valid(): newcasingdesign … -
How to login user from a specific database table of my choice using django
this is a sample code to login user from the database table "auth_user" created by django but how can i choose a table of my choice like the one i created to log user in def login(request): if request.method == 'POST': userName = request.POST['userName'] password = request.POST['password'] user = auth.authenticate(username=userName, password=password) if user is not None: auth.login(request, user) return redirect("/") else: messages.info(request, 'Invalid Credentials') return redirect ('login') else: return render(request, 'login.html') -
My django app font from Digital Ocean spaces are not working
I have a django app on a live server, the static files are hosted on Digital Ocean spaces. The static files are working well but the fonts are not. I thought probably it was because the font files are linked to the /static/ folder so I changed the @font-face src: url() parameter to the digital ocean spaces cdn link for the font files but its not still working. I even embedded the @font-face rule in the html template and connected the font files with the django static files template url but its still not working. Though the font is working on my loacalhost. {% load static %} <head> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no"> <style type="text/css"> @font-face { font-family: 'TT Norms Pro'; src: url(' {% static 'user/fonts/TTNormsPro-Bold.eot' %} '); src: local('TT Norms Pro Bold'), local('TTNormsPro-Bold'), url('{% static 'user/fonts/TTNormsPro-Bold.eot?#iefix' %} ') format('embedded-opentype'), url('{% static 'user/fonts/TTNormsPro-Bold.woff2' %}') format('woff2'), url('{% static 'user/fonts/TTNormsPro-Bold.ttf' %}') format('truetype'); font-weight: bold; font-style: normal; } @font-face { font-family: 'TT Norms Pro'; src: url('{% static 'user/fonts/TTNormsPro-Regular.eot' %}'); src: local('TT Norms Pro Regular'), local('TTNormsPro-Regular'), url('{% static 'user/fonts/TTNormsPro-Regular.eot?#iefix' %}') format('embedded-opentype'), url('{% static 'user/fonts/TTNormsPro-Regular.woff2' %}') format('woff2'), url('{% static 'user/fonts/TTNormsPro-Regular.woff' %}') format('woff'), url('{% static 'user/fonts/TTNormsPro-Regular.ttf' %}') format('truetype'); font-weight: normal; font-style: normal; } </style> <link … -
Prevent page refresh when submitting Django form
Is there any way to stop refreshing of the form page after hitting submit button? I am looking for doing this in front end using javascript. -
Django + React Integration
I have some knowledge on react as an intermediate.Now I want to build a backend with django for react-application.How can I integrate those?I want to have my own database,forms (built-in django forms to login etc.).Thanks in advance. -
Heroku deploy problem: ModuleNotFoundError: No module named 'FatCatFish.wsgi'
I'm trying to deploy a full-stack application with a django backend. Everything worked fine locally and heroku says the build succeeds but the webserver doesn't run. What am I missing? Do I need to start the project and run migrations? Procfile web: gunicorn FatCatFish.wsgi --log-file - Log: 2020-05-25T23:26:31.413415+00:00 heroku[web.1]: State changed from crashed to starting 2020-05-25T23:26:44.404022+00:00 heroku[web.1]: Starting process with command `gunicorn FatCatFish.wsgi --log-file -` 2020-05-25T23:26:47.619979+00:00 heroku[web.1]: Process exited with status 3 2020-05-25T23:26:47.668525+00:00 heroku[web.1]: State changed from starting to crashed 2020-05-25T23:26:47.481429+00:00 app[web.1]: [2020-05-25 23:26:47 +0000] [4] [INFO] Starting gunicorn 20.0.4 2020-05-25T23:26:47.482134+00:00 app[web.1]: [2020-05-25 23:26:47 +0000] [4] [INFO] Listening at: http://0.0.0.0:46677 (4) 2020-05-25T23:26:47.482290+00:00 app[web.1]: [2020-05-25 23:26:47 +0000] [4] [INFO] Using worker: sync 2020-05-25T23:26:47.487376+00:00 app[web.1]: [2020-05-25 23:26:47 +0000] [10] [INFO] Booting worker with pid: 10 2020-05-25T23:26:47.494729+00:00 app[web.1]: [2020-05-25 23:26:47 +0000] [10] [ERROR] Exception in worker process ... 2020-05-25T23:26:47.494768+00:00 app[web.1]: ModuleNotFoundError: No module named 'FatCatFish.wsgi' -
Using Django to show a csv pandas file in html
Building a site using Django. I am trying to show the information of a csv file in html. I am trying to arrange the file through python pandas. There are no errors being thrown up however what's contained in the file is not being shown. In the code below I am trying to display the printed result from the pandas in my html file. My python file: import pandas as pd df = pd.read_csv('faults.csv') printed = print(df) def reader(str): file = str + '.csv' return file My html page: <a href={% url 'thehomepage' %}>go back to the home page</a> <p>{{ input_from_home_page }}</p> <p>{{ printed }}</p> -
Django environment variables in MAC - os.environ.get() returns None
Working on Django project, I am at the production stage, trying to hide SECRET_KEY before production using environment variables in MAC computer. I have added secret keys in .bash_profile from Terminal using nano. However when I call the saved variable (secret key) on the terminal, I got key value using: echo $variable Then i tried calling secret key variable in settings.py in Django project using: secret_key = os.environ.get('saved variable(secret key) from .bash_profile) However, it is returning None . Please can someone help me with this? I have tried solutions on here but still have not resolved issue. I know the new MAC update Catalina uses zprofile but i do not know how my issue is linked to this. -
Submit button in template leading to HTTP ERROR 405
I am adding a comment section for my posts, the issue is after submitting it leads to HTTP ERROR 405 This is the first time to receive this error, I have reviewed the views several times but I think the error might be from the views.py in post detail view class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter(post=post).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') comment = Comment.objects.create( post=post, user=request.user, content=content) comment.save() return HttpResponseRedirect("post_detail.html") else: comment_form = CommentForm() context["total_likes"] = total_likes context["liked"] = liked context["comments"] = comments context["comment_form"] = comment_form return context here is the template <div class="main-comment-section"> {{comments.count}} Comment{{comments|pluralize}} {% for comment in comments %} <blockquote class="blockquote"> <p class="mb-0"> {{ comment.content}}</p> <footer class="blockquote-footer">by<cite title="Source Title">{{comment.user| capfirst}}</cite></footer> </blockquote> {% endfor %} here is the comments models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(max_length=160) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return '{}-{}'.format(self.post.title, str(self.user.username))