Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best practice for looping python script in Django
So I have an app design question I'm hoping someone can help me with. I am building a network automation app for my company and currently have a python script which runs on a constant loop every 15 seconds to check on the health of a few hundred network devices across the company, essentially just pinging out. As an FYI, the app is in a docker container and being deployed to an azure web app. The goal is to build a django app that interfaces with all this information so there is a nice little web front end to view the state of the network and run commands from. The problem is, when trying to get the looping function to be called from 'views.py' for my python script it just takes over the server, so now the website goes down while it's looping. I can't seem to run the forever looping python script and keep the django web server running at the same time. Is there a better way to do this with Django and a constantly looping python script? Should I take this particular script out of the django app entirely and host it separate in azure some how … -
Django Rest Framework - How to serialize reverse relation field
I have a CustomerSerializer which uses a reverse foreign key field images to return all associated Image objects. class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ('id', 'name', 'images') read_only_fields = ('id',) This is what I get from the response: [ { 'id': 1, 'name': 'John Doe', 'images': [ 1, 2, 3, 4, ... ] } ... ] Question: Instead of just showing images as a list of ids, how can I show a different property i.e. name? The desired result would be: [ { 'id': 1, 'name': 'John Doe', 'images': [ 'foo.jpg', 'bar.jpg', 'foobar.jpg', 'lorem.jpg', ... ] } ... ] My first attempt - I replaced the reverse foreign key images with image_names from the SerializerMethodField() in order to select the field name, but I get a null value. class CustomerSerializer(serializers.ModelSerializer): image_names = serializers.SerializerMethodField() def get_image_names(self, obj): return obj.images.name class Meta: model = Customer fields = ('id', 'name', 'image_names') read_only_fields = ('id',) Additional Info Example models: class Customer(models.Model): name = models.CharField() class Image(models.Model): name = models.CharField() customer = models.ForeignKey( Customer, related_name='images', on_delete=models.CASCADE) Please let me know if anything is unclear and I will update the question. Thank you. -
Im trying to get an id for a comment for update, delete, and to count Upvotes and downvotes
Im trying to get an id for a comment for update, delete, and to count Upvotes and downvotes, everything was working fine until I began using Django-mptt in order to have reply-able comments. Now Im trying to call the comments by node.id and it isn't working. Does anyone have any advice or know if this is every possible (without a ton of complex code). Here is my code urls.py path('<int:year>/<int:month>/<int:day>/<slug:post>/<node_id>/Upvote',views.Upvote_comment, name='Upvote_comment'), path('<int:year>/<int:month>/<int:day>/<slug:post>/<comment_id>/Downvote',views.Downvote_comment, name='Downvote_comment'), views.py def Upvote_comment(request, year, month, day, post, comment_id = None): post = get_object_or_404(Post , slug=post, status='cleared',publish__year=year,publish__month=month,publish__day=day) comments = post.comments.filter(active=True) comment = Comment.objects.get(id=comment_id) comment_form = CommentForm(data=request.POST) user = request.user if user in comment.Upvote.all(): comment.Upvote.remove(user) else: comment.Upvote.add(user) if user in comment.Downvote.all(): comment.Downvote.remove(user) comment.save(force_update=True) comment_form = CommentForm() messages.success(request, f'Comment has been Upvoted!') return HttpResponseRedirect( post.get_absolute_url() ) def Downvote_comment(request, year, month, day, post, comment_id = None ): post = get_object_or_404(Post , slug=post, status='cleared',publish__year=year,publish__month=month,publish__day=day) comments = post.comments.filter(active=True) comment = Comment.objects.get(id=comment_id) comment_form = CommentForm(data=request.POST) user = request.user if user in comment.Downvote.all(): comment.Downvote.remove(user) else: comment.Downvote.add(user) if user in comment.Upvote.all(): comment.Upvote.remove(user) comment.save(force_update=True) comment_form = CommentForm() messages.success(request, f'Comment has been Downvoted!') return HttpResponseRedirect( post.get_absolute_url() ) models.py class Comment(MPTTModel): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') parent = TreeForeignKey('self', on_delete=models.SET_NULL,null=True, blank=True, related_name='children') name = models.ForeignKey(User, on_delete=models.SET_NULL,null=True) body = models.TextField() … -
Do I need background tasks in django channels or can I just call functions inside the consumer?
I've just started learning how to use Django Channels - I've followed the tutorial on the docs and a read a bit online. My use case is fairly simple, I'm working with the Web MIDI API and I want to send MIDI to the server and have it represented in JSON, so that the client can query it later. I was doing this over HTTP, but the MIDI data was getting sent too fast and too often for HTTP to keep up. Once the data is received by the consumer, am I OK to just call a python function on it to store it in a dictionary directly inside the consumer, I've got functions already written that could do this. Is this an acceptable way to do it, or do I need to use these Worker or Background processes I've read about. The functions are quite simple, so I figured this method would be OK, but is there any reason why I should avoid this? -
Django code throws render to response error even though I'm not using it?
I get this error: ImportError: cannot import name 'render_to_response' from 'django.shortcuts' (C:\Python34\lib\site-packages\django\shortcuts.py) But my code looks like this: from django.shortcuts import render, redirect, render_to_response def proratesearch(request): context = { 'queryset': ers, 'ers2': ers2, } return render(request, 'conversion/query.html', context) What am I missing. Everything is like what people online say. -
How do I resolve a raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch error in Django 3.1 on Mac OS Catalina?
I'm currently going through "Python Crash Course" by Eric Matthes. I'm on Chapter 19 trying to add a page to a web app where users can enter data. If working correctly, the user can write an entry about a topic that he/she is learning about. I wrote the code exactly how the book told me. Sadly I keep getting the following error: File "/Users/jakeziegelbein/Desktop/crashCoursePython/learning_log/11_env/lib/python3.8/site-packages/django/urls/resolvers.py", line 685, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'learning_logs/new_entry' not found. 'learning_logs/new_entry' is not a valid view function or pattern name. Here are the files of code: views.py from django.shortcuts import render, redirect from .models import Topic, Entry from .forms import TopicForm, EntryForm def index(request): """The home page for Learning Log.""" return render(request, 'learning_logs/index.html') def topics(request): """Show all topics.""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) def topic(request, topic_id): """Show a single topic and all its entries.""" topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) def new_topic(request): """Add a new topic.""" if request.method != 'POST': # No data submitted; create a blank form. form = TopicForm() else: # POST data submitted; process data. form = TopicForm(data=request.POST) if form.is_valid(): form.save() return redirect('learning_logs:topics') # Display … -
Django MultiValueKeyDictError while saving data for a multistep form
class multi_form(View): model=Customer template_name='index.html' def get(self, request): return render(request, 'customer/index.html') def post(self,request): if(request.method!="POST"): return HttpResponseRedirect(reverse('')) else: first_name=request.POST.get("fname") last_name=request.POST.get("lname") personal_email=request.POST.get("Pid") official_email=request.POST.get("Oid") current_address=request.POST.get("Cadd") permanent_address=request.POST.get("Padd") pan_card_number=request.POST.get("Pan") aadhar_card_number=request.POST.get("Aadhar") loan_amount=request.POST.get("LAmount") request.session['fname']=first_name request.session['lname']=last_name request.session['Pid']=personal_email request.session['Oid']=official_email request.session['Cadd']=current_address request.session['Padd']=permanent_address request.session['Pan']=pan_card_number request.session['Aadhar']=aadhar_card_number request.session['Lamount']=loan_amount personal_photo=request.FILES['PhotoAttachment'] bank_statement=request.FILES['BankAttachment'] salary_slip=request.FILES['SalaryAttachment'] pan_card=request.FILES['PanAttachment'] aadhar_card=request.FILES['AadharAttachment'] try: CustomerForm1=CustomerInfo(first_name=first_name, last_name=last_name, personal_email= personal_email, official_email=official_email, current_address=current_address, permanent_address=permanent_address, pan_card_number=pan_card_number, aadhar_card_number=aadhar_card_number, loan_amount=loan_amount) CustomerForm2=Customer(first_name=first_name, last_name=last_name, personal_email= personal_email, official_email=official_email, current_address=current_address, permanent_address=permanent_address, pan_card_number=pan_card_number, aadhar_card_number=aadhar_card_number, loan_amount=loan_amount, personal_photo=personal_photo, bank_statement=bank_statement, salary_slip=salary_slip, pan_card=pan_card, aadhar_card=aadhar_card) CustomerForm1.save() CustomerForm2.save() messages.success(request, "Your Response has been recorded") return render(request, 'customer/index.html') except: return render(request, 'customer/index.html') So, I was trying to save fields of a multi-step form. Upon submission after only the first step and skipping the second step altogether I am displayed this error. MultiValueDictKeyError at / ('PhotoAttachment', None) How do I resolve this and save data of first of this form ie. CustomerForm1. I want to save data in form fields of both the forms although they contain duplicate fields Note: If I remove the submit button in first step and CustomerForm1 from views.py then I don't get this error implying forms works fine otherwise. -
How to hide/exclude certain fields of foreign key in graphene_django?
I have read about how to exclude (hide) certain fields in django and graphene_django in these Links: graphql-python repository Why does my excluded field still appear in this Django form? etc. Imagine that we have the following Post model which has foreign key to the User model. apps/posts/models.py from django.db import models from apps.users.models import User class Post(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, null=False ) created_at = models.DateTimeField( auto_now_add=True, ) title = models.TextField( null=False, max_length=100, ) content = models.TextField( null=False, ) def __str__(self): return self.title apps/users/models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser, models.Model): phone_no = models.CharField( blank=True, null=True, default="", max_length=10, verbose_name="Phone Number", ) avatar = models.ImageField( null=True, upload_to='static', ) USERNAME_FIELD = "username" EMAIL_FIELD = "email" def __str__(self): return self.username I tried the following but it faced to an error: apps/posts/schema.py import graphene from graphene import Mutation, InputObjectType, ObjectType from graphene_django.types import DjangoObjectType from .models import Post class PostType(DjangoObjectType): class Meta: model = Post exclude_fields = [ 'created_at', #it worked 'author.password', #the way I tried to hide the foreign key field ] class Query(ObjectType): posts = graphene.List( PostType ) def resolve_posts(self, info): #TODO: pagination return Post.objects.all() How can I hide certain fields of it (like author's password … -
KeyError 'password' for Django User Serializer(was working, just transferred to Postgres and now not working?)
I am not sure why it's not POST-ing new Users, since it was working right before I transferred by DB to Postgres (also not sure if that could even affect this?). I originally had CharField in my Models, but it was throwing an error, regarding the Max_Character length(even though it was under 50). So, I currently have my models as Text_Field. Anything helps! Model: from django.contrib.auth.models import User, AbstractUser class User(AbstractUser): username=models.TextField(unique=True) email=models.TextField(unique=True) password=models.TextField def __str__(self): return self.username View: class UserView(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (permissions.AllowAny,) Serializer: from rest_framework import serializers from . import models from django.contrib.auth.hashers import make_password class UserSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ('id', 'username', 'email', 'password', 'favorites', 'reviews') depth = 2 def create(self, validated_data): user = models.User( email = validated_data['email'], username = validated_data['username'], password = make_password(validated_data['password']) ) user.save() return user -
can we apply django ordering on a field of SerializerMethodField
I have a field like matchCount= serializers.SerializerMethodField('get_match') def get_match(self, obj): likes = obj.post.count #here will be logic of almost 120 lines so cant use annotate* return likes / time if time > 0 else likes Now I want to order on basis of this filed matchCount. what can be best solution in this case ? until now I found other developers are using annotate etc but as this logic is dynamic and will count match on run time , what can I do to sort on basis of this field ? -
How to Login_required for Comments inside a view, Django
So i have this post_detail view, and i want to apply login_required but only for the comments, so people is able to enter the detail_post view and watch but not to Comment. I should login_required a part of the view or may be the Comment model? I tried to login_required the model but didn't work, i get an error. view: def post_detail(request, post_slug): post = get_object_or_404(Post, slug=post_slug, status='published',) # List of active comments for this post comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': # A comment was posted comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = CommentForm() # List of similar posts post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids)\ .exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags'))\ .order_by('-same_tags','-publish')[:4] Model: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return f'Comment by {self.name} on {self.post}' -
Recurrent objects in Django
I need some help in order to manage adding a new feature on my website created in Django. I made a spendings tracker website where a user can add as many personalized spendings and budgets he/she likes but I have a problem. I want to make a user to have the possibility to create recurrent spendings and budgets. For example if a user creates a spending right now and he select to be recurrent the website should some how add in the next month the same spending at the same date. If I create now a new spending, next month on 20th September the website should add this automatically. Some help please. Spending object in models.py file: class Spending(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) category = models.CharField(max_length=100) amount = models.FloatField() date_created = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.user.username}\'s {self.name}' Function that create a spending in views.py file: @login_required def create_spending(request): Spending.objects.create(user=request.user, name=request.POST['spending_name'], category=request.POST['spending_category'], amount=request.POST['spending_amount']) return redirect('dashboard') I know that I need to add a new boolean row to table Spending and some if cases in this function but I don't have the exact idea and I need some help please. -
Django forcing logout on form submission
I have a Django application being used by multiple users. Users have told me that sometimes they will submit a form and it will redirect them to the login view (logs them out). When they log back in, the form was successfully submitted, but it is a strange and annoying bug. I have tried to duplicate this, but I can't seem to reproduce this behavior. Sorry for the lack of information here, but I am hoping someone has either seen this before, or can point me in the right direction for de-bugging an error like this. Thanks in advance! A little more info that may be useful: -I am using Django 3.1, and am running this on a local ubuntu Virtual machine within a corporate network. The VM is using postgres, NGINX, gunicorn to serve the application. -
Django Foreignkey in MongoDB's EmbeddedField
I am using Djongo engine for MongoDB in my Django project. I have two tables # app/models.py # My Main Table class Questions(models.Model): questionId = models.UUIDField(default=uuid.uuid4, editable=True, unique=True) question = models.TextField() answer = models.EmbeddedField( model_container=Answers ) date = models.DateTimeField(auto_now_add=True, blank=True) User = models.ForeignKey(UserDetailTable,on_delete=models.CASCADE,related_name='userinfo') and # app/models.py # This table needs to be Embedded in Questions Table class Answers(models.Model): answerId = models.UUIDField(default=uuid.uuid4, editable=True, unique=True) answer = models.TextField() date = models.DateTimeField(auto_now_add=True) User = models.ForeignKey(UserDetailTable,on_delete=models.CASCADE) class Meta: abstract = True I want to embed Answers in the Questions table. But I am getting this error django.core.exceptions.ValidationError: ['Field "App.Answers.User" of model container:"<class \'App.models.Answers\'>" cannot be of type "<class \'django.db.models.fields.related.ForeignKey\'>"'] I know this error is because I am using User = models.ForeignKey(UserDetailTable,on_delete=models.CASCADE) in Answers which is itself an EmbeddedField on Questions. How Can I solve this error? As there will be multiple answers from different users on the same question and with ForeignKey it will be simple to show the user's info along with his/her answer. I have also looked djongo's docs but couldn't find anything. Any help would be appreciated. -
How do i take care of these issue with django channels?
'''python manage.py runserver''' Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/abbracx/Documents/virtualenv/pycon/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/abbracx/Documents/virtualenv/pycon/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/abbracx/Documents/virtualenv/pycon/lib/python3.7/site-packages/django/core/management/__init__.py", line 244, in fetch_command klass = load_command_class(app_name, subcommand) File "/home/abbracx/Documents/virtualenv/pycon/lib/python3.7/site-packages/django/core/management/__init__.py", line 38, in load_command_class return module.Command() **AttributeError: module 'channels.management.commands.runserver' has no attribute 'Command'** Please these is the error i have been battling with when i include channels at the top of my install apps. when included bellow the install apps it is the django server that runs instead of Asgi channels server. Why? -
How to group by and count in a subquery with Django's ORM?
I have a table map(id, key, value) from where I would like to select the keys that have same value. In SQL I could do SELECT key FROM map WHERE value IN (SELECT value FROM map GROUP BY value HAVING COUNT(*) > 1); I tried to translate it into Django's ORM style from django.db.models import Count Map.objects.filter(value__in=Map.objects.values('value').annotate(count=Count('value')).filter(count__gt=1)).values('key') But it fails because the subquery in the __in filter returns two columns, the selected value column and a column for the count: SELECT "map"."key" FROM "map" WHERE "map"."value" IN (SELECT U0."value", COUNT(U0."value") AS "count" FROM "map" U0 GROUP BY U0."value" HAVING COUNT(U0."value") > 1) How can I remove the uneeded count column from that subquery? -
Unable to write Dynamic meta tag in django
Hello all i want to print dynamic meta tag values in django. i have _header.html as partial file which is common to all the pages. In that header file i want to add meta tags. The header file is included in base.html and base extends all the other pages i want different meta tags for different pages. the below code is for _header.html file {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> "here i want dynamic meta tags" <title>Random Blog</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href="{% static 'css/main.css' %}"> </head> -
django.db.utils.OperationalError: could not connect to server: Connection refused
I have 3 docker containers web(django) , nginx, db(postgresql) When I run the following command docker-compose -f docker-compose.prod.yml exec web python manage.py migrate --noinput The exact error is: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Address not available Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? docker-compose.prod.yml version: '3.7' services: db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.envs/.db web: build: context: ./tubscout dockerfile: Dockerfile.prod command: gunicorn hello_django.wsgi:application --bind 0.0.0.0:8000 volumes: - .static_volume:/home/app/web/staticfiles expose: - 8000 env_file: - ./.envs/.prod depends_on: - db nginx: build: ./nginx volumes: - .static_volume:/home/app/web/staticfiles ports: - 1337:80 depends_on: - web volumes: postgres_data: static_volume: Dockerfile.prod ########### # BUILDER # ########### # pull official base image FROM python:3.8.3-alpine as builder # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps -w /usr/src/app/wheels -r requirements.txt ######### # FINAL # ######### # pull official base … -
How to disable VSCode's Explorer opening directory of opened file?
I'm using VSCode (1.47.3) on Ubuntu Bionic with the MS Python Extension Pack. I really want to disable the feature whereby Explorer decides to open the parent folder of the file I have just opened and allow me the control to open this folder manually (if I want to, which I rarely do). Scenario: I have some app-specific .py files open and Explorer shows my app's folder: "app" - all good. I navigate to a DJango dependency e.g. models.Manager when suddenly Explorer automatically shows the folder: site-packages/django/db/models - which I don't to happen. I didn't ask it to happen. In order to go back to the context of my top-level "app" folder, I have to scroll 100km back to where I was! I just want Explorer to stay in my "app" directory, regardless of what other files I may open. I only opened the DJango dependency for context/reference. I have no intention of editing that file (obviously) so I don't need any other DJango context. If I want to open a parent directory of a random file I've opened, I'll do that myself. How can I disable VSCode from doing this? Is there some JSON config I can modify? -
How to store JWTs in HttpOnly Cookies?
I am currently developing a React-Django App and using JWTs for authentication. After a little research I found out that storing JWTs in client is not safe(XSS and XSRF) and most of the people advice that I should store them in server-side with HttpOnly cookies but nobody tells how to do it. So can anybody help with that? -
Save the voice recorder by Recorder js to the backend database DJANGO
So I was able to create a js code that takes user input and display it to the user so he can hear it, however, I'm not sure exactly how can I save it in Django database to be a voice message in short I don't know which thing I should pass to Django to save it within my ajax function Template view (index.html): <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous" /> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <link rel='stylesheet prefetch' href='https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css'> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="icon" href="https://medias.pylones.com/9387-thickbox_default/pen-rocket-pen.jpg" type="image/jpg" sizes="16x16"> <title>Recorder</title> </head> <body> <div id="ok"></div> <div class="col-md-5 container"> <button class="btn btn-secondary p-3" style="border-radius: 50%;" id="recorder"> <i class="fa fa-microphone" style="font-size: 67px"></i> </button> </div> <script> $(document).ready(function () { var i = 0, timeOut = 0; $('#recorder').on('mousedown', function (e) { timeOut = setTimeout(() => { $(this).addClass('btn-success') $(this).removeClass('btn-secondary') navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => { mediaRecorder = new MediaRecorder(stream) mediaRecorder.start(); chuck = []; mediaRecorder.addEventListener("dataavailable", e => { chuck.push(e.data) }) mediaRecorder.addEventListener("stop", e => { blob = new Blob(chuck); audio_url = URL.createObjectURL(blob); audio = new Audio(audio_url); audio.setAttribute("controls", 1); ok.appendChild(audio) }) }) }, 500); }).bind('mouseup touchhend', function (e) { $(this).addClass('btn-secondary') $(this).removeClass('btn-success') clearInterval(timeOut); mediaRecorder.stop() console.log(chuck) $.ajax({ url: "{% url 'create_voice' %}", method: 'get', dataType: 'json', data: { … -
Integrating Sqlalchemy with django
I am working on django project and new requirement is to change my django ORM to sqlalchemy and graphene. I am new to sqlalchemy and graphene. I need to perform crud using graphene. I am able to perform insert record using sqlalchemy, but not do with graphene. If any one has idea how to do that It would be highly helpful. Below is the my model definition in models.py file class Movie(models.Model): name = models.CharField(max_length=100) genere = models.CharField(max_length=50) budget = models.FloatField() releaseYear = models.IntegerField() I have converted for sqlalchemy as class Movie(Base): __tablename__:'movie' name = Column(String(100)) genere = Column(String(50)) budget = Column(Numeric) releaseYear = Column(Integer) -
How to create objects of forms through Django Admin
I have a problem that I need to solve. I have no clue what to search or how to approach the problem. I want with the help of Django, create my "own" custom forms through Django Admin so I can use these as Objects. For example through Django Admin I want to for example press a button "Create new form" and select what new field I want to use, for example I want to have one field of charfield, and two fields of datefield. So it will create a new form, and then next time when i press that button I want to create a different one, one with IntegerField and one with charfield. What things should I look into to solve this problem? I have already knowledge in Django but I have no idea what to use to solve this perticular problem. I have read through the documentation. -
Pythonanywhere Django app does not work with MySql
What do we have: Django app hosted on Pythonanywhere with sqlite db initialized MySql DB activated on Pythonanywhere (it provided me with db name, pasword and host - everything that I need to setup settings.py) pip install mysqlclient finished successfully python manage.py makemigrations - DONE python manage.py migrate - DONE mysql console on Pythonanywhere shows all my tables created but restarting app causes pythonanywhere error page and link to error log 2020-08-15 17:22:56,536: Error running WSGI application 2020-08-15 17:22:56,569: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. 2020-08-15 17:22:56,569: Did you install mysqlclient? So the question is how could it be possible? As i got it right migrations are used mysqlclient to manipulate DB, how can it be not installed? Might be someone did face with similar issue? -
Consume POST request data
I have two endpoints here as shown below. When I hit the app1 endpoint(http://localhost:8000/app1) i want to send ans to data_receiver via POST request and print the data but its printing None def app1(request): ans = {'key' : 1} headers = {'content-type': 'application/json'} requests.post("http://localhost:8000/data_receiver", data=ans, headers=headers) return JsonResponse({'message': 'ok'}) def data_receiver(request): user = request.POST.get('data') print(user) # printing None here return JsonResponse({'message': 'ok'}) Please suggest where I am doing wrong