Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django derive model field based on other field value
I have a CustomUser model class Account(AbstractBaseUser): email = models.EmailField(verbose_name = "email", max_length = 60, unique = True) username = models.CharField(max_length = 30, unique = True) I am using a User creation form to register new users as follows, class RegistrationForm(UserCreationForm): email = forms.EmailField(max_length = 60, help_text = "This will be your login.") class Meta: model = Account fields = ("email", "username", "password1", "password2") What I want to do is remove the "username" from the form fields, so fields = ("email", "password1", "password2") And then when the user submits the form, I wish to insert a value into the username field based on the email provided by the user, for e.g. email = abc@xyz.com, then username = abc. How do I do this? -
Django site on aws nginix server with supervisor and gunicorn [closed]
Hello everybody I have a issue. I deploy site on aws it is working properly. Than i host godaddy domain so i added that domain name in Allowed Hosts. www.mysite.com and mysite.com. when i go to the site with mysite.com it is working , but if i add www.mysite.com it is not working some times writes that it is now allowed host and sometimes not responding. have anyone idea ? I try restart reboot and everything like that. In /etc/ngninx/site-availabe/default file also written this domain names, if it sense, but cant repair it . -
Django does not create superuser using Custom User Model
I am creating a Django application and I am implementing a Custom User Model for authentication. I cannot create a superuser. I get an error saying RecursionError: maximum recursion depth exceeded while calling a Python object. I am using Django version 4.1.2. Here is my User Model class CustomAccountManager(BaseUserManager): def create_superuser(self, user_name, email, first_name, last_name, phone, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') return self.create_superuser(email=email, user_name=user_name, first_name=first_name, last_name=last_name, phone=phone, password=password, **other_fields) def create_user(self, user_name, email, first_name, last_name, phone, password, **other_fields): if not email: return TypeError(_('Please provide an email address')) email = self.normalize_email(email) user = self.model(email=email, user_name=user_name, first_name=first_name, last_name=last_name, phone=phone, **other_fields) user.set_password(password) user.save() return user class Users(AbstractBaseUser, PermissionsMixin): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) user_name = models.CharField(max_length=100, unique=True) email = models.EmailField(_('email address'), max_length=50, unique=True) phone = models.CharField(_('phone number'), max_length=50, unique=True) status = models.CharField(max_length=50) role_id = models.ForeignKey("Roles", on_delete=models.CASCADE, null=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_name', 'first_name', 'last_name', 'phone'] class Meta: ordering = ['id'] def __str__(self): return self.user_name … -
Get unique elements in an array and add the value if same element is found - django
<QuerySet [{'product': 6, 'quantity': 1}, {'product': 6, 'quantity': 10}, {'product': 7, 'quantity': 2}, {'product': 9, 'quantity': 3}] > how to get unique elements only in the array and add the quantity if same product is found. In the above eg: there are two "product: 6", so the new QuerySet should be <QuerySet [{'product': 6, 'quantity': 11}, {'product': 7, 'quantity': 2}, {'product': 9, 'quantity': 3}] > -
Filter QuerySet from a given list of indexs
I have a list of index i want to extract from another queryset. >>> allLocation = loc.objects.all() >>> allLocation <QuerySet [<loc: loc object (1)>, <loc: loc object (2)>, <loc: loc object (3)>, <loc: loc object (4)>, <loc: loc object (5)>]> >>> UserIndex = [0,3,4] >>> >>> allLocation[UserIndex[1]] <loc: loc object (4)> >>> filteredUser = ? I can query a single item but I want to filter all the index item from my allLocation given the index number in a list ( UserIndex ) and store it in filteredUser -
I am trying to show some extra data in my DRF via serializer
So I have created a shopping cart table with quantity, user, and product. I want to show all the detail of the product in the response. This is my models file for the shopping cart This is my serializer file this serializer shows all the detail of the user but the product id is showing twice if remove 'product' from the serializer then while I do the POST request it says that the NOT NULL constraint is violated And this is my response here I don't want to show 'product' and don't want any problem in POST request too if it's possible -
Deploying django using Apache and mod_wsgi problem
Was able to create a working Django application and works fine in development (runserver). However, I'm currently stuck with my production build using Apache as the web server. Hope someone can help. Have added the following lines in my httpd.conf file: # ServerName localhost:80 # use this if you're running this on a VirtualBox VM or PC ServerName localhost:8000 # Django Project LoadFile "C:/Users/Anton/AppData/Local/Programs/Python/Python310/python310.dll" LoadModule wsgi_module "C:/Users/Anton/Documents/Dad/PythonVirtual/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "C:/Users/Anton/Documents/Dad/PythonVirtual" WSGIPythonPath "C:/Users/Anton/Documents/Dad/Complere" WSGIScriptAlias / "C:/Users/Anton/Documents/Dad/Complere/Complere/wsgi.py" <Directory "C:/Users/Anton/Documents/Dad/Complere/Complere/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static/ "C:/Users/Anton/Documents/Dad/Complere/static/" <Directory "C:/Users/Anton/Documents/Dad/Complere/static/"> Require all granted ` Without the additional lines mentioned above, I can see the apache service running in background. However, once above lines have been added, the apache server is in stopped status. Below is the log file content. Starting the 'Apache2.4' service The 'Apache2.4' service is running. pm_winnt:notice] [pid 8692:tid 408] AH00455: Apache/2.4.54 (Win64) mod_wsgi/4.9.4 Python/3.10 configured -- resuming normal operations [Mon Nov 07 22:01:09.941909 2022] [mpm_winnt:notice] [pid 8692:tid 408] AH00456: Apache Lounge VS16 Server built: Jun 22 2022 09:58:15 [Mon Nov 07 22:01:09.941909 2022] [core:notice] [pid 8692:tid 408] AH00094: Command line: 'C:\\Apache24\\bin\\httpd.exe -d C:/Apache24' [Mon Nov 07 22:01:09.945903 2022] [mpm_winnt:notice] [pid 8692:tid 408] AH00418: Parent: Created child process 6552 Python … -
How to remove from QuerySet by some condition
I have a queryset, and lets say its described like this (in JSON) { [ { "name": "Alex", "01_correct_answers": 1, "02_correct_answers": 3, }, { "name": "John", "01_correct_answers": null, "02_correct_answers": null, }, { "name": "James", "01_correct_answers": null, "02_correct_answers": 3, }, ] } Here 01 and 02 are subject IDs. And I have a list of these IDs, now how can I loop through this list of IDs and check the queryset if the correct_answers of the student for these subjects are not null, if they are null (all subjects), just remove them from the queryset. And finally I would like to have a filtered queryset like below: { [ { "name": "Alex", "01_correct_answers": 1, "02_correct_answers": 3, }, { "name": "James", "01_correct_answers": null, "02_correct_answers": 3, }, ] } How can I achieve this in Django? -
AttributeError: module 'dotenv' has no attribute 'dotenv_values'
I am installed django-environ and try to get my values from .env. I haven't problems when I run server in local, but when i run my app with docker-compose up --build I have error: Traceback (most recent call last): File "/usr/bin/docker-compose", line 33, in <module> sys.exit(load_entry_point('docker-compose==1.29.2', 'console_scripts', 'docker-compose')()) File "/usr/lib/python3/dist-packages/compose/cli/main.py", line 81, in main command_func() File "/usr/lib/python3/dist-packages/compose/cli/main.py", line 200, in perform_command project = project_from_options('.', options) File "/usr/lib/python3/dist-packages/compose/cli/command.py", line 60, in project_from_options return get_project( File "/usr/lib/python3/dist-packages/compose/cli/command.py", line 148, in get_project config_data = config.load(config_details, interpolate) File "/usr/lib/python3/dist-packages/compose/config/config.py", line 442, in load service_dicts = load_services(config_details, main_file, interpolate=interpolate) File "/usr/lib/python3/dist-packages/compose/config/config.py", line 558, in load_services return build_services(service_config) File "/usr/lib/python3/dist-packages/compose/config/config.py", line 537, in build_services return sort_service_dicts([ File "/usr/lib/python3/dist-packages/compose/config/config.py", line 538, in <listcomp> build_service(name, service_dict, service_names) File "/usr/lib/python3/dist-packages/compose/config/config.py", line 526, in build_service service_dict = finalize_service( File "/usr/lib/python3/dist-packages/compose/config/config.py", line 947, in finalize_service service_dict['environment'] = resolve_environment(service_dict, environment, interpolate) File "/usr/lib/python3/dist-packages/compose/config/config.py", line 732, in resolve_environment env.update(env_vars_from_file(env_file, interpolate)) File "/usr/lib/python3/dist-packages/compose/config/environment.py", line 38, in env_vars_from_file env = dotenv.dotenv_values(dotenv_path=filename, encoding='utf-8-sig', interpolate=interpolate) AttributeError: module 'dotenv' has no attribute 'dotenv_values' I have my .env file: SECRET_KEY="django-insecure-t+)^5*1syzvs=p%tiy324)zxz26$ra!+__8)y8=!hnyjn_cg3m" My docker-compose: version: "3.10" services: postgres: image: postgres:13.3 env_file: - ./support/.env volumes: - .:/docker-entrypoint-initdb.d ports: - "5432:5432" healthcheck: test: ["CMD-SHELL", "pg_isready -U alexey_razmanov -d support_app_db"] interval: 10s timeout: 5s … -
django eccomerce prodcut name not showing in file
i am creating a new django eccomorce website now in product detail page here is my code the problem is i cant see product name correct in html page problem with first() when i use first then only product name showing but all products have same name i have 8 producs in my page eight product name same to first just like overwriting also i cant use for loop with first() i will add some pics urls.py path('collection/<str:cate_slug>/<str:prod_slug>',views.product_view,name="productview"), views.py def product_view(request,cate_slug,prod_slug): if (Category.objects.filter(slug=cate_slug, status=0)): if (Products.objects.filter(slug=prod_slug, status=0)): products = Products.objects.filter(slug=prod_slug, status=0).first() context = {'products':products} else: messages.error(request,"no such product found") return redirect("collection") else: messages.error(request,"no such category found") return redirect("collection") return render(request,"product_view.html",context) models.py class Products(models.Model): category = models.ForeignKey(Category,on_delete=models.CASCADE) slug = models.CharField(max_length=150, null=False, blank=False) product_name = models.CharField(max_length=150, null=False, blank=False) product_image = models.ImageField( upload_to=get_image,null=True,blank=True) description = models.TextField(max_length=500,null=False,blank=False) original_price = models.IntegerField(null=False,blank=False) selling_price = models.IntegerField(null=False,blank=False) status = models.BooleanField(default=False,help_text="0=default , 1=Hidden") trending = models.BooleanField(default=False,help_text="0=default , 1=Trending") meta_title = models.CharField(max_length=150,null=False,blank=False) meta_keyword = models.CharField(max_length=150,null=False,blank=False) meta_description = models.CharField(max_length=400,null=False,blank=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.product_name productview.html {% block content %} <h1>{{ products.product_name }} </h1> {% endblock %} i just want correct product name for every category i stucked here in morning helping are appreciated thank you all for helping till … -
Django admin keeps the users data when removed from the like-list
I created a like button with django which saves the information of the users who clicked the button. When the same user click the button again and 'unlike' it, the counter beside the button goes back to the number before the user clicked and the user is supposed to be removed from save-list. However, the data set in the admin keeps the user listed as one of whom clicked the button once after they clicked it. The code shows no error and I have no idea where to modify to remove the users who 'unlike'd from the data set because the code post_obj.liked.remove(user) seems running properly. My models.py is: class Post(models.Model): posts = models.CharField(max_length=420, unique=True) slug = models.SlugField(max_length=42) date_created = models.DateTimeField(auto_now_add=True) liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author') def __str__(self): return str(self.posts) LIKE_CHOICES = ( ('like', 'like'), ('unlike', 'unlike'), ) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='like', max_length=10) My views.py is: def likes(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if request.user.is_authenticated: if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value == … -
Django Channels. How to avoid exception RuntimeError: Task got Future attached to a different loop?
I use `Django Channels` with `channel_layers` (`RedisChannelLayer`). Using Channels I only need to get live messages from signals when post_save event happens. I try to send a message from the `signals.py` module. The fact that the message is sending properly, I got it successfully in the console, but then **disconnection** from the socket happens **with an Exception**: `RuntimeError: Task got Future attached to a different loop.` It refers to *`...redis/asyncio/connection.py:831`* All my settings were done properly in accordance with the documentation. My project also uses `DRF`, `Celery`(on Redis), `Redis` itself, `Daphne` server. I only try to implement it with Debug=True mode, let alone production. I have no idea what happens and how to solve it. Here are snippets from my code: consumers.py class LikeConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = "likes" await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def chat_message(self, event): message = event['message'] await self.send(text_data=json.dumps({ 'type': 'chat', 'message': message })) signals.py channel_layer = get_channel_layer() @receiver(post_save, sender=Like) def new_like(sender, instance, **kwargs): async_to_sync(channel_layer.group_send)( 'likes', { "type": "chat_message", "message": "1212341324, 213413252345" } ) script.js const likeSocket = new WebSocket(url); likeSocket.onmessage = function(e) { let data = JSON.parse(e.data); console.log(data); }; -
django eccomerce website problem with first() function
when i use first() it repeting first name to all products also when i use first() for loop is not working i just want to display correct name for products i really stucked here helping are appreciated thank you -
Import "django.urls" could not be resolved from source
I am expecting the solve please help me I m new at that. I tried searching but I could not find anything. -
Could not parse the remainder: ':' from '1:'
TemplateSyntaxError at /challeges/1 Could not parse the remainder: ':' from '1:' This is my challege.html {% if month == 1: %} <h1>This is {{ text }}</h1> {% else: %} <p>This is {{ text }}</p> {% endif %} This is my views.py def monthly_challege(request, month): return render(request, "challeges/challege.html", { "text": "Your Url Is Empty", month: month }) This is my urls.py urlpatterns = [ path("<month>", views.monthly_challege), ] -
How to stop DRF's ModelSerializer to use model field's default value?
I'm stucked with this strange bug(?) with BooleanField. While partial_update, serializer is always set all boolean values to false, if it is not set in request. My models.py class User(AbstractUser): agree_email = BooleanField(blank=True) agree_sms = BooleanField(blank=True) serializers.py class UserChangeSerializer(serializers.ModelSerializer): class Meta: model = AZUser fields = "first_name", "agree_email", "agree_sms" When i trying to set agree_email to True - it's validating as {'agree_email': True, 'agree_sms': False}, and if i try to set agree_sms to true - it'll validate it as {'agree_email': False, 'agree_sms': True} and update User object respectively. How to prevent such behavior of DRF? -
Table without primary key and two FKs - Django
I'm doing an API from a existing database (which means it's not an option to change de DB schema) with Django and rest_framework. I have a single table (foos_bars) with 2 FKs only. bar_id (FK) | foo_id (FK) 1 |1 2 |2 When I use the endpoint, I get: django.db.utils.OperationalError: (1054, "Unknown column 'foos_bars.id' in 'field list'") There is a way to work with? -
Single-query get_or_create in Django and Postgres
Currently Django performs get_or_create as a series of separate two calls: 1. try get 2. perform create if the DoesNotExist exception was thrown This can lead to IntegrityError exception being raised if the instance was created right after the DoesNotExist exception was thrown. Is there any existing solution that allows to swap current django code for a postgres-specific single-query get_or_create? No problem if the solution only works with postgres as the db backend. Bonus points if it allows async aget_or_create as well. I know this should be possible on posgres as in the accepted answer in this SO question: Write a Postgres Get or Create SQL Query But I want to look for existing solutions before customising the calls in my code one by one. -
Django Ajax Form Upload with Image
I am using Django + Ajax, and i'm trying to send a POST request to upload a form with an image. However, i still get an error KeyError: 'file' HTML form (notice i've added enctype="multipart/form-data"): <form id="addProduct" method="post" enctype="multipart/form-data"> <label class="form-label required-field" for="file">Image</label> <input class='form-control' id='file' name="file" type="file" accept="image/*" required/> </form> Javascript using AJAX requests: $("#addProduct").on("submit", function (e) { e.preventDefault() var data = new FormData(this); $.ajax({ url: '/admin/product/add/', data: data, type: 'post', success: function (response) { var result = response.result console.log(result) if (result == false) { alert("Add product failed") } else { alert("Add product successfully") } }, cache: false, contentType: false, processData: false }) } Django View - views.py: class ProductAddPage(View): def post(self, request): img = request.FILES['file'] try: #further processing except: traceback.print_exc() return JsonResponse({"result":False}, status=200, safe=False) return JsonResponse({"result":True}, status=200, safe=False) Traceback: Internal Server Error: /admin/product/add/ Traceback (most recent call last): File "D:\Codes\Django\env\lib\site-packages\django\utils\datastructures.py", line 84, in __getitem__ list_ = super().__getitem__(key) KeyError: 'file' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\Codes\Django\env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\Codes\Django\env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Codes\Django\env\lib\site-packages\django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "D:\Codes\Django\env\lib\site-packages\django\contrib\auth\mixins.py", line 73, in … -
Django: Object of type QuerySet is not JSON serializable
I am trying to remove items from cart using Jquery and Django, i have written the logic to do this but i keep getting this errror that says Object of type QuerySet is not JSON serializable, i can seem to know what the problem is because i have tried converting the code below to list using list() method in django and also values() but it still does not work as expected. views.py def RemoveWishlist(request): pid = request.GET['id'] wishlist = Wishlist.objects.filter(user=request.user) wishlist_d = Wishlist.objects.get(id=pid) delete_product = wishlist_d.delete() context = { "bool":True, "wishlist":wishlist } t = render_to_string('core/async/wishlist-list.html', context) return JsonResponse({'data':t,'wishlist':wishlist}) function.js $(document).on("click", ".delete-wishlist-product", function(){ let this_val = $(this) let product_id = $(this).attr("data-wishlist-product") console.log(this_val); console.log(product_id); $.ajax({ url: "/remove-wishlist", data: { "id": product_id }, dataType: "json", beforeSend: function(){ console.log("Deleting..."); }, success: function(res){ $("#wishlist-list").html(res.data) } }) }) wishlist-list.html {% for w in wishlist %} {{w.product.title}} {% endfor %} traceback Internal Server Error: /remove-wishlist/ Traceback (most recent call last): File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Destiny\Desktop\E-commerce\ecomprj\core\views.py", line 453, in RemoveWishlist return JsonResponse({'data':t,'wishlist':wishlist}) File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\http\response.py", line 603, in __init__ data = json.dumps(data, cls=encoder, **json_dumps_params) File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 234, in dumps return cls( … -
staticfiles.W004 Error, The directory '/app/static' in the STATICFILES_DIRS setting does not exist. Postgres tables are 0,
django project deployment on heroku was successful https://ddesigner.herokuapp.com/ "heroku run python collectstatic" fails with following error ?: (staticfiles.W004) The directory '/app/static' in the STATICFILES_DIRS setting does not exist. 1395 static files copied to '/app/staticfiles'. "heroku run python makemigrations" also gives same error although new migrations are made ?: (staticfiles.W004) The directory '/app/static' in the STATICFILES_DIRS setting does not exist. "heroku run python migrate" also gives same error and I see that migrations are applied (as displayed) but not actually. because postgres tables in heroku are zero. Please help me to fix this issue. I have tried removing STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] and also by changing STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') to STATIC_ROOT = os.path.join(BASE_DIR, 'static') but the error is same. -
How do I prefill django-simple-history HistoricalRecords with pre-existing admin model history?
I have a model with pre-existing history When I switch my admin from the Django default admin.ModelAdmin to django-simple-history simple_history.admin.SimpleHistoryAdmin I lose this history Note that this history is only lost from the user's perspective, switching back to ModelAdmin returns the history. Is it possible to prefill django-simple-history with prior history, or if not, to show the two alongside one another in the admin? -
first product name repeting to all others django eccomerce
hii i am newbie here creating a eccomerce website no errors showing in during template rendering but the problem is my first product name is repeting to all other products views.py def product_view(request,cate_slug,prod_slug): if(Category.objects.filter(slug=cate_slug, status=0)): if(Products.objects.filter(slug=prod_slug, status=0)): product = Products.objects.filter(slug=prod_slug, status=0).first() else: messages.warning(request,"product not found") return redirect("collection") else: messages.error(request,"something went wrong") return redirect("collection") return render(request,"product_view.html",{'product':product}) and i found an error when i remove first() from product its not showing product names but if i am not removing first() its showing first product name to all other remaning products i really stcuked this anyone help me please i want to display coorect name for every products here is repeting same name to all other name because of first() function i stucked this into 5 hours any one help me please -
google_link,google_text = google(result) make cannot unpack non-iterable NoneType object djanog BeautifulSoup
i try to make search google with BeautifulSoup in socialnetwork django site project i download it as open source and when i try to make that i receve a error message cannot unpack non-iterable NoneType object thats search.py import requests from bs4 import BeautifulSoup done def google(s): links = [] text = [] USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36' headers = {"user-agent": USER_AGENT} r=None if r is not None : r = requests.get("https://www.google.com/search?q=" + s, headers=headers) soup = BeautifulSoup(r.content, "html.parser") for g in soup.find_all('div', class_='yuRUbf'): a = g.find('a') t = g.find('h3') links.append(a.get('href')) text.append(t.text) return links, text and thats the view.py def results(request): if request.method == "POST": result = request.POST.get('search') google_link,google_text = google(result) google_data = zip(google_link,google_text) if result == '': return redirect('Home') else: return render(request,'results.html',{'google': google_data }) and thats a template {% for i,j in google %} <a href="{{ i }}" class="btn mt-3 w-100 lg-12 md-12">{{ j }}</a><br> {% endfor %} i reseve the message cannot unpack non-iterable NoneType object for google_link,google_text = google(result) -
Django _id in FK Model
I'm doing an API from a existing database (which means it's not an option to change de DB schema) with Django and rest_framework. I have 2 tables, Foos and Bars. foo_id 1 2 bar_id | foo_id (FK) 1 |1 2 |2 Bars model: foo = models.ForeignKey('Foos', on_delete=models.CASCADE) The Django Model changes de 'foo_id' FK into 'foo' only. There is a way to keep the FK with the '_id' suffix?