Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ImageField tamplate tag not displaying
The image is correctly saved to the static filed that I set in the setting filed. The image will display properly if I use a static path. But when I use a dynamic path, the image would not show and no error is given. As you can see the path, when called outside of , works correctly. But when puted inside of the , both {{item.image_1.path}}, nor {{item.image_1}},would show any picture. (item is the name of the model while image_1 is the name of the image_field) -----------For the not working dynamic path: {{item.image}} {{item.image.path}} <img src='{{item.image}}' alt=''> <img src='{{item.image.path}}' alt=''> [![for the not working method[1]][1] -----------For the working static path: {% static 'arrival7.png' as pic %} <img src='{{pic}}' alt=''> -
How can I restrict inserting data on behalf of another user in Django?
I have the following code in my django project. models.py from django.db import models class Doctor(models.Model): hospital = models.ForeignKey('auth.User', on_delete=models.CASCADE) name = models.CharField(primary_key=True, max_length=256, unique=True) education = models.CharField(max_length=256) class Patient(models.Model): doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) name = models.CharField(max_length=256) age = models.CharField(max_length=200) height = models.CharField(max_length=6) sex = models.CharField(max_length=12) serializers.py from rest_framework import serializers from .models import Doctor, Patient class DoctorSerializer(serializers.ModelSerializer): class Meta: model = Doctor fields = [ 'name', 'education' ] class PatientSerializer(serializers.ModelSerializer): class Meta: model = Patient fields = '__all__' views.py from rest_framework import status, permissions from rest_framework.response import Response from rest_framework.views import APIView from .models import Doctor, Patient from .serializers import DoctorSerializer, PatientSerializer class DoctorList(APIView): permission_classes = [permissions.IsAuthenticated] serializer_class = DoctorSerializer def get(self, request): doctors = Doctor.objects.filter(hospital=request.user) serializer = DoctorSerializer(doctors, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def post(self, request): serializer = DoctorSerializer(data=request.data) if serializer.is_valid(): serializer.save(hospital=request.user) return Response({"message": "Doctor inserted!"}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class PatientList(APIView): permission_classes = [permissions.IsAuthenticated] serializer_class = PatientSerializer def get(self, request): patients = Patient.objects.filter(doctor__hospital=request.user) serializer = PatientSerializer(patients, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def post(self, request): serializer = PatientSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({"message": "Patient inserted!"}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) These views are then wired up with endpoints doctors/ and patients/ respectively. The problem I am having is restricting the owner … -
blog.Post.tags: (fields.E300) Field defines a relation with model 'Tag', which is either not installed, or is abstract. in django
I am making a django blog app. But when i run python manage.py makemigrations blog, I get this error: SystemCheckError: System check identified some issues: ERRORS: blog.Post.tags: (fields.E300) Field defines a relation with model 'Tag', which is either not installed, or is abstract. Here is my models.py: from django.db import models from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User from taggit.managers import TaggableManager class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. tags = TaggableManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return f'Comment by {self.name} on {self.post}' At first I thought that this error means I had not installed django-taggit. But when I … -
Logging with django rest framework with WSGI
I am fairly new in backend development. I was trying to write some log with Django rest framework. I set up the WSGI mode and the 000-default.conf file is <VirtualHost *:80> ServerAdmin user@gmail.com DocumentRoot /home/ubuntu/myproject_backend/myproject ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/myproject_backend/myproject/static <Directory /home/ubuntu/myproject_backend/myproject/static> Require all granted </Directory> <Directory /home/ubuntu/myproject_backend/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/ubuntu/myproject_backend/myproject python-home=/home/ubuntu/myproject_backend/env WSGIProcessGroup myproject WSGIScriptAlias / /home/ubuntu/myproject_backend/myproject/myproject/wsgi.py WSGIPassAuthorization On </VirtualHost> I added the LOGGING in the setting.py LOGGING = { 'version': 1, # Version of logging 'disable_existing_loggers': False, #disable logging 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'my_log.log', } }, 'loggers': { 'django': { 'handlers': ['file'], 'level': env("LOG_LEVEL"), 'propagate': True, }, }, } I tried with a simple warning log logging.warning("Logging Tutorials") Now the log is working when I was testing locally with the runserver command. However, when I pushed the code to the server it's getting permission denied writing the error.log file. PermissionError: [Errno 13] Permission denied I was wondering how do I give the permission and which user? the server is a ubuntu OS. I know there are a few posts about this issue. However, I could not figure out what exactly do I have to … -
How can I re-direct a user from the login page to the sign up page?
So, I have been trying to do this problem for a couple of days, but I seem to be having no luck, in actually solving it. For my side-project, I am creating a student grade management system in Django, and the problem that I am getting is that everytime the user clicks on the signup button on the homepage/login page, I get an error, because I haven't re-routed the user successfully. Specifically, the error I get is that it says, Page not Found. The page that I am trying to re-route the user to is in another app. So, I'm trying to route the user to the base url of that app, which from there, it will pop open a view. Here is the code for my urls.py on the loginpage/homepage (App1) from django.urls import re_path from django.shortcuts import redirect # import signUpPage.views as signupview from . import views urlpatterns = [ re_path(r'^$', views.login, name='login'), # re_path('signUpPage', signupview.register, name='signUpPage') # re_path('') ] Here is the code for my forms.py on the loginpage/homepage (App1) from crispy_forms.helper import FormHelper from crispy_forms.layout import Fieldset, Layout class loginForm(forms.Form): UserName = forms.CharField( label="Username", help_text="Please enter your username", widget=forms.TextInput(attrs={"placeholder":"Username"}), required=False ) Password = forms.CharField( label="Password", help_text="Enter … -
how to mock the django model?
i have to test a block of code ,like this: model: ''' class LoginHistory(models.Model): id = models.AutoField('ID', primary_key=True) class meta: db_table = 'login_table' ''' test model: ''' class TestLoginHistory(models.Model): id = models.AutoField('ID', primary_key=True) class meta: db_table = 'test_login_table' ''' util: ''' def registLoginHistory(self, loginId): model = LoginHistory(login_id=loginId) model.save() ''' test method: ''' def test_registLoginHistory(self): loginId = '003136130001' self.util.registLoginHistory(loginId) ''' now,i want to use TestLoginHistory(a django model) to change LoginHistory, so i try to use mock to do that. but it didnt work. it is the code i tried: ''' def test_registLoginHistory(self): loginId = '003136130001' LoginHistory = mock.MagicMock() LoginHistory.return_value.save = mock.MagicMock(side_effect=TestLoginHistory.save) self.util.registLoginHistory(loginId) ''' what should i do ? thx in advance. -
I can access my database with django and query it with objects.get() but objects.filter() will not work
I am just making a simple website as I am learning django. I have a view function that looks like this: def vieworkout(request): date= datetime.today() obj = userworkouts.objects.filter(userid=52) date = request.POST['date'] context = { 'exercise': obj.exercise } return render(request, 'clientIndex.html', context) when I use userworkouts.object.get() I can pass the exercise object no problem. When I change it to filter I get an error, "'QuerySet' object has no attribute 'exercise'". Does anyone know why this is happening? -
is there a way of defining function in models and save them to database as default by also filtering the fields? in Python Djnago
what i want to do is compute the value in percent for each learning styles there are and save them as default value to the field **result** on AssessmentLearningStyle model here is the model #MODEL_FOURTEEN class QuestionResults(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) student = models.ForeignKey(to=FacilityUser, on_delete=models.SET_NULL, null=True, blank=True) question = models.ForeignKey(to=QuestionLearningStyle, on_delete=models.SET_NULL, null=True, blank=True) agree = models.BooleanField(null=False) disagree = models.BooleanField(null=False) def __str__(self): return str(self.question) #MODEL_FIFTEEN class AssessmentLearningStyle(models.Model): @property def test(self): u = self.learning_style s = 0 if u == QuestionResults.question.learning_style: k = int(QuestionResults.objects.filter(agree=True, question__learning_style=self.learning_style).count()) l = int(QuestionResults.objects.filter(question__learning_style=self.learning_style).count()) if l != 0: s = (k/l) * 100 else: s = 0 return float(s) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) student = models.ForeignKey(to=FacilityUser, on_delete=models.SET_NULL, null=True, blank=True) assessent_date = models.DateField(blank=True, null=True) learning_style = models.ForeignKey(to=LearningStyle, on_delete=models.SET_NULL, null=True, blank=True) result = models.FloatField(default=test, editable=False) def __str__(self): return str(self.student) i want to save the value of test function to the result field...but it says float can't accept the value of property...and if i remove property... this method doesn't work at all...can you guys help me to fix this or show me a better way of doing this? Blockquote -
What would be the better way to write this class based view memcached caching
I am trying to do some caching in Django Here is what I have so far... # Jobs List View @method_decorator([vary_on_cookie, cache_page(900)], name='dispatch') class JobsListView( ListView): template_name = 'jobs_list.html' context_object_name = 'jobs' model = Job paginate_by = 6 def dispatch(self,request,*args,**kwargs): cache_key = 'my_jobs' # needs to be unique cache_key_featured = 'my_featuredjobs' # needs to be unique cache_time = 900 # time in seconds for cache to be valid datajobs = cache.get(cache_key) datafeatured = cache.get(cache_key_featured) if not datafeatured: cache.set(cache_key_featured, Discuss.objects.featured()[:5], cache_time) if not datajobs: cache.set(cache_key, super().get_queryset(), cache_time) return super(JobsListView,self).dispatch(request,*args,**kwargs) def get_context_data(self, **kwargs): context = super(JobsListView, self).get_context_data(**kwargs) cache_key = 'my_featuredjobs' # needs to be unique context["featured_discuss"] = cache.get(cache_key) if not context["featured_discuss"]: context["featured_discuss"] = Discuss.objects.featured()[:5] return context def get_queryset(self, *args, **kwargs): cache_key = 'my_jobs' # needs to be unique data = cache.get(cache_key) if not data: data = super().get_queryset() return data This looks awry to me. The fact that I have to do the cache.get() in all three methods, dispatch(), get_context(), get_queryset(). There must be a better way of doing this. What would be the better way to rewrite this class for better performance. -
"ValueError: year is out of range" with Django
When I started my current position, I inherited a Django Rest API that sits on top of our Postgres database. It was still running on Django v.1.7.11. Now almost two years later, I decided it's finally time to upgrade. I first upgraded to Django v1.11.29 (planning on getting it more current, but wanted to upgrade somewhat incrementally). I fixed any errors caused by the upgrade and was all set. I was able to access it and everything worked properly, except for reading data from one table. This table contains four date fields, and when accessing it's API endpoint, I get the following error: Request Method: GET Request URL: http://obis.twalk.tech:81/api/obis/occurrence/ Django Version: 1.11.29 Exception Type: ValueError Exception Value: year is out of range Exception Location: /usr/local/lib/python2.7/site-packages/django/db/utils.py in inner, line 101 Python Executable: /usr/local/bin/python Python Version: 2.7.18 From what I could tell initially with the debug output, this error was caused by having a null values in one of the date fields. I'm working in a personal development environment so I was able to change, at the database level, each instance of a null value in any of the date fields to be a properly formatted date. I still got the same … -
Got AttributeError when attempting to get a value for field `user` on serializer
I am trying to upload a csv file and then using it to populate a table in the database (creating multiple objects). serializers.py: class FileUploadSerializer(serializers.ModelSerializer): filedata = serializers.FileField(write_only=True) class Meta: model = WorkData fields = ['user', 'filedata'] def create(self, validated_data): file = validated_data.pop('filedata') data_list = csv_file_parser(file) # utility method batch = instantiate_batch_objects(data_list, validated_data['user']) # utility method work_data_objects = WorkData.objects.bulk_create(batch) # print(work_data_objects[0]) return work_data_objects views.py: class FileUploadView(generics.CreateAPIView): queryset = WorkData.objects.all() permission_classes = [IsAuthenticated] serializer_class = FileUploadSerializer def get_serializer(self, *args, **kwargs): print(kwargs.get('data')) if isinstance(kwargs.get('data', {}), list): kwargs['many'] = True return super().get_serializer(*args, **kwargs) models.py class WorkData(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='work_data', ) work = models.IntegerField(blank=False, null=False) recordTime = models.DateTimeField(blank=False, null=True) When I upload the file and post it I get this error: Got AttributeError when attempting to get a value for field user on serializer FileUploadSerializer. The serializer field might be named incorrectly and not match any attribute or key on the list instance. Original exception text was: 'list' object has no attribute 'user'. But I can see table is populated successfully in the database. What could be the source for this error? -
Django collectstatic keeps waiting when run through Github Action
We are facing a very weird issue. We ship a django application in a docker container through Github Actions on each push. Everything is working fine except collectstatic. We have the following lines at the end of our CD github action: docker exec container_name python manage.py migrate --noinput docker exec container_name python manage.py collectstatic --noinput migrate works perfectly fine, but collectstatic just keeps on waiting if ran through the github action. If I run the command directly on the server then it works just fine and completes with in few minutes. Can someone please help me figuring out what could be the issue? Thanks in advance. -
TypeError: serve() got an unexpected keyword argument 'document_root'
my problem Here the image/file that the user uploaded aren't being displayed(They are being saved though!!) when I run the site using Terminal I get an error message on Terminal TypeError: serve() got an unexpected keyword argument 'document_root' but the site runs just fine. when I open my site on chrome it displays name of the image/file and only a symbol of an image/file but i want it to display the image/file it self not a symbol. Setting.py: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' ( This only some part of the urls.py) urls.py: from django.urls import path from django.conf import settings from django.conf.urls.static import static urlpatterns += static(settings.MEDIA_URL, documnet_root=settings.MEDIA_ROOT) ( This is also some part of the html file that displays the image) file.html {% if model.image %} <image src="{{model.image.url}}"> {% endif %} -
Django. Error saving empty string to DateTimeField(blank=True)
I have a model with a DateTimeField (blank=True, null=True). However, when I try to save an empty string in it, I get the following error: >>> from courses.models import Event >>> x = Event.objects.last() >>> x.date_start = "" >>> x.save() django.core.exceptions.ValidationError: ['“” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] I have never seen this, any ideas? All my migrations are up to date. -
Django + Mongo + Docker getting pymongo.errors.ServerSelectionTimeoutError
I've been struggling to get a simple app running using Django, Djongo, Mongo, and Docker Compose. My setup looks like this: docker-compose.yml services: mongodb: image: mongo:latest restart: always environment: MONGO_INITDB_ROOT_USERNAME: root MONGO_INITDB_ROOT_PASSWORD: mongoadmin MONGO_INITDB_DATABASE: django_mongodb_docker ports: - 27017:27017 web: build: ./src restart: always command: python src/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 links: - mongodb Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 RUN mkdir /code COPY . /code/ WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'HOST': 'mongodb', 'PORT': 27017, 'USER': 'root', 'PASSWORD': 'mongoadmin', 'AUTH_SOURCE': 'admin', 'AUTH_MECHANISM': 'SCRAM-SHA-1', } } What is annoying is that I am able to use pymongo from my web container to connect to the container running mongo. That works as follows. from pymongo import MongoClient c = MongoClient( 'mongodb://mongodb:27017', username='root', password='mongoadmin', authSource='admin', authMechanism='SCRAM-SHA-1') print(c.server_info()) The issue is that when I go to run migrations from within my web container I get the following error. pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 5f9c8d338cc55e515780edb9, topology_type: Single, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused')>]> Any help on this would be greatly appreciated. -
How to edit the html page and save it at the same page using Django?
I have HTML page that contains a title and content that title, I had created an edit link that directs me to another page that should let me update the title and the content, and after editing click a button to save that update. How i can let the user do this kind of updating using Django? this is my HTML page <h1>CSS</h1> <p>CSS is a language that can be used to add style to an HTML page.</p> <ul> <li><a href="{% url 'wiki:edit' %}">Edit</a></li> </ul> -
How to write if else condition to retrieve data by querying django filter
I want to write if else condition for django filter to retrieve data by querying in django rest framework. I want to qerry data by filtering class CreateRoutineFilter(filters.FilterSet): class Meta: model = CreateRoutine fields = ('batchCode', 'roomCode') class CreateRoutineViewSet(viewsets.ModelViewSet): queryset = CreateRoutine.objects.all() serializer_class = CreateRoutineSerializer filterset_class = CreateRoutineFilter filter_backends = (django_filters.rest_framework.DjangoFilterBackend,) __basic_fields = ( 'dpt_code', 'roomCode') filter_backends = (filters.DjangoFilterBackend, OrderingFilter) filter_fields = __basic_fields def retrieve(self, request, *args, **kwargs): params=kwargs print(params['pk']) # programs = Program.objects.all() if(coursesOffered = CourseOffered.objects.filter(batchCode = params['pk'])) else: (coursesOffered = CourseOffered.objects.filter(dpt_code = params['pk'])) serializer = CourseOfferedMiniSerializer(coursesOffered, many=True) return Response(serializer.data) -
Django Rest API: View definition delete queryset
I'm still pretty new to creating views in Django Rest Framework, I can make basic views but I still have no clue about definitions so please help me out here. I've got this View which gets the answers of a question (by a given question id). The list definition works perfectly, however I want to make a delete_all function which deletes these results. You can see what I came up with below. URL router.register('manager/course/question/answers', QuestionAnswerView) http://.../manager/course/question/answers/5 works. http://.../manager/course/question/answers/delete_all/5 does not work. View class QuestionAnswerView(viewsets.ModelViewSet): queryset = QuestionAnswer.objects.all() serializer_class = QuestionAnswerSerializer # works def list(self, request): queryset = QuestionAnswer.objects.all() if request.query_params: question_id = request.query_params['question_id'] queryset = QuestionAnswer.objects.filter(question=question_id) serializer = QuestionAnswerSerializer(queryset, many=True) return Response(serializer.data) # does not work def delete_all(self, request): if request.query_params: question_id = request.query_params['question_id'] queryset = QuestionAnswer.objects.filter(question=question_id) queryset.delete() return Response('success') -
Stream multiple files with a single request using python requests
I'm using python's requests library to upload images into a server created by django / drf. It is a simple task and test script looks like this: files = { 'client_files[0]': ('415.png', open('E:\\Olaylar\\test_set\\cvat_test_small\\415.png', 'rb')), 'client_files[1]': ('422.png', open('E:\\Olaylar\\test_set\\cvat_test_small\\422.png', 'rb')), 'client_files[2]': ('485.png', open('E:\\Olaylar\\test_set\\cvat_test_small\\485.png', 'rb')) } payload = { 'image_quality': 50 } response = requests.post(post_url, auth=auth, data=payload,files=files) The problem is, I need to upload hundreds, if not thousands of images, and in a single request. So when I try to read all files into memory in order to post them, I run out of memory quite fast. I know there is a possible solution, by putting a generator in data argument of post method, and streaming the data by chunks. That would solve my problem quite well, but requests library does not support that functionality in files argument of the post method too. I will be grateful for any help or advice how to solve this problem. Thanks in advance -
Webfaction Alternative
Will Heroku work for a website that has these features? We're looking for a web host with the following features—ideally a large, stable company (been around at least 5 years)—one that charges a reasonable monthly fee for the following: Latest versions of Django and Python Has inexpensive tier of hosting appropriate for a low-traffic Django site—on a typical day there may be a handful of users (perhaps between 5 and 50?), doing low-bandwidth activities (e.g. filling out text forms) Nginx or similar service to handle static files Postgres database (ideally with user-friendly database-management software for Postgres databases) Supports having multiple working versions (development, release candidate, and production) running at the same time, using different subdomains Supports wkhtmltopdf (to convert webpages to downloadable PDF files) Supports ability to send individual emails from Django -
Django field values are not getting autopopulated in TabularInline in admin.py
can you please help me with the below query in django TabularInline: In models.py, I have model A and B class A (models.Model): Name = models.CharField(max_length=100) Location = models.CharField(max_length=100) def__(str)__(self) : return "%s" %(self.Name) class B(models.Model): Name = models.ForeignKey(A, on_delete=models.cascade) Added_by = models.ForeigKey(User, null=True,on_delete=models.cascade,related_name="Added_by") Added_date = models.DateTimeField(default=datatime.now) Modified_by = models.ForeigKey(User, null=True,on_delete=models.cascade,related_name="Modified_by") Modified_date = models.DateTimeField(editable=False,blank=True) In admin.py , class B_admin(admin.TabularInline): model = B extra = 0 readonly_fields=["Added_by","Added_date","Modified_by","Modified_date"] classes = ('grp-collapse grp-closed',) inline_classes = ('grp-collapse grp-closed',) def save_model(self, request,obj form, change): if getattr(obj, '', None) is None: obj.Added_by = request.user obj.Modified_by = request.user obj.Added_date = datetime.now() obj.Modified_date = datetime.now() else: obj.Modified_by = request.user obj.Modified_date = datetime.now() obj.save() class A_admin (admin.ModelAdmin): Inline = [B_admin] list_display = ['Name','location'] list_filter = ['Name','location'] search_fields = ['Name','location'] classes = ('grp-collapse grp-closed',) inline_classes = ('grp-collapse grp-closed',) Here , the admin page A is working fine with Model B as TabularInline. Also, the readonly_fields looks good inside TabularInline. Now the problem is when the admin page gets saved , the readonly_fields(Added_by,Modified_by,Modified_date) are showing blank and are not getting autopopulated . Added_date is working correctly since i have mentioned default=datetime.now while declaring inside model B. Other 3 fields are not getting autopopulated. Kindly assist me in this . Thanks in … -
How can i add an item to a user in django (rest framework)
I have a Teammodel and a Usermodel. Every User can belong to one or more Teams. The creation of a user with a Team is working fine. But i want to add a existing user to a existing Team. I tried several options but for every option i get an error. The Models: class Teams(models.Model): name = models.CharField(max_length=20) file = models.FileField(upload_to='team_icons', null='True', blank='True') members = models.ManyToManyField(User, related_name='member') def __str__(self): return self.name **The Serializers:** class UserSerializer(serializers.ModelSerializer): member = serializers.PrimaryKeyRelatedField(many=True, queryset=Teams.objects.all()) class Meta: model = User fields =['id', 'username', 'owner', 'password', 'todos','member', 'email', 'first_name', 'last_name',] The View class AddUserToTeam(generics.RetrieveUpdateDestroyAPIView): queryset = models.User.objects.all() serializer_class = serializers.UserSerializer permission_classes = [permissions.AllowAny] So i want: user.member.add(x), x is the team where user had to be added to -
How to display data dynamically with ant design tables
first please my javascript skill level is not good, but here... I have a table i got from ant.design, im trying to build a frontend with react, so I want to display some data on the table from my database but im finding it had because of the want ant design table is set up. This is the code class OrderSummary extends React.Component { render() { const columns = [ { title: 'Number', dataIndex: 'number', key: 'number', render: text => <a>{text}</a>, }, { title: 'Event Name', dataIndex: 'name', key: 'name', }, { title: 'Event Price', dataIndex: 'price', key: 'price', }, { title: 'Quantity', dataIndex: 'quantity', key: 'quantity', }, { title: 'Total', dataIndex: 'total', key: 'total', }, ]; const datasource = {data.order_items.map((orderItem, i) => { return ( [ { key: {orderItem.id}, number: {orderItem.item.title} -{" "}, name: 32, price: 'NGN' {orderItem.item.price} , quantity: {orderItem.quantity}, total: {data.total}, }, // { // key: 1, // name: 'John Brown', // age: 32, // address: 'New York No. 1 Lake Park', // tags: ['nice', 'developer'], // }, ]; return ( <Layout> <div> <PageHeader className="site-page-header" onBack={() => null} title="Order Summary" /> <Table columns={columns} dataSource={datasource} /> </div> </Layout> ) } }; export default OrderSummary; Note where i commented … -
I have a problem when testing my api on localhost everything went okay however when deployed to dev server and need to test it I get KeyError 'Date'
class Prayers(APIView): parser_classes = (JSONParser,) permission_classes = (rest_permissions.AllowAny,) def get(self, request): """ API for the visitorstrong text to get all prayers paginated """ data = helpers.dict_filter(request.query_params.dict(), 'date','nbdays') if "nbdays" in data : days=timedelta(days=int(data['nbdays'])) if "date" in data: date = datetime.strptime(data['date'], constants.GENERAL.DATE_FORMAT) date=date+days else: today=datetime.now() date=today+days elif "date" in data: date = datetime.strptime(data['date'], constants.GENERAL.DATE_FORMAT) days=timedelta(days=30) date=date+days else: today=datetime.now() days=timedelta(days=30) date=today+days serializer = PrayerSerializer( models.Prayer.objects.get(pk=date) ) response = { "prayer times": serializer.data, } return Response(response, status=status.HTTP_200_OK) 'API to get prayers time through filtering' -
How to avoid repetition in Django model fields?
I have models that share many common fields. For example: class Customer(models.Model): name = models.CharField() email = models.CharField() address = models.CharField() phone = models.CharField() city = models.CharField() state = models.CharField() country = models.CharField() wallet = models.FloatField() class Seller(models.Model): # same fields from Customer class, except the field wallet To avoid repeating these fields, I have tried to create classes with these common fields and link using OneToOneField: class ContactInformation(models.Model): phone = models.CharField() email = models.CharField() class AddressInformation(models.Model): address = models.CharField() city = models.CharField() state = models.CharField() country = models.CharField() class Customer(models.Model): wallet = models.FloatField() contact_information = models.OneToOneField(ContactInformation) address_information = models.OneToOneField(AddresssInformation) class Seller(models.Model): contact_information = models.OneToOneField(ContactInformation) address_information = models.OneToOneField(AddresssInformation) But now it gets very messy if I try to create a ModelForm based on the Customer, as there is only the wallet field in it. To display my other OneToOneFields I have to create multiple forms: a form for the contact information and another for address information, as ModelForms don't simply display these OneToOneFields as a single form. The views get bloated, as I have to validate 3 forms in total and have to manually create the object instances. Am I missing something here? Should I use inheritance instead? Should I …