Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Login authentication in different user table django
I am using custom table for login and registration of user, But I am getting error in login for not matching data with same table of user. Here my code is : I have changed user model in settings file. settings.py AUTH_USER_MODEL = 'assets.userInfo' models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractBaseUser,BaseUserManager ,UserManager class userInfo(AbstractBaseUser): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) username = models.CharField(max_length=200) email = models.EmailField(max_length=200,verbose_name="email" , unique=True) password = models.CharField(max_length=200) abn = models.CharField(max_length=200) password = models.CharField(max_length=200) isActive = models.BooleanField(default=True) created_date = models.DateTimeField(default=timezone.now) REQUIRED_FIELDS =['username'] USERNAME_FIELD = 'email' objects = UserManager() class Meta: db_table="userInfo" views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate from django.contrib.auth.models import User , auth from django.contrib import messages from .models import userInfo , sector ,companyInfo ,capability , saleStages ,companySaleStages from django.contrib.auth.hashers import make_password from .forms import CompanyDataForm # Create your views here. def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] password1 = request.POST['password1'] password2 = request.POST['password2'] abn = request.POST['abn'] email = request.POST['email'] if password1==password2: if userInfo.objects.filter(username=username).exists(): messages.info(request,'Username Taken') return redirect('register') elif userInfo.objects.filter(email=email).exists(): messages.info(request,'Email Taken') return redirect('register') elif userInfo.objects.filter(abn=abn).exists(): messages.info(request,'ABN Number Taken') return redirect('register') else: user = userInfo.objects.create(username=username, password=make_password(password1), email=email,first_name=first_name,last_name=last_name,abn=abn) user.save() # … -
Django Webpack Loader, in production django.cgi not rendering VUE.js dist/ file
I am having an issue about rendering /dist file that collected as static. It's very much renders without a problem on development serve. But after I build, it doesn't. vue.config file const BundleTracker = require("webpack-bundle-tracker"); module.exports = { publicPath: "https:/domain.com/django-folder/", // publicPath: "http://0.0.0.0:8080/", outputDir: './dist/', chainWebpack: config => { config .plugin('BundleTracker') .use(BundleTracker, [{filename: './webpack-stats.json'}]) config.output .filename('bundle.js') config.optimization .splitChunks(false) config.resolve.alias .set('__STATIC__', 'static') config.devServer // the first 3 lines of the following code have been added to the configuration .public('http://127.0.0.1:8080') .host('127.0.0.1') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .disableHostCheck(true) .headers({"Access-Control-Allow-Origin": ["\*"]}) }, // uncomment before executing 'npm run build' css: { extract: { filename: 'bundle.css', chunkFilename: 'bundle.css', }, } }; django settings.py STATIC_URL = '/django-folder/static/' STATIC_ROOT = "/home/domain-name/www/django-folder/static/" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "frontend/dist"), ] after I built the vue frontend. I copy/paste the dist folder inside the domain.com/django-folder/frontend/ and then run manage.py collectstatic command. All /dist collects in the static folder without a problem. But it doesn't renders. NO ERROR, just a blank page. Additionally django.cgi I am appending the django-folder like below. # Change this to the directory above your site code. sys.path.append("/home/domain-name/venv/lib/python3.8/site-packages") sys.path.append("/home/domain-name/www/django-folder") os.environ["DJANGO_SETTINGS_MODULE"] = "src.settings" And Django paths are working like admin/ or api/endpoints But vue is not showing up. -
How to do a POST request in a DetailView
im following a tutorial for the project but it does it on function views and im trying to do it on class based views i get a ( The view blog.views.PostDetailView didn't return an HttpResponse object. It returned None instead.) error but thats not my concern now ... because the data(new comments) arent getting saved so how can i save them with the post request and redirect to the same page of the DetailView my urls app_name = 'blog' urlpatterns = [ path('', views.PostListView.as_view(), name='blog-home'), path('blog/<slug:slug>/', views.PostDetailView.as_view() , name='post-detail'), ] my models class Post(models.Model): options = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish_date') publish_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') content = models.TextField() status = models.CharField(max_length=10, choices=options, default='draft') class Meta: ordering = ('-publish_date',) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'slug': self.slug}) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() publish_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-publish_date',) def __str__(self): return f'Comment By {self.author}/{self.post}' my forms class AddCommentForm(forms.ModelForm): content = forms.CharField(label ="", widget = forms.Textarea( attrs ={ 'class':'form-control', 'placeholder':'Comment here !', 'rows':4, 'cols':50 })) class Meta: model = Comment fields =['content'] my views class PostDetailView( DetailView): … -
Django RestAPI 500 error when trying to GET a list of records
What I am trying to achieve: Is get a simple list of ALL links FOR THE logged in User - using this end point : http://127.0.0.1:8000/api/affypartnerlinks/ The list should include ALL of the fields (including key) from the USERaffylinks model table PLUS the associated site_name from the USERaffiliates table - but only for the current logged in user. CURL test curl -X GET http://127.0.0.1:8000/api/affypartnerlinks/ -H 'Authorization: Token afdf84a95d53e15aea484b011fd3c754b165c1f2' This is the error I am getting. 500 Error: AttributeError: Got AttributeError when attempting to get a value for field owner_link_useraffyid on serializer USERaffylinksSerializer. The serializer field might be named incorrectly and not match any attribute or key on the USERaffiliates instance. Original exception text was: 'USERaffiliates' object has no attribute 'owner_link_useraffyid'. --- Thank you :) VIEWS.py @action(methods=['POST','GET',], detail=True) class AffyPartnerLinksViewSet(viewsets.ModelViewSet): queryset= USERaffylinks.objects.all() #need to filter on login user > owneruserid=request.user.id serializer_class = USERaffylinksSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated, ) def get_queryset(self): #restrict to current logged in user user = self.request.user return USERaffiliates.objects.filter(owneruserid=user) SERIALIZER.py class USERaffylinksSerializer(serializers.ModelSerializer): class Meta: model = USERaffylinks fields = '__all__' extra_fields = ['site_name'] #from USERaffiliates table extra_kwargs = { 'owneruserid': {'required':True}, 'owner_link_useraffyid': {'required':True} } def get_field_names(self, declared_fields, info): expanded_fields = super(USERaffylinksSerializer, self).get_field_names(declared_fields, info) if getattr(self.Meta, 'extra_fields', None): … -
order_by not working on a filtered queryset
i have this view def post_list(request,user_id=None): posts = Post.objects.all().order_by('-created') if user_id: user = User.objects.get(id=user_id) posts = Post.objects.filter(user=user).order_by('-created') return render(request,'post/list.html',{'posts': posts}) the Order_by is working for Post.objects.all() but not for Post.objects.filter(user=user) , any idea why? they are rendered the same way, to the same html -
Add AJAX to Django to update data without a page reload
I've seen other similar questions, but still confused as to how AJAX implementation works. I have an html table that currently gets updated when the page gets reloaded. I would like to accomplish this asynchronously using AJAX to Django. My views.py def scan_status(request): path = 'network_path/test/example.json' try: scan_data = json.load(open(path)) except Exception: traceback.print_exc() scan_data = None print('Path not found!') if scan_data is not None: df = pd.DataFrame( columns=['Folder', 'Scan Time', 'Generate Time']) for folder in scan_data['input_folders']: scan_time = scan_data['input_folders'][folder]['scan_time'] if 'generate_time' in scan_data['input_folders'][folder]: generate_time = scan_data['input_folders'][folder]['generate_time'] df = df.append({'Folder': folder, "Scan Time": scan_time, 'Generate Time': generate_time}, ignore_index=True) else: df = df.append({'Folder': folder, "Scan Time": scan_time}, ignore_index=True) table = df.to_html( na_rep='0', justify='left', float_format='%.0f', border=0, index=False) else: table = None return render(request, 'webpage/scan.html', context={'table': table}) My HTML <div> {{table | safe}} </div> -
Generate PDF Document From Django And Dot Net Core
I developed some web apps by Django and .NET Core which let user input the formatted text and saved to database by using TinyMCE editor. The formatted text will be saved as HTML text. I want to generate a PDF document which include the formatted text and the document has fixed format of every page. For example, the Purchase Order will show the Supplier and PO number on every pages. I try JasperReport community and FastReport Open Source but found that it is lack of HTML tags they supported. So the output of HTML text almost unformatted. Do you have any suggested Reprot Tools which have better support of HTML used in Django and .NET Core? Thank you! -
DRF. Matching query does not exist
Okay I have been at this for a while and cannot figure it out. Whenever I make a new job post I get the following error jobs.models.Positions.DoesNotExist: Positions matching query does not exist. Business Model: from django.db import models from django_google_maps import fields as map_fields from django.conf import settings User = settings.AUTH_USER_MODEL Company = settings.COMPANY_USER_MODEL class Business(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) business = models.CharField(max_length=50, unique=True) address = map_fields.AddressField(max_length=200, null=True) geolocation = map_fields.GeoLocationField(max_length=100, null=True) about = models.TextField(max_length=1000, null=True) def __str__(self): return self.business Job Model: from django.db import models from django_google_maps import fields as map_fields import uuid as uuid_lib from django.conf import settings User = settings.AUTH_USER_MODEL Business = settings.BUSINESS_MODEL class Positions(models.Model): position = models.CharField(max_length=100) def __str__(self): return self.position class Job(models.Model): employer = models.ForeignKey(User, on_delete=models.CASCADE) business = models.ForeignKey('business.Business', related_name='jobs', on_delete=models.CASCADE) position = models.ForeignKey(Positions, on_delete=models.CASCADE) address = map_fields.AddressField(max_length=200, null=True) geolocation = map_fields.GeoLocationField(max_length=100, null=True) uuid = models.UUIDField(db_index=True, default=uuid_lib.uuid4, editable=False) job_detail = models.TextField() # TODO: set length full_time = models.BooleanField(default=False) part_time = models.BooleanField(default=False) date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.address Job Serializer: from rest_framework import serializers, fields from .models import Job, Type, Positions def get_business_model(): return django_apps.get_model(settings.BUSINESS_MODEL, require_ready=False) Business = get_business_model() # Position Serializer class PositionSerializer(serializers.ModelSerializer): class Meta: model = Positions fields = "__all__" class JobSerializer(serializers.ModelSerializer): … -
How to colve SSL SYSCALL error: Bad file descriptor with celery?
I had an issue running celery tasks. celery was down for unkonwn issue. I tried to use django dbshell to check the table contains the task results: SELECT * FROM django_celery_results_taskresult LIMIT 1; Here is the query output: I found an error related to SSL and the same errors populated over and over on sentry issue. Is there a way to get rid of it? -
get M2M model from intermediate table name
I need to get access to m2m model from intermediate table name. Example models: class Person(models.Model): name = models.CharField(max_length=128) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person) so the table name is group_person, how can i access to it's model only from name? Due to circumstances i can't use through/etc from parent/related model. Im getting list of m2m tables names like this: m2m_fields = model_class._meta.local_many_to_many if m2m_fields: for field in m2m_fields: table = field.remote_field.through intermediate_table_name = table.__name__ while iterating over some models Thanks! Sorry for bad eng:) -
django: how to implement public like button
I would like to implement a simple 'like' button. No need for user authentication etc, I prefer to be simple, on click +1 like. Any ideas on how to implement this like btn? I appreciate your help! models.py class Mainnews(models.Model): author = models.ForeignKey(Author, on_delete=models.DO_NOTHING, default= True) title = models.CharField(max_length=200) description = models.TextField() image = models.ImageField(upload_to = 'photos/%Y/%m/%d/') is_published = models.BooleanField(default = True) publish_date = models.DateTimeField(default = datetime.now, blank = True) views_counter = models.IntegerField(default=0) likes = models.IntegerField(default=0) def number_of_likes(self): return self.likes.count() def __str__(self): return self.title -
Uncaught TypeError: Cannot read property 'id' of undefined at HTMLParagraphElement.<anonymous>
I've been looking at this for ages and feel like I'm missing something obvious, any help much appreciated! I'm trying to create nested accordions to represent a Django model in a convenient way. Paragraph elements are created and given ids using a Django for loop. Then JS is used to assign functionality (code below). The title error points to the first id reference from this line, suggesting it is undefined. if (acc2[i].id.slice(acc2[i].indexOf("_")+1) === acc3[j].id.slice(acc3[j].indexOf("_")+1)) { However, using console.log I can get the expected values for these ids ("chain_name_1" and "chainseq_1" in the first iteration of the loop, when the error occurs). I can't figure out why they subsequently show up as undefined. var acc2 = document.getElementsByClassName("prot_acc_2"); var acc3 = document.getElementsByClassName("prot_acc_3"); var i; var j; for (i = 0; i < acc2.length; i++) { acc2[i].addEventListener("click", function() { for (j = 0; j < acc3.length; j++) { console.log(acc2[0].id) console.log(acc3[0].id) var content = acc3[j]; if (acc2[i].id.slice(acc2[i].indexOf("_")+1) === acc3[j].id.slice(acc3[j].indexOf("_")+1)) { if (content.style.display === "block") { content.style.display = "none"; } else { content.style.display = "block"; } } } }); } -
Call Python command within Javascript using Django
I have a registration form that asks for username. So in javascript I want to check if the username exists in the database (via python), every time the text is edited. So how can I call a python command from within javascript and get the resulting list/array? $("#inputUsername").change(function() { var userNameInput = $("#inputUsername").val(); var existingUsernames = getExistingUsernames(); // get from python if (existingUsernames.includes(userNameInput)) { // reject form } }) def getExistingUsernames(): return database.get("users").usernames() -
How can i do a POST request in a Deatil View with a create view for comment form / Django
i dont think my approach is a good one by passing my CommentView to the DetailView... and because of the the comment view makes a form for the post model instead of the comment model but now i dont know how to save the form and return the new comments and when i try to do that a new empty post is made instead (draft) .. (i see the post in the admin site) and i get a Reverse for 'post-detail' not found. 'post-detail' is not a valid view function or pattern name error should i change the whole code to function views? my urls app_name = 'blog' urlpatterns = [ path('', views.PostListView.as_view(), name='blog-home'), path('blog/<slug:slug>/', views.PostDetailView.as_view() , name='post-detail'), ] my models class Post(models.Model): options = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish_date') publish_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') content = models.TextField() status = models.CharField(max_length=10, choices=options, default='draft') class Meta: ordering = ('-publish_date',) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'slug': self.slug}) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() publish_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-publish_date',) def __str__(self): return f'Comment By {self.author}/{self.post}' my forms class … -
How to Save all models changes in one query on Django
I try to modify many instance of some model (like User model), and this changes is different (I don't want to use update QuerySet method and not works for my scenario), For example some user need to change first_name and some user need to change last_name. and get users like : all_user = User.objects.all() I think if I use save method for each instance after change, Django sent one query for save that! How can I save all changes to database in one query insteadof use foreach on models and save that one by one? -
Django local http://127.0.0.1:8000/ Is Not Connecting
I am currently trying out a Django Tutorial(link below), and after I type in "python manage.py runserver" , and click on the link provided, I recieve this error: ERR_CONNECTION_REFUSED Error I disabled all of my firewalls and antivirus programs, and am extremely confused as I know nothing about Django. Tutorial link:https://realpython.com/get-started-with-django-1/ I have tried other tutorials, and recieved the exact same error. -
How to create instance of model during user registration process? Django
I am writing a simple event app in django. I have register and login process. I have two models. Model creator has one OneToOneField with attribute User. Event model has attribute "creator" as foreignKey which contain specific user. What is my problem? When I create new user, I want to create new instance of Creator model at the same time and when i log in as that user and create new event, I want to set value of creator in Event as this user. How can I do it? models.py and views.py below: models.py class Event(models.Model): SPORT = ( ('Football', 'Football'), ('Volleyball', 'Volleyball'), ('Basketball', 'Basketball'), ('Futsal', 'Futsal'), ('Tennis', 'Tennis'), ('Handball', 'Handball'), ('Ice Hockey', 'Ice Hockey'), ('Paintball', 'Paintball') ) creator = models.ForeignKey(Creator, null=True, on_delete=models.SET_NULL) sport = models.CharField(max_length=20, null=True, choices=SPORT) event_name = models.CharField(max_length=30) event_date = models.DateTimeField(default=date.today()) end_event_date = models.DateTimeField(default=date.today()) current_members = models.IntegerField(default=1) total_members = models.IntegerField(default=0) event_location = models.CharField(max_length=50) cost = models.FloatField(default=0, max_length=5) description = models.CharField(max_length=300, blank=True) def __str__(self): return self.event_name class Creator(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) views.py @unauthenticated_user def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Account created successfully!') return redirect('login') context = {'form': form} return render(request, 'events/register.html', context) -
Django validation steps process
So, I would like to create a validation process of a post between multiple users. Let say for example that a user creates a post and click on validate or "ask for review". I would like to be able to send the new post to a specific user in order to allow him to check the post and its content before validate and publish it. I would like to let multiple users of the same app to send the post to this specific "team leader" user. So I think that I need to : Create a model for the post Create a specific view and render it into an html page for the creation part When user click on "ask for notice" button, I want the post to appear in the posts_notice.html page where the "team leader" user would be able to see all the current posts asking for notice and validation. Of course, this team leader user will have the possibility to edit each post. To filter all the posts I was thinking about using a boolean field called "is_noticed". If yes the post is not rendered. If False it is rendered. Once all the posts are edited, the … -
Guidence on buliding a Django model
I am trying to build a job tracker, I have a Job model where the admin can create a job, then here's where it gets tricky for me. The employee can go to the jobs sections, check out the job, then record the start time and end time. Then display the total time worked on the job. Each time the employee works on the job it will update the total time. My initial model looks like this but not sure how to handle the start, end, and total times. I would appreciate any guidance. class TaskModel(models.Model): """ Using many to many field because incase a user checks out more than one job. Maybe a better solution? """ PROGRESS_STATUS = [ ('IN PROGRESS', 'In Progress'), ('COMPLETE', 'Complete') ] intern = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) task = models.ManyToManyField("app.Model", verbose_name="")(JobModel, verbose_name="jobs", on_delete=models.CASCADE) progress = models.CharField(choices=PROGRESS_STATUS, default="In Progress", max_length=20) start_time = models.TimeField(default=timezone.now) end_time = models.TimeField() total_time = models.IntegerField(default=0) checkout_time = models.DateTimeField(default=timezone.now) -
Delete an object automatically after specified time
Trying to delete an object after a specified time from the database. Here's my Code: from datetime import timedelta from django.db import models from django.utils.timezone import now class Email(models.Model): email = models.EmailField(max_length=256) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return 'code: ' + str(self.code) @property def deletes_in_ten_seconds(self): time = self.created_at + timedelta(seconds=10) query = Email.objects.get(pk=self.pk) if time > now(): query.delete() Yet it's not working. Do I have to call the delete method after a while somehow? I really don't have a clue. (new to django) -
How to get the pk of the selected radio button in django
I'm having a hard time trying to learn Django :) I have the following line (which might not be in the best form but they work so far): models.py class Mani(models.Model): title = models.CharField(max_length=64) description = models.TextField() duration = models.ForeignKey(Duration, on_delete=models.CASCADE) price = models.PositiveSmallIntegerField() def __str__(self): return "%s %s kostet €%s und dauert %s min" % (self.title, self.description, self.price, self.duration.duration) forms.py class ManiForm(forms.Form): service_title = forms.ModelChoiceField(widget=forms.RadioSelect(attrs={'class': 'serviceForm'}), label='Bitte whälen Sie Ihre Packet', queryset=Mani.objects.all()) views.py def booking_service_detail(request, pk): service = Service.objects.get(pk=pk) if request.method == 'POST': service_form = ManiForm(request.POST) mani = Mani.objects.get(pk=pk) return render(request, template, { 'service': service, 'service_form': service_form, 'extra_form': extra_form, 'mani': mani }) mani = Mani.objects.all() service_form = ManiForm() context = { 'service': service, 'service_form': service_form, } return render(request, template, context) and finaly part of the html: <div class="content"> <form action="" method="POST"> {% csrf_token %} <h3>Bitte whälen Sie Ihre Packet</h3> <ul class="serviceForm"> {% for radio in service_form.service_title %} <li> {{ radio }} </li> {% endfor %} </ul> {% if extra_form %} <h4>Bitte whälen Sie Ihre Extra</h4> <p>{{ mani.pk }}</p> <ul class="serviceForm"> {% for radio in extra_form.extra_title %} <li> {{ radio }} </li> {% endfor %} </ul> {% endif %} <input type="submit" value="Auswählen"> </form> One of the li items from here: … -
Django and PostgreSQL dynamic schema creation and model manipulation
I've been searching all day and given up. Django does not have proper support for Postgres schemas, hence the question. Problem: I want each user in my app to have their own database schema with a unique name (created when signing up). The tables in each schema are identical to every those in every other schema but obviously the data is different (I want users to have their data isolated from each other). I need to create new DB schemas dynamically, migrate existing models to them dynamically AND retrieve data from the tables using models. This is for an API not a template. Sub-problems: Creating new Postgres DB schema dynamically Retrieving data from tables (with dynamic names) inside DB schema using models [assuming that the name is passed as an argument to a view] Thus far I've only been able migrate models to empty schemas I manually create (i.e. name is known) using the code below Inside the model: Meta: db_table='schema_name\.\.model_name'</pre> And during runtime: from django.core.management import call_command call_command('makemigrations') call_command('migrate') Questions Sub-problem (1): Is it best to create a Postgress procedure/function and then to call it from inside django? Can I just create a new empty schema in this procedure … -
How specify special class name li tag for pagination in django templates?
I want to add a class to my a tag named "active" But I can't specify a class because a tag is in a for loop with Django template language if I add a class like this, I will be added all the a tags {% for num in page_obj.paginator.page_range %} <a href="?page={{ num }}">{{ num }}</a> {% endfor %} Here is my pagination section {% if is_paginated %} {% if page_obj.has_previous %} <a href="?page=1">First</a> <a href="?page={{ page_obj.previous_page_number}}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a href="?page={{ num }}">{{ num }}</a> {% elif num > page_obj.number|add:'-3' %} <a href="?page={{ num }}">{{ num }}</a> {% elif num > page_obj.number|add:'3' %} <a href="?page={{ num }}">{{ num }}</a> {% endif %} {% endfor %} {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}">Next</a> <a href="?page={{ page_obj.paginator.num_pages}}">Last</a> {% endif %} {% endif %} -
When trying to create a new Django CreateView form, my forms are being populated with the data that was entered in the last form
Using Class Based Views, ModelForms, and Inlline Formsets. I’m making a recipe application in Django. Each user has their own OneToOne RecipeBook object, which in turn can hold as many recipes as needed, as each Recipe has a ForeignKey relationship to the RecipeBook object. There are also Ingredient and Direction objects that each have a FK relationship to the Recipe object. The good news is that I can create a Recipe object using my CreateView, with as many associated Ingredient and Direction objects as I want. The Ingredient/Direction objects should be unique to each Recipe object (and by extension, each User). However, when I create a Recipe object, and then I try to create a new Recipe object, its Ingredient and Direction fields are already populated on the new object, form the old object. So if I had just created a Recipe with 3 Ingredient/Direction fields all set to '1', and then go to create another Recipe, the new Recipe object will have all blank fields, but will have 3 Ingredient/Direction objects all set to 1. This will happen to each user that is logged in. I want to make it so these objects are all staying together. I think … -
Cannot assign "{'business': ''}": "Job.business" must be a "Business" instance. DRF
Okay I have been at this for days and cannot figure it out. Whenever I make a new job post I get the following error Cannot assign "{'business': 'some existing business name'}": "Job.business" must be a "Business" instance. Business Model: from django.db import models from django_google_maps import fields as map_fields from django.conf import settings User = settings.AUTH_USER_MODEL Company = settings.COMPANY_USER_MODEL class Business(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) business = models.CharField(max_length=50, unique=True) address = map_fields.AddressField(max_length=200, null=True) geolocation = map_fields.GeoLocationField(max_length=100, null=True) about = models.TextField(max_length=1000, null=True) def __str__(self): return self.business Job Model: from django.db import models from django_google_maps import fields as map_fields import uuid as uuid_lib from django.conf import settings User = settings.AUTH_USER_MODEL Business = settings.BUSINESS_MODEL class Positions(models.Model): position = models.CharField(max_length=100) def __str__(self): return self.position class Job(models.Model): employer = models.ForeignKey(User, on_delete=models.CASCADE) business = models.ForeignKey('business.Business', related_name='jobs', on_delete=models.CASCADE) position = models.ForeignKey(Positions, on_delete=models.CASCADE) address = map_fields.AddressField(max_length=200, null=True) geolocation = map_fields.GeoLocationField(max_length=100, null=True) uuid = models.UUIDField(db_index=True, default=uuid_lib.uuid4, editable=False) job_detail = models.TextField() # TODO: set length full_time = models.BooleanField(default=False) part_time = models.BooleanField(default=False) date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.address Job Serializer: from rest_framework import serializers, fields from .models import Job, Type, Positions, Business # Position Serializer class PositionSerializer(serializers.ModelSerializer): class Meta: model = Positions fields = "__all__" class JobSerializer(serializers.ModelSerializer): date_posted = …