Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Error : (fields.E304) Reverse accessor for field clashes with reverse accessor for another field
Below is my models.py file in a Django project. Whenever I try to run the project I get the following error. Please assist as I have just started picking up django I tried changing the names of the foreign columns as suggested by the error but no avail. A lot of answers out there suggest changes with respect to related_name which does not exist in my case. Error from console app_fin.TblLockerCoutCin.jewel_item: (fields.E304) Reverse accessor for 'TblLockerCoutCin.jewel_item' clashes with reverse accessor for 'TblLockerCoutCin.jewel_item_code'. HINT: Add or change a related_name argument to the definition for 'TblLockerCoutCin.jewel_item' or 'TblLockerCoutCin.jewel_item_code'. app_fin.TblLockerCoutCin.jewel_item: (fields.E304) Reverse accessor for 'TblLockerCoutCin.jewel_item' clashes with reverse accessor for 'TblLockerCoutCin.jewel_item_name'. HINT: Add or change a related_name argument to the definition for 'TblLockerCoutCin.jewel_item' or 'TblLockerCoutCin.jewel_item_name'. app_fin.TblLockerCoutCin.jewel_item_code: (fields.E304) Reverse accessor for 'TblLockerCoutCin.jewel_item_code' clashes with reverse accessor for 'TblLockerCoutCin.jewel_item'. HINT: Add or change a related_name argument to the definition for 'TblLockerCoutCin.jewel_item_code' or 'TblLockerCoutCin.jewel_item'. app_fin.TblLockerCoutCin.jewel_item_code: (fields.E304) Reverse accessor for 'TblLockerCoutCin.jewel_item_code' clashes with reverse accessor for 'TblLockerCoutCin.jewel_item_name'. HINT: Add or change a related_name argument to the definition for 'TblLockerCoutCin.jewel_item_code' or 'TblLockerCoutCin.jewel_item_name'. app_fin.TblLockerCoutCin.jewel_item_name: (fields.E304) Reverse accessor for 'TblLockerCoutCin.jewel_item_name' clashes with reverse accessor for 'TblLockerCoutCin.jewel_item'. HINT: Add or change a related_name argument to the definition for 'TblLockerCoutCin.jewel_item_name' or 'TblLockerCoutCin.jewel_item'. β¦ -
Joining 2 Django query sets
I have made 2 query sets in django which combine filters and counts and I need to find a way to join them. The models look like this: from django.db import models from django.contrib.auth.models import User # Create your models here. class Jokes(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField() date = models.DateTimeField() class Likes(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) joke_id = models.ForeignKey(Jokes, on_delete=models.CASCADE) dislike = models.BooleanField() class Meta: unique_together = ('user_id', 'joke_id',) The queries look like this: jokeLikes = Likes.objects.filter(dislike = False).select_related('joke_id') jokeDislikes = Likes.objects.filter(dislike = True).select_related('joke_id') countLikes = jokeLikes.values('joke_id__id', 'joke_id__text').annotate(Count('joke_id__id')) countDislikes = jokeDislikes.values('joke_id__id','joke_id__text').annotate(Count('joke_id__id')) I want an output that has this format: joke_id, joke_text, NumberOfLikes, NumberOfDislikes Any help is appreciated! -
Can't see me save a foreign key field that is set outside a form to the DB
My second post but I'm wondering where I'm going wrong. I'm running over a MySQL database, Python 3.73 and Django 2.2.1. Similar forms on other tables in my project work except those don't have a foreign key that I'm trying to load behind the scenes of the form in the view. I figured essions was they way to go to pass the organisation selected to the add_group view. This looked like the perfect solution but it doesn't have sessions values how to set foreign key during form completion (python/django) so I figured I missed something or haven't completely understood how sessions work properly. I've added comments in views.py where I suspect it is going wrong (I think). What I'd like to achieve is to have the foreign key (InternalOrgID) loaded by default (depending upon the user's earlier selection) so that any users don't have to remember what organisation they belong to. Any pointers would be greatly appreciated. Thank you in advance. models.py class group_table(models.Model): Default_OrgGroupID = '1234567890' OrgGroupID = models.CharField(max_length=45, primary_key=True, default=Default_OrgGroupID) GroupID = models.CharField(max_length=45) GroupName = models.CharField(max_length=45) InternalOrgID = models.ForeignKey(org_table, on_delete=models.CASCADE, db_column='InternalOrgID', blank=True, null=True) def __str__(self): return self.OrgGroupID class Meta: ordering = ['InternalOrgID'] class org_table(models.Model): Default_InternalOrgID = 'AAAZZZ' Default_OrgID β¦ -
Not able to delete tupple in Django when called "values"
How to perfrom below task ??? There are Three tables "Task" "Bug" and "TaskBug"(many to many) I want to delete task from "Task" table , Bug from "Bug" table which are in relationship with each other @csrf_exempt def project_detail(request, pk): if request.method == 'DELETE': task_obj=Task.objects.filter(project_id=pk).values("taskid") task_bug_obj = TaskBug.objects.filter(task_id__in=task_obj).values("bug_id") bug_obj = Bug.objects.filter(bugid__in=task_bug_obj) task_obj.delete() bug_obj.delete() project.delete() return HttpResponse(status=status.HTTP_204_NO_CONTENT) -
How can I deactivate registration if the user is logged in?
I have got a website with a user registration and login. Both is working fine, but the registration page can still be accessed when the user is logged in. Maybe there is something like a @logout_required decorator I can wrap around the registration view? -
How to run previously created Django Project
I am new to Django. I am using Python 3.7 with Django 2.2.6. My Django development environment is as the below. I am using Microsoft Visual Studio Code on a Windows 8.1 computer To give the commands I am using 'DOS Command Prompt' & 'Terminal window' in VS Code. Created a virtual environment named myDjango Created a project in the virtual environment named firstProject Created an app named firstApp. At the first time I could run the project using >python manage.py runserver Then I had to restart my computer. I was able to go inside the previously created virtual environment using workon myDjango command. But my problem is I don't know how to go inside the previously created project 'firstProject' and app 'firstApp' using the 'Command prompt' or using the 'VSCode Terminal window' Thanks and regards, Chiranthaka -
Validation of empty field, requier input DJANGO
I am creating an app where a user can search for ingredents by inputing them in search field. What i want to do is when search-field is empty or string is empty then he get messeage 'please put input!" and he is kept on the same page. But now when I am searching for empty string i get Page not found 404 and i do not know how to fix it with URLS now. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/search/drink_list.html Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ [name='drink_list'] search/ [name='search_results'] The current path, search/drink_list.html, didn't match any of these. My views: from django.shortcuts import render from django.db.models import Q #new from .models import Recipe from .models import Ingredient from django.contrib import messages from django.shortcuts import redirect def drink_list(request): template = "drinks/drink_list.html" return render(request, template) def search_results(besos): query = besos.GET.get('q') if not query or query == '': messages.error(besos, "Please put input") return redirect('drink_list.html') else: q = Q() for queries in query.split(): q |= (Q(ingredients__ingredient_name__icontains=queries)) #why it look for 'sok z cytryny' and show as well sok z limonki results = Recipe.objects.filter(q) template = "drinks/search_results.html" context = { 'results' : β¦ -
How to use Django's session authentication with Django Channels?
I am developing a chess web app using Django, Django Channels and React. I am using websockets for the game play between the online players and for getting updated which players are now online and available to play. However I am stuck on the authentication part. I first started with token authentication, but I found that it is not possible to send custom headers with the token in them as part of the websocket request. Then I went back to the default django.contrib.auth session authentication. Unfortunately, when the client logs in and connects to the websocket I am not able to get their user info as if the user is using a different session with the websocket. I get the value AnonymousUser when I print self.scope["user"] in the websocket consumers. Note that I am able to exchange messages using the websocket, and the authentication works well with normal http requests as I can prevent users who are not logged in from accessing views. I am guessing the problem is related to the fact that websocket requests on the client side don't access or use the cookie for the authentication like the http requests. Has anybody faced a similar problem and β¦ -
Newbie Django database question, how to select multiple entries from seperate database and add to current data base (admin side)
Hi everyone just started learning Django and python and really loving it so far been able to google my way through most things but I'm trying to now upgrade my database and having a little bit of difficulty. below is my models.py file class artists(models.Model): name = models.CharField(max_length=255, verbose_name="artist",default= "artistsdefault") def __str__(self): return self.name class song(models.Model): song_youtube_url = models.URLField(max_length=200,default= "urldefault") song_num = models.IntegerField(default= 0 ) song_title = models.CharField(max_length=200,default= "titledefault") artists_included = models.ForeignKey(artists, verbose_name="artists",on_delete=models.CASCADE,default= "artists") The above works but when I manually add a song class in the admin backend I can only select 1 artist included from a drop-down list? View of the admin page where I would like to select multiple artists instead of just 1 from the dropdown I would like to be able to select multiple artists and save to the song database by selecting multiple artists from the drop-down not just one ?. any help would be really appreciated -
Aldryn-Django Incompatibilities with Django Versions
I've been trying to setup the Divio Cli environment this morning for my project and I do seem to be having so many issues, which is getting quite annoying. First my pip broke, both versions original and pip3. Now finally at least got pip back on to try and reinstall the requirements needed for the project and now I occur these issues. And just to add the top to this, my django project should be at least on 2.2, otherwise I'll need to re-write my code for 1.1. Can anyone find a solution to this apart from using a virtual environment in which I don't use at all? Bash Logs Below LenovoTP220x Desktop # pip install Django==1.11 Collecting Django==1.11 Downloading https://files.pythonhosted.org/packages/47/a6/078ebcbd49b19e22fd560a2348cfc5cec9e5dcfe3c4fad8e64c9865135bb/Django-1.11-py2.py3-none-any.whl (6.9MB) |ββββββββββββββββββββββββββββββββ| 6.9MB 6.5MB/s Collecting pytz Downloading https://files.pythonhosted.org/packages/e7/f9/f0b53f88060247251bf481fa6ea62cd0d25bf1b11a87888e53ce5b7c8ad2/pytz-2019.3-py2.py3-none-any.whl (509kB) |ββββββββββββββββββββββββββββββββ| 512kB 3.6MB/s ERROR: aldryn-django 1.6.11.1 requires pyOpenSSL, which is not installed. ERROR: aldryn-django 1.6.11.1 has requirement Django==1.6.11, but you'll have django 1.11 which is incompatible. Installing collected packages: pytz, Django Successfully installed Django-1.11 pytz-2019.3 LenovoTP220x Desktop # pip install Django==1.6.11 Collecting Django==1.6.11 Using cached https://files.pythonhosted.org/packages/80/86/f52eec28e96fb211122424a3db696e7676ad3555c11027afd9fee9bb0d23/Django-1.6.11-py2.py3-none-any.whl ERROR: aldryn-django 1.6.11.1 requires pyOpenSSL, which is not installed. ERROR: django-storages 1.7.2 has requirement Django>=1.11, but you'll have django 1.6.11 which is incompatible. ERROR: β¦ -
How to save multiple ManytoMany instances to a Django object?
I have a django app with several Question objects. Question and Quiz are related through a ManyToManyField. I want to create Quiz objects such that each quiz is randomly assigned 3 questions. I've tried to create a save method where I first use a queryset to get 3 questions. I save the Quiz instance, then I try to set the queryset to the Quiz and save again. Most of my searches on this topic have shown where people are using a form to save the m2m object. class Question(models.Model): name = models.CharField(max_length=12) q_text = models.TextField() answer = models.CharField(max_length=12) class Quiz(models.Model): """quiz which will have three questions.""" name = models.CharField(max_length=12) questions = models.ManyToManyField(Question) completed = models.DateTimeField(auto_now_add=True) my_answer = models.CharField(max_length=12) def save(self, *args, **kwargs): """need to create an instance first, for the m2m""" super(Quiz, self).save(*args, **kwargs) """get 3 random questions""" three_questions = Quiz.objects.all().order_by('?')[0:3] self.questions.set(three_questions) super(Quiz, self).save(*args, **kwargs) I've tried a few variations of the above code. Currently this code gives the error: 'Question' instance expected, got <Quiz: Quiz object (4)> from the line self.questions.set(five_questions) How can I save multiple questions to one instance of the quiz? -
What is the proper way to structure an optional react date field feeding a django rest framework model?
I have a django rest framework datetime field (marked null=true, blank=true) which is being fed from a react form field. Currently if I leave the (react) form field blank it causes an error upon submit to the DRF backend (understandable as the react state has it as an empty string, and thus not null). I get around this by overrriding the submitted date field as null if the form field is empty. I would like to know if there is a better or more standard way to do this, as this method seems a little clunky. models.py class MyModel(models.Model): my_date = models.DateTimeField(blank=True, null=True) React form component export class Record extends Component { state = { my_date: "", }; onChange = e => this.setState({ [e.target.name]: e.target.value }); onSubmit = e => { e.preventDefault(); const { my_date } = this.state; const record = { my_date: my_date === "" ? null : moment(my_date).format("YYYY-MM-DD HH:mm") }; this.props.addRecord(record); }; <form render code> -
How can I view my HTML page in Python using Django
I'm new into creating projects in Python using Django. I'm creating a website in Python using the Django framework. I've created an "index" function in the "views.py" file to render the "index.html" file present in the "templates" folder. Below is the code for the "views.py" file. from django.http import HttpResponse from django.shortcuts import render # Create your views here. def index(request): return render(request,"index.html",{}) I've also added the navigation for the "index" page. Below is the code for "urls.py" file. from django.contrib import admin from django.urls import path from gallery import views urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index,name="index") ] But when I try to open the "index" page URL, I'm not able to view the page. What could be wrong while defining the navigation for the "index" page? Let me know if any other information is required. -
How to update multiply models using a single form
So i have been trying to update three models i.e., models.py: from django.db import models from postlog.models import FlightNum class pnr(models.Model): pnr=models.CharField(max_length=9,primary_key=True) def __str__(self): return self.pnr class name(models.Model): pnr=models.OneToOneField(pnr,on_delete=models.CASCADE,related_name='p1') name=models.CharField(max_length=10) def __str__(self): return self.name class passenger(models.Model): pnr=models.OneToOneField(pnr,on_delete=models.CASCADE,primary_key=True,related_name='p2') name=models.ForeignKey(name,on_delete=models.CASCADE) dob=models.CharField(max_length=10) passport_no= models.CharField(max_length=10,blank=True) fl_no=models.ForeignKey (FlightNum,on_delete=models.SET_NULL,null=True,unique=False) So what I'm trying to do is create a form where i can take input from the user for pnr,name,dob,passport_no and update all three models at the same time i have created 3 model forms which look like this: forms.py: from Django.forms import ModelForm from postlog.models import FlightNum from passenger.models import pnr,name,passenger class pnrForm(ModelForm): class Meta: model = pnr fields = '__all__' labels = { 'pnr' : ('PNR') } class nameForm(ModelForm): class Meta: model = name fields = ('name',) labels = { 'name' : ('Name') } class passenForm(ModelForm): class Meta: model = passenger fields = ('dob', 'passport_no', 'fl_no') labels = { 'dob' : ('Date Of Birth'), 'passport_no' : ('Passport Number'), 'fl_no' : ('Flight Number'), } my views.py: from django.shortcuts import render,redirect from passenger.forms import passenForm, pnrForm, nameForm from django.views.generic import ListView, CreateView, UpdateView, DeleteView from django.urls import reverse_lazy def passengerAdd(request): if request.method =="POST": formA = pnrForm(request.POST, prefix= 'pnr') formB = nameForm(request.POST, prefix= 'name') formC = passenForm(request.POST, prefix= β¦ -
how to transfer ImageField file to multipart/form-data which will be posted by requests
python3.6 got a ImageField image in Django 2.2, how can i transfer it to multipart/form-data ,then post it with requests I had tried requests-toolbelt, add Content-Type: Multipart/Form-data boundry=...... it returns 403 here is code: multipart_encoder = MultipartEncoder(fields={ "api_key": self.api_key, "api_secret": self.api_secret, "return_url": return_url, "notify_url": notify_url, "comparison_type": comparison_type, "image_ref1": (image_ref1.name.rsplit("/")[1], image_ref1.file.file, "image/" + "jpeg" if image_ref1.name[-3:] == "jpg" or image_ref1.name[-3:] == "jpeg" else "png") if image_ref1 else None, "uuid": uuid, "biz_no": biz_no, "screen_replay": "1", "biz_extra_data": str(biz_extra_data) }) self.headers["Content-Type"] = "multipart/form-data; boundary=${bound}" self.headers['Content-Type'] = multipart_encoder.content_type if all([self.api_key, self.api_secret, return_url, notify_url, biz_no]): # try: res = requests.post(url=API_URL, headers=self.headers, data=multipart_encoder, timeout=5) 403 Denied, request wil be ok without image -
Django channels with postgreSQL
I'm working on a project and I need to use Django-channels in it. I followed this tutorial step by step but it used Redis to make layer (which is not supported in Windows OS) so is it possible to use PostgreSQL instead of Redis for stack data? sorry for my bad grammar! English is not my native language! -
Returning Dictionary From templatetags and Printing in template
I am trying to return most voted answer for each question.also i want to send also extra infomation of that answer like vote and id. Printing one value is easy but for more than one i have to return dictionary.So how can i return dictionary and print all values in template. from django import template register = template.Library() @register.simple_tag def getmostvotedanswer(answers): answer = answers.order_by('-vote')[0] answer_info = { 'answer':answer.answer, 'vote':answer.vote, 'id':answer.id } return answer_info index.html <p class="small text-muted ">{% getmostvotedanswer question.answer_set.all %}</p> Output {'answer': 'THIS IS ANSWER THIS IS ANSWER THIS IS ANSWER THIS IS ANSWER THIS IS ANSWER', 'vote': 7, 'id': 1} I can call template_tag 3 times for three values. But I don't want to call templatetag again and again i think it will affect performance. -
How to increase model class field at some rate in Django?
I am creating a product page(10 products) in Django, wherein I need to increase dummy views in all products by some rate. Dummy Views(D) on any product during a given day N is D = N * Y * X where X for each product is selected randomly already for each product(also will be constant thereafter) and Y is taken randomly from a set each day for different products. So basically I need to increase views on each refresh of page and as a result D/24*60, would give us an increase in views per minute. How exactly I can increase my views at some rate per minute? Models.py class Products(models.Model): title = models.CharField(max_length = 100) description = models.TextField() views = models.IntegerField(null = True) image = models.ImageField(upload_to = 'productImages/') dateUploaded = models.DateField(auto_now_add=True) Daytimestamp = models.DateField(auto_now_add=True) actualViews = models.IntegerField(null = True) class Meta: ordering = ['title'] class Views(models.Model): X = ArrayField(models.IntegerField(blank = True)) Y = ArrayField(models.FloatField(blank= True)) Viewtimestamp = models.DateTimeField(auto_now_add=True) My home function in views.py is def home(request): products = Products.objects.all() views = Views.objects.all() # caculate Days(N) delta = (datetime.date.today()-products[0].dateUploaded) if delta.days == 0: Day = 1 else: Day = delta.days + 1 # if next day then change Y if datetime.date.today() β¦ -
Django statement to save date and time when a button is clicked
I'm making a notes creator web application in django and I want to save the date and time when a note is created. (i.e. save date and time as soon as 'Submit' button is clicked.) What could be the django statement to do the same ? -
How to get POST to work with Django AJAX?
I'm making a form that has dynamic fields for a quiz builder that I initialize in the body like this: <form class="form-signin" action="{% url 'main:link' %}" id="qForm"> {% csrf_token %} <div class="div1" style="width: 50%; margin: auto"> <button class="add_form_field">Add Question &nbsp; <span style="font-size:16px; font-weight:bold;">+ </span> </button> </div> <div style="width:50%;margin: auto; padding-top:15px "> <input class="btn btn-primary" type="submit" value="Submit"> <a href="/link/home" id="cancel" name="cancel" class="btn btn-secondary">Cancel</a> </div> </form> I need to POST this. This is what I have, but I haven't been able to get it to post successfully. The inner loop creates an object like "payload" with the form data. I haven't put it in yet, because I can't even get dummy payload code to post successfully. $( "#qForm" ).submit(function( event ) { $('#q2 input').each(function () { ....do stuff }); var $form = $( this ), path = $form.attr( "action" ); payload = {"tKey":"test"}; var posting = $.ajax({ url: path, method: "POST", headers: {'X-CSRFToken': '{{ csrf_token }}'}, data: payload, dataType: "application-json", }); console.log(payload); posting.done(function() { console.log("posted"); }); posting.fail(function() { console.log( "error" ); }); The payload will print to console, but "error" follows. This is the views.py: def maker(request): if request.method == 'GET': return render(request, 'link.html') elif request.method == 'POST': data = json.loads(request.body) payl β¦ -
Django view Formview.get() executes Form __init__ code twice, is this the correct approach?
When django serves a view the form class UserRegisterForm(forms.Form) is used and this form's init function is executed twice. I'm unable to determine why the form is executed twice. The RegisterView overrides the get() function provided by FormView. If I comment out the get function, the Form is returned correctly and the init function for UserRegisterForm is only executed once. class RegisterView(generic.FormView): template_name = 'dl_user/register.html' form_class = UserRegisterForm success_url = reverse_lazy('dl_user:register_success') def get(self, request): request.session._get_or_create_session_key() prices_json = json.dumps(settings.prices, cls=DjangoJSONEncoder) context = { 'form': self.form_class, 'prices': prices_json, } request.session['prices'] = prices_json return render(request, self.template_name, context) RegesterView renders UserRegisterForm class UserRegisterForm(forms.Form): request = None payment_method = forms.TypedChoiceField( choices=payment.getPaymentOptions(), coerce=lambda x: str(x), widget=forms.Select, initial='1', required=True) payment_amount = forms.DecimalField(required=True, max_digits=100, decimal_places=8) # mandatory schema fields during registration username = forms.CharField(required=True, min_length=3, max_length=30, help_text='Choose a memorable name e.g jdoe', validators=[UnicodeUsernameValidator()]) password = forms.CharField(widget=forms.PasswordInput, min_length=8) password1 = forms.CharField(widget=forms.PasswordInput, min_length=8, label='Confirm Password') def __init__(self, *args, **kwargs): self.request = kwargs.get('request') if 'request' in kwargs: del kwargs['request'] super(UserRegisterForm, self).__init__(*args, **kwargs) self.ldap_ops = LDAPOperations() self.helper = FormHelper() self.helper.form_id = 'id-user-data-form' self.helper.form_method = 'post' # self.helper.form_action = 'register' self.helper.add_input(Submit('submit', 'Submit', css_class='btn-success')) self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-2' self.helper.field_class = 'col-md-8' self.helper.error_text_inline = False self.helper.layout = Layout( Fieldset('Login Details', 'username', 'password', 'password1'), β¦ -
How to change python environment in Django virtual environment
I have a project made in Django in a python 2.7.16 virtual environment. How do I migrate/change the virtual environment from python 2.7.16 to python 3 versions? -
How to Search efficiently mongodb queries with python django, i have 3 collections and each collection have 100k documents
I have 3 collections and each collection has 100k documents.I successfully connected with database, but it is taking lot of time to get the result. I need to search a query with these three collections (in python django). Is there any technique for to speedup the query process? mycode is ``` import pymongo from pymongo import MongoClient outputvideos = [] ching = 2 myclient = MongoClient('mongodb://localhost:27017/') myclient = myclient.feedbox #mydatabase mydb = myclient.lunchbox_youtubechannelid #collection1 for x in mydb.find({"id": int(ching),"status":"checked"}): chid = x['feedlist'] outputvideos.append(chid) mydb = myclient.lunchbox_youtubechannelid2 #collection2 for y in mydb.find({"id": int(ching),"status":"checked"}): chid = y['feedlist'] outputvideos.append(chid) mydb = myclient.lunchbox_youtubechannelid3 #collection3 for z in mydb.find({"id": int(ching),"status":"checked"}): chid = z['feedlist'] outputvideos.append(chid) print(outputvideos) -
How can I POST without form in Django
I'm using dynamic fields for my input. I have a form with a submit button and div to append the dynamic fields. Right now I'm just trying to POST with dummy data, but I'll switch it to an array when it works. <form class="signin" action="{% url 'main:link/link' %}" id="Form1"> This is my request in my html. var $form = $( this ), path = $form.attr( "action" ); payload = {"tKey":"test"}; var posting = $.ajax({ url: path, method: "POST", headers: {'X-CSRFToken': '{{ csrf_token }}'}, data: payload, dataType: "application-json", }); console.log(payload); posting.done(function() { console.log("posted"); }); posting.fail(function() { console.log( "error" ); }); This is my views: def test1(request): if request.method == 'GET': return render(request, 'link.html') elif request.method == 'POST': data = request.POST.get('data') return render(request, 'link.html') Unfortunately it keeps failing. Any ideas what I'm doing wrong? Thanks! -
AttributeError at /jobseeker/addskills 'list' object has no attribute 'jobseeker'
I am trying to make use of model formset in Django. Howwever, My Model has a foreignkey which I want to make use of request.user in the form to assist me in tracking the person that save the information. I am getting this error. @jobseeker_required def add_skills(request): template_name = 'jobseeker/addskill.html' heading_message = 'Formset Demo' SkillFormSet = modelformset_factory(JobSeekerSkills, fields=('skill', 'level',)) form = SkillFormSet() if request.method == 'POST': form = SkillFormSet(request.POST) a = form.save(commit=False) a.jobseeker = request.user.id a.save() return render(request, template_name, {'form': form}) class JobSeekerSkills(models.Model): LEVEL = ( ('Beginner', 'Beginner' ), ('Intermediary', 'Intermediary'), ('Advance', 'Advance'), ) jobseeker = models.ForeignKey(User, on_delete=models.CASCADE) skill = models.CharField(max_length=255) level = models.CharField(max_length=25, blank=True, null=True, choices=LEVEL, default='Beginer') updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True)