Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
telling the cmd what version of python im using
IM trying to make a website with django and im following a tutorial that is telling me i need to tell my cmd prompt what version of python im using. this is the video https://www.youtube.com/watch?v=FNQxxpM1yOs at the 10:46 mark he says to put C:/Python35/ python manage.py runserver. I am putting thi but it is not working. I am using version 3.7 so i replaced 35 with 37 but it is still not working. can someone please helps with this. -
Is raise ImproperlyConfigured is missing in django library
django library path: django\views\generic\detail.py class : SingleObjectTemplateResponseMixin why raise ImproperlyConfigured is not mentioned in 2nd last line of the code? class SingleObjectTemplateResponseMixin(TemplateResponseMixin): template_name_field = None template_name_suffix = '_detail' def get_template_names(self): """ Return a list of template names to be used for the request. May not be called if render_to_response() is overridden. Return the following list: * the value of ``template_name`` on the view (if provided) * the contents of the ``template_name_field`` field on the object instance that the view is operating upon (if available) * ``<app_label>/<model_name><template_name_suffix>.html`` """ try: names = super().get_template_names() except ImproperlyConfigured: # If template_name isn't specified, it's not a problem -- # we just start with an empty list. names = [] # If self.template_name_field is set, grab the value of the field # of that name from the object; this is the most specific template # name, if given. if self.object and self.template_name_field: name = getattr(self.object, self.template_name_field, None) if name: names.insert(0, name) # The least-specific option is the default <app>/<model>_detail.html; # only use this if the object in question is a model. if isinstance(self.object, models.Model): object_meta = self.object._meta names.append("%s/%s%s.html" % ( object_meta.app_label, object_meta.model_name, self.template_name_suffix )) elif getattr(self, 'model', None) is not None and issubclass(self.model, models.Model): names.append("%s/%s%s.html" % … -
How do i fix this issue with django start project?
after i installed django i wrote the start project command to verify django is working or not. i.e, django-admin startproject mysite cd mysite python manage.py runserver after that i got a ip address(http://127.0.0.1:8000/) but when i link to this http://127.0.0.1:8000/, it is showing unable to connect. what should i do now? -
Django POST method returns 500 server error on EC2 server
I am trying to build a web app using Django Rest framework. When I run the app on localhost 127.0.0.0/8000 it works fine. But when I deploy it on an EC2 server the POST methods return 500 server error. Here is one of the post methods in the views.py - class customer_location(APIView): def post(self, request, *args, **kwargs): customer_id = json.loads(request.body).get('customer_id') queryset = customers.objects.filter(cid= customer_id) serialize = customer_details(queryset, many=True) return Response(serialize.data, status=status.HTTP_200_OK) The urls.py is like this - from django.conf.urls import include, url from django.urls import path from rest_framework import routers from . import views urlpatterns = [ url(r'^customer_location/$', views. customer_location.as_view(), name='customer_location'), ] The DEBUG mode is set to False and the EC2 instance IP address is added in the ALLOWED_HOSTS. The GET methods are working fine but the POST methods give error. How to solve this ? -
Queryset with different datasets based on obj type
I want to implement in my application something similar to instagram's local notifications. The main problem is that local notifications can be different types. For example: 1) Simple one: "user started following you" (this is pretty straightforward) 2) More complicated: "user and +7 other liked your photo X" The first step of solution is to GROUP all notifications by targeted_user, event_type and user_who_triggered_event. For the first case it's okay as we will have all information. For the second case we will lack some information as Count of similar notifications. Also what if I need some additional information about those +7 user's who also liked photo X? class Notification(TimeStampedModel): OPEN_QUEST = 'open_quest' OPEN_PHOTO = 'open_photo' ACTION_CHOICES = ( (OPEN_PROFILE, _('Open profile')), (OPEN_PHOTO, _('Open photo')), ) LIKED_PHOTO = 'liked_photo' NEW_FOLLOWER = 'new_follower' EVENT_CHOICES = ( (LIKED_PHOTO, _('Liked photo')), (NEW_FOLLOWER, _('New follower')) ) action = models.CharField( max_length=255, choices=ACTION_CHOICES, ) event = models.CharField( max_length=255, choices=EVENT_CHOICES, ) title = models.CharField( max_length=255, ) body = models.TextField() class Meta: db_table = 'notifications' For this example I have 2 notifications in data base. Also I have ReceivedNotification model with FK to user and FK to notification and also data field(JSONField) to store actual information which particular user will … -
django ,model migrate: TypeError: an integer is required (got type str)
I am writing a apps and run makemigrations and migrate multiple time when i add new field. And now i have added a new foreignKey Field in models and then i run the command: python3 manage.py makemigrations after this, i run this command python3 manage.py migrate but it throws me following error TypeError: an integer is required (got type str) and later again i run this command pythion3 manage.py migrate --fake and i have successfully migrated and got another problem, when i go to django admin templates and click on my models to add data, it throws me this error: OperationalError at /admin/booking/seats/ no such column: booking_seats.seat_for_id I am not getting whats wrong with it, can anyone help me to fix this? for your reference, see my models: class Seats(models.Model): alias = models.UUIDField( primary_key=True, default=uuid4, editable=False ) seat_no = models.IntegerField( choices=SeatChoices.choices(), ) availability = models.IntegerField( choices=SeatAvailability.choices(), default=SeatAvailability.AVAILABLE ) seat_for = models.ForeignKey('booking.show', on_delete=models.CASCADE) def __str__(self): return str(self.seat_no) class Show(models.Model): alias = models.UUIDField( primary_key=True, default=uuid4, editable=False ) show_schedule = models.IntegerField( choices=ShowSchedule.choices(), ) movie = models.CharField(max_length=50) def __str__(self): return str(self.show_schedule) I just added this new field seat_for = models.ForeignKey('booking.show', on_delete=models.CASCADE) then i facing the problem Can anyone help me in this case? -
Chartjs in Django, special characters in label not supported?
I have some values passed to Chart.js but I found neither / nor - is supported. If the labels are harded coded as UK-aaa or N/A, it works fine. If it is passed as a varible which the project requires, UK or N (letters before the special characters will not recognized and no chart shows. Is there a workround on Javascript other than removing special characters in labels? Thanks. var C3 = document.getElementById(canv3.getAttribute('id')); if (C3.getContext) { if (C3.getContext) { new Chart(document.getElementById(canv3.getAttribute('id')), { type: 'bar', data: { labels: [{{res.21}},{{res.22}},{{res.23}}], //this is not supported if same value as below passed. //labels: ['UK-aaa','N/A','N/A'], //this is supported datasets: [ { backgroundColor: "rgba(35, 35, 0.5)", borderColor : "rgba(149, 62, 205, 1)", pointBackgroundColor: "rgba(62, 149, 205, 1)", data: [{{res.18}},{{res.19}},{{res.20}}] //numeric value }, ] }, options: { responsive: false, maintainAspectRatio: false, scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); }} -
making modal for every entry in a list view using Js?
I have a page where multiple images are present and I want to make the users able to crop any of them so I made a for loop to make a modal for each image and I looped the js function also. this is my modal. {% for image in Patient_detail.images.all %} <div class="modal fade" id="modalCrop{{image.pk}}"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title">Crop the photo</h4> </div> <div class="modal-body"> <img src="" id="image{{image.pk}}" style="max-width: 100%;"> </div> <div class="modal-footer"> <div class="btn-group pull-left" role="group"> <button type="button" class="btn btn-default js-zoom-in"> <span class="glyphicon glyphicon-zoom-in"></span> </button> <button type="button" class="btn btn-default js-zoom-out"> <span class="glyphicon glyphicon-zoom-out"></span> </button> </div> <button type="button" class="btn btn-default" data-dismiss="modal">Nevermind</button> <button type="button" class="btn btn-primary js-crop-and-upload">Crop and upload</button> </div> </div> </div> </div> {% endfor %} and here's the function I used {% for image in Patient_detail.images.all %} $(function () { /* SCRIPT TO OPEN THE MODAL WITH THE PREVIEW */ $("#crop{{image.pk}").click(function () { var img_src = document.getElementById("img{{image.pk}}").src $("#image{{image.pk}}").attr("src", img_src); $("#modalCrop{{imahge.pk}}").modal("show"); } }); /* SCRIPTS TO HANDLE THE CROPPER BOX */ var $image = $("#image{{image.pk}}"); var cropBoxData; var canvasData; $("#modalCrop{{image.pk}}").on("shown.bs.modal", function () { $image.cropper({ viewMode: 1, aspectRatio: 1/1, minCropBoxWidth: 200, minCropBoxHeight: 200, ready: function () { $image.cropper("setCanvasData", canvasData); $image.cropper("setCropBoxData", … -
django usercreationform is_valid always return false
i'm green hand to django, when i try to use the usersignupform, the request post is like `<QueryDict: {'csrfmiddlewaretoken': ['Wxlj42vbyAweKevBeSs5TvGj1ot8tJknUOGzmlKCphs5cDnqvsmriCSK9wYDuAof'], 'username': ['dulong11'], 'email': ['stephen.du@abc.com'], 'password1': ['dulong'], 'password2': ['dulong'], 'submit': ['']}` then the usercreationform.is_valid() will always return false, i do not know why, and how it happens? why it cannot work?? form.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class UserSignUpForm(UserCreationForm): #username = forms.CharField() email = forms.EmailField(max_length=100) #password1 = forms.CharField() #password2 = forms.CharField() class Meta: model = User fields = ('username', 'email', 'password1', 'password2') register.html <form action="." method="post" id="frm" class="frm"> {% csrf_token %} <div class="r-list"> <div class="line"> <i class="dqfont icon-mobilephone"></i> <input type="text" name="username" placeholder="用户名" autocomplete="off"> <span class="error" id="tel_error"></span> </div> </div> <div class="r-list"> <div class="line"> <i class="dqfont icon-mobilephone"></i> <input type="email" name="email" placeholder="请输入邮箱" autocomplete="off"> </div> <span class="error"></span> </div> <div class="r-list"> <div class="line"> <i class="dqfont icon-pass"></i> <input type="password" name="password1" placeholder="请输入密码" autocomplete="off"> </div> <span class="error"></span> </div> <div class="r-list"> <div class="line"> <i class="dqfont icon-pass"></i> <input type="password" name="password2" placeholder="请再次输入你的密码" autocomplete="off"> </div> <span class="error"></span> </div> <div class="r-list"> <div class="protocol"> <span class="checkbox-checked" id="accept">我已阅读并同意<a href="#" target="_blank">《IPLink用户协议》</a>和<a href="#" target="_blank">《隐私保护》</a></span> </div> </div> <div class="r-list"> <span class="error"></span> <!--a href="#" class="btn" id="btn">同意协议并注册</--a>--> <button type="submit" class="btn" name="submit" id="btnSubmit" style="width:380px">同意协议并注册</button> </div> </form> -
Is it possible to have a hosted Django site use the client's interfaces to create a SSH session with a local privately addressed device
I am trying to learn programming to expand my horizons a bit. I have been creating a Django app that automates several aspects of my day to day job. It would be nice if that Django app could be on a public server for accessibility but also have a view that can initiate an SSH session with various privately addressed devices, mostly to verify network changes were successful. In my mind the script would almost need to run on the client side to use their IP address within the private network but from my understanding, Django is server side. Any advice on how to work around this? -
AssertionError: You need to pass a valid Django Model in UserProfile.Meta, received "None"
I'm adding Django Model to a graphql api using the AbstractBaseUser custom user model. The Admin works fine except that I get an error when trying to access the graphql api, 'You need to pass a valid Django Model in UserProfile.Meta, received "None"' I've tried adding AUTH_USER_MODEL = 'noxer_app.MyUser' to settings, yet it doesn't work In models.py: from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class MyUserManager(BaseUserManager): def create_user(self, email, first_name, last_name, company, company_reg_no, address, phone, image, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, company=company, company_reg_no=company_reg_no, address=address, phone=phone, image=image, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name, company, company_reg_no, address, phone, image, password): user = self.create_user( email, password=password, first_name=first_name, last_name=last_name, company=company, company_reg_no=company_reg_no, address=address, phone=phone, image=image, ) user.is_admin = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(max_length=255, default='') last_name = models.CharField(max_length=255, default='') company = models.CharField(max_length=255, default='') company_reg_no = models.CharField(max_length=255, default='') address = models.CharField(max_length=400, default='') phone = models.CharField(max_length=13, default='') image = models.ImageField(default='noimage.jpg', upload_to = 'profile_pics') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'company', 'company_reg_no', 'address', 'phone', 'image'] def __str__(self): … -
Is it recommended to manually redirect sub-domains to an application from the project itself?
We have different types of users whom we'd like to redirect to different views based on the sub-domain in the URL. In our project directory, we examine each and every request for the sub-domain keywords, viz. ut1.domain or ut2.domain. Is this a good solution? If not, please suggest something better. User Type 1 ut1.domain.com/login/ User Type 2 ut2.domain.com/login/ This is how the sub-domains are being planned to be handled. def handle_urls(request): if "ut1.domain." in request.build_absolute_uri(): return HttpResponseRedirect('login/') context = {} return render(request, "home.html", context) The purpose of the sub-domains is to point to different applications in the same project. We expect to add more than a dozen sub-domains in the next few months for various new applications. Thank you for your time reading this. -
how to perform count for a secod foreign key in django?
i have three models Category,Post,Comment class Category(models.Model): class Meta: verbose_name_plural = "Categories" COLOR_CHOICES = ( ('primary', 'Blue'), ('success', 'Green'), ('info', 'Sky Blue'), ('warning', 'Yellow'), ('danger', 'Red') ) title = models.CharField(max_length=250, unique=True) description = models.CharField(max_length=250) slug = models.SlugField(max_length=200,) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) visited = models.IntegerField(default=0) color = models.CharField( max_length=20, default='primary', choices=COLOR_CHOICES) class Post(models.Model): STATUS_CHOICES = ( (True, 'Visible'), (False, 'Hidden') ) title = models.CharField(max_length=250) author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) body = models.TextField() category = models.ForeignKey( Category, on_delete=models.SET_NULL, null=True) slug = models.SlugField(max_length=200,) status = models.BooleanField(default=False, choices=STATUS_CHOICES) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) visited = models.IntegerField(default=0) class Comment(models.Model): STATUS_CHOICES = ( (True, 'Visible'), (False, 'Hidden') ) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True) author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.BooleanField(default=True, choices=STATUS_CHOICES) i want to perform a query set to get categories and number of comments of each category, i cant find a good way. i already know how to count posts for each category using annotate. i tried : categories = Category.objects.annotate(nb_comments=Count('post__comment')) -
Django apache2 KeyError for SECRET_KEY with environment variable
I try to deploy django on a debian server. To protect the secret key i store them in a environment variable. I edit /etc/profile an add: SECRET_KEY="123456789...."; export SECRET_KEY I tested if the variable is set with printenv | grep SECRET_KEY and echo $SECRET_KEY. It works fine but if i open the website i get Forbidden You don't have permission to access / on this server. and in the error.log from apache: .... raise KeyError(key) from None [Tue Sep 17 14:11:20.062194 2019] [wsgi:error] [pid 13523:tid 140622223152896] [client 123.456.78.910:50361] KeyError: 'SECRET_KEY' .... Why django can't read the environment variable? -
why am I getting a none value in my method inside of my model with nested if?
I'm new in django trying to do a project of management of a small restaurant, in my consummation model,I have attributes that are foreign keys, and the date of consummation, now I try to calculate the sum of those attributes in a method inside the model by returning the total. I tried class Consommation(models.Model): entree = models.ForeignKey(Entree, models.CASCADE, verbose_name="L'entree", null=True, blank=True) food = models.ForeignKey(Meals, models.CASCADE, verbose_name='Plat de resistance', null=True, blank=True) dessert = models.ForeignKey(Dessert, models.CASCADE, verbose_name='Dessert', null=True, blank=True) boisson = models.ForeignKey(Boisson, models.CASCADE, verbose_name='Boisson', null=True, blank=True) autres = models.ForeignKey(Autres, models.CASCADE, verbose_name='Snacks', null=True, blank=True) consomme_le = models.DateTimeField(default=timezone.now, editable=False) class Facture(models.Model): consommation = models.OneToOneField(Consommation, models.CASCADE, null=True, blank=True, verbose_name='Facture') fait_le = models.DateField(default=timezone.now, editable=False) is_regle = models.BooleanField(default=False, verbose_name='Est regle') initials_caissier = models.CharField(max_length=5, verbose_name='Initiales du Caissier') def __str__(self): return 'Facture du :' + ' ' + str(self.fait_le) def get_absolute_url(self): return reverse('clients:facture_detail', kwargs={'pk': self.pk}) def net_a_payer(self): if self.consommation: if not self.consommation.entree: self.consommation.entree.price = int(0) if not self.consommation.food: self.consommation.food.price = int(0) if not self.consommation.dessert: self.consommation.dessert.price = int(0) if not self.consommation.boisson: self.consommation.boisson.price = int(0) if not self.consommation.autres: self.consommation.autres.price = int(0) return self.consommation.entree.price + self.consommation.food.price + self.consommation.dessert.price + self.consommation.boisson.price + self.consommation.autres.price net_a_payer: means the total sum to pay I expect the result to be the sum of the attibutes instead of … -
Creating a generic search view in Django
I am struggling to create my custom generic view in django to easily create search pages for certain models. I'd like to use it like this: class MyModelSearchView(SearchView): template_name = 'path/to/template.html' model = MyModel fields = ['name', 'email', 'whatever'] which will result in a view that returns a search form on GET and both form and results on POST. The fields specifies which fields of MyModel will be available for a user to search. class SearchView(FormView): def get_form(self, form_class=None): # what I'v already tried: class SearchForm(ModelForm): class Meta: model = self.model fields = self.fields return SearchForm() def post(self, request, *args, **kwargs): # perform searching and return results The problem with the code above is that form will not be submitted if certain fields are not be properly filled. User should be allowed to provide only part of fields to search but with the code I provided the form generated with ModelForm prevents that (for example because a field in a model cannot be blank). My questions are: Is it possible to generate a form based on a model to omit this behaviour? Or is there any simpler way to create SearchView class? I don't want to manually write forms if … -
How to redirect to previous page after language changing?
When I am trying to use next it doesn't work because in next-url there are old language code so language doesn't change. my template: <a href="{% url "set_language_from_url" user_language="en" %}?next={{request.path}}">en</a> <a href="{% url "set_language_from_url" user_language="ru" %}?next={{request.path}}">ru</a> my url: path('language-change/<user_language>/', views.set_language_from_url, name="set_language_from_url"), my view: def set_language_from_url(request, user_language): translation.activate(user_language) request.session[translation.LANGUAGE_SESSION_KEY] = user_language redirect_to = request.POST.get('next', request.GET.get('next', '/')) return redirect(redirect_to) -
Run multiple Django application on mutilple subdomains with nginx and Gunicorn
I want to run multiple sites on the same instance of EC2. I configured my site as per this doc. I have two projects: 1. project_1 2. project_2 project_1 on beta.example.com project_2 on api.example2.com I am running project_1 successfully with Nginx and gunicorn and want to add project_2. I have tried this answer but is not working. -
Django throws a 404 error on all static files while everything seems to be correct
Recently, I added some static files to my project which for some reason threw an error (I can't remember what kind of error.) I removed these files and redeployed but now, when I push my Django project to the docker container, the static files have stopped working all together, while everything seems to be in order. These are the settings I use for the static files: STATIC_ROOT = str(ROOT_DIR("staticfiles")) STATIC_URL = "/static/" STATICFILES_DIRS = [str(APPS_DIR.path("static"))] STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] I am running the installation in a Docker container, taken from the django-cookiecutter project. I have only changed one thing in the Docker configuration, I removed the Postgres image, since my container connects to an external postgres server. I have tried running manage.py collectstatic, and manage.py collectstatic --clear, to no avail. Also, when I run manage.py findstatic --verbosity 2 css/custom.css, I get a message saying that the file was found, with a list of all the folders searched, which does include the static folders for all my apps inside my project. (There are no static files located outside of default folders.) At this point, I'm pretty lost as to what could be the issue. My best guess would that … -
Factory boy foreign key field with null=True
I have a foreign key field called nutrition on the Product model with null=True. How can you use factory boy randomize the field so that sometimes it's null and sometimes it's a SubFactory? class ProductFactory(factory.DjangoModelFactory): class Meta: model = Product exclude = ('has_nutrition',) has_nutrition = factory.Faker('pyint', min_value=1, max_value=10) nutrition = factory.LazyAttribute( lambda _: factory.SubFactory(NutritionFactFactory) if _.has_nutrition == 10 else None) Calling ProductFactory.create_batch(500) results in the following error ValueError: Cannot assign "factory.declarations.SubFactory object at 0x7fe91c3f8128": "Product.nutrition" must be a "NutritionFact" instance. -
how to include object into category or subcategory?
I need to make that sort of relations: └───SCOPE01 ├───PROJECT01 │ └───WORKER01 └───WORKER02 Worker can be busy on some project or be free on some scope. Have I chosen the right approach, and how can I do otherwise? #models.py from django.db import models class Scope(models.Model): title = models.CharField(max_length=30) class Project(models.Model): title = models.CharField(max_length=30) scope = models.ForeignKey( Scope, related_name='projects', on_delete=models.CASCADE ) class Worker(models.Model): title = models.CharField(max_length=30) project = models.ForeignKey( Project, related_name='workers', on_delete=models.CASCADE ) scope = models.ForeignKey( Scope, related_name='workers', on_delete=models.CASCADE ) If that is correct, how to limit the simultaneous worker addition into both scope and project? -
DataError value too long for type character varying(100)
I need to make changes to my profiles object at the admin site in Django, but when I click save, I get the error DataError at /admin/profiles/profiles/31/change/ value too long for type character varying(100). The weird thing is, it worked when I made changes to the same field locally, but when I deployed to Heroku, it gave me the 'DataError'. My image url is the only long string in my object. Currently: http://res.cloudinary.com/firslovetema/image/upload/v1568570093/ypqiiwg5eq5uyd7oie6g I have tried setting the max_length to 512. it still did not work. my models.py file: from django.db import models from cloudinary.models import CloudinaryField class profiles(models.Model): firstname = models.CharField(max_length=120, default = 'null') #max_length=120 lastname = models.CharField(max_length=120, default = 'null') gender = models.CharField(max_length=120, default = 'null') dob = models.CharField(max_length=120, default = 'null') callNumber = models.CharField(max_length=120, default = 'null') whatsappNumber = models.CharField(max_length=120, default = 'null') ministry = models.CharField(max_length=120, default = 'null') centre = models.CharField(max_length=120, default = 'null') campus = models.CharField(max_length=120, default = 'null') hostel_address = models.CharField(max_length=120, default = 'null') city = models.CharField(max_length=120, default = 'null') qualification = models.CharField(max_length=120, default = 'null') profession = models.CharField(max_length=120, default = 'null') maritalStatus = models.CharField(max_length=120, default = 'null') bacenta = models.CharField(max_length=120, default = 'null') layschool = models.CharField(max_length=120, default = 'null') imagefile = CloudinaryField('image', null=True, … -
Serializing Date field in django-rest-marshmallow results in an error
I am using django-rest-marshmallow along with django-rest-framework to build simple APIs. The following works if I dont include the created_at field in the serializer and gets the results as expected but upon inclusion, it throws and exception. models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=50) created_at = models.DateField() serializers.py from rest_marshmallow import Schema, fields class CategorySerializer(Schema): id = fields.Integer() name = fields.String() created_at = fields.Date() # works, if I dont include this views.py from rest_framework import viewsets class CategoryViewSet(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer This results in the following error Django version 2.2.5, using settings 'app.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: /api/v1/categories/ Traceback (most recent call last): File "/home/abcdefg/mpk/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/abcdefg/mpk/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/abcdefg/mpk/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/abcdefg/mpk/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/abcdefg/mpk/lib/python3.7/site-packages/rest_framework/viewsets.py", line 114, in view return self.dispatch(request, *args, **kwargs) File "/home/abcdefg/mpk/lib/python3.7/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/home/abcdefg/mpk/lib/python3.7/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/home/abcdefg/mpk/lib/python3.7/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/home/abcdefg/mpk/lib/python3.7/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, … -
Django Saleor Stripe SCA Issue
I have a Django Saleor application that handles payment through Stripe.js which is working well. I need to update the application for SCA but despite the code update, I don't get the 3D prompt. Followed the instructions here: https://teams.microsoft.com/join/7z30xkdir2ep Any help is appreciated. -
Django database design for dynamic fields with inheritance
I have a problem with my models design. I have various templates and documents that can created from a template. For example: class Templates(models.Model): name = models.CharField(max_length=255) descripton = models.TextField() content = models.TextField() class Meta: abstract = True class TemplateTest1(Templates): class Meta: verbose_name = "Test 1" class TemplateTest2(Templates): class Meta: verbose_name = "Test 2" And these are the document models: class Test1(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) template = models.ForeignKey(TemplateTest1, on_delete=models.CASCADE) class Test2(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) template = models.ForeignKey(TemplateTest2, on_delete=models.CASCADE) Now the templates should contain various variables. If a user create a document he must filled the variables. Some variables should filled from the system automatically. These variables get the data from the database itself. For example the $system_companyname in the content from TemplateTest2 should show the name from the company that the document is created for. For example the content from TemplateTest1 and TemplateTest2 looks like this: --- TemplateTest1 content --- I am from $town and live in $street. Would you like to go? $dropdown-yes-no --- TemplateTest2 content --- Hello $system_companyname, please check the right answer. $checkbox1 I am older than 16 $checkbox2 I have an apartment So the templates contain various variables and types. The document would store …