Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using multiple Mixins as inherited, order of methods execution problem
I have the following structure in Django: class EmailView(View, ABC): def post(self, request): pass def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) ......... class Base(AccessMixin, EmailView, ABC): ..... class ADTView(ABC): def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) ....... class BaseMixin(Base, SubscribeNewsletterView, ADTView, ABC): def get_context_data(self, *args, **kwargs): .............. class ItemListView(BaseMixin, ListView): ............... If EmailView is inherited by Base(as in example) the method get_context_data from ADTView is not called. If EmailView is not inherited by Base : class Base(AccessMixin, ABC) the method get_context_data from ADTView is called. What is in the method it, doesn't matter (even if I get context , not modifying and returning it) the same thing happen. What I want is the execution of the method order: AccessMixin, EmailView, ADTView, ListView I suppose is happen because ListView inherits from View, but in EmailView I used View, because I need as_view. Basically I'm calling the EmailView with an url, using Ajax. -
Setting queryset within forms.ModelChoiceField()
The queryset for the 'jurisdiction' field is set below in the initialization. The queryset is dependent on the id that is passed in, which comes from a specific link that a user clicks. As a result, I can't define a singular queryset within the forms.ModelChoiceField(), but it seems that django requires me to do this. class TaxForm (forms.ModelForm): #Will be used for state tax and other taxes jurisdiction = forms.ModelChoiceField(queryset=?????) class Meta: model = Tax exclude = ('user', 'taxtype',) def __init__(self, *args, **kwargs): self.taxtype = kwargs.pop('taxtype',None) super(TaxForm, self).__init__(*args, **kwargs) if int(self.taxtype) == 1: self.fields['jurisdiction'].choices = [(t.id, t) for t in State.objects.all()] elif int(self.taxtype) == 2: self.fields['jurisdiction'].choices = [(t.id, t) for t in Country.objects.all()] else: self.fields['jurisdiction'].choices = [(t.id, t) for t in State.objects.none()] How can I indicate that I want the jurisdiction field to be a dropdown, but not specify one queryset within the forms.ModelChoiceField()? Alternatively, how can I make the queryset that is referenced in forms.ModelChoiceField() refer to the queryset that I initialize based on the taxtype? Thanks! -
Mutation for a model that contains some foreignkey fields
I have a Podcast model : class Podcast(models.Model): title = models.CharField(max_length=255,) user = models.ForeignKey(User, related_name="podcasts", on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) channel = models.ForeignKey(Channel, related_name="podcasts", null=True, blank=True, on_delete=models.CASCADE) message = models.TextField() Here is the Channel model: class Channel(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) description = models.TextField(blank=True, default='') and I used get_user_model for User model Then I want to create mutation for Podcast model. How can do it? I know if there isn't foreingkey in model it will done by : class CreatePodcast(graphene.Mutation): class Input: title = graphene.String(required=True,) message = graphene.String(required=True,) Output = PodcastType @staticmethod def mutate(root, info, **kwargs): podcast = PodcastModel(**kwargs) podcast.save() return podcast How can I import channel field when creating a podcast by mutation? -
How do I turn my Python/Django web app into a native Android app that connects to the same database?
How do I turn my Python/Django web app into a native Android app / iOS app that connects to the same database? I have read a few answers but would prefer a more authoritative and robust view on this. What is the most used pathway in the development of Android apps and Django web app? For example, take Instagram. Is it built on server-side language like python first before they are connected to Android with some REST? Another example is an AI enabled image recognition Android app. If the AI is built with Python and Tensorflow, how would an experienced developer offer the service in Android app store / Apple iOS? One last example is Coursera app. I understand that Coursera is built with Kotlin for it's Android app. But how does Coursera built and connect Kotlin for Android to it's web app? I have programmed in Python with Django, Html, CSS, Javascript, C++. Currently, I am learning Java on Android Studio with the view of building an app. But I would prefer to be able to build mainly on Django with Python. However I am worried that not building Android natively might not be a robust solution. I have … -
How to add TokenAuthentication authentication classes to Django FBV
I know how to create token authentication in CBV of Django Rest Framework. See a random example below class EmbroApiView(viewsets.ModelViewSet): """Handles Creating, reading and updating Patients""" serializer_class = serializers.EmbryoSerializer queryset = Embryo.objects.all() authentication_classes = (TokenAuthentication,) filter_backends = (filters.SearchFilter,) permission_classes = (IsAuthenticated,) search_fields = ("code_name", "karyotype", "sex", "down_syndrome",) I want to create a token authentication for my FBV. Is that possible. Below are my views. My whole project is on Django rest Framework. Only the below function renders in a regular django template template. I want to add token authentication to the below function @login_required #I tried this decorator but this does not work. def generate_pdf(request, pk): patient = Patient.objects.get(pk=pk) embryos = Embryo.objects.filter(patient=patient) template = get_template("patients/genome_pdf.html") context = { "patient": patient, "embryos": embryos } pdf = render_to_pdf("patients/genome_pdf.html", context) if pdf: return HttpResponse(pdf, content_type="application/pdf") return HttpResponse("Not found") -
Django. AttributeError when running migrations on test database before tests in docker
Long story short, I am trying to run tests inside docker container like: ./manage.py test but getting error: /app/gauss # ./manage.py test nosetests --where=tests/ --verbosity=2 --with-coverage --cover-package=gauss.catalogues --cover-package=gauss.requests --cover-package=gauss.core --cover-xml --cover-xml-file=gauss_coverage.xml --with-xunit --xunit-file=gauss_xunit.xml Creating test database for alias 'default'... /usr/local/lib/python3.6/site-packages/django/db/backends/postgresql/base.py:259: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the default database instead. RuntimeWarning Got an error creating the test database: database "test_gauss" already exists Type 'yes' if you would like to try deleting the test database 'test_gauss', or 'no' to cancel: yes Destroying old test database for alias 'default'... Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) ... File "/app/gauss/gauss/catalogues/migrations/0001_initial.py", line 13, in <module> class Migration(migrations.Migration): File "/app/gauss/gauss/catalogues/migrations/0001_initial.py", line 57, in Migration ('web_url', models.CharField(blank=True, max_length=100, validators=[gauss.catalogues.validators.validate_url], verbose_name='web_url')), AttributeError: module 'gauss' has no attribute 'catalogues' 'gauss' is my django-project name and 'catalogoues' is app inside it. Error do not appers when I am running same command on my local computer. All project structure: Project settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', … -
Django Pagination error at object of type 'HttpResponse' has no len()
I am developing ontop of my views the ability to have Django paginate my product list. Without pagination my code worked absolutely fine . This is the code I had before pagination class JobListIndex2(TagMixin, ListView): template_name = 'jobs/job_list.html' model = Job paginate_by = 10 context_object_name = 'job' def get_queryset(self, *args, **kwargs): request = self.request return Job.objects.all() I have then decided to integrate pagination and updated my code to this class JobListIndex2(TagMixin, ListView): template_name = 'jobs/job_list.html' model = Job paginate_by = 10 context_object_name = 'job' # def get_queryset(self, *args, **kwargs): # request = self.request # return Job.objects.all() def get_queryset(self, *args, **kwargs): request = self.request queryset_list = Job.objects.all().order_by("-time_starting") paginator = Paginator(queryset_list, 10) # Show 10 jobs per page page = request.GET.get('page') queryset = paginator.get_page(page) context = { 'job': queryset, 'title': 'Jobs' } return render(request, 'jobs/job_list.html', context) The resulting error relates to object of type 'HttpResponse' has no len() which I am not sure where that has come from. My traceback Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.1-py3.7.egg\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.1-py3.7.egg\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.1-py3.7.egg\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.1-py3.7.egg\django\views\generic\base.py", line 68, in view return … -
"django.db.utils.IntegrityError: " NOT NULL constraint failed: adoptions_pet.submission_data
I am trying to fill my adoption website with a testing data from a CSV file django.db.utils.IntegrityError: NOT NULL constraint failed: adoptions_pet.submission_data i run python manage.py makemigrations Then i run python manage.py migrate After that i wrote a command to run the a scripting file called load_pet_data.py the will insert the testing data to the file the command was python manage.py load_pet_data After some search i tried to delete the "db.sqlit3" and re-migrate but i still getting the same error - This is the load_pet_data.py script file from csv import DictReader from datetime import datetime from django.core.management import BaseCommand from adoptions.models import Pet, Vaccine from pytz import UTC DATETIME_FORMAT = '%m/%d/%Y %H:%M' VACCINES_NAMES = [ 'Canine Parvo', 'Canine Distemper', 'Canine Rabies', 'Canine Leptospira', 'Feline Herpes Virus 1', 'Feline Rabies', 'Feline Leukemia' ] ALREADY_LOADED_ERROR_MESSAGE = """ If you need to reload the pet data from the CSV file, first delete the db.sqlite3 file to destroy the database. Then, run `python manage.py migrate` for a new empty database with tables""" class Command(BaseCommand): # Show this when the user types help help = "Loads data from pet_data.csv into our Pet model" def handle(self, *args, **options): if Vaccine.objects.exists() or Pet.objects.exists(): print('Pet data already loaded...exiting.') … -
Django Rest Framework List field
I use Django rest framework, I have some question for my nested serializers my Serializers class SerUserSubCreateView(serializers.Serializer): email = serializers.EmailField() is_active = serializers.BooleanField() class SerUserCreateView(serializers.Serializer): user = SerUserSubCreateView() clients_id = serializers.CharField(max_length=50) my views.py class CreateUserView(CreateAPIView): serializer_class = serializers.SerUserCreateView permission_classes = [IsAuthenticated] queryset = UserClients.objects.all() def post(self,request,format=None): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): ................. my context { "user": { "email": "", "status": false }, "clients_id": "" } but I want { "user":[ { "email": "", "status": false }, ], "clients_id": "" } There have any method? or anything? -
Django admin add extra fields in list
In my project i have a table with a foreign key to another one. In django admin i would to display fields from the two tables. This is my original model: class t_time(models.Model): history_main = models.IntegerField(default=0) elapsed_t = models.DecimalField(max_digits=20, decimal_places=6, default=Decimal('0.0000')) in admin.py i try to make a query fro extract and add to my view extra fields from the tables but probably i was wrong in some point. I try to override get_queryset like this: class t_timeAdmin(admin.ModelAdmin): list_display = ('id','hist_data','elapsed_t') def get_queryset(self, request): queryset = super().get_queryset(request) myqs = t_history.objects.get(id=t_time.history_main) queryset = queryset.annotate( _hist_data=myqs.test_type, #_villain_count=Count("villain", distinct=True), ) return queryset def hist_data(self, obj): return obj._hist_data but i get an error about a returned type (int) that probably is related to annotate() directive. How can i add extra field from a query to my django admin view? So many thanks in advance -
django channels on heroku hosting
Since I cant use redis I used the other channel layer that is InMemoryChannelLayer WSGI_APPLICATION = 'django_analytics.wsgi.application' ASGI_APPLICATION = "django_analytics.routings.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer", "CONFIG": { }, }, } I deployed it, on heroku but I am getting error (index):9 WebSocket connection to 'wss://mkmnim.herokuapp.com/ws/chat/page/' failed: Error during WebSocket handshake: Unexpected response code: 404 I got it working at my local server but I am not able to do the same in hosting it online,Also will I have to do something related to daphne ? Initially I used redis and ran redis server locally but while hosting redis setup was paid so I choose InMemoryChannelLayer (channels without channel layer or any other free hosting) so what should I do ? -
Django queryset filtering
I have 2 main entities in my models.py: class IPGroup(models.Model): name = models.CharField(max_length=50, unique=True) address = models.CharField(max_length=50, unique=True) class Tag(models.Model): name = models.CharField(max_length=100) value = models.CharField(max_length=100) These two tables are linked through a 3rd through table as follows: class IPGroupToTag(models.Model): ip_group = models.ForeignKey(IPGroup) tag = models.ForeignKey(Tag) My requirement is to find all the tags with the name "SecurityZone" when the only input I have is the name of the IPGroup. My attempt is as follows: ip_group_id = IPGroup.objects.get(name="test_ip_group").id zone = IPGroupToTag.objects.filter(ip_group_id=ip_group_id).values('tag__name') which gives me the following Queryset: <QuerySet [{'tag__name': 'Title'}, {'tag__name': 'Site'}, {'tag__name': 'SecurityZone'}, {'tag__name': 'DataCenter'}, {'tag__name': 'Pod'}]> How do I then find the id of the tag with the name SecurityZone and then find its value -
Django custom ModelForm metaclass, "object has no attribute '_meta'"
I am trying to create a custom Django ModelForm metaclass which will allow some extra customisation of Form fields inherited from the source Model, such as: Limit choices to a subset of all available for a particular Model field Define read only and required form fields Set initial values for fields I'm doing this because I need a few different ModelForms for a single Model, each with variations of the above options. Here's my metaclass: class CustomModelFormMetaclass(models.ModelFormMetaclass): """ Custom ModelForm metaclass which adds extra configuration of fields inherited from Model """ def __new__(mcs, name, bases, attrs): new_class = super(models.ModelFormMetaclass, mcs).__new__(mcs, name, bases, attrs) # Set initial field values #initials = attrs.get('initial_values') for field_name, initial_value in new_class.initial_values.items(): field = new_class.base_fields.get(field_name, None) if field and field.initial is None: field.initial = initial_value # Set refined choices #refined_choices = attrs.get('refined_choices') for field_name, refined_choices in new_class.refined_choices.items(): set_field_choices(new_class, field_name,refined_choices) # Set disabled fields for field_name in new_class.read_only_fields: field = new_class.base_fields.get(field_name, None) if field: #field.disabled=True field.widget.attrs['readonly'] = True # Set required fields for field_name in new_class.required_fields: field = new_class.base_fields.get(field_name, None) if field: field.required=True # Set DateTime and Date help texts for field in new_class.base_fields.values(): if field.help_text is None: if type(field).__name__ == 'DateTimeField': field.help_text = 'YYYY-MM-DD HH:MM:SS' elif … -
How can I designate 'url' of 'BUNDLE_DIR_NAME' correctly?
I'm using Django and react with webpack While setting up WEBPACK_LOADER in settings.py, I've faced the problem! My file tree is like this. Cebula4 - back - manage.py - front - bundles - MainPage.js (webpacked) I'd like to get my bundled(webpacked) file, MainPage.js but, Server said there is none at that url Please understand my low level of programming, Could I ask what is the correct url that I can get exact MainPage.js? -
TypeError: data.forEach is not a function
This is my code: $.ajax({ url: "some_url/", type: "GET", dataType: "json", success: function(data){ console.log(data); data.forEach(function(element){ console.log(element); }); } }); I get the error that for each does not work on the data variable. However, when I log data to the console, I get [{"model": "app.mdl", "pk": 1, "fields": {"name": "test", "rank": 1}}] This is clearly an array and iterable, so I don't get what exactly is wrong. EDIT: data is returned via JsonResponse in Django. -
Django Rest Create hashed password manually
I want to create hashed passwords manually that should be exactly same when we hash password using set_password() function. I tried make_password(), but when I use it, it gives different outputs for same input like this How can I solve it? -
Django on creating new model store records of existing user and its data
I have a model Customer, class Customer(models.Model): name = models.CharField(max_length=20, db_index=True) address = models.CharField(max_length=100, blank=True) email = models.EmailField(max_length=100, blank=True) phone = models.IntegerFeild(max_length=100, blank=True) I have created a new model say XYZ, class XYZ(models.Model): customer = models.OneToOneFieldOneToOneField(Customer, on_delete=models.CASCADE) abc = models.CharField(max_length=10) user = models.OneToOneField(User, on_delete=models.CASCADE) So how should I insert data into this XYZ table for existing customer, without using manually Insert into query. Is there any django query or way to insert the existing customer records in XYZ table ? -
Incorrect type. Expected pk value, received dict. Django Rest Framwork - Vue
I'm new to Django and Django Rest Framework. This is a little project I'm trying to do to improve my skills but I've been stuck here a lot of time. ViewSets.py from rest_framework import viewsets, filters from .models import Plazo, Perfil, Solicitud, Estatus from .serializers import (PlazoSerializer, PerfilSerializer, SolicitudSerializer, EstatusSerializer, SolicitudExpandeSerializer) class PlazoViewSet(viewsets.ModelViewSet): queryset = Plazo.objects.all() serializer_class = PlazoSerializer class EstatusViewSet(viewsets.ModelViewSet): queryset = Estatus.objects.all() serializer_class = EstatusSerializer class PerfilViewSet(viewsets.ModelViewSet): queryset = Perfil.objects.all() serializer_class = PerfilSerializer class SolicitudViewSet(viewsets.ModelViewSet): queryset = Solicitud.objects.all() serializer_class = SolicitudSerializer def get_serializer_class(self): serializer_class = self.serializer_class if self.action in ['list', 'retrieve']: serializer_class = SolicitudExpandeSerializer return serializer_class Serializers.py from rest_framework import serializers from .models import Plazo, Perfil, Solicitud, Estatus class PlazoSerializer(serializers.ModelSerializer): class Meta: model = Plazo fields = '__all__' class EstatusSerializer(serializers.ModelSerializer): class Meta: model = Estatus fields = '__all__' class PerfilSerializer(serializers.ModelSerializer): class Meta: model = Perfil fields = '__all__' class SolicitudSerializer(serializers.ModelSerializer): class Meta: model = Solicitud fields = '__all__' class SolicitudExpandeSerializer(SolicitudSerializer): perfil = PerfilSerializer(many=False, read_only=False) status = EstatusSerializer(many=False, read_only=False) Models.py from django.db import models class Plazo(models.Model): plazo_id = models.AutoField(primary_key=True) nombre = models.CharField(max_length=100) meses = models.IntegerField() intereses = models.IntegerField() def __str__(self): return self.nombre class Meta: verbose_name = 'plazo' verbose_name_plural = 'plazos' class Perfil(models.Model): perfil_id = models.AutoField(primary_key=True) nombre = models.CharField(max_length=250) def … -
Passing CHOICES from models.py into form initialization
I've got one form called 'TaxForm'. Within my models.py, I've got two choices lists defined: States and Countries I've got a template page where the user can create a tax. They can click a "Create Federal Tax" button or "Create a State Tax" button. The first button is passing and id of 1 to the view and the second is passing and id of 2 to the view. I want to setup the form it is initialized with the 'States' choices if the user clicks "Create a State Tax". Similarly, I want the form to be initialized with the "Countries" options if the "Create a Federal Tax" is clicked. I know how to pass the id from the view to forms.py. Is there a way to do this? I know how to initialize a for with choices based on a queryset of model instances, but I'm not sure how to do it with choices that are defined in the models.py. Within my forms.py class, I'd have this: def __init__(self, *args, **kwargs): id = kwargs.pop('id') if id == 1: self.fields['juristiction'].choices = #Federal Tax Options from models.py. Not sure how to get these... else: self.fields['juristiction'].choices = #State Tax Options from models.py. Not … -
python manage.py shell < scripts/myscript.py not working when the file contains if __name__ == '__main__'
I am trying to run a script(myscript.py) using python manage.py shell < scripts/myscript.py but nothing happens. Here is my code myscript.py def foo(x): print(x+1) if __name__ == '__main__': x = 10 foo(x) any help please Note: I am new to django I am using python 3.6 and django 1.10.6 -
Is there any better API library available for Bse Star in Django?
Is there any latest APIs library available for Bse Star in Django? I have found https://github.com/utkarshohm/mf-platform-bse , but it doesn't contain the latest operations. -
Why getting 'reverse match error' when moving templat files relating to specific to app to master template folder
I am new to Django. I have found many links matching to this problem, but I did not understand them. I am creating blog app. Everything was working fine, until I created another app called 'services', and created separate template folders for 'blog', 'services' and 'master'. Now, when I click on 'create new post' in blog app, I get 'Reverse for 'post_publish' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['blog\/post\/(?P[0-9]+)\/publish\/$']' Please help me, I do not understand what that error is trying to tell. Blog_views.py from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from blog.models import Post, Comment from django.utils import timezone from blog.forms import PostForm, CommentForm from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView) from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin from django.utils.text import slugify # Create your views here. class PostListView(ListView): model = Post template_name ="blog/blog/post_list.html" def get_queryset(self): return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') class PostDetailView(DetailView): model = Post template_name ="blog/blog/post_detail.html" class CreatePostView(LoginRequiredMixin,CreateView): login_url = '/login/' template_name ="blog/blog/post_detail.html" redirect_field_name = 'blog/blog/post_form.html' form_class = PostForm model = Post # template_name ="blog/blog/post_detail.html" class PostUpdateView(LoginRequiredMixin,UpdateView): login_url = '/login/' redirect_field_name = 'blog/blog/post_detail.html' form_class = PostForm model = Post class DraftListView(LoginRequiredMixin,ListView): login_url = '/login/' redirect_field_name = 'blog/blog/post_list.html' model = Post def get_queryset(self): return … -
django-rest-framework raises an error in a model when accessing another model with a foreign key
I have two models, one referring the other one: class RatesTable(models.Model): hotel = models.ForeignKey(Hotel, on_delete=models.PROTECT, related_name='rates_tables', verbose_name=_('Hotel')) contract = models.ForeignKey(Contract, on_delete=models.PROTECT, null=True, blank=True, related_name='rates_tables', verbose_name=_('Contract')) name = models.CharField(max_length=100, verbose_name=_('Name')) description = models.TextField(null=True, blank=True, verbose_name=_('Description')) is_base = models.BooleanField(verbose_name=_('Is a base rate-table?')) start_date = models.DateField(null=True, blank=True, verbose_name=_('Start Date')) due_date = models.DateField(null=True, blank=True, verbose_name=_('Due Date')) release = models.IntegerField(verbose_name=_('Release')) class Meta: verbose_name = _('Rates Table') verbose_name_plural = _('Rates Tables') unique_together = ('contract', 'start_date', 'due_date') indexes = [ models.Index(fields=['hotel',]), ] def __str__(self): return "[{}][{}]{} {} {}-{}".format(self.id, self.hotel.name, self.contract.id, self.name, self.start_date, self.due_date) class Rate(models.Model): rates_table = models.ForeignKey(RatesTable, on_delete=models.PROTECT, related_name='rates', verbose_name=_('Rates Table')) product = models.ForeignKey(Product, on_delete=models.PROTECT, related_name='product_rates', verbose_name=_('Product')) rate = models.FloatField(verbose_name=_('Rate')) class Meta: verbose_name = _('Rate') verbose_name_plural = _('Rates') unique_together = ('rates_table', 'product') def __str__(self): return "[{}][{}][{}]{}".format(self.id, self.rates_table.contract, self.rates_table.id, self.product.name) Each one has its own standard end-point in urls.py. End-point for model RatesTable works perfectly, but end-point for model Rate raises this error: return "[{}][{}]{} {} {}-{}".format(self.id, self.hotel.name, self.contract.id, self.name, self.start_date, self.due_date) AttributeError: 'NoneType' object has no attribute 'id', and this error is raised on method __str__(self) of model RatesTable, not model Rate! I don't know why DRF raises an error in the referenced model. It's the only case it happens, and I have many models with … -
Django mongoengine create dynamic document using request data
How can I get the request body data, parsed it such that its key is fields in mongo document and save the corresponding value to the field? I am using mongoengine in which we need to pre-define the fields and serializer to save data as below: models.py class Model(Document): timestamp = fields.StringField() source = fields.StringField() email = fields.StringField() serializer.py class ModelsSerializer(mongoserializers.DocumentSerializer): class Meta: model = Model fields = '__all__' def create(self, validated_data): validated_data = dict((k.lower(), v.lower()) for k, v in validated_data.items()) logger.info("Request Data "+str(validated_data)) instance = Models.objects.create(**validated_data) return instance Suppose my request body is: { "timestamp": "1542085502174", "source": "source", "medium": "med, "term": "termvalue, "email": null, } The problem with this code is that it saves only timestamp, source and email field of request body. But I need to save the document in such a way that the document creates new field medium and term and adds the corresponding value med and termvalue in mongo. -
Django template img src using url link instead of file
Hi i'm currently new to Django and i'm trying to popular a product page. I'm having problem with the img to show the image(which uses an image url online instead of a file) for example an img src="media3.scdn.vn/img2/2018/6_2/ZIBLXA_simg_b5529c_250x250_maxb.jpg" The url already in my database with the text media3.scdn.vn/img2/2018/6_2/ZIBLXA_simg_b5529c_250x250_maxb.jpg But when i tried to render it in template the image doesn't show I tried to used the but it still not work Any help would be appreciate! My template {% for discount in discounts|slice:":8" %} <div class="col-md-3 product-men women_two"> <div class="product-googles-info googles"> <div class="men-pro-item"> <div class="men-thumb-item"> <img src="{{STATIC_URL}}{{discount.product_image}}" alt=""/> <div class="men-cart-pro"> <div class="inner-men-cart-pro"> <a href="single .html" class="link-product-add-cart">Quick View</a> </div> </div> <span class="product-new-top">New</span> </div> <div class="item-info-product"> <div class="info-product-price"> <div class="grid_meta"> <div class="product_price"> <h4> <a href="single.html">{{discount.product_name}}</a> </h4> <div class="grid-price mt-2"> <span class="money ">{{discount.product_old_price}}</span> </div> </div> <div> <h3>{{discount.product_sit}}</h3> </div> <div><h2 style="color:red">Chi con {{discount.product_price}}!</h2></div> </div> </div> <div class="clearfix"></div> </div> </div> </div> </div> {% endfor %}