Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ModelSerializer: How do I serialize a OneToMany relation
I'll try to simplify my question: I have a model X. I also have a model Y that has a ForeignKey field pointing at X. This means in reality I could have many instances of Y belonging to X (hence one to many relation). When I am serializing X though, it has no knowledge of Y instances pointing at it. How can I serialize all the Y instances that are associated with the X I'm currently serializing? Do I have to have some kind of custom serialization? Or does Django support this somehow? -
Force password reset on manually created User
In my project I have an open signup form, where you can create your Company and all the information bellow it. After that you can invite people to help you administrate the information of your company. To do that, my idea was to, when the logged user add another admin, I would create the user manually with a fake password and send a Reset Password request to the created email, so he can create his own password. The important code is below: from django.contrib.auth.forms import PasswordResetForm ... email = form.cleaned_data.get("email") random_pass = User.objects.make_random_password() user = User(username=email, email=email, password=random_pass) user.save() company.add_admin(user) reset_form = PasswordResetForm({'email': email}) reset_form.save( email_template_name="rh/password_reset_email.html", subject_template_name="rh/password_reset_subject.txt") return redirect('dashboard') Unfortunately, the above code returns a Exception Type: AttributeError 'PasswordResetForm' object has no attribute 'cleaned_data' To note: I already have a fully working reset password feature, using everything from django and custom templates. That's why I'm trying to make this work this way I would like to customize the email_template_name and subject_template_name, like in my code thanks in advance -
How to save multiple forms in on page in Django
I am trying to make a betting app in Django. After a user signs in, there's a page with several forms, each responsible for saving the result of a match. Each form takes two integer inputs (number of goals for each team). I want to have a save button at the end of these forms such that when clicked, the input data are recorded in the database. I have two models, Game and Bet. Game is responsible for storing the actual result of games, while Bet is responsible for recording user predictions. class Game(models.Model): team1_name = models.CharField(max_length=100) team2_name = models.CharField(max_length=100) team1_score = models.IntegerField() team2_score = models.IntegerField() class Bet(models.Model): user = models.ForeignKey(User) game = models.ForeignKey(Game) team1_score = models.IntegerField() team2_score = models.IntegerField() And here's the main page {% for game in games %} <form action="../place_bet/" method="post"> {% csrf_token %} <table> <tr> <th class="table-col"><label for="team1_score">{{ game.team1_name}}</label></th> <th class="table-col">{{ form.team1_score }}</th> </tr> <tr> <td class="table-col"><label for="team2_score">{{ game.team2_name}}</label></td> <td class="table-col">{{ form.team2_score }}</td> </tr> </table> <input type="submit" value="Submit" id="submit-button"/> </form> {% endfor %} My question is how I can capture the input fields for different forms in the place_bet view that is triggered when submit button is clicked. -
Avoiding exception traceback in console output
So I'm testing that a view returns a Http404 exception using assertRaises(Http404) and it works fine. The problem is that my test console output looks like this: Creating test database for alias 'default'... Traceback (most recent call last): File "/home/dan/aiva/django/aiva/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/dan/aiva/django/aiva/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/dan/aiva/django/aiva/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/dan/aiva/django/aiva/local/lib/python2.7/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/home/dan/aiva/django/aiva/local/lib/python2.7/site-packages/django/views/generic/detail.py", line 117, in get self.object = self.get_object() File "/home/dan/aiva/django/aiva/local/lib/python2.7/site-packages/django/views/generic/detail.py", line 56, in get_object {'verbose_name': queryset.model._meta.verbose_name}) Http404: No contact found matching the query ... ---------------------------------------------------------------------- Ran 3 tests in 0.299s OK Destroying test database for alias 'default'... What's a good way to avoid this from happening? -
Django DRF+Model Serializer: How to serialize real data from FK and ManyToMany
My model, let's call it X has this: # skills skills = models.ManyToManyField(Skill) Skill has the following fields in addition to id: name = models.CharField(db_index=True, max_length=45, null=False) strength = models.IntegerField(db_index=True, null=False) last_practiced_at = models.DateField(db_index=True, null=False) I have a ModelSerializer for X which lists the fields from X for the serialization, skills being one of them. The problem is that when I serialize an object of x, I do not get the full Skill set of fields, just the id, like this: . . . "skills": [ "92ba37a6-6bed-480e-a767-f19080d6e27a" ], What can I do in order to have the ModelSerializer give a detailed view of my sub-models, where I an choose the fields I want visible, not just the id? -
Django 1.11 Migrate Runs But Creates New Migration File For Unrelated Table
I'm running a simple migration that adds a couple of extensions to a Postgres database. After running the migration, a new migration file appears that changes management options for an unrelated table: Migration 1: class Migration(migrations.Migration): dependencies = [ ('app_name', '0017_auto_20170531_2028'), ] operations = [ migrations.RunSQL('CREATE EXTENSION postgres_fdw;'), migrations.RunSQL('CREATE EXTENSION dblink;'), ] Auto-created mystery migration: class Migration(migrations.Migration): dependencies = [ ('app_name', '0018_auto_20170615_1931'), ] operations = [ migrations.AlterModelOptions( name='table_name', options={'managed': False}, ), ] Why is the second migration file being created? Thanks -
Examples of Project Based Tutorials to learn to integrate front/back end development?
I know Python/Django & JS/CSS/Html fairly well and need help via projects/tutorials to be able to integrate these. Basically need help applying what I already know in the languages. Thanks! -
Nested regex with python
How can I parse [u][i][b]sometext[/i][/u] into <u><i>[b]sometext</i></u>? I have some sort of markup which I need to convert into tags. Regex works good until tags can be nested. Is there any library for this in python/django? -
auth.User _default_manager doesn't have attribute 'get_by_natural_key'
I'm upgrading django from 1.8 to 1.11 and I'm getting this error when I try to create a superuser: Traceback (most recent call last): File "./manage.py", line 21, in <module> execute_from_command_line(sys.argv) File "/opt/app/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/opt/app/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/app/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/opt/app/lib/python2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute return super(Command, self).execute(*args, **options) File "/opt/app/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/opt/app/lib/python2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 121, in handle self.UserModel._default_manager.db_manager(database).get_by_natural_key(username) AttributeError: 'Manager' object has no attribute 'get_by_natural_key' As UserModel I use django.contrib.auth.User. Also, django created a new migration in django.contrib.auth.migrations: # -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-06-15 19:53 from __future__ import unicode_literals import django.contrib.auth.models from django.db import migrations import django.db.models.manager class Migration(migrations.Migration): dependencies = [ ('auth', '0008_alter_user_username_max_length'), ] operations = [ migrations.AlterModelManagers( name='user', managers=[ ('_default_django_manager', django.db.models.manager.Manager()), ('objects', django.contrib.auth.models.UserManager()), ], ), ] I ran it, but I have the same error. -
Django Form Data Does Not Save to DB (sqlite)
When I submit the form my terminal says: "POST /polls/ HTTP/1.1" 200 851. When I check through python manage.py shell, the form data does not show up. I am not sure why the data is not saving to the db, which is sqlite. I think the error is in the view section when I try to save the form. I have read through different post, which seem to have similar issues, but I can't seem to figure out what my issue could be. Model: from django.db import models class Stores(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=30) city = models.CharField(max_length=30) state = models.CharField(max_length=2) def __str__(self): return "%s (%s,%s) %s" % (self.name, self.city, self.state, self.address) Forms: from django.forms import ModelForm from mysite.polls.models import Stores class StoreForm(ModelForm): class Meta: model = Stores fields = ['name','address','city','state'] Views: from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.core.urlresolvers import reverse from mysite.polls.models import Stores from mysite.polls.forms import StoreForm def index(request): downtown_store = Stores.objects.get(name="Corporate") store_name = downtown_store.name store_address = downtown_store.address store_state = downtown_store.state if request.method == 'Post': form = StoreForm(request.POST) if form.is_valid(): form.save(commit=True) return HttpResponseRedirect(reverse('index')) else: form = StoreForm() context = {'store_name':store_name, 'store_address':store_address, 'store_state':store_state, 'form':form,} return render(request,'polls/index.html',context) Templates: <html> <body> <h1> {{store_name}} </h1> <h2> {{store_address}} … -
Django - Regroup By Date
I have a model with the following fields: "Date", "Employee", and "Planned Hours". Each employee has various planned hours for various dates. I'm attempting to structure my template where employees are listed in rows and their planned hours are listed in columns under the correct corresponding date. I'm currently filtering by two dates. One employee has time for the second date, but not the most current date. I would like his time to be listed correctly under the 2nd date, but currently it's displaying under the current date. See 1 hour for Chase: http://i.imgur.com/O4sake8.png My view: def DesignHubR(request): emp3_list = Projectsummaryplannedhours.objects.values_list('displayval', 'employeename').\ filter(businessunit='a').filter(billinggroup__startswith='PLS - Project').filter(Q(displayval=sunday2)|Q(displayval=sunday)).\ annotate(plannedhours__sum=Sum('plannedhours')) emp3 = map(lambda x: {'date': x[0], 'employee_name': x[1], 'planned_hours': x[2]}, emp3_list) context = {'sunday': sunday, 'emp2': emp2, 'sunday2': sunday2, 'emp3': emp3} return render(request,'department_hub_ple.html', context) My Template: {% regroup emp3 by employee_name as emp9 %} {% for employee_name in emp9 %} <!--Job--> <div class="table-row table-job-column employee-row">{{employee_name.grouper}}</div> {% regroup employee_name.list by date|date as date_list %} {% for y in date_list %} <div class="table-row table-fr-column">{{y.list.0.planned_hours|default:"0"}}</div> <div class="table-row table-fr-column">{{y.list.1.planned_hours|default:"0"}}</div> {% endfor %}{% endfor %} emp3_list Data: [{'date': 'W/E 6/18/17', 'planned_hours': Decimal('45.00000'), 'employee_name': 'Waylan'}, {'date': 'W/E 6/25/17', 'planned_hours': Decimal('45.00000'), 'employee_name': 'Waylan'}, {'date': 'W/E 6/18/17', 'planned_hours': Decimal('17.00000'), 'employee_name': 'Michael'}, {'date': … -
Custom Django forms within template and hidden inputs
Very, very quick question. I'm rendering my own custom forms within my html template...how would I go about submitting the hidden input when the user submits that form? template.html <form class="contact-form" name="contact-form" method="post" action="."> {% csrf_token %} <div class="row"> <div class="col-sm-12"> <div class="form-group"> <label for="four">Your Text</label> <textarea class="form-control" type="text" name="{{ comment_form.content.name }}" {% if comment_form.content.value %}value="{{ comment_form.content.value }}"{% endif %} placeholder="" required="required" id="four"></textarea> </div> </div> </div> <div class="form-group text-center"> <button type="submit" class="btn btn-primary pull-right">Submit Comment</button> </div> </form> form.py from django import forms from .models import Comment class CommentForm(forms.ModelForm): content_type = forms.CharField(widget=forms.HiddenInput) object_id = forms.IntegerField(widget=forms.HiddenInput) #parent_id = forms.IntegerField(widget=forms.HiddenInput, required=False) content = forms.CharField(widget=forms.Textarea) class Meta: model = Comment fields = ('content',) -
Python: Creating a list of pairs using list comprehensions? What's the syntax?
While I am working with some models I created in Django (a web dev framework that uses Python), I think that this question is mostly a python question. Check these lines of code. sorted_greek_books=sorted(BookTitlesGreek.objects.all(),key=lambda book: (book.book_type,book.title_of_book)) booklist_greek= [book.title_of_book for book in sorted_greek_books] For each book in booklist_greek, I would like the book title to be paired with the book type. Is this possible? What is the syntax for that? I took a guess (albeit for the latin books on my website, but the lines of code are written in the exact same structure). But I don't have an easy way to actually test this, since it requires connection to my database and django and some other backend components. Here's my guess: def IndexView(request): sorted_latin_books=sorted(BookTitles.objects.all(),key=lambda book: (book.book_type,book.title_of_book)) booklist_latin= [(book.title_of_book, book.book_type) for book in sorted_latin_books, for book in sorted_latin_books] So if this could yield something like... [("Textbook Title", "textbook"), ("List Title", list) ... ] then that would be my goal. Is this possible? Does anyone know the syntax? Also if you're going to link a really basic documentation that has you thinking "wow how did OP not read this he shouldn't be programming what a fool" please send the documentation because I … -
Upload file with plain AJAX/JS and Django
this is my popup form <div class="popup media-upload-form"> <div class="border cf"> <div class="close">X</div> </div> <form class="cf" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <!-- {{ form.as_p }} this is what i use, just putting plain html to show you all inputs --> <p> <label for="id_audio">Audio:</label> <input type="file" name="audio" required id="id_audio" /> </p> <input class="button" type="submit" value="Upload" /> </form> </div> this how i used to do it without ajax def upload_media(request): if request.method == 'POST': form = forms.MediaForm(request.POST, request.FILES) if form.is_valid(): media_file = form.cleaned_data['audio'] media = models.PlayerMedia() media.user = request.user media.title = str(media_file) media.description = 'good song' media.media = media_file media.save() return HttpResponse('done') file is coming from requets.FILES['filename'] and that's the problem, i don't know how to send file from js to django view. JQuery has some plugins but i want to do it without any libraries. this is what i have so far var uploadForm = document.querySelector('.media-upload-form form'); var fileInput = document.querySelector('.media-upload-form form #id_audio'); uploadForm.onsubmit = function(e) { e.preventDefault(); var fileToSend = fileInput.value; // this is not it } so how do i get reference to selected file and send it with ajax to Django for processing? -
django javascript submit button
Im working on web app project for studies. I had a problem with file upload. Then i realized that my team mate changed default submit button in create_form.html. It works like in 5. and 6. and i need to collect file data as well. What should i add to .js files (i am total beginner at javascript) to submit and save file? Please, help. forms.py class DocumentUpload(forms.ModelForm): class Meta: model = Form fields = ('file',) models.py class Form(TimeStampedModel, TitleSlugDescriptionModel): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=512) is_final = models.BooleanField(default=False) is_public = models.BooleanField(default=False) is_result_public = models.BooleanField(default=False) file = models.FileField(null=True, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('form-detail', kwargs={'slug': self.slug}) views.py def create_form(request): if request.method == 'POST': user = request.user data = ParseRequest(request.POST) print(data.questions()) print(data.form()) parsed_form = data.form() parsed_questions = data.questions() # tworzy formularz o podanych parametrach formfile = DocumentUpload(request.POST, request.FILES or None) if formfile.is_valid(): form = formfile.save(commit=False) print(form) form.author = user form.title = parsed_form['title'] form.is_final = parsed_form['is_final'] form.is_result_public = parsed_form['is_result_public'] form.description = parsed_form['description'] form.save() # zapisuje pytania z ankiety wraz z odpowienimi pytaniami for d in parsed_questions: question = Question(form=form, question=d['question']) question.save() # dla kazdego pytania zapisz wszystkie opcje odpowiadania for opt in d['options']: option = Option(question=question, option=opt) option.save() return … -
Django HTML render error
I am trying to set different styles for buttons depending on whether they are activated or not. So I do it as in this post (see code below), which works fine if I open the HTML file directly in my Webbrowser: The working button is blue while the disabled one is grey. Now, I try to access the site via the IP of the django server and it doesn't work. The buttons are standard buttons and do not have any design applied by the CSS code. However, things like background - which I set in the CSS file - are working properly. This is how it looks: Here is the code: button { border: 1px solid #0066cc; background-color: #0099cc; color: #ffffff; padding: 5px 10px; } button:hover { border: 1px solid #0099cc; background-color: #00aacc; color: #ffffff; padding: 5px 10px; } button:disabled, button[disabled]{ border: 1px solid #999999; background-color: #cccccc; color: #666666; } <div> <button> This is a working button </button> </div> <div> <button disabled="true"> This is a disabled button </button> </div> -
Django Login with Model Extending User
I have created an employee model that extends the User model. When i create an employee I can also find the same user in User.objects so I know it is created. When i try login with that user's credentials the credentials are not authenticated (incorrect username or password) class Employee(User): start_date = models.DateField() @property def leave_days_remaining(self): #to calculate calculated_days=10 return calculated_days def trial(request): emp = Employee.objects.create(username='lll', password='pass', email="myemail@emails.com", first_name='Mokgadi, last_name='Rasekgala', start_date=datetime.date.today()) found=User.objects.get(username='lll') print found.email print found.username print found.password #Found exists return render(request, 'leave/trial.html') {% if form.errors %} <p>{{ form.errors }}Your username and password didn't match. Please try again.</p> {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} <p> <label>Username</label> <input type="text" name="username"> </p> <p> <label>Password</label> <input type="password" name="password"> </p> <button type="submit">Login</button> </form> -
how to save objects to a user in django 1.10
I created a model name song, and I made a form to upload song to the website. I was wondering how to save songs to a specific user, so I can query the database for all of the songs uploaded by a user My models: class Song(models.Model): user=models.ForeignKey(User, null = True) song_name = models.CharField(max_length = 100) audio = models.FileField() My View: class SongCreate(CreateView): model = Song fields=['song_name','audio'] summary: I can upload songs but i can't link them to a user p.s I'm very new to django -
'QuerySet' object does not support item assignment' error
I am making a blog in django and am trying to implement this algorithm (algo.py) to the search question option in one of my pages.The algorithm takes input from the user and should display the sorted results list on the basis of scores of each question. algo.py import string import math from consult.models import Question, Reply def main(search_text): search_words = split_text(search_text) idf_array = [0] * len(search_words) for i in range(0, len(search_words)): idf_array[i] = idf(search_words[i]) score = [0] * Question.objects.all().count() k = -1 for post in Question.objects.all(): k += 1 score[k] = scores(post, search_words, idf_array) sorted_list = Question.objects.all() quickSort(score, sorted_list) return sorted_list def split_text(text): text_words = [word.strip(string.punctuation) for word in text.split()] stop_words = {'with', 'at', 'from', 'into', 'of', 'on', 'by', 'and', 'after', 'how', 'since', 'but', 'for', 'to', 'in', 'what', 'when', 'where', 'who', 'whom', 'why'} for w1 in stop_words: for w2 in text_words: if w1 == w2: text_words.remove(w1) return text_words def idf(term): cnt = 0 for post in Question.objects.all(): title_words = split_text(post.title) body_words = split_text(post.body) answers_words = [] ans = Reply.objects.filter(name=post) for a in ans: a_words = split_text(a.text) answers_words = answers_words + a_words words = title_words + answers_words + body_words for t in words: if t == term: cnt += 1 break … -
Clean automated text from email clients
I'm receiving emails from mailgun routes and using stripped-text to obtaing the body of some response without quote, but Gmail Is adding the next line above the quote 2017-06-15 12:58 GMT-04:00 first_name <user@domain.com>: And this line not are part of quote text. How I should clean this automated text?. -
Friend Request and Confirmation issue
so i currently have my likes app which deals with friend requests, and it works fine however my notification dont seem to be working. Whenever some likes someone else regardless of weather they are liked by that user or not it only sends the second of the two notify.send. heres my code: View.py def like_user(request, id): pending_like = get_object_or_404(User, id=id) user_like, created = UserLike.objects.get_or_create(user=request.user) user = get_object_or_404(User, username=request.user) liked_user, like_user_created = UserLike.objects.get_or_create(user=user) if pending_like in user_like.liked_users.all(): user_like.liked_users.remove(pending_like) elif request.user in liked_user.liked_users.all(): user_like.liked_users.add(pending_like) notify.send(request.user, #action=request.user.profile, target=request.user.profile, recipient=pending_like, verb='sent you a friend request view'), else: user_like.liked_users.add(pending_like) notify.send(request.user, #action=request.user.profile, target=request.user.profile, recipient=pending_like, verb='accepted your friend request view') return redirect("profile", username=pending_like.username) models.py class UserLikeManager(models.Manager): def get_all_mutual_likes(self, user, number): try: qs = user.liker.liked_users.all().order_by("?") except: return [] mutual_users = [][:number] for other_user in qs: try: if other_user.liker.get_mutual_like(user): mutual_users.append(other_user) except: pass return mutual_users class UserLike(models.Model): user = models.OneToOneField(User, related_name='liker') liked_users = models.ManyToManyField(User, related_name='liked_users', blank=True) objects = UserLikeManager() def __unicode__(self): return self.user.username def get_mutual_like(self, user_b): i_like = False you_like = False if user_b in self.liked_users.all(): i_like = True liked_user, created = UserLike.objects.get_or_create(user=user_b) if self.user in liked_user.liked_users.all(): you_like = True if you_like and i_like: return True else: return False as you can see in my views.py i have an if … -
Django create same query in several tables
I'm doing the same query for 3 tables and then the all together. But I feel that I am consuming a lot of resources that way since they are a bit complex queries, I would like to be able to create a single query for all three tables, is this possible in Django? I know that in SQLALCHEMY there is something similar: SQLAlchemy How to joiun several tables by one query Code: # Review Dish recent_dish_review = restaurant.models.DishReview. \ objects.filter(user_id__in=id_follows, created_at__lte=timezone.now(), created_at__gte=days ).order_by('-created_at')[:limit] # Review Restaurant recent_restaurant_review = restaurant.models.RestaurantReview. \ objects.filter(user_id__in=id_follows, created_at__lte=timezone.now(), created_at__gte=days ).order_by('-created_at')[:limit] # User Like Dish recent_like_dish = restaurant.models.DishesLikes. \ objects.filter(foodie_id__in=id_follows, created_at__lte=timezone.now(), created_at__gte=days ).order_by('-created_at')[:limit] return list(sorted(chain(recent_restaurant_review, recent_dish_review, recent_like_dish)) -
How to give users an individual instance of an app?
I have made an app within a Django project that is basically a message board. I have also made full login feature, everything there is working properly. When a user logs in, they go to /username/app/, a view that displays all messages . However, they all end up on the same message board with the same messages on it. What I want is for every user to have their own instance of this message board isolated from all other users. How can I implement this? I feel like there is something obvious that I am missing. I looked at stuff like this https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html but it doesn't seem to do what I want it to. If anyone could point me to some resources for understanding this problem I would greatly appreciate it. -
CORS headers not working on Django project
I have an iframe on another site. I can control the code of that iframe, but not the site itself. In the iframe, several ajax API calls to other websites are made, and a single GET request to my own website built on Django. However, this call returns error with code 0. The request isn't even logged in the network browser tab (I use Firefox). Running the same on the Django website works well, so obviously the problem is in cross-origin requests. I added and enabled django-cors-headers module, but it still doesn't work. The same error is thrown and nothing really happens. My Django version is 1.10.5. Module installed via pip for Python3.5. The whole thing works on VPS. Settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'install', 'account', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CSRF_TRUSTED_ORIGINS = ( 'https://widget.insales.ru', ) Request: $.ajax({ type: "GET", url: "http://project_url/scripty", data: { "data": JSON.stringify(r) }, dataType: 'text/plain', success: function(data){ console.log(JSON.stringify(r)); console.log("Success!"); console.log(data); }, error: function(xhr, status, errorThrown){ console.log(JSON.stringify(r)); console.log("Status: " + status + "\nThrown: " + errorThrown); console.log(xhr); } }); Not sure what to add, so ask in comments. Am I … -
Django django.db.utils.ProgrammingError. The relation <<Pages_account>> does not exist
I'm new to Django. Actually have a custom model user and when try to python manage.py migrate i´m having the following error. i'm using django 1.11 and postgres database manager. Note: In english, is it : "The relation << Pages_account >> does not exist. Operations to perform: Apply all migrations: Pages, admin, auth, contenttypes, sessions Running migrations: Applying Pages.0002_auto_20170615_1214...Traceback (most recent call last): File "C:\Users\cesar\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\db\backends\utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: no existe la relación «Pages_account» The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\cesar\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Users\cesar\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\core\management\__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\cesar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\cesar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Users\cesar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle fake_initial=fake_initial, File "C:\Users\cesar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\cesar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\cesar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\cesar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\cesar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\operations\fields.py", line 215, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "C:\Users\cesar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\base\schema.py", line …