Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the pk of a post in which a comment is contained?
In my code, I have an "add comment" option on my posts, but am struggling to make a cancel button for the create comment form as I keep getting a NoReverseMatch error. I'm trying to just have the cancel button be a link back to the post instead of anything too fancy, but it doesn't seem to recognize the URL I'm giving it. It's supposed to be a link to my posts, while calling the pk of the post that contained the comment. I've been trying to make some kind of workarounds, including a designated cancel function, trying to pull info from the URL, etc. but just can't see what I'm doing wrong. Even more puzzling is that the template related to CommentCreateView doesn't work, but the one related to CommentUpdateView does even though they're the exact same. I've included the relevant code below, and I'm new to django so please let me know if there's anything else that would be helpful to include. Thank you! error message: NoReverseMatch at /post/29/comment/ Reverse for 'post-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/$'] views.py: class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = ['text'] def form_valid(self, form): form.instance.author = self.request.user form.instance.post_id … -
Django Form Error: Make select field not required
I have a web app in which users can add items to a list and categorize those items. The users can also create those categories. The system works great when the user selects a category from the dropdown, though if the user hasn't made any categories, or wishes to not categorize an item, django throws an error under form.is_valid, stating: Select a valid choice. That choice is not one of the available choices. I have gone as far as to modify the choices on the form to be whatever the user submits but to no avail. I attempted to set the choice to a premade "None" category, but this still did not work. Here is my post method (when the user clicks the "create" button to make the item: def post(self, request, *args, **kwargs): form = ItemForm(request.POST) print("Post Request: " + str(request.POST)) choice = request.POST.get('category') print("Selected choice index: " + str(choice)) current_list = List.objects.get(id=request.session["list"]) category_choice = Category.objects.filter(list=current_list, id=choice) if not category_choice.exists(): no_category_list = List.objects.get(id=26) category_choice = Category.objects.filter(list=26, name="None") #Set the choice to whatever the user inputted form.fields['category'].choices = [(str(choice), category_choice)] print("Category Object: " + str(category_choice)) print("Form Choices: " + str(form.fields['category'].choices)) if form.is_valid(): item = form.save() json = { "item": item.to_json() … -
Django get all related date from Airtable
May I know how to search the date from Airtable in Django? below is my template file: <form action="{% url 'date' %}" method="get" class="form-inline my-2 my-lg-0" style="padding-right: 35px"> {% csrf_token %} <div class="form-group"> <input class="form-control mr-sm-2" type="date" name="query" class="form-control" > <button class="btn btn-outline-primary my-2 my-sm-0" type="submit" value="Search">Search by Date</button> </div> </form> my urls: urlpatterns = [ path('', views.home, name='home'), path('create/', views.createoreder, name='order_create'), path('<str:order_id>/', views.detail, name='detail'), path('edit/<str:order_id>', views.edit, name='edit'), path('delete/<str:order_id>', views.delete, name='delete'), path('Dates/', views.search_by_date, name='date'), ] my views.py: def search_by_date(request): if request.method == "GET": user_query = request.GET.get('query', '') date = AT.search('{Dates}', user_query) #date = AT.get_all(formula="FIND('" + user_query + "', {Dates})") return render(request, 'search_by_date.html', {'date':date}) search.html: {% extends 'base.html' %} {% block content %} {% for order in date %} order.fields.Name {% endfor %} {% endblock %} -
Uploading multiple images into django rest framework/react
Trying to do a fairly simple project where I can upload multiple images to my server with just a few other fields. I tried to follow this post but wasn't able to get anywhere on it. I know I am going to need to break my models into two with 'PostImage' having a ForeignKey that relates to Post. And I know I will need to modify the serializer in order to allow an array of image files. Any help would be greatly appreciated. models.py: from django.db import models class Post(models.Model): title = models.CharField(max_length = 100) content = models.TextField() image = models.ImageField(upload_to='post_images') def __str__(self): return self.title serializers.py: from rest_framework import serializers from .models import Post class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' views.py: from django.shortcuts import render # Create your views here. from .serializers import PostSerializer from .models import Post from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response import Response from rest_framework import status # Create your views here. class PostView(APIView): parser_classes = (MultiPartParser, FormParser) def get(self, request, *args, **kwargs): posts = Post.objects.all() serializer = PostSerializer(posts, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): posts_serializer = PostSerializer(data=request.data) if posts_serializer.is_valid(): posts_serializer.save() return Response(posts_serializer.data, status=status.HTTP_201_CREATED) else: print('error', … -
Left Join in Django ORM
Say I have models called "Post" and "Reaction" and I have made a Post, saved it and now I want to react on it with a Reaction. Now, when I visit my feed where a list of Posts is, I want to show my reaction if I had one. Which means: {% if post.my_reaction %}{{ post.my_reaction.contents }}{% endif %} Now, obviously I want to load more than just one Post; posts which don't have my reactions on it. I know that I used to solve this with SQL in PHP with SELECT * FROM Post LEFT JOIN Reaction ON Reaction.Post = Post.id AND Reaction.Author = <me> It's not quite clear how I could achieve this in Django -
Django dynamic url pattern based on model names: how to do it?
I was searching this for a while and did not figure out anyway. Let's say we have a models.py with 3 models dogs, cats and birds. In url.py we want to have a single line that works with generic ListView and DetailView for each model type. Our views.py is dynamic and accepts models from url.py. smth for eaxmple: from django.urls import path from django.views.generic import TemplateView from . import views from . import models urlpatterns = [ path('animals/<???>/', views.AnimalList.as_view(template_name = 'animals.html', model = ???), name='lots'), ] so when we go to .../animals/dogs, it loads data from dogs, or when we go to .../animals/cats we get data from cats table, and so on. How do we do this? p.s. I have the working views.py based on generic so I am not sharing it here :) -
Serialize many-to-many relation with intermediate model in Django Rest
I tried to check another topics, but didn't found a solution... I have a many-to-many model, that have intermediate model with another field additional_field inside. class BoardField(models.Model): title = models.CharField(max_length=500, default='') class Article(models.Model): title = models.CharField(max_length=500, default='') fields = models.ManyToManyField(BoardField, through='ArticleField', through_fields=('article', 'board_field')) class ArticleField(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='task') board_field = models.ForeignKey(BoardField, on_delete=models.CASCADE) additional_field = models.CharField(max_length=200, blank=True, null=True) I want serialize Article with structure: [ "title":"Title", "fields":[ { "board_field": { "title":"Title" }, "additional_field":"Additional info" } ] ] So, I wrote serializer: class BoardFieldSrl(serializers.Serializer): class Meta: model = BoardField fields = ( 'title', ) class ArticleFieldSrl(serializers.Serializer): board_field = BoardFieldSrl() class Meta: model = ArticleField fields = ( 'board_field', 'additional_field', ) class ArticleListSrl(serializers.ModelSerializer): fields = ArticleFieldSrl(many=True) class Meta: model = Article fields = ( 'title', 'fields', ) But I always got an error: Got AttributeError when attempting to get a value for field `board_field` on serializer `ArticleFieldSrl`. The serializer field might be named incorrectly and not match any attribute or key on the `BoardField` instance. Original exception text was: 'BoardField' object has no attribute 'board_field'. I made another several examples, but they doesn't gave my result, that I need... My maximum - I got BoardField with levels, but without intermediate model... … -
Django crispy formset not showing client validated erros
I have a Django application using django crispy formsets. The forms render well but I don't get the expected client-side feedback for errors(Bootstrap default) What I am expecting in case of error: Instead the page just kind of reloads without the above expected error. This is what the template looks like: ...... <h1>My Form</h1> <div class="row"> <div class="col-8"> <form action="{% url 'myapp:myform_view' %}" method="POST"> {% csrf_token %} <div class="card"> <div class="card-body"> {% crispy formset helper %} </div> </div> </form> </div> </div> The view: ...... def myform(request): MyFormSet = formset_factory(MyForm, extra=0) helper = MyFormSetHelper() formset = MyFormSet(initial=helper_method_to_get_accurate_value_here()) return render(request, 'myapp/template.html', {"formset": formset, "helper": helper}) code for MyFormSetHelper: ..... class MyFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super(MyFormSetHelper, self).__init__(*args, **kwargs) self.add_input(Submit('submit', 'Submit')) Thanks for your help in advance! -
Django DRF Getting Missing Auth Headers with JWT, but With Permission and Auth on ReadOnly Views
I'm working with both the latest Django 3.0.2 and DRF 3.11.0 using djangorestframework-simplejwt 4.4.0. I did not have this problem before on a previous Django 2.2.0 project (and older lib versions), but I cannot figure out why I cannot access a view with readonly permissions set and default authentication looks okay in settings. If I specify the authentication_classes as empty in the view, then it works fine, but this is just an example. I expected the defaults to work, from settings: unless I'm incorrect and should be explicitly set this way. I have also tried using gunicorn and waitress-serve, and it's the same result. Here is the view: class NoteList(generics.ListAPIView): """ List all Notes. Not used """ # authentication_classes = [] permission_classes = (permissions.AllowAny,) serializer_class = NoteSerializer def get_queryset(self): notes = Note.objects.all() return notes Here is my settings: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { # When you enable API versioning, the request.version attribute will contain a string # that corresponds to the version requested in the incoming client request. 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning', # Authentication settings 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', 'drf_firebase_auth.authentication.FirebaseAuthentication', ], # Permission settings 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly', 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.IsAdminUser', 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ], # … -
How to know my current Django project was created under which virtual environment?
I am new in Django, recently I have created several project directories under several virtual-environments. Now I have reopened my recent project directory, but forgot which virtual environment I was using for this project. How to find it out? -
Django-bootstrap-modal-form don't return data if not using class-based view
I am trying to use modal forms for a photo gallery in my django site. The site uses django-bootstrap4 and django-bootstrap-modal-forms. Modal forms works fine for modifying photo comments or to remove photo from a gallery. But if I want to add photos to the gallery using a form with no related model the modal form returns no data when submitted after selecting one or several files and the modal form displays an error message : This field is required. If I use normal form to add photo (not modal), it works fine. I think something is missing but cannot find what. models.py : class Gallery(models.Model): title = models.CharField(max_length=256, verbose_name='Title') description = models.TextField(blank=True, default='', verbose_name='Gallery description') class Photo(models.Model): gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE, verbose_name='Gallery') photo = models.ImageField(verbose_name='Photo') comment = models.TextField(max_length=256, verbose_name='Photo comment', blank=True, default='') def get_absolute_url(self): return reverse('manage', kwargs={'pk': self.gallery.pk}) @receiver(post_delete, sender=Photo) def submission_delete(sender, instance, **kwargs): instance.photo.delete(False) forms.py : class GetPhotosForm(forms.Form): file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}), label='Add photos') class PhotoForm(BSModalForm): class Meta: model = Photo fields = ['comment'] views.py # Manage gallery (add photos) def manage_gallery(request, pk): gallery = get_object_or_404(Gallery, pk=pk) photos = Photo.objects.filter(gallery=gallery) return render(request, 'gallery/manage.html', {"gallery":gallery, "photos": photos}) # Add photos to gallery def add_photos(request, pk): if request.method == 'POST': … -
Trying to trace a circular import error in Django Python
I understand circular import error has been asked about a lot but after going through these questions I haven't been able to solve my issue. When I try to run my server in Django, it is giving me this error message: django.core.exceptions.ImproperlyConfigured: The included URLconf 'starsocial.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. The issue started when I added a new app which has a urls.py like the following: from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ url(r'login/$', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'), url(r'logout/$',auth_views.LogoutView.as_view(), name='logout'), url(r'signup/$',views.SignUp.as_view(), name='signup'), ] My project urls.py has a line which points to the app and looks like the following code: from django.contrib import admin from django.urls import path,include from django.conf.urls import url from . import views urlpatterns = [ url(r'^admin/',admin.site.urls), url(r'^$', views.HomePage.as_view(), name='home'), url(r'^accounts/', include('accounts.urls', namespace='accounts')), url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^test/$', views.TestPage.as_view(), name='test'), url(r'^thanks/$', views.ThanksPage.as_view(), name='thanks') ] My application's view looks like the following: from django.shortcuts import render from django.urls import reverse from django.views.generic import CreateView from . import forms # Create your views here. class SignUp(CreateView): form_class … -
Building Comment Model Django
enter code here class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') NameError: name 'Post' is not defined After this code make migrations also Giving this Error post is not defined.A lot of people work with this code in different sites.why its not working every time showing Post is not defined.what can i do.Please help. -
How to ensure for the delete check box to appear on Django inline formset
I am using Django inlineformset in a scenario where there are dependent (child) objects (purchase order and its item lines). For generating additional formsets at runtime I am using the utility from here. During change/update, I need an option where I can delete one or multiple line items from among the formset lines. The best way to do this (I have found so) is to have a manual over ride (in child form definition) where the auto_id is set to "False", and I have a "Delete" check box appear against each line item which I can mark "true" and on save, the marked lines are deleted. If the auto_id is set to "True", I find that the check box does not appear. (Actually, I can see that the check box appears momentarily but then disappears). I have tried to use the "Remove" option which appears on the item lines but find that even after save, the items are not physically removed from database. I am also marking "can_delete=True" in the formset definition. Where am I going wrong? How do I ensure that the "Delete" check box appears at all times. -
How to run a script using django rest framework integrated with react
I am trying to summon a script that sends an email when you press a button in react, my problem is that i haven't found any good way to do so. I currently have the function on a views file such as follows def sender(request): function and import it on the url file urlpatterns = [path('send/', views.sender) I am using axios on the react front with the following code axios.get('http://127.0.0.1:8000/api/send/') and it gives me this error when I try to access run it AttributeError: 'function' object has no attribute 'encode' -
Did anyone has run Django website on NameCheap shared hosting? [closed]
I have run python apps on NameCheap shared hosting by Cpanel. is there any way that I can run Django or Flask on my hosting ?? it will be very helpful if anyone tells me the step by step guide. -
Convert comma to dot in Python or MySQL
I have a Python script which collects data and sends it to my MySQL table. I noticed that the "Cost" sometimes is 0,95 which results in 0 in my table since my table use "0.95" instead of "0,95". I assume the best solution is to convert the , to . in my Python script by using: variable.replace(",", ".") However, couldn't one solution be to change format in my MySQL table? So that I store numbers in this format: 1100 0,95 0,1 150000 My Django Model cost = models.DecimalField(max_digits=10, decimal_places=4, default=None) Any feedback on how to best solve this issue? Thanks -
django link to another page does render new page
What I am trying to do: I want to click a link on my page and then be redirected to another of my pages. HTML: `<a class="btn btn-primary" href="{% url 'new_user' %}">New user</a>` urls.py in main app: urlpatterns = [ path("", include("orders.urls")), path("new_user/", include("users.urls")), path("login/", include("users.urls")), path("admin/", admin.site.urls), ] urls.py in users: urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("new_user", views.new_user_view, name="new_user") ] views.py: def index(request): if not request.user.is_authenticated: return render(request, "users/login.html", {"message": None}) context = { "user": request.user } return render(request, "users/user.html", context) def login_view(request): username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "users/login.html", {"message": "Invalid credentials."}) def new_user_view(request): username = request.POST["username"] password = request.POST["password"] user = User.objects.create_user(username=username, password=password) if user is not None: user.save() login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "users/new_user.html", {"message": "Invalid credentials."}) Behavior: What happens is I go to localhost:8000/login press the link for a new user, my browser redirects me to localhost:8000/new_user but is still rendering login.html and not new_user.html What am I missing? -
Django.admin - How to make a Modelfield disable if other field is == False
I am developing a website in which I need to automate the creation of new pages through Django admin platform. So the ideia is to create a new tab on the main menu of the site if a display parameters is set to True. However I wanna give the user the option to create a dropdown menu like this one, Dropdown menu. So my ideia is to have a checkbox Dropdown Menu, that whenever the user sets it True, a list of all the available pages to "nest" under de dropdown menu wil be automatically enabled below it. I'm attaching the admin page as it is today,Admin fields.. models.py of app creat_pages class CreatePage(models.Model): name = models.CharField("Nome", max_length=100) slug = models.SlugField("Atalho") tittle = models.CharField("Título", max_length=100) description = models.TextField("Descrição", blank=True) body = models.TextField("Corpo", blank=True) display = models.BooleanField("Mostrar no Site", default=False) dropdown_menu = models.BooleanField("Dropdown Menu", default=False) dropdown_options = models.ForeignKey("self", null=True, related_name='dropdown', on_delete=models.CASCADE) created_at = models.DateTimeField("Criado em", auto_now_add=True) updated_at = models.DateTimeField("Última alteração", auto_now=True) objects = models.Manager() def __str__(self): return self.name def get_absolute_url(self): from django.urls import reverse return reverse("create_pages:detail", kwargs={"slug": self.slug}) class Meta: verbose_name = "Criar Página" verbose_name_plural = "Criar Paginas" ordering = ["-name"] Admin.py: class CreatePageAdmin(admin.ModelAdmin): list_display = ["name", "slug", "tittle", "display", "created_at"] … -
Unable to import error in Django, any fix?
Hello, I am trying to create Django app to upload images but I am getting these errors showed in the image, also I am getting error of "no module named 'web1' " in terminal, please can someone help me, beginner here -
How can I get the ID from one model and pass it to another one? Django
I have a two models like so : class Entity(models.Model): contact = models.ForeignKey(User, default=None, on_delete=models.CASCADE) company_name = models.CharField(max_length=40, blank=False, null=True) vat_registration = models.CharField(max_length=12, blank=False, null=True) street_number = models.CharField(max_length=10, blank=False, null=True) street_name = models.CharField(max_length=100, blank=False, null=True) post_code = models.CharField(max_length=10, blank=False, null=True) city = models.CharField(max_length=40, blank=False, null=True) country = models.CharField(max_length=60, blank=False, null=True) email = models.EmailField(max_length=240, blank=False, null=True) class Invoices(models.Model): invoice_number = models.CharField(max_length=12, blank=False, null=True) invoice_date = models.DateField() invoice_code = models.CharField(max_length=10, blank=False, null=True) client_ref = models.CharField(max_length=10, blank=False, null=True) supplier = models.ForeignKey(Suppliers, default=None, on_delete=models.CASCADE) net_amount = models.FloatField() vat_paid = models.FloatField() vat_reclaimed = models.FloatField() invoice_type = models.CharField(max_length=10, blank=False, null=True) entity_name = models.ForeignKey(Entity, blank=True, null=True, default=None, on_delete=models.CASCADE) I have a page where I input some data from invoices and I would like to link the invoice which is entered to the company to which it belongs to. Below is my (not working views.py): def claim_details(request): #save the invoice onto DB form = forms.SaveInvoice(request.POST) if request.method == 'POST': if form.is_valid(): instance = form.save(commit=False) inv = Entity.objects.values_list('id', flat=True) instance.entity_name = inv[0] print(instance) instance.save() return redirect('accounts:claim') else: form = forms.SaveInvoice() args = {'form': form} return render(request, 'dashboard/claim_details.html', args) I am trying to include the id from the Entity to the Invoice which is saved. Any idea ? I am … -
how to save and retrieve data from a django array field
so am new to django. i have this model model.py from django.contrib.postgres.fields import ArrayField class Pv(models.Model): staff_id = ArrayField(models.CharField(max_length = 500,blank=True)) name = ArrayField(models.CharField(max_length = 500,blank=True)) rank = ArrayField(models.CharField(max_length = 500,blank=True)) def __str__(self): return self.name here is an html and jquery example of what i want to accomplish. <div class="card"> <div class="card-header"> <h4 class="m-0 d-flex justify-content-center">Beneficiaries</h4> </div> <div class="card-body"> <div class="float-right"> <button class="btn btn-sm mt-3 btn-success">Save</button> </div> <div > <div class="addbtn "> <button class="btn btn-success btn-sm add-more mt-3" type="button" onclick="add_fields();">Add Beneficiaries </button> </div> </div> </div> </div> $(document).ready(function(){ var add = 0; $("body").on("click",".add-more", function(){ add++; $(".addbtn").append( '<div class="control"><br>'+ '<div class="row" id="remve">'+ '<div class="col-4">' + ' <div class="row">'+ '<label for="" class="col pr-0 col-form-label-sm">Staff ID</label>'+ ' </div> ' + '<div class="col pl-0">'+ '<input type="text" class="form-control form-control-sm" name="staff_id">'+ '</div>'+ '</div>'+ '<div class="col-4">' + '<div class="row">' + '<label for="" class="col pr-0 col-form-label-sm">Name</label>'+ '</div>'+ '<div class="col pl-0">'+ '<input type="text" class="form-control form-control-sm" name="name">'+ '</div>'+ ' </div>'+ ' <div class="col-3"> '+ ' <div class="row">'+ ' <label for="" class="col pr-0 col-form-label-sm">Rank</label>'+ '</div> '+ '<div class="col pl-0">'+ ' <input type="text" class="form-control form-control-sm" name="rank">'+ ' </div>'+ ' </div>' + '<div >'+ ' <button style="margin-top:39px;" class="btn btn-danger btn-sm remove" type="button" onclick="add_fields();">remove</button>'+ '</div>'+ '</div>'+ '</div>'); }); $("body").on("click",".remove",function(){ $(this).parents("#remve").remove(); }); }); </script> anytime the … -
How to connect mysql in django
Here is my connection details DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django4webo1', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', } } when i start server error will come and i also need migrations table in db super(Connection, self).__init__(*args, **kwargs2) django.db.utils.OperationalError: (1049, "Unknown database 'django4webo1'") -
Django - link one model fields to another model's fields
I'm using the below definition for two models of my app: class Model1(models.Model): Code = models.AutoField(primary_key=True) fCityCode = models.CharField( verbose_name='City', max_length=100) fCountyCode = models.CharField( verbose_name='County', max_length=100) fCountryCode = models.CharField( verbose_name='Country', max_length=100, default='RO') CityPicture = models.ImageField(upload_to='cities') def __str__(self): return self.fCityCode class Model2(models.Model): Code = models.AutoField(primary_key=True, editable=False) fUser = models.ForeignKey( User, on_delete=models.PROTECT, verbose_name='Belongs to') MainDescription = models.CharField( verbose_name='Description/title', max_length=100) fCityCode = models.OneToOneField( AreaMap, on_delete=models.PROTECT, verbose_name='City') fCountyCode = models.OneToOneField( AreaMap, on_delete=models.PROTECT, related_name='fcountycode') def __str__(self): return self.MainDescription According to my model definition (which is wrong), both fields from my second model inherits the same values that comes from fCityCode belonging to the first model. What I want is that in my second model, for fields fCityCode and fCountyCode to be able to select only the values that are being held in the first model, in the same columns - fCityCode and fCountyCode. How can I achieve something like this? Thanks -
i got this error while fetching data from the models.py
def publicationlist(request): context = {'publication_list' : AddPublication.objects.all()} return render(request,"publication_list.html", context) Class 'AddPublication' has no 'objects' member