Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django .count() on ManyToMany has become very slow
I have a Django project that consists of a scraper of our inventory, run on the server as a cronjob every few hours, and the Django Admin page - which we use to view / access all items. We have about 30 items that are indexed. So each 'Scraping Operation' consists of about 30 individual 'Search Operations' each of which get around 500 results per run. Now, this description is a bit confusing, so I've included the models below. class ScrapingOperation(models.Model): date_started = models.DateTimeField(default=timezone.now, editable=True) date_completed = models.DateTimeField(blank=True, null=True) completed = models.BooleanField(default=False) round = models.IntegerField(default=-1) trusted = models.BooleanField(default=True) class Search(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) date_started = models.DateTimeField(default=timezone.now, editable=True) date_completed = models.DateTimeField(blank=True, null=True) completed = models.BooleanField(default=False) round = models.IntegerField(default=1) scraping_operation = models.ForeignKey(ScrapingOperation, on_delete=models.CASCADE, related_name='searches') trusted = models.BooleanField(default=True) def total_ads(self): return self.ads.count() class Ad(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='ads') title = models.CharField(max_length=500) price = models.DecimalField(max_digits=8, decimal_places=2, null=True) first_seen = models.DateTimeField(default=timezone.now, editable=True) last_seen = models.DateTimeField(default=timezone.now, editable=True) def __str__(self): return self.title Now here is the problem we've run into. On the admin pages for both the Search model and the SeachOperation model we would like to see the amount of ads scraped for that particular object (represented as a number) This works fine four … -
Does graphene-django dynamically create an API documentation?
I'm considering using GraphQL with a Django backend service but I couldn't find much information regarding the API documentation. I need some solution to dynamically generate the documentation, perhaps like npm's graphql-docs with a result similar to GitHub's API docs. Is it feasible to accomplish with graphene-django? If not, what's a good alternative for a python environment? -
Django Admin display foreign key value
I'm trying to display the foreign key value itself in the Django Admin Panel. admins.py: class CateogoriesAdmin(admin.ModelAdmin): list_display = ('category_name',) class CateogoriesItemAdmin(admin.ModelAdmin): list_display = ('category_name', 'item_name', 'item_description',) Models.py: class Category(models.Model): category_name = models.CharField(max_length=50) class CategoryItems(models.Model): category_name = = models.ForeignKey(Categories, related_name='categoriesfk', on_delete=models.PROTECT) item_name = models.CharField(max_length=50) item_description = models.CharField(max_length=100) With the above, I just get Categories Object (1) as value, I want to display the actual value in the Django admin panel not object (1), e.g. if there is a category called "Bicycle", it should display Bicycle. -
Django: Can you create a relationship with an auto-generated through table?
My code looks something like this: from django.db import models from django.conf import settings User = settings.AUTH_USER_MODEL class Dish(models.Model): name = models.CharField(max_length=200) class Meal(models.Model): name = models.CharField(max_length=200) dishes = models.ManyToManyField(Dish) The many-to-many dishes field will result in a database table called 'myapp_meal_dishes' being created that includes id, meal_id, and dish_id fields. I would like to add a MealDishEater model that connects with that auto-generated table: class MealDishEater(models.Model): meal_dish = models.ForeignKey(MealDishes, on_delete=models.CASCADE) eater = models.ForeignKey(User, on_delete=models.PROTECT) ate_meal = models.BooleanField(default=False) Of course, that doesn't work, because MealDishes is not defined. Is there a way to do this or do I have to create my own through table? -
Heroku Django app: ECONNRESET: read ECONNRESET
I'm getting the below error when trying to run the command heroku run python manage.py migrate from the terminal. ECONNRESET: read ECONNRESET I followed the link in the heroku docs to check if there was a firewall issue, but I had a successful telnet connection. I haven't been able to find any other examples of anyone running into this issue unless they are having a proxy/firewall issue but according to the telnet test it doesn't seem like I have a problem right? I've also tried testing any other heroku run command I can think of and I get the same result. -
Django: issue with relationships between tables
I am creating an enrolment page for a website using Django. I have three tables: the default User table, a Profile table (to capture additional info) and a Subscription table. I have setup the Profile table as follows: class Profile(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) profile_id = models.AutoField(primary_key=True) I have setup the Subscription table as follows: class Subscription(models.Model): subscription_no = models.AutoField(primary_key=True) user_id = models.ForeignKey(User, on_delete=models.CASCADE) profile_id = models.ForeignKey(Profile, on_delete=models.CASCADE) When a new user enrols, I create a new Profile and Subscription object for that user in views.py: #Create a new Profile object for the User user_profile = Profile() lookup_user = User.objects.get(username=username) lookup_user_id = lookup_user.pk user_profile.user_id = User.objects.get(pk=lookup_user_id) #Create a new Subscription object for the User user_subscription = Subscription() user_subscription.user_id = User.objects.get(pk=lookup_user_id) lookup_profile = Profile.objects.get(user_id=user_profile.user_id) lookup_profile_id = lookup_profile.pk user_subscription.profile_id = Profile.objects.get(pk=lookup_profile_id) Everything works okay, except I am worried that I am establishing the relationship between the tables in an incorrect manner. When I add the User, Profile and Subscription tables to the Django Admin app, the following appears for each new user profile: The following appears for a Subscription object created for a new User: And finally, if I open up a Subscription object, for example, the relationship field (which should be … -
Cannot multiply values from IntegerFields in django
I am confused regarding how to multiply the values of two IntegerFields in django. I am relatively new to django so I might be missing something fairly obvious. My code gives me the following exception: "ValueError at /multiplication/multiplied The view multiplication.views.post didn't return an HttpResponse object. It returned None instead. Request Method: POST" Here is the code from my views.py: from django.shortcuts import render,get_object_or_404 from django.shortcuts import render_to_response from django.template import RequestContext from django.views.generic import TemplateView from django import forms from multiplication.forms import HomeForm template_name1 = 'multiplication/detail.html' template_name2 = 'multiplication/multiplied.html' class myForm(forms.Form): quantity1 = forms.IntegerField(required=False) quantity2 = forms.IntegerField(required=False) form = myForm() def get(request): return render(request,template_name1,{'form': form} ) def multiply_two_integers(x,y): return x*y def post(request): if (form.is_valid()): x = request.POST('quantity1') y = request.POST('quantity2') product = multiply_two_integers(x, y) return render(request, template_name2, {'form': form, 'product': product }) Template 1: <h1>Multiplication Function</h1> <form action = "{% url 'multiplication:post' %}" method = "post"> {{ form.as_p }} {% csrf_token %} <input type = "submit" value ="Multiply"> <!--<button type="submit"> Multiply </button>--> <h1>{{product}}</h1> </form> Template 2: <h1>{{product}}</h1> -
Django Channels 2.0 channel_layers not communicating
So I've been migrating my server that was using Django Channels 1.x -> 2.x+ The original design would send a task to celery using getAFTreeTask.delay(message.reply_channel.name) and by having access to the channel_name it could haply reply asynchronously from celery import task from channels import Channel @task def getAFTreeTask(channel_name): tree = Request().cache_af_tree() Channel(channel_name).send({ "text": json.dumps({ "channel": "AF_INIT", "payload": tree }) }) Now I've migrated my server to Channels 2.x+ for various reasons. According to the docs class Consumer(JsonWebsocketConsumer): def connect(self): print("Client Connected: ", self.channel_name) self.accept() def receive_json(self, content, **kwargs): print(content) parse_request(self.channel_name, content) def disconnect(self, content): print(content) def chat_message(self, event): print("Entered reply channel") print(event) A consumer set out like this should receive request via the channel layer providing I use the right channel_name, now the consumer works as a send-receive websocket correctly if the response has access to self.send_json() or self.send() for the other generic consumers, so I'm assuming all my settings are correct, my problem is when I try to use the channel layer to send something, like this (according to https://channels.readthedocs.io/en/latest/topics/channel_layers.html#single-channels) from channels.layers import get_channel_layer from asgiref.sync import AsyncToSync def parse_request(channel_name, content): print("parsed ", channel_name, content) channel_layer = get_channel_layer() AsyncToSync(channel_layer.send)(channel_name, { "type": "chat.message", "text": "Hello there!", }) I get 2018-02-02 … -
I need to do something like form.save(commit=False) in my model in Django
I have a model that needs to include the ID in another field when its created... see below: id = models.AutoField(primary_key=True) ticket_number = models.CharField(max_length=200, blank=True) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True) ... def save(self, *args, **kwargs): shortname = self.brand.shortname super(Job, self).save(*args, **kwargs) self.ticket_number = shortname.upper() + '-' + str(self.id) super(Job, self).save(*args, **kwargs) It works, which is good, and creates a unique ticket number. I'm new to Django, but I know enough that I feel like saving a post twice is inefficient. Is there something like .save(commit=False) for Models? I'd like to only save it once per save. -
Django - How do you get the corresponding model object in a for loop in html?
I am trying to create a simple django website where any user can rate and create posts. As displayed in this django tutorial (https://docs.djangoproject.com/en/1.7/topics/templates/), you can display all the model objects in html using a for loop. In my case, each object is going to be displayed with a Like and a Dislike button, so people can rate the post. My problem is: How do I know which object belongs to which like/dislike button so that the corresponding model field can be changed for that particular object? Thank You for answers! models.py from django.db import models # Create your models here. class Post(models.Model): post_text = models.CharField(max_length=500) pub_date = models.DateTimeField("date published") likes = models.IntegerField(default=0) dislikes = models.IntegerField(default=0) def __str__(self): return self.post_text index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>AllPosts</title> </head> <body> {% if post_list %} <ul> {% for post in post_list %} <li>{{post.post_text}}</li> <p>This post has {{post.likes}} likes and {{post.dislikes}} dislikes.</p> <br>Leave a <button type="button" method="LIKE">Like</button> or a <button type="button" method="DISLIKE">Dislike</button>!</p> {% endfor %} </ul> <h2>If you want to create a post yourself, <a href="{% url 'create' %}">click here.</a></h2> {% else %} <h1>There are no posts yet...</h1> {% endif %} </body> </html> views.py from django.http import HttpResponse from django.template import … -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin
I create a project using Django called PROJECT_2.when I try the website with the URL admin "http://127.0.0.1:8000/admin" it gives me this error 'Page not found (404)'.I have no clue what the error could be as this is occurring right at the beginning before I even start code. PROJECT_2/urls.py from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), ] settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'PROJECT_2.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'PROJECT_2.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password- validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, … -
Django Heroku postgres connectivity error
I'm trying to push a basic Wagtail Django site (pip install wagtail) to Heroku following this guide with guidance from the Heroku docs and I am getting a very common postgres connectivity error (below). I can see from the dashboard that Heroku is providing the live database, and I can access it with heroku pq:psql. The project runs locally and also when I run heroku local. My `project/app/settings/production.py' is set up as recommended: import os env = os.environ.copy() SECRET_KEY = env['SECRET_KEY'] from __future__ import absolute_import, unicode_literals from .base import * DEBUG = False try: from .local import * except ImportError: pass # Parse database configuration from $DATABASE_URL import dj_database_url DATABASES = {'default': dj_database_url.config(default='postgres://localhost')} print('check') print(DATABASES) # Honor the 'X-Forwarded-Proto' header for request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Allow all host headers ALLOWED_HOSTS = ['*'] The error I get: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? Can anyone … -
Django: Is it OK to set a field to allow null which is assigned in clean func?
My Career model has fields, since, until, and currently_employed. # resume/models.py ... class Career(models.Model): resume = models.ForeignKey(Resume, on_delete=models.CASCADE) since = models.DateField() until = models.DateField(blank=True, null=True) currently_employed = models.BooleanField() company = models.CharField(max_length=50) position = models.CharField(max_length=50) achivement = models.TextField(default='') I'd like to set until to current date if currently_employed is checked in the django(python) code, not in the template(html/js), as possible. # resume/forms.py ... class CareerForm(forms.ModelForm): ... def clean(self): cleaned_data = super().clean() if cleaned_data['currently_employed'] == True: cleaned_data['until'] = timezone.now().date() # Check since < until if cleaned_data['since'] >= cleaned_data['until']: raise ValidationError('"Until" should be later than "Since"') ... Is it OK to set the until nullable?(and its form field set required=False) However, it would not be null in my logic since by currently employed, or user put that. -
Django Unit Tests - Unable to create the django_migrations table
I'm trying to write some unit tests and run them using manage.py test but the script can't create the django_migrations table for some reason. Here is the full error: Creating test database for alias 'default'... Traceback (most recent call last): File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\utils.py", line 83, in _execute return self.cursor.execute(sql) psycopg2.ProgrammingError: no schema has been selected to create in LINE 1: CREATE TABLE "django_migrations" ("id" serial NOT NULL PRIMA... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\migrations\recorder.py", line 55, in ensure_schema editor.create_model(self.Migration) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\base\schema.py", line 298, in create_model self.execute(sql, params or None) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\base\schema.py", line 117, in execute cursor.execute(sql, params) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\utils.py", line 83, in _execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: no schema has been selected to create in LINE 1: CREATE TABLE "django_migrations" ("id" serial NOT NULL PRIMA... ^ During handling of the … -
Add a field using javascript in django-admin
In my admin I want a select field with choices based on the user choice in another admin field, so I think I have to use javascript. Here my models.py (simplified): class Society(models.Model): name = models.CharField(max_length=32, unique=True) class Title(models.Model): name = models.CharField(max_length=32, unique=True) society = models.ForeignKey(Society, on_delete=models.PROTECT) class Mymodel(models.Model): society = models.ForeignKey(Society, on_delete=models.PROTECT) class Myuser(User_Add, BaseUser): ... myfield = models.ManyToManyField(Mymodel, through='Mytable') ... class Mytable(models.Model): myuser = models.ForeignKey(Myuser, on_delete=models.CASCADE) myfield = models.ForeignKey(Mymodel, null=True, on_delete=models.CASCADE) title = models.ForeignKey(Title, on_delete=models.CASCADE) My admin.py: class MytableInline(admin.TabularInline): model = Mytable extra = 0 exclude = ('title',) class MyuserAdmin(admin.ModelAdmin): inlines = [MytableInline] Mytable is showed inline with myuser and it has just one field: myfield. When I choose the value of this field (so a Mymodels instance) I want another field to appear (or become active): title. In this new field I don't want all the Title instance but only the one with society field ugual to the society field of the Mymodel instance choosen. First thing is to write the javascript function. In my javascript.js: $(document).ready(function() { document.getElementById('id_myuser_mytable-__prefix__-myfield').addEventListener('change', function() { console.log('changed') }); }); This dosn't do nothing. I find that id looking at the source of my django generated admin page. -
What's the best non-volatile way of storing data for a Django 2.0 project?
I want to create an app using Django that users can interact with and post to using HTTP requests, but I don't want to store the data in a database, the data should be lost once the server is turned off. I was thinking of using arrays and sessions but I'm just wondering if there are other options. It is a very simple app only storing strings and integers. Thank you in advance! -
Merging PDFs using reportlab and PyPDF2 loses images and embedded fonts
I am trying to take an existing PDF stored on AWS, read it into my backend (Django 1.1, Python 2.7) and add text into the margin. My current code successfully takes in the PDF and adds text to the margin, but it corrupts the PDF: When opening in the browser: Removes pictures Occasionally adds characters between words Occasionally completely changes the character set of the PDF When opening in Adobe: Says "Cannot extract the embedded font 'whatever font name'. Some characters many not display or print correctly" Says "A drawing error occured" If there were pictures pre-edit, says "Insufficient data for an image" I have made my own PDF with/without predefined fonts and with/without images. The ones with predefined fonts and no images work as expected, but with images it throws "There was an error while reading a stream." when opening in Adobe, and just doesn't show the images in the browser. I have come to the conclusion that missing fonts is the reason for the problems with the characters, but I'm not sure why the images aren't showing. I don't have control over the contents of the PDFs I'm editing so I can't ensure they only use the predefined … -
Reactstrap + django + django framework
I am working on a project and I want to know if it's possible integrate reactstrap with Django and Django Framework and how to go about it -
Django allauth AssertionError
Hello received AssertionError when try to add ACCOUNT_USERNAME_VALIDATORS = ('allauth.socialaccount.providers.battlenet.validators.BattletagUsernameValidator',) Same happen when it is a list, and if i add just str , i am receiving error that ACCOUNT_USERNAME_VALIDATORS must be a list -
How to create a compound form in Django
There are models: class Account(models.Model): num_account = models.CharField(max_length=11,blank=False,primary_key=True) ... class Counter(models.Model): num_account = models.ForeignKey(Account, on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) class HistoryApplication(models.Model): counter = models.ForeignKey(Counter, on_delete=models.CASCADE) application = models.DecimalField(max_digits=4, decimal_places=1, blank=False, null=False, validators=[MinValueValidator(0)]) Imagine: there is Account, two Counter are tied to the Account, each Counter has Histories Application. How to make a form that displays fields for input from History Applicaton for each Counter from Counter model tied to Account -
django-python3-ldap Does TLS Encrypt Passwords over http
I have implemented django-python3-ldap and integrated AD with my Django project. The project will be hosted on IIS as an intranet site that is served solely over http. I am deciding between using this solution or Django's RemoteUserBackend. Using RemoteUserBackend with IIS and enabling Windows Authentication prevents clear text passwords from being sent across the network. Is the same thing happening when I set LDAP_AUTH_USE_TLS = True and my LDAP_AUTH_URL is pointing to an LDAPS domain controller? Is it more secure (all relative, I know) to use this solution or the IIS RemoteUserBackend solution? -
how to reference a foreign key's value in a django model?
I'm trying to build a simple Queue app, where a user can take a ticket with a number in a queue of a certain room. The problem I have is that I don't know how to create a field that on the ticket creation the ticket value should be the value of the next free number in the room, however, when another ticket will be created the value of the first ticket shouldn't be changed. Here is my failed attempt (its failing on the save method of ticket): from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Room(models.Model): name = models.CharField(max_length=100) room_master = models.ForeignKey(User, on_delete=models.CASCADE) current_visitor_number = models.BigIntegerField(default=0) next_number_to_take = models.BigIntegerField(default=0) def __str__(self): return self.name + ' ' + str(self.room_master) def get_cur_room_q(self): return Ticket.objects.filter(room=self.name).order_by('request_date') class Ticket(models.Model): request_date = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) number = models.BigIntegerField(default=0) def save(self, *args, **kwargs): self.number = self.room.next_number_to_take self.room.next_number_to_take += 1 super(Ticket, self).save(*args, **kwargs) def __str__(self): return str(self.user.first_name) + ' ' + str(self.user.last_name) + ' ' + str(self.request_date) I have previously tried the following which also failed: class Ticket(models.Model): request_date = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) number = … -
Which do I would use between Sylius (Symfony) and Oscar (Django) as a component or service for another system?
I currently have to decide between using Oscar or Sylius framework to add e-commerce functionalities to a custom learning management system (LMS). I had noticed that both are good, modular and component-oriented, also they have ReST API to use them from another app, but even so, I can't choose one of the two. So I want opinions or ideas of anyone with experience on this stage. -
python Django API, How to Serialize and POST and GET files in DJANGO? [on hold]
i am having trouble seeking about the logic and how to implement a serializer and a view for the Files. as the Files are going to be represented in an API so the pdf files must go through some sort of changing like we do in the images and change them to string64! i searched alot and could run to any thing helpful so can someone guide a fellow lost programmer? -
Django - How to assign a instance to a foreign key attribute
I'm having a problem to assign an foreign key attribute to a new object. When I try to make that I get this error Cannot assign "(< ConceptType: Producto >,)": "Receipt.concept" must be a "ConceptType" instance. Well, this is the code in the view if form.is_valid(): receipt = form.save(commit=False) receipt.concept = ConceptType.objects.get(id=1), this is for create a receipt using django-afip (https://gitlab.com/WhyNotHugo/django-afip) Thanks