Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter_horizontal for Many-to-One relations
I need to create a DropDown with search field in django admin panel. After a little surfing, I found "filter_horizontal" which does something similar to what I want, but it works only for M2M relations. Any suggestions, please. -
Django API OneToOne relationship using Auth, User model, Views, Serializers
I'm trying to connect the HighScore model to my User model. This way I can save a HighScore instance for each User. No matter what I do, I get a 500 internal server error. I've tried creating a custom user model using AbstractUser. I've tried setting up OneToOne using settings.AUTH_USER_MODEL, and I've tried doing User = get_user_model() and all come back with a 500 internal server error. # models.py from django.conf import settings from django.db import models # Create your models here. class HighScore(models.Model): # user = models.OneToOneField( # settings.AUTH_USER_MODEL, # on_delete=models.CASCADE, # primary_key=True, # ) value = models.IntegerField(default=0) def __str__(self): return "{}".format(self.value) # urls.py from django.urls import path from .views import ListHighScoresView, CreateHighScoresView, HighScoresDetailView, LoginView, RegisterUsersView urlpatterns = [ path("highscores/", ListHighScoresView.as_view(), name="high-scores-all"), path("highscores/create/", CreateHighScoresView.as_view(), name="high-scores-create"), path("highscores/<int:pk>/", HighScoresDetailView.as_view(), name="high-scores-detail"), path("auth/login/", LoginView.as_view(), name="auth-login"), path("auth/register/", RegisterUsersView.as_view(), name="auth-register"), ] # serializers.py from rest_framework import serializers from .models import HighScore from django.contrib.auth.models import User class HighScoreSerializer(serializers.ModelSerializer): class Meta: model = HighScore fields = ("id", "value") def update(self, instance, validated_data): instance.value = validated_data.get("value", instance.value) # instance.user = validated_data.get("user", instance.user) instance.save() return instance class TokenSerializer(serializers.Serializer): token = serializers.CharField(max_length=255) class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ("username", "email") # views.py from django.shortcuts import render from … -
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>'error in django
i am trying to open my group project in my windows system. what should i install to to eliminate this error i tried intalling this" pip install django_adminlte_theme". while i enter this "PS D:\stock1\stock_prediction-version2.2\stock> python manage.py runserver" it show -"PS D:\stock1\stock_prediction-version2.2\stock> python manage.py runserver" and "ModuleNotFoundError: No module named 'django_adminlte_theme'" and "OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: ''" -
How to filter with different conditions?
Here I am trying to filter staffs by three conditions by selecting joined date year,month and organization.And for this I have tried like this but it is not working .What I am doing wrong here ? Exception Type: ValueError Exception Value: invalid literal for int() with base 10: '' And also I find this method that I tried below too long for my problem.If there any better solution for this then it would be a great help views.py def filter_staff_users(request): year = request.GET.get('year') month = request.GET.get('month') organization = request.GET.get('organization') present_year = datetime.datetime.today().year years_list = range(2016,present_year + 1) if year or month or organization: staffs = Staff.objects.filter( Q(joined_date__year=year) | Q(joined_date__month=month) | Q(organization=organization)) return render(request, 'organization/view_staff_users.html', {'years_list': years_list, 'staffs': staffs, 'year': year, 'month': month, 'organization': organization}) elif year and month and organization: staffs = Staff.objects.filter(Q(joined_date__year=year), Q(joined_date__month=month), Q(organization=organization)) return render(request, 'organization/view_staff_users.html', {'years_list': years_list, 'staffs': staffs, 'year': year, 'month': month, 'organization': organization}) elif year: staffs = Staff.objects.filter(joined_date__year=year) return render(request, 'organization/view_staff_users.html', {'years_list': years_list, 'staffs': staffs, 'year': year, 'month': month, 'organization': organization}) elif month: staffs = Staff.objects.filter(joined_date__month=month) return render(request, 'organization/view_staff_users.html', {'years_list': years_list, 'staffs': staffs, 'year': year, 'month': month, 'organization': organization}) elif organization: staffs = Staff.objects.filter(organization=organization) return render(request, 'organization/view_staff_users.html', {'years_list': rangeyears_list, 'staffs': staffs, 'year': year, 'month': month, … -
How can I get whether models.CharField is checked or not?
I want to know whether models.CharField is checked or not. I wrote in models.py like class Check(models.Model): STATUS = { 'A': '1', 'B': '2', } Check = ( (STATUS['A'], 'a'), (STATUS['B'], 'b'), ) check = models.CharField( max_length=1, choices=Check, default=STATUS['A']) in views.py def check(self): check_status = Check.objects I want to check whether STATUS['B'] is checked or not and I want to get all data b is retruned by using only one code check_status = Check.objects But I cannot understand how I should write a code. -
nested loop for checkbox values which compared with input form & saved form values which in json format. And how to avoid duplicates in checkbox goup
nested loop for checkbox values which compared with input form & saved form values which in json format. And how to avoid duplicates in checkbox group var form_fields = {{ i.form_field|safe }}; var save_for_details = {{ i.saved_form_details|safe }}; if(form_fields[i].type=='checkbox-group' || form_fields[i].type=='radio-group' ){ for(j=0;j<form_fields[i].values.length;j++){ for(k=0;k<save_for_details.length;k++){ if(form_fields[i].name+"[]" == save_for_details[k].name){ if(save_for_details[k].value== j){ var checked = "checked"; }else{ var checked = ""; } html += '<input class="" style="width: 25px !important;" type="'+fields+'" id="'+form_fields[i].values[j].value+'" '+checked+' name="'+form_fields[i].name+'[]" value="'+j+'"><label>'+form_fields[i].values[j].value+'</label>'; } } } checked & uchecked need to display only once -
Unable to Update InlineFormset in Django with CBV
class PreChildrenView(CreateView): model = PreDealDetails2 template_name = 'cam_app/children_form.html' fields = '__all__' success_url = reverse_lazy('forms_app:deal-entering') session_initial = 'children_' def get_initial(self,**kwargs): initial = super(PreChildrenView, self).get_initial(**kwargs) initial['deal_id'] = self.request.session['deal_id'] return initial def get_context_data(self, **kwargs): data = super(PreChildrenView, self).get_context_data(**kwargs) if self.request.POST: data['childrens'] = ChildrenFormSet(self.request.POST) print('post') else: print('get') data['childrens'] = ChildrenFormSet() data['childrens'].extra = 5 data['info'] = 'Children Details' return data def form_valid(self, form): print('wwwww') context = self.get_context_data() childrens = context['childrens'] if form.is_valid(): pass if childrens.is_valid(): count = 0 self.object = form.save() childrens.instance = self.object childrens.save() self.request.session[self.session_initial + 'children_count'] = count self.request.session['valid_children'] = True messages.success(self.request, 'Successfully filled Children Details') return self.render_to_response(self.get_context_data(form=form)) else: return super(PreChildrenView, self).form_invalid(form) class UpdatePreChildrenView(UpdateView): model = PreDealDetails2 template_name = 'cam_app/children_form.html' fields = '__all__' success_url = reverse_lazy('forms_app:deal-entering') session_initial = 'children_' def get_object(self, queryset=None): return PreDealDetails2(deal_id = self.request.session['deal_id']) def get_context_data(self, **kwargs): data = super(UpdatePreChildrenView, self).get_context_data(**kwargs) if self.request.POST: a = PreDealDetails2.objects.get(deal_id = self.request.session['deal_id']) data['childrens'] = ChildrenFormSet(self.request.POST) print('post') else: print('get') data['childrens'] = ChildrenFormSet(instance=self.object) data['childrens'].extra = 5 data['info'] = 'Children Details' return data def form_valid(self, form): print('update valid') context = self.get_context_data() childrens = context['childrens'] if form.is_valid(): print('wejri') self.object =form.save() if childrens.is_valid(): childrens.instance = self.object childrens.save() count = 0 self.request.session[self.session_initial + 'children_count'] = count self.request.session['valid_children'] = True messages.success(self.request, 'Successfully filled Children Details') return self.render_to_response(self.get_context_data(form=form)) else: return super(UpdatePreChildrenView, self).form_invalid(form) else: … -
Pagination in search results django
I want to implement pagination in search results. After search I see good result (e.g. http://127.0.0.1:8001/search/?q=mos) But, when I click "next", I have an error: ValueError at /search/, Request URL: http://127.0.0.1:8001/search/?city=2 Cannot use None as a query value I think that problem in urls (search_results.html). How can I fix it? How can I change: <a href="/search?city={{ page_obj.next_page_number }}">next</a> models.py from django.db import models class City(models.Model): name = models.CharField(max_length=255) state = models.CharField(max_length=255) class Meta: verbose_name_plural = "cities" def __str__(self): return self.name views.py class HomePageView(ListView): model = City template_name = 'cities/home.html' paginate_by = 3 page_kwarg = 'city' def city_detail(request, pk): city = get_object_or_404(City, pk=pk) return render(request, 'cities/city_detail.html', {'city': city}) class SearchResultsView(ListView): model = City template_name = 'cities/search_results.html' paginate_by = 3 page_kwarg = 'city' def get_queryset(self): # new query = self.request.GET.get('q') object_list = City.objects.filter( Q(name__icontains=query) | Q(state__icontains=query) ) return object_list urls.py urlpatterns = [ path('search/', SearchResultsView.as_view(), name='search_results'), path('', HomePageView.as_view(), name='home'), path('city/<int:pk>/', views.city_detail, name='city_detail'), ] search_results.html <ul> {% for city in object_list %} <li> {{ city.name }}, {{ city.state }} </li> {% endfor %} </ul> <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="/search?city={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="page-current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next … -
Where to start - Python For Interactive Websites
So I can code basic python already and built myself a program that uses sqlite to track certain stuff (data I need to input each day by myself) & wanted to make an online version of it. I read a whole book on django but I literally don't know the first step on how to go forward, cause at least in that book, he always used views that are already implemented in django & it seems like he only worked with posts. What I need to do is the following though. I need to enter certain data on the website and then send it upon a click to the database, and then the website should update (it has certain fields like means etc...). And secondly, again upon a click it should display certain stuff. I want this to be a one-page website so that's why again I felt like django isn't a good start since each 'app' kinda has multiple urls or at least that's how I understood it. Since I have literally zero idea of how to do it, posting here is my last attempt to figure it out, otherwise I'm thinking of hiring a developer only to show … -
How to calculate max requests per second of a Django app?
I am about the deploy a Django app, and then it struck me that I couldn't find a way to anticipate how many Gunicorn workers I will actually need to serve my audience provided that I know how many visitors per second my website will receive. Is there a way of calculating how many requests per second can my Django application handle, without resorting to things like doing a test deployment and use an external tool such as locust? I know there are several factors involved (such as number of database queries, etc.), but perhaps there is a convenient way of calculating, even estimating, how many visitors can a single Django app instance handle -
How to index search results on location bases not the whole model django
I am trying to create a location based app. I want to index search result on location basis. There will be cluster with whom objects will be associated. Index search results per cluster. I have seen some examples of elastic-search but the most examples I found are indexing the whole model. How can someone index but at different locations we have different search indexes. Every cluster and its associated products have their own search index. my models are as follows: from django.db import models from django.contrib.gis.db.models.fields import PointField class Cluster(models.Model): name = models.CharField(max_length=30) location = PointField(srid=4326, geography=True) class Product(models.Model): title = models.CharField(max_length=30) description = models.CharField(max_length=255) cluster = models.ForiegnKey(Cluster, on_delete=models.DO_NOTHING) Now I want to index search results per cluster not the whole Product model at once. -
Bootstrap 4 Popover not working for django Infinite Scroll
I am using bootstrap popover to show some data, in my django site. I have use infinite scroll to show list of products. We django iterate its pagination bootstrap popover don't works. page size : 3 total record : 12 For 1st 3 record popover works but for next record it won't template : <div class="row infinite-container"> {% for i in task %} <div class="col-lg-3 col-md-6 wow infinite-item"> <a href="#0" data-toggle="popover" title="Popover title" data-content="data {{forloop.counter}}" class="grid_item"> {{i.name}} </a> </div> {% endfor %} <div class="loading loader" style="display:none"></div> {% if page_obj.has_next %} <a class="infinite-more-link" style="display:none" href="?page={{ page_obj.next_page_number }}">More</a> {% endif %} </div> </div> Js code : // for infinite scroll var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function ($items) { $('.loading').hide(); } }); -
Saving django model formsets
I have one ModelForm and one modelformset and I want to save them in one click. My ModelForm is getting saved but modelformset. So I want to know to handle these in views.py. So please help with the modelformset. form: class someform(forms.ModelForm): name=forms.CharField(max_length=200,widget=forms.TextInput(attrs= {'class': 'form-control'})) class Meta: model=somemodel fields=['name'] formset: formset=modelformset_factory( somemodel1, fields=('desc',), extra=1, widget={ 'desc':forms.TextInput(attrs={'class': 'form-control'}), } ) These are forms and formsets. I want to know how to handle them in views.py. -
How would I print this field in Django?
So I am trying to print out a field in my models.py file to a HTML file. (I couldn't think of any other word besides print). I am able to do it for the username, but I am struggling for the description/bio in this case. I have tried things like self.user.bio, self.userprofileinfo.bio among other things models.py relevant class class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50,blank=True,null=True) last_name = models.CharField(max_length=50,blank=True,null=True) bio = models.CharField(max_length=150) image = models.ImageField(upload_to='profile_pics',default='default.png') joined_date = models.DateTimeField(blank=True,null=True,default=timezone.now) verified = models.BooleanField(default=False) def __str__(self): return self.user.username def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) forms.py class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('username','email','password') class UserProfileInfoForms(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ('first_name','last_name','bio','image') user_posts.html {% extends 'mainapp/base.html' %} {% block content %} <div class="sidebar"> <p class="active" href="#">{{ view.kwargs.username }}</p> <p>{{ view.kwargs.bio }}</p> <p>Lorem</p> <p>Lorem</p> </div> {% for post in posts %} <div class="content"> <div class="post"> <h1 class='posttitle'>{{ post.title }}</h1> {% if post.published_date %} <!-- <div class="postdate"> <i class="fas fa-calendar-day"></i> &nbsp; <p>Posted {{ post.published_date|timesince }} ago</p> </div> --> <div class="posted-by"> <p>Posted by <strong>{{ post.author }}</strong> {{ post.published_date|timesince }} ago</p> </div> {% … -
Is it possible to access the Database Data inside Forms? Using QuerySet inside a Django Form (if possible)
I want to make a CheckboxSelectMultiple from the data present in DB. This data in DB is related to user using a ForeignKey. I think I can access the data of a particular user using data=user.ModelName_set.all() How can I make a CheckBoxSelectMultiple Form from this Data and save the result in different Model by connecting it to the same User? -
Django model field validators: coding style
Could you have a look at the code example below: from datetime import date from rest_framework import serializers def validate_age(date_of_birth): today = date.today() age = today.year - date_of_birth.year - ((today.month, today.day) < (date_of_birth.month, date_of_birth.day)) if (not(20 < age < 30)): raise serializers.ValidationError("You are no eligible for the job") return dob class EligibilitySerializer(serializers.Serializer): email = serializers.EmailField() name = serializers.CharField(max_length=200) date_of_birth = serializers.DateField(validators=[validate_age]) Suppose, this validate_age will not be used anywhere else. In this case a reasonable choice would be to incapsulate it inside the class as a private method. Is it possible in django somehow? If it is not possible, maybe a notation should be used? Something like this: _validate_age(date_of_birth). So that programmers should know that this function definitely is not for reusing, not for importing. -
In Django, how do I restrict certain information in a view to being viewed by the super user?
I want to have a page where anyone who is a superuser can get access to the information on a page but nobody else can do it. if (not request.user. [however I tell that someone is a superuser]): return HttpResponse('You cannot access that') with open("test.csv") as csvfile: csv_reader = csv.reader(csvfile, delimiter=',') Basically what do I need to do that sends everyone away except superusers and gives them access to the data in the csv? -
Python Django in how to daily data to weekly conversation in error in ValueError at /filter 'DATE' is not in list
I have daily data that data convert in weekly data. That in problem in error is ValueError at /filter 'DATE' is not in list view.py def filter(request): date_min = request.POST.get('date_min') date_max = request.POST.get('date_max') qs = weather_data.pdobjects.filter(DATE__range=(date_min,date_max)) df = pd.DataFrame(qs) logic = {'ET':'sum','EP':'sum','BSS':'sum','RF':'sum','WS':'sum','DT1':'sum','WT1':'sum','DT2':'sum','WT2':'sum','MAXT':'sum','MINT':'sum','RH11':'sum','RH22':'sum','VP11':'sum','VP11':'sum','CLOUDM':'sum','CLOUDE':'sum','SOIL1':'sum','SOIL2':'sum','SOIL3':'sum','SOIL4':'sum','SOIL5':'sum','SOIL6':'sum','MinTtest':'sum','MaxTtest1':'sum','MaxTtest2':'sum'} offset = pd.offsets.timedelta(days=-6) df = pd.read_clipboard(parse_dates=['DATE'], index_col=['DATE']) df = df.resample('W', loffset=offset).apply(logic) df.head() return render(request,"reports.html",locals()) ValueError at /filter 'DATE' is not in list Request Method: GET Request URL: http://localhost:8000/filter Django Version: 2.2.3 Exception Type: ValueError Exception Value: 'DATE' is not in list Exception Location: C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\parsers.py in _set, line 2290 Python Executable: C:\Users\student\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.3 Python Path: ['E:\sem-7_Rupesh\Project\prectis', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32', 'C:\Users\student\AppData\Roaming\Python\Python37\site-packages', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib\site-packages', 'c:\users\student\src\django-import-export', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib\site-packages\odf', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib\site-packages\odf', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib\site-packages\odf', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib\site-packages\odf', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib\site-packages\odf', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib\site-packages\odf', 'C:\Users\student\AppData\Local\Programs\Python\Python37-32\lib\site-packages\odf'] Server time: Wed, 11 Sep 2019 17:52:53 +0000 -
How to modify django manytomany relationship default input selection form to Multiple Search Selection?
django manytomany relationship default input selection form default multiple selection form Multiple Search Selection dowpdown Multiple Search Selection Using default django class based Viewsto create form is not userfriendly in case of manytomany realtionship model from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) -
django concurrent bulk_create not inserting all values to database
i'm using django's bulk_create to store large amount of data to postgresql database. This is happening inside a celery task. Many instance of this tasks are invoked at once based on different parameter values. There are 4 different workers which run each task instance in parallel. When only one task instance is run, all values are getting added to database but when multiple instances are running together via different workers, only some values are getting inserted while creating a list of model objects for bulk_create, i added a print to cross check if the value was getting inserted in the list. i found that the value is always added to the list but after bulk_create, the same values don't reflect in db. I had partially solved this issue by adding time.sleep to add latency and batch_size parameter in bulk_create. But this solution is not ideal and doesn't solve the issue anymore since the data has increased. i cannot post exact code, but it is something like this: * celery task: def some_function(): param_lst=[1,3,..]#many values all_task=[] for i in param_lst: all_task.append(some_task1.si(i)) #some_task1 and some_task2 are using majorly similar only some data processing changes. both use bulk_create to store values all_task.append(some_task2.si(i)) ch … -
POST with None data in Request Factory in Django
I'm moving my django application from 1.x to 2.2, When running unit tests, I get a error about posting None as data. Is it allowed to post None in previous versions? Is there any way to post None via RequestFactory? I don't want to give a empty string, since the field needs to be validated r = RequestFactory() rr = r.post("some-url",{"name":"sri", "kd_ratio":None}) -
is it possible to apply join on tables which do not have foreign key, by specifying the id name?
I have a pre-made database in which there is no foreign key constraint. I was wondering if we can apply join in django ORM without foreign keys (I know its not the best practice but since its pre-made schema, I cant change it). I looked it up but I didn't find a solution which matches my requirements. I tried the following, https://books.agiliq.com/projects/django-orm-cookbook/en/latest/join.html Join over django models https://www.caktusgroup.com/blog/2009/09/28/custom-joins-with-djangos-queryjoin/ https://www.quora.com/How-do-I-join-tables-in-Django I have table1 TId = models.BigIntegerField(primary_key=True) field1 = models.FloatField(null=True, blank=True, default=None) field2 = models.CharField(max_length=10, default=None) field3 = models.CharField(max_length=10, default=None) field4 = models.CharField(max_length=10, default=None) and table2, SId = models.BigIntegerField(primary_key=True) field5 = models.FloatField(null=True, blank=True, default=None) field6 = models.CharField(max_length=10, default=None) field7 = models.CharField(max_length=10, default=None) field8 = models.CharField(max_length=10, default=None) I want the query to be, select t1.field1, t1.field2, t2.field5 from table1 t1 inner/outer/left/right join table2 t2 on t1.TId = t2.SId where t2.field7 = "value"; -
How to save CSV in database of Django?
I made a logic to download the CSV file but now I also want to save it in the database. I have tried to save that by the file name but that doesn't work def index(request): if request.method == "POST": url = request.POST.get('url', '') username = request.POST.get('username','') r = requests.get(url) soup = BeautifulSoup(r.content, features="lxml") p_name = soup.find_all("h2",attrs={"class": "a-size-mini"}) p_price = soup.find_all("span",attrs={"class": "a-price-whole"}) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="product_file.csv"' for name,price in zip(p_name,p_price): writer = csv.writer(response) writer.writerow([name.text, price.text]) return response csv_file = csv.writer(response) csv_save = csv_save(url=url,username=username,csv_file=csv_file) csv_save.save return render(request, 'index.html') -
Cross-database in django-import-export
I have a local table which needs to reference a view from remote database. Both models are defined in same app. Now, I want to use django-import-export to import datas from excel. But it keeps reading the wrong database. @@ My local database is sqlite and the remote one is MSSQL. Model used to access the view: class EmpView(models.Model): class Meta: db_table = 'View_Emp' managed = False indexes = [ models.Index(fields=['code',]), ] ... I set the router to let django read the remote database when the model is the view otherwise read from the default one: def db_for_read(self, model, **hints): if model.__name__ == 'EmpView': return 'emp' return 'default' when I try to import datas from excel, it shows the error: Traceback (most recent call last): File "E:\Projects\Envs\.as\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "E:\Projects\Envs\.as\lib\site-packages\django\db\backends\sqlite3\base.py", line 298, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: main.View_Emp You can tell it reads the local database, but it suppose to read the remote one. What should I do? -
Django: reverse OneToOneField matching without related_name
I have several models representing different type of user profiles, class User(models.Model): pass class ProfileA(models.Model): user = models.OneToOneField(User, related_name="%(app_label)s_%(class)s_related",) class ProfileB(models.Model): user = models.OneToOneField(User, related_name="%(app_label)s_%(class)s_related",) class ProfileC(models.Model): user = models.OneToOneField(User, related_name="%(app_label)s_%(class)s_related",) Now, let's say I get the user instance: how can I get the related profile object? All three profile models(in my code I've 6 different profile models extending BaseProfile model, which is abstract) have additional fields, and I basically need the whole profile object accessible from within User object instance.