Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker Django, redis and celery conf
I dont know what part I am missing but celery not conneting to redis when I am running docker-compose up --build error: Cannot connect to redis://127.0.0.1:6379/0: Error 111 connecting to 127.0.0.1: 6379. Connection refused. Here is my file docker-compose.yml version: '3' services: web: build: . image: resolution depends_on: - db - redis - migration - celery command: bash -c "python3 /code/manage.py migrate && python3 /code/manage.py initialsetup && python3 /code/manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" links: - db:db - redis:redis - celery:celery restart: always environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - PGHOST=trust - PGPORT=5432 db: image: postgres:latest environment: POSTGRES_DB: 'postgres' POSTGRES_PASSWORD: 'postgres' POSTGRES_USER: 'postgres' POSTGRES_HOST: 'trust' redis: image: "redis:alpine" ports: - "6379:6379" restart: on-failure celery: image: resolution command: celery -A mayan worker -l info environment: - DJANGO_SETTINGS_MODULE=mayan.settings.production volumes: - .:/code depends_on: - db - redis links: - redis:redis restart: on-failure -
Implement customizable ForeignKey in packaged Django app
Hello wonderful community, I have a question about the best way to make a ForeignKey in a packaged Django app customizable. Apologies for the long post, the majority of it is just a detailed example. I just started with Django last week (although I have quite a lot experience with Python and packaging) and I'd highly appreciate some feedback from more experienced Django developers. Summary I would like to create a Django app that can also be installed via pip. In this app, I create a model that holds a ForeignKey field which should point to a model in a different app (i.e. the target of the ForeignKey is not part of the developed package). My question is, what is the best way to make this target flexible? The buildings example Here is an example of the principal problem (the full bash script to generate this example is at the bottom of this post). This is not my real project, but it's quite similar. Consider a Building django model, that describes properties of a building. This building has a contact field that points to a user that is responsible for the building. i.e. from django.db import models from django.contrib.auth.models import … -
Django Error: Reverse for 'update-qty' with no arguments not found. 1 pattern(s) tried: ['update\\-qty/(?P<slug>[^/]+)/$']
I am trying to fix a no reverse error but I am making something wrong I can't figure it out. The error is shown to be the following line in the views (there is an arrow to it) Here is the views.py: class OrderSummaryView(LoginRequiredMixin, View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) context = { 'object': order } return render(self.request, 'order_summary.html', context)<---------------- Error except ObjectDoesNotExist: messages.warning(self.request, "You do not have an active order") return redirect("/") Here is the template: <div class="pull-center"> <form method="POST" action="{% url 'core:update-qty' %}"> {% csrf_token %} <button type="submit" name="action" value="minus" class="btn mr-2"><i class="fa fa-minus"></i></button> {{ order_item.quantity }}<button type="submit" name="action" value="plus" class="btn ml-2"><i class="fa fa-plus"></i></button> <input type="hidden" name="item_slug" value="{{ order_item.item.slug }}"> <input type="hidden" name="order_item" value="{{ order_item.pk }}"> </form> </div> </td> here is the urls: path('update-qty/<slug>/', update_qty, name='update-qty'), -
Ii know Django and flutter. Would it be possible to use these two to make a website? if yes, could we use the same code for the mobile app?
i wanted to build a website for someone. I know Django and flutter. would it be possible to use these two to make a website? if yes can we use the same code for the mobile app? if you know the answer would you be kind enough to enter the steps or the way to do this? thanks stay safe -
python manage.py runserver - Doesnt work in Django project
I started my first project with Django framework (Window platform). When trying to run manage.py runserver, i received an Error. Python version - 3.8.5 , Django version - 3.1 I am attaching the Error i received in the Terminal (venv) C:\Users\shai.QIL\PycharmProjects\djangoProject>python manage.py runserver Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\shai.QIL\PycharmProjects\djangoProject\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\shai.QIL\PycharmProjects\djangoProject\venv\lib\site-packages\django\core\management\__init__.py", line 345, in execute settings.INSTALLED_APPS File "C:\Users\shai.QIL\PycharmProjects\djangoProject\venv\lib\site-packages\django\conf\__init__.py", line 83, in __getattr__ self._setup(name) File "C:\Users\shai.QIL\PycharmProjects\djangoProject\venv\lib\site-packages\django\conf\__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "C:\Users\shai.QIL\PycharmProjects\djangoProject\venv\lib\site-packages\django\conf\__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\shai.QIL\Python\Python38-32\lib\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 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\shai.QIL\PycharmProjects\djangoProject\djangoProject\settings.py", line 57, in <module> 'DIRS': [os.path.join(BASE_DIR, 'templates')] NameError: name 'os' is not defined Thanks for your help! -
what is the exception: "TemplateDoesNotExist at /myapp/form" in Django project
I created Django project, using html- form. the form.html: <form action = "" method = "get"> <label for="your_name">Your name: </label> <input id="your_name" type="text" name="your_name"> <input type="submit" value="OK"> </form> the views.py: from django.shortcuts import render def dateform(request): return render(request, 'templates/form.html' ) the urls.py: from django.urls import path from . import views urlpatterns = [ path('form', views.dateform,name = 'form') ] the setting.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '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', ], }, }, ] When I run the project in this URL: http://localhost:8000/myapp/form I get an error: TemplateDoesNotExist at /myapp/form templates/form.html Request Method: GET Request URL: http://localhost:8000/myapp/form Django Version: 3.1 Exception Type: TemplateDoesNotExist Exception Value: templates/form.html Exception Location: C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader.py, line 19, in get_template Python Executable: C:\Users\User\AppData\Local\Programs\Python\Python38-32\python.exe Python Version: 3.8.3 Python Path: ['C:\\Users\\User\\Desktop\\smarti\\myproject', 'C:\\Users\\User\\Desktop\\smarti\\myproject', 'C:\\Program Files\\JetBrains\\PyCharm ' '2020.2\\plugins\\python\\helpers\\pycharm_display', 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Users\\User\\AppData\\Roaming\\Python\\Python38\\site-packages', 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages', 'C:\\Program Files\\JetBrains\\PyCharm ' '2020.2\\plugins\\python\\helpers\\pycharm_matplotlib_backend'] Server time: Sat, 08 Aug 2020 20:03:51 +0000 What is the problem? I must your help necessary! Thanks in advance. -
Why do people use .env file on server?
Why do people put a .env file to store all their secrets in a server? If someone hacks it, isn't the .env equally accessible as all the other files? Thanks! -
Button click action in Django to trigger a function
I'm trying to build a button that, when clicked, toggles a model's Boolean value to True from False. I'm stuck on how to call a Django function when this button is clicked on. -
Permission denied after creating django app inside docker container
So I am following this tutorial and have gotten all the way to the 'media' section and when I run the command: docker-compose exec web python manage.py startapp upload it all works fine but when I open the newly created views.py file and edit and try to save I get a permission denied error. I can open the file as root and edit it but now thru my Atom code editor. I don't know where I am going wrong can someone help me? Here's my code: Dockerfile: # pull official base image FROM python:3.8.3-alpine # 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 install -r requirements.txt # copy entrypoint.sh COPY ./entrypoint.sh . # copy project COPY . . # run entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] docker-compose.yml: services: web: build: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=hello_django - POSTGRES_PASSWORD=hello_django - POSTGRES_DB=hello_django_dev volumes: postgres_data: entrypoint.sh: if [ "$DATABASE" = … -
Rest Django MultipleObjectsReturned error
I'm new to Rest Django and hope you'll help me. I'm trying to call an api by Get function with a parameter using GenericAPIView, when I put just one object into my DataBase,my object displays but when I add an other object the MultipleObjectsReturned raises the class I used into my view serializer_class = PartiSerializer queryset = Parti.objects.all() lookup_field = 'projet' #authentication_classes = [SessionAuthentication, BasicAuthentication] #authentication_classes = [TokenAuthentication] #permission_classes = [IsAuthenticated] def get(self, request, projet = None): if projet: return self.retrieve(request) else: return self.list(request) def post(self, request): return self.create(request) def put(self, request, projet): return self.update(request, projet) def delete(self, request, projet): return self.destroy(request, projet) An other question ; Can I use a GenericViewSet but with changing the lookup_field ? the default GenericViewSet class PartiViewSet(viewsets.ModelViewSet): serializer_class = PartiSerializer queryset = Parti.objects.all() -
I can't log in to admin site in django
I am currently using a custom user model in django. After creating the user model and Migrating to db, we created the superuser account and ran the server. But after accessing the admin page, I entered my information correctly, but I couldn't log in. Can I know the cause? Here is my code models.py class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, email, profile, nickname, password): user = self.model( email=self.normalize_email(email), nickname=nickname, profile=profile, ) user.set_password(password) user.save() return user def create_superuser(self, email, password, nickname, profile): user = self.create_user( email=self.normalize_email(email), password=password, nickname=nickname, profile=profile, ) user.staff = True user.admin = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(_('email address'), unique=True) nickname = models.CharField(max_length=10) profile = models.ImageField(default='default_image.jpeg') is_staff = models.BooleanField(_('staff status'),default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['nickname', 'profile'] admin.py from django.contrib import admin from .models import User admin.site.register(User) -
How to get a query set where time property of objects cover the last day?
Accept my apologies I couldn't explain the question any better in the title. I have a model like below: class MyModel(models.Model): created_time = models.DateTimeField(auto_now_add=True) The objects can be created at any time and have that time saved in created_time. I want to filter all the objects that are created from just before yesterday until now. So if we consider that we are at 22:00 now, and we have 5 objects from yesterday 22:00 until now, I also want the last object that is created before yesterday 22:00, and it can be created a month ago. The query below not work because it omits the last object before yesterday: from datetime import timedelta, datetime yesterday = datetime.today() - timedelta(days=1) objs = MyModel.objects.filter(created_time__gte=yesterday) Can anyone help me with this? -
unable to send audio file in django backend
I am trying to get the recorded audio file from the HTML to my Django backend but getting MultiValueDictKeyError at /audiomarge/ 'ouraudio' here is my script <script> // set up basic variables for app const record = document.querySelector('.record'); const stop = document.querySelector('.stop'); const soundClips = document.querySelector('.sound-clips'); const canvas = document.querySelector('.visualizer'); const mainSection = document.querySelector('.main-controls'); var x = document.getElementById("myAudio"); // disable stop button while not recording stop.disabled = true; // visualiser setup - create web audio api context and canvas let audioCtx; const canvasCtx = canvas.getContext("2d"); //main block for doing the audio recording if (navigator.mediaDevices.getUserMedia) { console.log('getUserMedia supported.'); const constraints = { audio: true }; let chunks = []; let onSuccess = function (stream) { const mediaRecorder = new MediaRecorder(stream); visualize(stream); record.onclick = function () { x.play(); mediaRecorder.start(); console.log(mediaRecorder.state); console.log("recorder started"); record.style.background = "red"; stop.disabled = false; record.disabled = true; } stop.onclick = function () { x.pause(); mediaRecorder.stop(); console.log(mediaRecorder.state); console.log("recorder stopped"); record.style.background = ""; record.style.color = ""; // mediaRecorder.requestData(); stop.disabled = true; record.disabled = false; } mediaRecorder.onstop = function (e) { console.log("data available after MediaRecorder.stop() called."); const clipName = prompt('Enter a name for your sound clip?', 'My unnamed clip'); const clipContainer = document.createElement('article'); const clipLabel = document.createElement('p'); const audio = document.createElement('audio'); … -
Automatically populate Age field in postgres DB from birth date in django module
I'm new to Django and i'm working on web app for Employee data set. So i have 'birth_date' field in my model and i want to calculate Age based on birth date & also store the age in postgres database and age should automatically update in database. So how can i do this in django? -
How filter by url in django rest framework
VIEWS lass PageView(viewsets.ModelViewSet): serializer_class = postserializer # queryset = Page.objects.all() def get_queryset(self,request,*args,**kwargs,): queryset = Page.objects.all() return Page.objects.filter(event=self.kwargs['author']) URLS router = routers.DefaultRouter() router.register('^author/(?P<author>.+)/$', PageView ,basename="author") router.register(r'authors',views.AuthorView, basename="authors") urlpatterns = [ path("", include(router.urls)) ] Model class Page(models.Model): author = models.CharField(max_length=30) post = models.TextField() how to search for particular authors of my post like /author/bob/ i've been trying to follow offical documentation but its unclear to me :\ http://www.tomchristie.com/rest-framework-2-docs/api-guide/filtering -
Conditional Foreign key in Django
Is there any way I can do a conditional foreign key in django? What I mean is that I currently have this (I am providing a bit simplified version without the unneeded stuff): c = ( (1, "mobile"), (2, "laptops"), (3, "IT"), (4, "hardware"), (5, "earphones"), (6, "headphones"), ) class Product(models.Model): product_name = models.CharField(max_length=100) category = models.IntegerField(choices=c) I also have models created for every category. Now what I need to do is to add a foreign key to the model which matches the category. Basically I want to do something like this (which is not a way to solve this problem): if category==1: category_model=models.ForeignKey(Mobile, on_delete=models.CASCADE, related_name='category_products') And then I want to do the same for the rest of the cases. Is there a real way to do that? If not how would you recommend approaching the categories (I have to use models and not just choices because I am planning to add choices to every category model in order to be able to implement subcategories)? -
Uploading images in django using Dropzone
I am trying to upload images using dropzone, giving the user the option to upload images (It is not a required field): However, when uploading images the form does not get submitted correctly and my ajax request does not seem to be executed: Below is my js code for dropzone and ajax: Dropzone.autoDiscover = false; $(document).ready (function () { var myDropzone = new Dropzone("#my-dropzone" , { // my dropzone fields - removed for clarity init: function () { var myDropzone = this; $('#sub-etal').on("click", function (e) { if (myDropzone.getQueuedFiles().length > 0) { e.preventDefault(); e.stopImmediatePropagation(); myDropzone.processQueue(); } else { myDropzone.uploadFiles([]); //send empty } }); this.on('sendingmultiple', function(file, xhr, formData) { // Append all form inputs to the formData Dropzone will POST var data = $('.post-create-form').serializeArray(); $.each(data, function(key, el) { formData.append(el.name, el.value); }); }); this.on("error", function (files, data) { }); myDropzone.on("complete", function(file) { myDropzone.removeFile(file); }); } }); }) my ajax: $('#modal-post').on("submit",".post-create-form", function (e){ e.preventDefault(); e.stopImmediatePropagation(); var form = new FormData(this); $.ajax({ url: $(this).attr('data-url'), type: $(this).attr('method'), data: form, cache: false, processData: false, contentType: false, dataType: 'json', success: function(data){ if(data.form_is_valid){ $('#modal-post').modal('hide'); $('#_np2u').prepend(data.post); } else { $('#modal-post .modal-content').html(data.html_form) } } }) }) my Django form: <form method="POST" data-url="{% url 'home:post-create' %}" id="my-dropzone" class="dropzone post-create-form" enctype="multipart/form-data"> {% csrf_token … -
how to use slug in django urls - i have ((NoReverseMatch)) error
hey im trying to use slug instead of id in my django project but i get NoReverseMatch error how can i fix it ? models.py class Product (models.Model): name = models.CharField(max_length=100) price = models.FloatField(default=0) description = models.TextField(null=True, blank=True) color = models.ForeignKey(Color , on_delete=models.DO_NOTHING) material = models.ForeignKey(Material, on_delete=models.DO_NOTHING) image = models.ManyToManyField(Image) category = models.ForeignKey(Category,on_delete=models.DO_NOTHING , default=0) slug=models.SlugField(max_length=300 , allow_unicode=True , blank=True , null=True , unique=True) views.py def details(request , prslug): pr = get_object_or_404(models.Product , slug=prslug) context = { 'products': pr } return render(request, "prDetails.html" , context) urls.py urlpatterns = [ path('' , views.page), path('<slug:slug>/' , views.details , name="details") ] prDetails.html <a href="{% url 'details' pr.slug %}" class="h4">{{pr.name}}</a> and i get this error : Exception Type: NoReverseMatch Exception Value: Reverse for 'details' with keyword arguments '{'slug': 'first_product'}' not found. 1 pattern(s) tried: ['paachin/(?P[-a-zA-Z0-9_]+)/$'] -
What is the best way to go about creating Django model instances from API using Python script?
I am creating a webapp that displays interesting graphics using my running data (from Strava API) using Django. I'm currently trying to figure out how I want to populate my database. Currently, I have a script written (in python) that gets all of my running activities from the API. I want to make all of these into instances in the Django model called Run that I have created. I plan on running this script every so often to get any new runs given by the API however, the API returns ALL of my runs while I only need the new ones after running the script for the first time. What is the best way to go about only selecting the new entries from the API? The way I currently have the script set up, it will try to create a new model instance for EVERY item in the returned API response. Here is my current model for reference: from django.db import models # Create your models here. class Run(models.Model): id = models.IntegerField(primary_key=True) distance = models.DecimalField(max_digits=8, decimal_places=2, null=True) # In meters elapsed_time = models.IntegerField(null=True) # In seconds start_date = models.DateTimeField(null=True) # DateTime object, local average_speed = models.DecimalField(max_digits=8, decimal_places=2, null=True) # In … -
How to use django-chartjs with model
hi i am trying to create Data Logger Dashboard using django i am getting this blank chart , views.py from django.shortcuts import render from django.http import JsonResponse from .models import * from django.views.generic import TemplateView from chartjs.views.lines import BaseLineChartView # Create your views here. class LineChartJSONView(BaseLineChartView): def get_labels(self): levels=DataLogs.objects.values('date_time').distinct() top_levels=[] for l in range(0,100): top_levels.append(levels[l]) print(top_levels) return top_levels def get_providers(self): """Return names of datasets.""" return [] def get_data(self): datas=DataLogs.objects.filter(tag_name='temp') data=[] for l in range(0,100): data.append(datas[l]) print(data) return data line_chart = TemplateView.as_view(template_name='main.html') line_chart_json = LineChartJSONView.as_view() i am generating my data using arduino ,generation code is # Importing packages from pyfirmata import Arduino,util from time import sleep from datetime import datetime import os import mysql.connector import keyboard # configuring board port='COM5' board=Arduino(port) sleep(5) it=util.Iterator(board) it.start() # Configuring Pins a0=board.get_pin('a:0:i') a1=board.get_pin('a:1:i') l=board.get_pin('d:13:o') h=board.get_pin('d:12:o') # massage print(" Dataloger is going to start ") # main loop try: while True: db_connection = mysql.connector.connect( host='localhost', user='root', passwd='101090', auth_plugin='mysql_native_password',database='data_logs', ) db_cursor = db_connection.cursor() db_cursor.execute('USE data_logs') volt_1=0.2 sensor_1=a0.read() sensor_2=a1.read() temp_max=200 pressure_max=10 if type(sensor_1) == type(12.00): percentage=(sensor_1-volt_1)/(.8) data_1=temp_max*percentage if data_1<0: data_1=0 else: data_1=999999 if type(sensor_2) == type(12.00): percentage=(sensor_2-volt_1)/(.8) data_2=pressure_max*percentage if data_2<0: data_2=0 else: data_2=999999 date_time=datetime.now() print("______________________________________________________________________________________________") print(date_time.date()) date_hour=date_time.time() print(date_time) print("______________________________________________________________________________________________") hour_log=date_time.hour print('hour_log : ',hour_log) min_log=date_time.minute print('min_log :',min_log) second_log=date_time.second print('second_log … -
How to block specific user to visit specific pages in Django
My Django project have some 10 apps. I am using default User. Then there is Role model, something like this class Role(models.Model): user_type = models.OneToOneField(User, on_delete = models.CASCADE) is_manager = models.BooleanField() is_employee = models.BooleanField() As I told I have 10 apps. Each app has its urls.py User with is_manager = True can visit all first 8 apps pages(pages those are in urls.py). But they should not be able to visit other 2 app pages. Similarly is_employee = True, User can only visit last 2 app pages and they cannot visit first 8 app pages. I don't know how to achieve such situation. -
How do I call slurm sbatch in a separate process?
I need to run another program with parameters based on the form data. I have a page handler on Django. It builds a .sh file from the form, this file is called in a separate process using Popen and SBatch. All this runs fine but the page itself hangs and memory overflow occurs via the python3 process. Below is a sample program: def sbatch_subproc(self, file_path): >>Creates .sh file. pop_sbatch = subprocess.Popen(args = ["sbatch", sh_file_path]) def post(self, *args, **kwargs): >>The path to the .sh file is created. proc = Process(target = self.sbatch_subproc, args=(sh_file_path)) proc.start() Example .sh file: #!/bin/sh srun ./program -param1 value1 -param2 value2 -param3 value3 exit 0 -
How can I work with a form, that uses a model, which has 2 foreign keys? Automatically updating author and linking form to database
New to django. Currently have 2 problems with one form. I created a form from the model'Submission', in which the user can change the submission _author. How can I set it so that django automatically assigns the current logged in user to the submission_author(undetiable field type of thing)? Whenever I submit the form, this error pops up (NOT NULL constraint failed: themainpage_submission.post_id), where post_id is taken from the Submissions model(linked image). How can this be fixed? sceenshot from the database models.py class Post(models.Model): title = models.CharField(max_length=40) author = models.ForeignKey(User, on_delete=models.CASCADE) post_creation_time = models.DateTimeField(auto_now_add=True) genre = models.CharField(max_length=30, blank=True, null=True, choices= genre_choices) stage = models.CharField(max_length=30, blank=True, null=True, choices= stage_choice) optional_notes = models.CharField(max_length=80, default= 'dummy-text') def get_absolute_url(self): return reverse('home_view') def __str__(self): return self.title + ' | ' + str(self.author) class Submission(models.Model): post = models.ForeignKey(Post, related_name='submissions', on_delete=models.CASCADE) submission_author = models.ForeignKey(User, on_delete=models.CASCADE) submission_title = models.CharField(max_length=40) submission_creation_time = models.DateTimeField(auto_now_add=True) submission_body = models.TextField() def __str__(self): return self.submission_title + ' | ' + self.submission_body forms.py class CreateNewSubmission(forms.ModelForm): class Meta: model = Submission fields = ('submission_title', 'submission_body', 'submission_author') urls.py path('view_post/<str:pk>', views.ViewPostMain, name='view_post'), path('view_post/<str:pk>/create_submission', CreateSubmission.as_view(), name='create_submission'), views.py def ViewPostMain(request, pk): post = Post.objects.get(id=pk) submissions = Submission.objects.filter(post_id = pk) context = {'post' : post, 'submissions' : submissions} return render(request, 'view-post.html', context) … -
Django/Graphene Mutation error "you need to pass a valid Django model" can't fix it
Below is the RDBMS diagram of the Django/Graphene example I am working with: Below is the code for my model.py for the app: from django.db import models # Create your models here. class ProductCategory(models.Model): category = models.CharField(max_length=50) parentCategory = models.ForeignKey('self',null=True, on_delete=models.CASCADE) class Product(models.Model): productNumber= models.CharField(max_length=50) description = models.CharField(max_length=50) productCategory= models.ForeignKey('product.ProductCategory', on_delete=models.PROTECT) Below is Schema.py for the app: import graphene from graphene_django import DjangoObjectType from .models import Product, ProductCategory class ProductType(DjangoObjectType): class Meta: model = Product class ProductCategoryType(DjangoObjectType): class Meta: model = ProductCategory class Query(graphene.ObjectType): products = graphene.List(ProductType) productCategories = graphene.List(ProductCategoryType) def resolve_products(self, info): return Product.objects.all() def resolve_productCategories(self,info): return ProductCategory.objects.all() class CreateProductCategory(DjangoObjectType): productCategory = graphene.Field(ProductCategoryType) class Arguments: category = graphene.String(required=True) parentCategory = graphene.Int() def mutate(self, info, category, parentCategory): productCategory = ProductCategory(category = category, parentCategory = parentCategory) productCategory.save() return CreateProductCategory(productCategory=productCategory) return CreateProductCategory(category=category,parentCategory=parentCategory) class Mutation(graphene.ObjectType): createProductCategory= CreateProductCategory.Field() Without the mutation codes, query request works fine as illustrated below But it would output an error when mutation codes are added and I can't figure out what I did wrong as I am a noob. Please help!! AssertionError: You need to pass a valid Django Model in CreateProductCategory.Meta, received "None". -
How can password2 be null in django rest auth registration
I don't want to write password2 in the rest auth. So I want to use RegisterSerializer to remove the value of password2, what can I do?