Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Filter name is not defined
I'm trying to filter my Todos by the test_id pulled from the URL. It pulls the id from the URL but it cant seem to filter with todo__test. I have also tried "test", "Todo.test.test_id", "Todo.test". I guess I'm confused about what variable I need to filter and the Django restframework documentation doesn't explicitly show what variable to use. Their example uses "purchaser__username" which I don't understand where it comes from. https://www.django-rest-framework.org/api-guide/filtering/ class TodoList(generics.ListAPIView): queryset = Todo.objects.all() serializer_class = TodoSerializer def get_queryset(self): test_id = self.kwargs['test_id'] return Todo.objects.filter(todo__test == test_id) class Todo(models.Model): test = models.ForeignKey(Test, on_delete=models.CASCADE) content = models.TextField(blank=True) order = models.IntegerField() def __str__(self): return self.content + ' - ' + self.test.test_name class Meta: ordering = ['test_id'] -
Cant upload multilple images using django admin
I have two models: one is the post model that can have multiple linked images. The image model has a foreign key to the post. That is, the images have a foreign key for a single post. When adding a new post I want to upload multiple images at the same time. Here is the code: model.py class Post(models.Model): title = models.CharField(max_length=255) thumbnail = models.ImageField(upload_to='thumbnails') summary = RichTextField() body = RichTextUploadingField() created_at = models.DateField(auto_now_add=True) class Meta: ordering = ['-created_at',] def __str__(self): return self.title class Imagens(models.Model): img = models.ImageField( upload_to = "media/", ) post = models.ForeignKey( "Post", on_delete=models.CASCADE, default=1) admin.py class ImageAdminForm(forms.ModelForm): class Meta: model = Imagens fields = ['img',] def __init__(self, *args, **kwargs): super(ImageAdminForm, self).__init__(*args, **kwargs) self.fields['img'] = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class ImageInline(admin.TabularInline): model = Imagens extra = 1 form = ImageAdminForm class PostAdmin(admin.ModelAdmin): search_fields = ['title'] inlines = [ImageInline,] def save_model(self, request, obj, form, change): obj.save() files = request.FILES.getlist('img') #he gets nothing print(files) for f in files: x = Imagens.objects.create(post=obj,img=f) x.save() admin.site.register(Post, PostAdmin) The problem is that if I save the post object it saves only one image and if I try to get the list of images it gives an empty list. Sorry I'm new to Django and even … -
Checkbox and function in Django
I welcome everyone who answers and helps if possible and thank you all in advance! There is a Django web application that downloads videos from YouTube using the python library. It will convert the video to audio and make a transcript of the text into a file. The question is that there is a variable in the language function that will change the language of text extraction. You need to change the value that corresponds to the video every time. How to make a language selection in a template that supports google web speech. I can't implement this idea, any help is welcome! Links to files at the bottom https://github.com/Erekeakz/Youtube-to-text.git -
Django; How can I display the questions foreign key for a responses table and then saving the responses using Django forms?
Hey I'm working on a survey app that has 7 questions and accepts a 1-3 integer answer for all of them except the last question which is free response. My models.py looks like this: class Question(models.Model): question = models.CharField(max_length=255) class Response(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="response") response = models.IntegerField(validators=[MinValueValidator(0),MaxValueValidator(3)]) respondantEmail = models.EmailField(unique=True) I was planning on storing the 7 questions in the questions table and then have the survey's response split into 7 rows per user submission. I don't know if there's a better approach to this so feel free to direct me towards another way of storing the responses. This works well in my admin view but I can't get it to display properly in the front-end. What I currently have is: Forms.py class ResponseForm(ModelForm): class Meta: model = Response fields = { "response","respondantEmail"} widgets = {"response": forms.TextInput(attrs={'type':"range", 'min':'1','max': '3'})} index.html <form action="{% url 'AssessmentForm:submit' %}" method="post"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> Now this obviously only displays a single range input field and an email input field but I'd like it to display a range field and an email field for every question there is stored in my Questions table, alongside the question itself. How do … -
How to return variables and store them from ready() method in Django?
I want to initialize a class ONCE when the app starts and store the return variable from the ready() method in apps.py. But I don't see how to return the variables. I searched google and everyone is pointing to apps.py is the preferred location to write these kinds of "Run Only Once" functions. This is my code- class MainPageConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'main_page' def ready(self) -> None: print("Hello ready") load_dotenv(".env") logging.set_verbosity_error() x, y = ModelProcessorCaller()() return x, y How to use this x and y later? What is the better alternative? And also why is the load_dotenv not working in the ready() method even though there is a .env file? The main idea is that I want to run this ModelProcessorCaller only once and store it for future use. -
How can i have same html for multiple categories or pages and then add specific or different data from database to them in django restframework?
In this program i have these two functions in my views.py: def home(request): p=product.objects.all() return render(request,'home.html',{'p':p}) def foods(request): p=product.objects.all() return render(request,'foods.html',{'p':p}) They both have access to the same data from database i mean if i want to post some json with django restframework then foods and home will have the same data because they have the same html: <div class="grid"> {% for i in p%} <div class='card'> <img src="{{i.image}}"></img> <p id="id">{{i.description}}</p> <a href="{{i.buy}}" target='_blank' rel='noopener noreferrer'> <button><span class="price"> ${{i.price}}</span> buy</button> </a> </div> {%endfor%} </div> it is good for me to have just one html for multiple pages and then access to different data from database but if i add some json both of them will contain the same data(for some reason data of foods is empty but it will generate the same number of products based on json like home) I want to know how can you have same html for multiple categories or pages and then add specific or different data from database to them? More details: models.py: from django.db import models # Create your models here. class product(models.Model): image=models.CharField(max_length=500) description=models.CharField(max_length=500) price=models.CharField(max_length=50) buy=models.CharField(max_length=100) serializers.py: from rest_framework import serializers from .models import product class productSerializer(serializers.ModelSerializer): class Meta: model= product fields="__all__" … -
Do I need a User Class in my models? Or is there an easy fix to the foreign key?
Made some modification to my code (there is was some mistake) which created a new problem. Pulling the following error message: "insert or update on table "main_productreview" violates foreign key constraint "main_productreview_user_id_bdd4771a_fk_main_user_id" DETAIL: Key (user_id)=(3) is not present in table "main_user"." (I used to have a User class in my models.py which I have removed as registered Users where not moved to Main. Removing the class sorted the problem, but created this one) What I am trying to do: when a user is logged in, the user can leave a review against a specific product. Any idea? Models.py from django.db import models from django.contrib.auth.models import User from decimal import Decimal import locale import logging class Product(models.Model): name = models.CharField('Product Name', max_length=120, null=True) description = models.TextField(blank=True, null=True) price = models.DecimalField(null=True, max_digits=6, decimal_places=3) #venue = models.ForeignKey(Venue, blank=True, related_name="venue", on_delete=models.CASCADE) tasters = models.ManyToManyField(User, blank=True) image_url= models.URLField('Image Web Address', blank=True) product_url = models.URLField('Product Web Address', blank=True) class Meta: db_table='Product' def __str__(self): return str(self.name) RATING=( (1,'1'), (2,'2'), (3,'3'), (4,'4'), (5,'5'), ) class ProductReview(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE) product=models.ForeignKey(Product,related_name="comments", on_delete=models.CASCADE) review_text=models.TextField(max_length=250) review_rating=models.IntegerField(choices=RATING,max_length=150, default=0) date_added = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s - %s'%(self.user, self.product, self.date_added) Views.py from django.shortcuts import render, redirect from django.http import … -
Django Form/Models: Adding Row Data To Existing Model Instance Via Form
Description of Database Hello so my problem is that I have a Database with three models: Beacon: Which collects data about hosts that ping back data to it. Command_Node: Which collects commands to be executed by the host in question via a form submitted by the website user. Executed_Commands: Which will collect any Commands contained within a Command_Node when they are collected through a query by a connecting machine via a function to be implemented, it will also delete the Commands in a Command_Node as they are now previous commands. (To be implemented) Problem I want to add multiple commands to a single instance of a Command_Node. Via a form, which allows me to select which host I want to give commands to, and which allows me to select which commands to issue to which host. It should then adds those commands into the current_commands column of that Command_Node as a new row, in the selected Command_Node instance. However I don't know how to do this. I don't need to edit existing commands, I don't need to create a new Command_Node instance as the present code does. I just need to add more rows to existing instances. Any ideas on … -
django.core.exceptions.ImproperlyConfigured: Set the DB_NAME environment variable
I have some troubles. I'm running Django on Ubuntu 20.04. Everytime that I try to set environment variable instead of a string i get an error, when I use python3 manage.py runserver I am getting django.core.exceptions.ImproperlyConfigured: Set the DB_NAME environment variable and I am using docker , docker-compose . my config/settingsfile: env = environ.Env( DEBUG=(bool, False), ) DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': env('DB_NAME'), 'USER': env('DB_USER'), 'PASSWORD': env('DB_PASSWORD'), 'HOST': env('DB_HOST'), 'PORT': 5432, } } EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = env('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') SERVER_EMAIL = EMAIL_HOST_USER DEFAULT_FROM_EMAIL = EMAIL_HOST_USER BACKEND_DOMAIN = '' my .env file: DB_NAME=my_db_name DB_USER=postgres DB_PASSWORD=my_password EMAIL_HOST_USER=my_email_address EMAIL_HOST_PASSWORD=my_password OPENROUTE_API_KEY= MY FILES: enter image description here -
How can i get parameter from a url with django
i have this in the url: localhost/apli/orden/devices/Instalacion%20LB%20+%20BA/ so i need to get the parameter Instalacion%20LB%20+%20BA in a view, how can i do it? this is the url path: path('orden/devices/<str:tipoOrden>/', asignDevicesView.as_view(), name='devices_ot') I clarify that I do not use models where this info is saved, the info comes from a variable from js that I rescue from an object of a web service -
Add the result of a queryset to another queryset
I have 2 models : class ModelA(models.Model): some_fields = .... class ModelB(models.Model): model_a = models.ForeignKey(Model_A) How can I in my viewset of ModelA return a response which will include all ModelB who have model_a as FK ? Can I do it in the get_queryset function ? -
Architecture clarification for Warehouse Django application
everyone, I've started implementing my next project under the Warehouse title :) And actually, I am stuck, again. I guess I've made things too complicated and I don't know how to get out of it. So basic assumptions of Warehouse application: We have a few products You take the goods to the warehouse - the order consists of multiple products. You must know the purchase price and qty for each of them. Some model which will store information about current stock status. I guess it will be Singleton? You sell products from Warehouse - order consists of products sell price, product qty Ok, It seems to me all the above are basic assumptions, below is what I wrote to reach my target but I am pretty sure it doesn't work as is intended. I will be very grateful for any tips and tricks and clarification on architecture. class OrderIn(models.Model): # Standard fields last_updated = models.DateTimeField(auto_now=True, editable=False) ordered = models.DateField(auto_now_add=True, editable=True) received = models.DateField(auto_now_add=True, editable=True) class OrderOut(models.Model): # completed = models.BooleanField(default=False) # Standard fields last_updated = models.DateTimeField(auto_now=True, editable=False) ordered = models.DateTimeField(auto_now_add=True, editable=True) class MiddleOrder(models.Model): order_in = models.ForeignKey(OrderIn, on_delete=models.CASCADE, blank=True, null=True) order_out = models.ForeignKey(OrderOut, on_delete=models.CASCADE, blank=True, null=True) def save(self, *args, **kwargs): super(MiddleOrder, … -
NameError name 'F' is not defined
when i tried this code to add 10 point to user after he fill out one survey it show this error However, I am running into a problem. I get the error: models.py", line 22, in give_coins user.coins = F('coins') + count NameError: name 'F' is not defined models.py class User(AbstractUser): user_pic = models.ImageField(upload_to='img/',default="",null=True, blank=True) coins = models.IntegerField(default=10) def get_image(self): if self.user_pic and hasattr(self.user_pic, 'url'): return self.user_pic.url else: return '/path/to/default/image' def give_coins(user, count): user.coins = F('coins') + count user.save(update_fields=('coins',)) user.refresh_from_db(fields=('coins',)) views.py : @require_http_methods(["POST"]) def submit_survey(request): request.user.give_coins(count=10) form_data = request.POST.copy() form_items = list(form_data.items()) print("form_items", form_items) form_items.pop(0) # the first element is the csrf token. Therefore omit it. survey = None for item in form_items: # Here in 'choice/3', '3' is '<choice_id>'. choice_str, choice_id = item choice_id = int(choice_id.split('/')[1]) choice = Choice.objects.get(id=choice_id) if survey is None: survey = choice.question.survey choice.votes = choice.votes + 1 choice.save() if survey is not None: participant = Participant(survey=survey, participation_datetime=timezone.now()) participant.save() return redirect('/submit_success/') so .. where is the error here -
Problem with Cors and fetching information in react
I have a problem with CORS and fetch with REACT.JS. That's my code: let componentMounted = true; useEffect(() => { const getCars = async () => { const response = await fetch('http://127.0.0.1:8000/dealership/cars/?format=json', {mode: 'no-cors'}); if(componentMounted){ setData(await response.clone().json()); setFilter(await response.json()); } return () => { componentMounted = false; } } getCars(); }, []); In the Chrome console i have this error: Uncaught (in promise) SyntaxError: Unexpected end of input (at Cars.js:17:1) at getCars (Cars.js:17:1) And this: Cross-Origin Read Blocking (CORB) blocked cross-origin response http://127.0.0.1:8000/dealership/cars/?format=json with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details. In the backend i have Django and I have import Cors-headers like this: CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', ] -
Django & POSTMARK API Templates
I'm trying to send a receipt template using POSTMARK API from my Django application but I'm struggling with retrieving multiple items under receipt details. I'm converting my query of items within an order to a list, then from the list, we are serializing it to JSON. Here is the output I get with the JSON with products when I run print: [{'product__name': 'Pokemon 25th Anniversary', 'quanity': 1, 'product__point_price': 100.0}] The serialization all looks correct however if you have multiple items, this becomes an issue. If you look down at my code under receipt details you will see I had to specify [0] before specifying the key name. How do I do this without specifying [0] so I can get all items? Here is my code : VIEW @login_required def checkoutcomplete(request): customer = request.user order = Order.objects.get(customer= customer , complete = False, ) favorites = Favorite.objects.filter(customer = customer.id) today_date = datetime.datetime.today() today_date_strf = datetime.datetime.strftime(today_date,"%m/%d/%Y" ) items = order.orderitem_set.all() data = list(items.values("product__name","quanity","product__point_price")) save_json = json.dumps(data, indent = 2) my_cart_json = json.loads(save_json) #POST MARK API url = "https://api.postmarkapp.com/email/withTemplate" payload = json.dumps({ "From": "", "To": "", "TemplateId": 28132290, "TemplateModel": { "counselor_name": "Fellow Counselor", "student_name": student.student_name, "receipt_id": str(order.transaction_id), "date": today_date_strf, "points": order.get_cart_total, "receipt_details": [ { … -
I am trying pass the obj2 to the frontend but it is not working passing it show the previous values not the updated values in django
when I am trying to pass the context in the post method it works and displays the content in the front-end but when I am trying to pass the context in the get method it is not working. I am trying to change the view based on the filer. if(request.POST): # it is form print("%%%%%%%%%%%%%% post ") chapter_tag = request.POST.get('chap_tag') chapter_name = request.POST.get('chap_name') pub_id_chap = pub_id[0][0] data = { 'chapter_tag': chapter_tag, 'publication_id': pub_id_chap, 'std': int(clas), 'chapter_name': chapter_name } form = chapter_details_master_form(data) if form.is_valid(): form.save() print("*********** ___________") pub_id, summa_list = chapter_list(pub, sub, clas) content = { 'pubk_list': mylist, 'obj': summa_list } redirect(reverse('publication_chapter_list')) return render(request, "publication_chapter_list.html", content) else: print(form.errors.as_data()) #print('$$$$$$$$$$$$',pub,sub,clas) pub_id, summa_list = chapter_list(pub, sub, clas) content = { 'pubk_list': mylist, 'obj': summa_list } print('----------------------------') return render(request, "publication_chapter_list.html", content) if request.method == 'GET': print("%%%%%%%%%%%%%% get ") pub = request.GET.get('publication') clas = request.GET.get('class_value') sub = request.GET.get('subject_id') flag = request.GET.get('flag') request.session['clas'] = clas request.session['sub'] = sub request.session['pub'] = pub pub_id = 0 if flag: pub_id, summa_list = chapter_list(pub, sub, clas) request.session['pub_id'] = pub_id #print('%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%% ',summa_list) chapter_tag_list = summa_list request.session['list_chap'] = summa_list content = { 'pubk_list': mylist, } content['obj'] = chapter_tag_list print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ', content) return render(request, "publication_chapter_list.html", content) -
Django User Model (Employee and Customer)
I am currently working on a mobile app delivery system which involves two types of users: "Employee" and "Customer". Each type of user would have different views and permissions within the app. In addition, each type of user would their own "profile", if you will. The employee's profile purpose is mostly just to designate company roles. The customer's profile is mostly used to save an address for delivery. I am trying to get some opinions on what the best practice to achieve something like this would be. I can't decide if its better to use AbstractBaseUser or AbstractUser. Below is a visual of the models I am wanting to create along with their relationship: Below is the the user/models.py file that I mocked up: class UserTypes(models.Model): type = models.CharField(max_length=100) def __str__(self): return self.type class User(AbstractBaseUser): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField() phone_number = models.CharField(max_length=20) is_employee = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) def __str__(self): return f'{self.first_name} {self.last_name}' # if user.is_employee == True class EmployeeProfile(models.Model): EMPLOYEE_ROLES = ( ('Driver', 'driver'), ('Production', 'production'), ('Manager', 'manager') ) user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.CharField(max_length=12, choices=EMPLOYEE_ROLES) def __str__(self): return self.user # if user.is_customer == True class CustomerProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = … -
Django, more type of user - I need advice
I need advice. I want make 3 types of user: member (only nickname/password/email) company (nickname/password/email/company/regon + permision for edit model) admin My question is aobut how make model for this users: make big model for member and company together but field which are only for comapny make empty for member. Next to by admin panel i can make group and add "comapny" ppl make 2 type of user (here i will need advice like what i should use on it) and seperate website register for member and company and login should be the same form Thank you for answer -
How can I show posts on page using django TemplateView class?
I used a ready-made template for the blog project. When the button is clicked on the template in home page, a modal opens and login registration processes are performed from here. On the home page, both view and login and register functions should work at the same time. I did login and registration with template view, but this time my posts disappeared. no error on the page or terminal.Anybody can help me to do this! Thanks all! views.py class HomeView(TemplateView): # model = Post template_name = 'blog/index.html' # ordering = ['-last_updated'] def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context['posts'] = Post.objects.all() print(context['posts']) return context def get(self, request, *args, **kwargs): return self.render_to_response({'loginform': AuthenticationForm(prefix='loginform_pre'), 'registerform': UserCreationForm(prefix='registerform_pre')}) def post(self, request, *args, **kwargs): # self.object_list = self.get_queryset() loginform = _get_form(request, AuthenticationForm, 'loginform_pre') registerform = _get_form(request, UserCreationForm, 'registerform_pre') if loginform.is_bound and loginform.is_valid(): # Process loginform and render response user = loginform.get_user() login(request, user) return redirect('index') elif registerform.is_bound and registerform.is_valid(): user = registerform.save() login(request, user) return redirect('index') return self.render_to_response({'loginform': loginform, 'registerform': registerform}) html template <div class="row"> {% for post in posts %} <div class="col-lg-4 col-md-6 col-12 mb-4"> <div class="blog-item"> <div class="image-blog"> <img src='{{ post.image.url }}' alt="blogImage" class="img-fluid" style="height: 162px;overflow: hidden;"> </div> ... -
intcomma after widthratio in Django templates
I want to do "intcoma" after "widthratio" in the Django template. I thought about it as below, but it doesn't work. {{ {% widthratio p.price 2 1 %}|intcomma }} -
How to manipulate Django Admin
I created this class: class Orcamento(models.Model): id = models.IntegerField(primary_key=True) Cliente = models.CharField(max_length=40, default=0) Cod_Cliente= models.CharField(max_length=40, default=0) N_Orcamento = models.CharField(max_length=40, default=0) Endereço = models.CharField(max_length=50, default=0) Email = models.CharField(max_length=40, default=0) Telefone = models.CharField(max_length=40, default=0) Departamento = models.CharField(max_length=40, default=0) Data = models.CharField(max_length=40, default=0) Revisao = models.IntegerField(default=0) #Serviços = models.CharField(max_length=100, default=0) Serviços = ArrayField(models.CharField(max_length=50),default=list, size=20) #função para usar o nome do objeto e não a instância def __str__(self) -> str: return self.Cliente But in the Admin page "Serviços" has just 1 field and not a array, how can I manipulate it? I want to enter with some date in more than 10 fields Image bellow: Djando Admin page -
Django get sum of value from list of objects in jsonfield
I have a model with the following implementation class MyModel(models.Model): data = models.JSONField(null=True, blank=True) The I have json in this format: { "name": "Name", "irrelevant_list": [], "items": [ { "name": "Name 1", "quantity": 1, "other_list_of_objects": [] }, { "name": "Name 2", "quantity": 2, "other_list_of_objects": [] } ] } I want to annotate db rows with the sum of quantity (i.e. quantity = 3 for this db row), I have tried multiple approaches, still not getting the right query. -
Sending emails with django and Celery - how to return error message if sending failed?
I'm using django with celery to send emails with verification code. I use third-party service (SendGrid) to send emails. If there is any error on the email server side (say, I exceeded a daily email limit) I want to tell users about that, but since celery is async and does not return the actual response from the server, how could I accomplish that? -
django.db.migrations.exceptions.NodeNotFoundError: Migration app.0172_auto_20220603_1746 dependencie _auto_20220601_2313')
I deleted some migration files that were giving me the error. Then when I write "python3 manage.py showmigrations" I get the following error: root@chat-manager:/var/www/jinabot# python3 manage.py makemigrations Traceback (most recent call last): File "manage.py", line 23, in <module> main() File "manage.py", line 19, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/dist-packages/django/core/management/__init__.py", line 419, in exe utility.execute() File "/usr/local/lib/python3.7/dist-packages/django/core/management/__init__.py", line 413, in exe self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 354, in run_fro self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.7/dist-packages/django/core/management/commands/makemigrations.py", l loader = MigrationLoader(None, ignore_no_migrations=True) File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/loader.py", line 259, in build_g self.graph.validate_consistency() File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/graph.py", line 195, in validate [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/graph.py", line 195, in <listcom [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/graph.py", line 58, in raise_err raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration app.0172_auto_20220603_1746 dependencie _auto_20220601_2313') How to fix it? -
RelatedObjectDoesNotExist at /authentication/update-user-bio.html User has no user_bio
i have a userBio model class UserBio(models.Model): user=models.OneToOneField(User, verbose_name=("User's Bio"), on_delete=models.CASCADE,related_name='user_bio') user_profile_bio=models.TextField(max_length=200,null=True,default='This user has no Bio yet') def __str__(self): return self.user.username +"s' bio" When someone wants to update their bio; i want to create a userbio object and show it to them or pass to through the form. here's views.py def Userbio(request): form=form=UserBioForm(instance=request.user.user_bio) if not request.user.user_bio: txt='User Bio' a=UserBio.objects.create(user=request.user,user_profile_bio=txt) a.save() form=UserBioForm(instance=request.user.user_bio) if request.method == 'POST': form = UserBioForm(request.POST, instance=request.user.user_bio) if form.is_valid(): form.save() messages.success(request,'Change Saved succesfully!') return HttpResponseRedirect(reverse('profile')) return render(request, 'authentication/User_bio.html', context={'form':form}) but it says RelatedObjectDoesNotExist at /authentication/update-user-bio.html User has no user_bio. what's the problem here? Or you can help me in another way. How can i create an userbio object when someone signs up?if i can auto create an usebio object for everyone who signs up it would be better than this.