Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image url not found in html
I have some images stored in my django db. And i am trying to display all of them on my web. Python file def index(request): if request.method == "GET": result = Video.objects.all() return render(request, "videos/index.html", { "data": result }) HTML file {% for x in data %} <div class="content"> <img src="{{ x.image }}"> <h3>{{ x.title }}</h3> <h3>{{ x.user }}</h3> <video class="embed-responsive embed-responsive-16by9" controls="controls" > <source src="{{ x.video.url }}" type="video/mp4" /> </video> </div> <br /> {% endfor %} Surprisingly, the video is loading, but the image isn't. When I opened the source code on the browser <img src(unknown)> this is what I see. -
How to fix ModuleNotFoundError when I try to run Django framework?
I want to start Django framework learning but whenever I run python manage.py runserver ===> ModuleNotFoundError: No module named 'C:\Users\LENOVO' PS C:\Users\LENOVO\Dev\cfeproj> I dont know what to configure from here, my C drive became a module? Dont know how that happened ={ really frustrating ,i keep failing. Can anyone help me to resolve this issue? -
Consolidate Django migrations into a package
In my django project I have my migrations being created and applied from each app inside migrations folder, however I need all those migrations to be consolidated and migrated from a saperate package outside my app. -
Best way to integrate a Django project into existing program, using same backend logic?
I am very new to Django so I apologize in advance if there are any misconceptions about the framework within this question. I have developed a log analysis program that currently uses the command-line as the user interface using the cmd2 library. I am attaching an image of the project structure with the different Python files. The program is started from log_analyze.py. The commands are parsed in user_interface.py. Other classes like sddc_log.py, get_logs.py, etc. contain logic that is used in the commands for parsing through logs. We currently run this program from VM that our teammates have access to. We are thinking of also creating a web UI for this program so that team members can connect to the VM from the browser to perform log analysis. My question is what would be the best way to organize a Django project that can leverage the existing logic we have in these other Python files and use that information to populate the web UI. Specifically, what would be the proper file structure? Are there any other aspects that I should pay specific attention to? Would this even be a good use case of Django? Thanks for your help in advance. project … -
How do you use Django Login function properly
What I understand so far is that when you're using regular Django you import and use AuthenticationForm and you put the request.POST there and it will retrieve the user you're looking for. But in this case I'm using DRF and some third party authentication system that retrieve the user for me. so in order to test the login function I made this dummy code to test it: @api_view(["GET"]) def login_view(request): if request.method == "GET": #actuall users that exist user = { "id": 1, "email": "test@gmail.com", "name": "melly", "date_joined": "2021-07-09T11:33:44.440889Z" } login(request, user) return Response('test') and it gave me this error Can someone explain to me about this error and why is this happening, thank you! -
Page title with class based function in django
I want to create page titles+subtitles which I wish to control and occasionally modify from the Admin space and pass them to the templates with class based model. Yet, after I enter the inputs in the admin space, the variable I specify in the template provides not value. That is the fields are empty. What do I do wrong? Any advise as to the logic I should use to pass the template? models.py: class Page(models.Model): page_title = models.CharField(max_length=250) page_subtitle = models.TextField() def __str__(self): return self.self template: <h3 class="title mb-0">{{page.page_title}}</h3> <h6 class="title mb-0">{{page.page_title}}</h6> Views: I tried with different views, none of them functioned. TemplateView: class Page(TemplateView): template_name = 'painting_list.html' # the template where I want to display the title def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['page'] = self.Page return context #I also tried it with:# context['page'] = Page.objects.get(id=1) return context DetailView: class Page(generic.DetailView): model = Page context_object_name = 'page' template_name = 'painting_list.html' -
Need help to setup support chat in django-react app using twilio
I need to know should I setup everything in my backend (django) for chat, and call it in my frontend (react)? And what is the best practice to add it in my site. First time, I'm trying and confuse cuz read alot of different blogs. -
vscode django cookiecutter development setup
i am using django cookiecutter with VS code. I am using docker with it. Now whenever i try to code i do not get any linting, snippets recommendation, library detection etc. Any suggestion/recommendation/guide for that problem will be a great help. Thankyou. -
Can't import restframework.generics in user model
In our codebase, if we put import rest_framework.generics with the rest of our imports at the top of the file for our user class (i.e. our subclass of BaseUserManager), we get an error that looks like this: File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 178, in get_model return self.models[model_name.lower()] KeyError: 'acmeuser' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/contrib/auth/__init__.py", line 157, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 211, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 180, in get_model raise LookupError( LookupError: App 'acme_api' doesn't have a 'AcmeUser' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/topher/colony/platform/acme-api/manage.py", line 46, in <module> main() File "/Users/topher/colony/platform/acme-api/manage.py", line 38, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python@3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen … -
Filter using parent model's field
class Genre(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Book(models.Model): genre= models.ForeignKey(Genre, related_name="book", on_delete=models.CASCADE) name = models.CharField(max_length=20) def __str__(self): return self.name I want to filter books with a specific genre as following: def get_books(genre="horror"): books = pd.DataFrame(list(Book.objects.filter(genre__name=genre).values())) print(books) But I get an empty dataframe printed. Is this filter syntax above correct? (That is a double underscores in the filter code) -
Why does my Django login work on development server but not production server?
I have an issue where I can login to Django via my development server but it will not work on the production server. I am using Heroku to deploy. All the pages work correctly but I can't login to my Django database. -
How to add model instances to a Foreign Key field in Django Rest Framework
I need to get the ItemModel instances from the item model and store them in the foreign key field in the OrderModel but I am not sure how. I've tried to iterate through the item order list and add one but it doesn't display correctly. Any help would be much appreciated. My goal is to display the data like this: { "payment_method": "test", "confirmation": "14087147WA285750M", "total_price": "15.00", "is_paid": "True", "order_created": "2021-07-09T19:51:18Z", "item_order": [ { "id": 2, "name": "Carrots", "image": "image link", "slug": "carrots", "price": "5.00", "itemID": "ct1", "quantity": 1 }, { "id": 8, "name": "Dog Food", "image": "image link", "slug": "dog-food", "price": "10.00", "itemID": "df4", "quantity": 1 } ] } View: @api_view(['POST']) def create_order(request): user = request.user order = request.data order_item = OrderModel.objects.create( user=user, payment_method=order['payment_method'], confirmation=order['confirmation'], total_price=order['total_price'], is_paid=order['is_paid'], order_created=order['order_created'], item_order= """ The item model instance """ ) ordered_items = OrderSerializer(order_item, many=True).data return Response(ordered_items) Order Model: class OrderModel(models.Model): user = models.ForeignKey(CustomerModel, on_delete=models.CASCADE) item_order = models.ForeignKey( ItemModel, on_delete=models.CASCADE) payment_method = models.CharField(max_length=50) confirmation = models.CharField(max_length=255) total_price = models.DecimalField( max_digits=5, decimal_places=2) is_paid = models.BooleanField(default=False) has_been_sent = models.BooleanField(default=False) order_created = models.DateTimeField() def __str__(self): return str(self.id) Order Serializer: class OrderSerializer(serializers.ModelSerializer): item_order = ItemSerializer(many=True) class Meta: model = OrderModel fields = ['payment_method', 'confirmation', 'total_price', 'is_paid', 'has_been_sent', 'order_created', … -
Crispy FormHelper object has no attribute 'attrs'
My views: class OrderCreate(CreateView): model = Order template_name = 'order_create.html' form_class = orderForm object = None def get(self, request, *args, **kwargs): """ Handles GET requests and instantiates blank versions of the form and its inline formsets. """ self.object = None form_class = self.get_form_class() form = self.get_form(form_class) orderDetailform = orderDetailForm() return self.render_to_response( self.get_context_data(form=form, orderDetailForm=orderDetailform, helper=orderDetailFormHelper() ) ) def post(self, request, *args, **kwargs): """ Handles POST requests, instantiating a form instance and its inline formsets with the passed POST variables and then checking them for validity. """ self.object = None form_class = self.get_form_class() form = self.get_form(form_class) orderDetailform = orderDetailForm(self.request.POST) if form.is_valid() and orderDetailform.is_valid(): return self.form_valid(form, orderDetailform) else: return self.form_invalid(form, orderDetailform) def form_valid(self, form, assignment_question_form): """ Called if all forms are valid. Creates Assignment instance along with the associated AssignmentQuestion instances then redirects to success url Args: form: Assignment Form assignment_question_form: Assignment Question Form Returns: an HttpResponse to success url """ self.object = form.save(commit=False) # pre-processing for Assignment instance here... self.object.created_by = self.request.user self.object.save() # saving AssignmentQuestion Instances orderDetailforms = orderDetailForm.save(commit=False) for aq in orderDetailforms: # change the AssignmentQuestion instance values here # aq.some_field = some_value aq.save() content = {"name": self.object.created_by, "id": self.object.pk} send_gmail_message(['philippe@gustafoods.com', 'doro@gustafoods.com'], content) return reverse_lazy("procurement:order_detail", kwargs={'pk': self.object.pk}) forms.py: class orderDetailFormHelper(FormHelper): … -
Save card id to model on form submission
I want to save the stripe payment method id to my order when it's created for recurring orders. When using a previously saved card, it works as intended saving a "card_idxxxxx" which references a stripe payment method. Currently if the new card is input, it saves as "add-new-card", which is wrong. I would like it to save the newly input card to the customer, and also to the payment method field. What I'm mostly unsure about is: Why my card isn't saving to the customer in stripe How can I pass the new card's id to my view? template <div class="form-check my-3 bg-gray-200 p-2 rounded-md"> <input class="form-check-input" type="radio" name="payment-methods" id="add-new-card" value="add-new-card" onclick="addCard()"> <label class="form-check-label" for="add-new-card"> Add new payment method </label> <div id="new-card" style="display: none;"> <label class="block uppercase text-gray-600 text-xs mb-2" for="cardholder-name"> Name on Card </label> <input id="cardholder-name" class="mb-2 border-0 px-3 py-3 placeholder-gray-300 text-gray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150" value="{{customer.name}}" detype="text"> <!-- placeholder for Elements --> <label class="block uppercase text-gray-600 text-xs mb-2" for="card-element"> Card Details </label> <div id="card-element" class="mb-2 border-0 px-3 py-3 placeholder-gray-300 text-gray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150"> <!-- A Stripe Element will be inserted here. --> </div> <div id="card-result"></div> … -
Modifying oscarapi to show some endpoints as public from admin endpoints
What I am trying to achieve is to customize the oscarapi to expose the partner api to be public api instead of just for admin I have followed the docs on how to customize the api and also did as suggested by Jamie Marshall in Extending django-oscarapi API ROOT to custom API class So far I am able to overwrite the root.py file but failing to get oscar see the new urls.py file. My work so far is as follows I created a api_customization/views/partner.py file I created a api_customization/views/root.py file I tried to extend the urls.py file by creating a api_customization/urls.py file However, I'm getting the following error Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/contextlib.py", line 74, in inner return func(*args, **kwds) File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/rest_framework/decorators.py", line 50, … -
Troubles with DeleteView in Django
recently I have been working on a board project for my courses. I wrote a DeleteView for a certain model. It worked for a while, and then it started giving me 404 error. Downbelow I will attach my code with the whole View and urls. PS: I know that I am not supposed to give all of that, but how knows, maybe you can help me with other mistakes)) Views.py class Post_list(LoginRequiredMixin, ListView): model = Post template_name = 'Post/list_of_posts.html' context_object_name = 'Posts' def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(Post_list, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context class Post_details(LoginRequiredMixin, DetailView): model = Post template_name = 'Post/post_details.html' context_object_name = 'Post' class Post_create(LoginRequiredMixin, CreateView): model = Post template_name = 'Post/post_create.html' form_class = PostForm class Post_update(LoginRequiredMixin, UpdateView): template_name = 'Post/post_update.html' form_class = EditForm context_object_name = 'Post' def get_object(self, **kwargs): # Here we are getting the id so Django could stalk the change ID = self.kwargs.get('pk') return Post.objects.get(pk=ID) class Post_delete(LoginRequiredMixin, DeleteView): template_name = 'Post/post_delete.html' queryset = Post.objects.all() context_object_name = 'Post' success_url = '/Posts' def CategoryView(request, cats): category_posts = Post.objects.filter(cat=1) return render(request, 'Post/categories.html', {'cats': cats, 'category_posts': category_posts}) class Add_comment(LoginRequiredMixin, CreateView): model = Comments template_name = 'Post/add_comment.html' form_class = CommentForm success_url = '/Posts' def … -
'ManyToManyDescriptor' object has no attribute 'filter in Django while trying add item to favorite
Can someone please help me? I'm getting this error while I'm trying to change the icon color when added to favorites. Is there any solution for this error? This is the view where I'm adding my post to Favorite: @login_required def favourite_post(request, id): post = get_object_or_404(Car, id=id) if post.favourite.filter(id=request.user.id).exists(): post.favourite.remove(request.user) else: post.favourite.add(request.user) return HttpResponseRedirect(post.get_absolute_url()) This is my Model class Car(models.Model): favourite = models.ManyToManyField(User, related_name='favourite', blank=True) And this where I want to send is_favourite bool which show is added to favorite or not def show_all_car_page(request): filtered_cars = CarFilter( request.GET, queryset=Car.objects.all() ) paginator = Paginator(filtered_cars.qs, 3) page = request.GET.get('page', 1) posts = paginator.get_page(page) is_favourite = bool if filtered_cars.Meta.model.favourite.filter(id=request.user.id).exists(): is_favourite = True context = { 'filtered_cars': filtered_cars, 'posts': posts, 'is_favourite': is_favourite } return render(request, 'index.html', context=context) And here CarFilter is my filter.py where i can filter my posts, class CarFilter(django_filters.FilterSet): class Meta: model = Car fields = ['brand', 'city', 'body_type', 'model', 'year', 'transmission'] And also in my template I'm doing like this : {% if request.user.is_authenticated %} <a href="{% url 'car:favourite_post' id=car.id %}" title="Seçilənlərə Əlavə et"> {% if is_favourite %} <i class="fas fa-heart" style="color: red"></i> {% else %} <i class="far fa-heart"></i> {% endif %} </a> {% else %} <a href="{% url 'user:login' %}" … -
Djanog, IntegrityError, NOT NULL constraint failed: ask_response.postinfo_id
I am new to Django and I have been following some YouTube tutorials to understand it's concepts. The website that I am creating is a blog/forum. Now I came to the part where I have to implement the comments for the user's posts, I created the model for the responses, and bonded it with the actual post. Everything works just fine when I add a response/comment for a specific post from the admin page, but when I try to add a new response/comment from the template form it gives me an error like this: IntegrityError at /question-1 NOT NULL constraint failed: ask_response.postinfo_id I assume it must be something about the form that doesn't want to work, but I cannot understand what. Here is the models.py: class PostInfo(models.Model): title = models.CharField(max_length=70) content = models.TextField(max_length=5000) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) likes = models.ManyToManyField(User, related_name="blog_posts") views = models.IntegerField(default=0) class Response(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) postinfo = models.ForeignKey(PostInfo, on_delete=models.CASCADE, related_name="responses") body = models.TextField() date_published = models.DateTimeField(default=timezone.now) Views.py: def detailed_view(request, pk): post = get_object_or_404(PostInfo.objects.filter(id=pk)) comments = post.responses.all() new_comment = None if request.method == 'POST': comment_form = ResponseForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() else: comment_form = ResponseForm() return render(request, … -
showing an attribute of a foreign key in admin for prepopulated_fields
Sorry for bad description of my issue in title ... I tried to find solution here with some answers but none helps me :( Here is my admin.py (a piece of) @admin.register(Espece) class EspeceAdmin(admin.ModelAdmin): list_display = ['nom', 'slug'] prepopulated_fields = {'slug': ('nom',)} [...] @admin.register(Produit) class ProduitAdmin(admin.ModelAdmin): list_display = ['nom', 'slug', 'prix', 'stock', 'stock_bis', 'available', 'espece', 'variete', 'portegreffe'] list_filter = ['available', 'prix', 'espece', 'portegreffe'] list_editable = ['prix', 'stock', 'available', 'stock_bis'] prepopulated_fields = {'nom': ('espece', 'variete', 'portegreffe', 'spec'), 'slug': ('nom',),} list_per_page = 200 search_fields = ('nom',) [https://ibb.co/TYCmk5Q][1] [1]: https://i.stack.imgur.com/SgfnN.png Thanks to link above, you'll see the issue on admin ... and my need When I choose a value in Select , I don't want to have the Id for espece into 'nom', but the value of espece... I don't know how to do this... And for my best exp, if it's possible ... after having good value, I need to prepopulated slug like nom but in slug format ;) Thanks for your help -
django multiple database migrations:how to prevent to create django default tables in each database
i have multiple databases and each app bind to one database through router class class DatabaseRouter: """ A router to control all database operations on models in the auth and contenttypes applications. """ lawyer_app_labels = {'lawyer'} court_app_labels = {'court'} type_app_labels = {'type'} def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.lawyer_app_labels: return 'lawyer_db' if model._meta.app_label in self.court_app_labels: return 'court_db' if model._meta.app_label in self.type_app_labels: return 'type_db' return None def db_for_write(self, model, **hints): """ Attempts to write auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.lawyer_app_labels: return 'lawyer_db' if model._meta.app_label in self.court_app_labels: return 'court_db' if model._meta.app_label in self.type_app_labels: return 'type_db' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth or contenttypes apps is involved. """ if ( obj1._meta.app_label in self.lawyer_app_labels or obj2._meta.app_label in self.lawyer_app_labels ): return True if ( obj1._meta.app_label in self.court_app_labels or obj2._meta.app_label in self.court_app_labels ): return True if ( obj1._meta.app_label in self.type_app_labels or obj2._meta.app_label in self.type_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the auth and contenttypes apps only appear in the 'auth_db' database. """ if app_label in self.lawyer_app_labels: return db == … -
when you enter an input field, throws an error although the whole model is correct. Python django
the form does not pass validation and throws an error, although the correct data is entered, what is the problem? I enter in the input field +79211234569 and gives an error in html Select the correct option. Your option is not among the valid values. form data: <'form': <RelatedAddForm bound=True, valid=False, fields=(name;phone)> forms class ListTextWidget(forms.Select): template_name = 'include/_forms_clients_datalist.html' def format_value(self, value): # Copied from forms.Input - makes sure value is rendered properly if value == '' or value is None: print('ListTextWidget None') return '' if self.is_localized: print('ListTextWidget local') return formats.localize_input(value) return str(value) class ChoiceTxtField(forms.ModelChoiceField): widget=ListTextWidget() class RelatedAddForm(forms.ModelForm): phone = ChoiceTxtField(queryset=Clients.objects.order_by('-phone')) class Meta: model = Clients fields = ['name', 'phone'] widgets = { 'name': forms.TextInput(attrs={'class': 'form-control', 'autocomplete': 'off'}), } models class Clients(models.Model): name = models.CharField(max_length=150, blank=True, verbose_name='Имя') phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = models.CharField(validators=[phone_regex], unique=True, max_length=17, verbose_name='Телефон') def get_absolute_url(self): return reverse('view_clients', kwargs={'pk': self.pk}) def __str__(self): return self.phone -
Integrate Google Search Console API with Django Project
I am looking to integrate Google Search Console API with a Django project to fetche a list of sites verified in the site Search Console account and list any sitemap files submitted. I found this resource, but I am not sure how to use in the Django framework. Where should I place these functions and imports? https://developers.google.com/webmaster-tools/search-console-api-original/v3/quickstart/quickstart-python -
Nginx return 404 with vue router in second level path when press F5
Here the nginx config. server { listen 80; server_name server_ip; location = /favicon.ico { access_log off; log_not_found off; } error_page 404 /index.html; location /static/ { root /home/demo; } root /var/www/html/edu_vue/dist; index index.html; location / { try_files $uri $uri/ /index.html; } location ^~ /api/ { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /admin { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } When i visis http://example.com/path and press F5 to reload everything is ok. But if path will be http://example.com/path/some_nested_path i'll get 404 from ngingx. Using Django Drf + Vue js + Vue Router in history mode true -
How to implement the add/edit links on a field in the admin change page that does not have an expressed FK relationship in the model?
I have a Django 3.x web site. There are 3 models, among others, Document, MetaData, MetaDataValue. The MetaDataValue model has a foreign key relationship to the MetaData model. In a simple world, there would be a foreign key relationship from MetaData to Document. Then the DocumentAdmin would display the MetaData field as a dropdown, filled with the appropriate MetaDataValues. There would also be edit/add (pencil/plus) links next to the dropdown to allow the user to edit/add the MetaDataValue for that MetaData object. However, one of the requirements for the project was not to define which, or how many, MetaData objects would be associated with a particular Document type until run time. Those associations are through another set of models. Therefore, the Document admin change page adds the different MetaData fields to the change admin page at run time, by looking into the database for which MetaData fields are associated with this type of Document, and then adding them to the fieldset through the get_fieldsets method. The implication of this design is that one cannot edit/add values to a particular MetaData field on the Document admin change page, because, I assume, Django lost the underlying foreign key relationship between the Document … -
Django many 2 many through rest framework
I am working on a small project but i cant get the serializers to work I have tried these and i am not sure what i am doing wrong. My model is a many to many through #serializers.py class CompanyVisitedSerializer(serializers.HyperlinkedModelSerializer): company_id = serializers.ReadOnlyField(source="company.id") company_address = serializers.ReadOnlyField(source="company.business_address") company_name = serializers.ReadOnlyField(source="company.business_name") company_address = serializers.ReadOnlyField(source="company.business_address") checked_in = serializers.ReadOnlyField(source="user.checked_in") checked_out = serializers.ReadOnlyField(source="user.checked_out") class Meta: model = CompanyUser fields = ( "checked_in", "checked_out", "company_name", "company_address", "company_id", ) class VisitorSerializer(serializers.ModelSerializer): # visited = CompanySerializer(many=True) visited = CompanyVisitedSerializer( many=True, ) ``` but i get this back empty {}: { "address": "192 millie road", "city": "singapore", "phone": "2066980", ... "visited": [ {}, //i want to populate this with { company: name_of_company, checkin, checkout} {} ] } I have read through these: https://bitbucket.org/snippets/adautoserpa/MeLa/django-rest-framework-manytomany-through Django: Serialize a model with a many-to-many relationship with a through argument