Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
MIGRATION in mongoDB not processing, error concerning 'e'
-fit |_ bin |_ gadsonF | |__pycache | |_.. | - __init__.py, asgi.py, settings.py, urls.py, wsgi.py | |_rican | |_ migrations | |_ __init__.py | |_ admin.pu | |_ apps.py | |_ models.py | |_ tests.py | |_ views.py | manage.py | |_ lib |_ .gitignore |_ pyvenv.cfg |_ gadfitAA (webfiles ) ''' Traceback (most recent call last): File "/home/cameronnc/Desktop/fit/gadfitA/gadsonF/manage.py", line 22, in <module> main() File "/home/cameronnc/Desktop/fit/gadfitA/gadsonF/manage.py", line 11, in main from django.core.management import execute_from_command_line File "/home/cameronnc/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 52 except ImportError,e: ^ SyntaxError: invalid syntax I created a basic django app above is my file structure I have several models below: from django.db import models from django.db.models import Model class GadsonA(models.Model): """Alyssa Gadson of Puerto Rico""" Alyssa = { "race":"Caucasian", "llc":"Alyssa Gadson LLC", "height":[163, 1.63, "5ft 4 in"], "weight":[110, 130], "hair_color":"Brown", "DOB":"25 November 1989", "eye_color":"Dark Brown", "ethnicity":"Latin/Hispanic", "figure_size":"34D-25-42", "show_size":9, "home_town":"Miami, Flordia, United Stated of America", "gender":"female", "zodiac":"Sagittarius", "hobbiesInterest":['Traveling', 'Shopping', 'Selfie Lover', 'Dog Lover', 'Internet Surfing'], 'philosophy':['self help', 'spirituality', 'fitness', 'working out', 'teaching', 'blogging and acadamia'], "clothingBrands":{"Calvin Klein", "LOUIS VUITTON", "Tommy Hilfiger", "Levi Strauss & Co"}, "gadgets":["Smartphone", "DSLR Camera", "Smart Watch", "DJI Mavic Drone"], "dress_size":"38(EU)", "netWorth":200000, "profession":('fitness trainer', 'model', 'philosopher', 'teacher', 'intellectual', 'model', 'actress', 'buisness woman', 'blogger') } AmealPlan = [] … -
Fetching data from models using OneToOneField in Django
well my college is making us go learn a framework and make a website with it in a month, and it's really killing me, because of that I couldn't really get a good understanding of the Django framework as I am making progress while watching YouTube vids and reading docs. Anyways my models are all messed up which made the job even harder, and whenever I solve a problem another one arises, but the deadline is close and making any changes to the models will cost me a great deal of time. This time my problem is about fetching data. The concerned models are the following: The User class for authentication class User(AbstractBaseUser, PermissionsMixin): id = models.AutoField(primary_key=True,null=False) username = models.CharField(max_length=50) email = models.EmailField(unique=True) nom = models.CharField(max_length=255) prenom = models.CharField(max_length=255) usertype = models.CharField(choices=types,max_length=20,default="user") date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) student_data = models.OneToOneField(Etudiant, on_delete=models.CASCADE,blank=True, null=True,related_name='Etudiant_access') Prof_data = models.OneToOneField(Prof, on_delete=models.CASCADE,blank=True, null=True) objects=UserManager() def __str__(self): return self.prenom + " " + self.nom USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] The Students(Etudiant) class for managing the students: class Etudiant(models.Model): filiere = models.ForeignKey(Filiere, on_delete=models.DO_NOTHING) classe = models.ForeignKey(Classe,null=True, on_delete=models.DO_NOTHING) notes = models.ManyToManyField(note,blank=True, null=True) The class Classe (LMAO) for managing … -
How to create Tests for Class Based views in Django
This question might be a little too simple idk. I am very new to testing. I recently made a Django project using all Class-Based views. While I am pretty familiar with Django I am not very familiar with the class-based views so decided to use them in my recent project. I am learning Testing and implemented pytest in one of my FastAPI projects recently. I would say writing tests were easier than I expected or maybe my application was too simple. While there are thousands of pytest courses or testing courses in general available online. I have not seen any focusing on Django class-based views. I am asking this because in class-based views there is a lot of inheritance of prebuilt methods and Views. Will I be able to create tests for class-based views if I go through a good pytest course or do you suggest any particular resource that is specific to the class-based views? I am asking because I want to present this project in an interview and that company seems to care a lot about testing. Here is the Github repo of the project I want to implement tests on: https://github.com/sumitdadwal/django-bookstore-project Also, this is the course I … -
django database path : no unsupported opperand type
In the django settings.py, the database is by default : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } But when i do in python a={'a':'a'/'b'}, i get the error TypeError: unsupported operand type(s) for /: 'str' and 'str'. How come the error doesnt show up in django? I would like to define a different path for my database, in a subfolder so as django automatically create the subfolder and the sqlite database...how can i do that? thank you -
Redirect specific view based on a field django
I need to redirect after login to a specific view according to the "Profesor" field, if this is False, redirect to "vistaAlumno", if True, redirect to "vistaProfesor". views.py def profesor(user): return (user.profesor) @login_required @user_passes_test(profesor) def vistaProfesor(request): rut= request.user.rut_user notas = Nota.objects.select_related('id_asignatura','rut_alumno').filter(rut_profesor=rut) observaciones = Observacion.objects.filter(rut_profesor=rut) return render(request, 'core/vistaProfesor.html', {'notas': notas, 'observaciones': observaciones}) @login_required def vistaAlumno(request): if request.user.profesor == False: rut= request.user.rut_user notas = Nota.objects.select_related('id_asignatura').select_related('rut_profesor').filter(rut_alumno=rut) asistencias = Asistencia.objects.filter(rut_alumno=rut) #Necesito unir la tabla observacion con profesor, lo cual ya hace, pero luego quiero unir la tabla profesor con asignatura y mostrar el nombre en el vistaAlumno.html observaciones = Observacion.objects.select_related('rut_profesor').filter(rut_alumno=rut) curso = Alumno.objects.filter(rut_alumno=rut).values_list('id_curso') horarios = Horario.objects.select_related('rut_profesor','id_asignatura','id_sala').filter(id_curso__in=curso) return render(request, 'core/vistaAlumno.html', {'notas': notas, 'asistencias': asistencias, 'observaciones': observaciones, 'horarios': horarios}) else: vistaProfesor(request) models.py class User(AbstractUser): profesor = models.BooleanField(default=False) rut_user = models.IntegerField(null=True) settings.py LOGIN_REDIRECT_URL = '/vistaAlumno' -
django like button not showing up
I been trying to implement a like button to my django blog but it dosent show up. Anyone got any ideas why the like button wont show up on my blogposts? would really appreciate if someone could help me on this one. newsapp folder views.py from django.shortcuts import render, get_object_or_404, redirect from django.views import generic from .models import Post, Like from .forms import CommentForm class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' paginate_by = 6 def post_view(request): qs = Post.objects.all() user = request.user context = { 'qs': qs, 'user': user, } return render(request, 'newsapp/main.html', context) def like_post(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() return redirect('newsapp:post-list') def post_detail(request, slug): template_name = 'post_detail.html' post = get_object_or_404(Post, slug=slug) comments = post.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: … -
Add foreign key to one-to-one model (Extended User Model)
My porpouse is allow users from Client model to login. I extended User model with one-to-one relationship as Django Documentation says. Client model: class Client(models.Model): name = models.CharField(max_length=45) surname = models.CharField(max_length=45) address = models.CharField(max_length=45) email = models.EmailField(max_length=50, blank=False, null=False, default='example@example.com') Extended User: from django.contrib.auth.models import User class ExtendedUser(models.Model): user = models.OneToOneField(User, on_delete=models.DO_NOTHING) # client = models.ForeignKey('Client', on_delete=models.DO_NOTHING, blank=True, null=True) class Meta: managed = True db_table = 'extended_user' On Client table (mysql) I have rows. When I use python manage.py migrate terminal shows me django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint'). If I don't write ForeignKey line it don't have error, but I need this ForeignKey. What is wrong here? I tried different parameters on ForeignKey line but nothing. -
Field.__init__() got an unexpected keyword argument 'max_lenght'
I am trying to create an app that would accept an input. views.py: from django.views import generic from .models import GitHubInput class DetailView(generic.DetailView): model = GitHubInput models.py: from django.db import models class GitHubInput(models.Model): body = models.CharField(max_lenght=500) def __str__(self): return f"(self.body)" I get the following error: class GitHubInput(models.Model): File "/Users/swantewit/Dev/tryDjango/git_hub_repo/git_hub/models.py", line 4, in GitHubInput body = models.CharField(max_lenght=500) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/fields/__init__.py", line 1097, in __init__ super().__init__(*args, **kwargs) TypeError: Field.__init__() got an unexpected keyword argument 'max_lenght' Couldn't find anything in the documentation that would help me. Perhaps I am using a too old tutorial? https://www.youtube.com/watch?v=fblkFtsNg6E 1:10 -
Django database query: how to get multiple objects by id?
i want to get a filtered object with several id's that i will specify TestQuestionBlok.objects.filter() How to write this filter? -
How to send formData from React Native to Django REST using axios
I have a form that is sent as JSON currently. I need to switch it over to using a FormData object since i need to add a file to the request. Django Rest ModelViewSet: class BusinessProfileViewSet(MixedPermissionModelViewSet): """ API endpoint that allows business profiles to be viewed, created, or edited. """ queryset = BusinessProfile.objects.all().order_by('-created_on') serializer_class = BusinessProfileSerializer permission_classes_by_action = { 'list': [IsOwnerOrStaff], 'create': [AllowAny], 'update': [IsOwnerOrStaff], 'retrieve': [IsOwnerOrStaff], 'partial_update': [IsOwnerOrStaff], 'destroy': [IsAdminUser] } paginator = None parser_classes = (MultiPartParser, FormParser,) React-Native: const createFormData = (businessTypes, input) => { const phone = formatPhoneNumForSubmission(input.phone); const typeId = convertBusinessTypeToID(businessTypes); const formData = new FormData(); formData.append("name", input.name); formData.append("type", typeId); formData.append("email", input.email); formData.append("phone", phone); formData.append("street_address", input.street_address); formData.append("city", input.city); formData.append("state", input.state); formData.append("zip_code", input.zip_code); return formData; }; const handleSubmit = () => { const formData = createFormData(businessTypes, newInput); dispatch(createBusiness(formData)); } }; Redux dispatch using axios: export const createBusiness = createAsyncThunk( "business/createBusiness", async (body, { rejectWithValue }) => { try { const response = await axiosInstance.post("/api/businesses/", body); return response.data; } catch (err) { console.log(err.response.data); return rejectWithValue(err.response.data); } } ); Output of console.log(formData): Form data: FormData { "_parts": Array [ Array [ "name", "Dqwd", ], Array [ "type", 1, ], Array [ "email", "qwd@dw.co", ], Array [ "phone", "+115598983333", ], … -
how to customize the response of a api from retrieve function in mixin
I'm a beginner to Django, i have written a class-based API view with mixin. the functionality is simple i.e fetch the data of the given id.Im pasting the code below. class GenericAPi(generics.GenericAPIView,mixins.ListModelMixin,mixins.RetrieveModelMixin): serializer_class=ArticleSerializer queryset=Article.objects.all() lookup_field="id" def get(self,request,id): if id: data=self.retrieve(request) return Response({"data":data.data,"status":data.status_code}) else: return self.list(request) this is the response I'm getting {"id":5,"title":"loream","author":"me"} then I navigate to the retrieve function in the mixin, to make some changes in the response. def retrieve(self, request, *args, **kwargs): print('Retrieving') instance = self.get_object() serializer = self.get_serializer(instance) return Response({"result":serializer.data}) and then I make a call to API, but still, I'm getting the same response. How to customize the response in the retrieve function itself. I need response like this. {"result":{"id":5,"title":"loream","author":"ipsum"}} -
How can I check the health status of my dockerized celery / django app?
I am running a dockerized django app using the following dockerfile: services: web: build: context: . dockerfile: Dockerfile.prod command: gunicorn PriceOptimization.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles networks: - dbnet ports: - "8000:8000" environment: aws_access_key_id: ${aws_access_key_id} redis: restart: always image: redis:latest networks: - dbnet ports: - "6379:6379" celery: restart: always build: context: . command: celery -A PriceOptimization worker -l info volumes: - ./PriceOptimization:/PriceOptimization depends_on: - web - redis networks: - dbnet environment: access_key_id: ${access_key_id} nginx: build: ./nginx ports: - "80:80" volumes: - static_volume:/home/app/web/staticfiles depends_on: - web networks: - dbnet database: image: "postgres" # use latest official postgres version restart: unless-stopped env_file: - ./database.env # configure postgres networks: - dbnet ports: - "5432:5432" volumes: - database-data:/var/lib/postgresql/data/ # persist data even if container shuts down volumes: database-data: static_volume: media_volume: I have added celery.py to my app, and I am building / running the docker container as follows: docker-compose -f $HOME/PriceOpt/PriceOptimization/docker-compose.prod.yml up -d --build Running the application in my development environment lets me check at the command line that the celery app is correctly connected, etc. Is there a way that I can test to see if my celery app is initiated properly at the end of the build process? -
Django query with relative time using database's clock
I'm trying to find all the ORM objects updated in the last 30 seconds. The standard way to do this would be: reftime = timezone.now() - relativedelta(seconds=30) queryset = MyModel.objects.filter(updated_at__gte=reftime) This works so long as all the application servers running the django app have their clocks synchronized, which sounds easy but in practice really isn't. Clock skew is real. Fortunately the database server has a single clock which we should be able to rely on as the definitive clock for this kind of thing. And django has this nice object called Now() in django.db.models.functions which seems like it should be helpful for this kind of thing. But I've never seen any code sample for this method that does any math to shift the time by something like 30 seconds. e.g. this does NOT WORK: reftime = django.db.models.functions.Now() - relativedelta(seconds=30) How can I do a django ORM query using a timestamp relative to the SQL server's clock? -
expected str, bytes or os.PathLike object, not HttpResponse
I need to convert a csv file to an ofx file in my django application, but there was an error when i try to convert it. the error is: expected str, bytes or os.PathLike object, not HttpResponse this is my views.py: def UploadFile(request): if request.method == 'POST': form = BlogForm(request.POST,request.FILES) if form.is_valid(): form.save() ofx = OFX(mapping) records = read_csv(request.FILES, has_header=True) groups = ofx.gen_groups(records) trxns = ofx.gen_trxns(groups) cleaned_trxns = ofx.clean_trxns(trxns) data = utils.gen_data(cleaned_trxns) content = it.chain([ofx.header(), ofx.gen_body(data), ofx.footer()]) filenamee = form.cleaned_data.get("filename") response = HttpResponse(content_type='text/ofx') content_disposition = f'attachment; filename=filenamee.ofx' response['Content-Disposition'] = content_disposition res = write(response, IterStringIO(content)) return res else: form = BlogForm() context = { 'form':form, } return render(request, 'pages/Upload.html', context) any help will be appreciated. thanks in advance. -
Changing an image name in django
So I have 5 images as static files and I want to randomly select an image to display when I press a button. I'm having problems with getting the imagename update. When I hard code the name into html it does work. In my views I have: def test(request): imagename = 'img' + str(random.randint(0,5)) + '.jpeg' #all the images end with jpeg so this can't be the problem print(imagename) return render(request, 'mainbook/index.html', {'image': imagename}) In urls.py I have urlpatterns = [path('test/', views.test, name='test')] And finally in index.html I have: <form method="post" action="{% url 'mainbook:test' %}"> {% csrf_token %} <button id="button">Press here</button> </form> <img src="{% static '/mainbook/images/{{image}}' %}"></img> This is of course a simplified version but I do think the problem is somewhere in this code. I just don't know where exactly. -
How do I upload images on django?
I have been trying to upload an image in Django using a custom view and I'm failing. The admin panel is letting me upload though, what could be the problem? I have installed Pillow and made sure that the form has the multipart/form-data property. Am I supposed to make a separate model for images? models.py class Profile(models.Model): username = models.OneToOneField(User, on_delete=models.CASCADE) gender = models.TextField(max_length=10) dob = models.DateField(null=True, blank=True) phone_no = models.CharField(unique=True, max_length=9) address = models.CharField(max_length=50) profile_pic = models.ImageField(null=True, blank=True, upload_to="profile_pic/") nrc_front = models.ImageField(null=True, blank=True, upload_to="nrc_front/") nrc_back = models.ImageField(null=True, blank=True, upload_to="nrc_back/") is_verified = models.BooleanField(default=False) is_group_admin = models.BooleanField(default=False) is_group_member = models.BooleanField(default=False) temp_code = models.CharField(max_length=6, null=True, blank=True) def __str__(self): return str(self.username) settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join( BASE_DIR / 'media' ) view.py def updateProfilePic(request): profiledata = get_profile_data(request) form = UpdateProfilePicForm() if request.method == "POST": form = UpdateProfilePicForm(request.POST, request.FILES) if form.is_valid(): profile_pic = form.cleaned_data.get("profile_pic") Profile.objects.filter(username=request.user).update(profile_pic=profile_pic) return redirect('profile') else: form = UpdateProfilePicForm() context = { "profiledata":profiledata, "form":form } return render(request, 'base/profile-update-picture.html', context) template {% extends 'base/base.html' %} {% block title %}Update Picture{% endblock %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <div class="form-container shadow p-3 mb-5 bg-white rounded mx-auto"> {% crispy form %} </div> </div> {% endblock %} browser rendering <form … -
How to convert Date().toLocaleString() to YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]
I am trying to make an axios post request to django datetimefield, it requires the datetime format of YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]. I am currently getting the format Sun May 29 2022 02:42:00 GMT+0800 (香港標準時間) from Date().toLocaleString() in reactjs. The (香港標準時間) means Hong Kong Time. Anybody has an idea on converting the date format in Reactjs? Much thanks. -
Cannot assign "'user_name'": "Class.user" must be a "Account_class" instance
enter image descripI am getting this error when I try to make a post requesttion here How to can I solve this problem? Here is my model: class Coffee(models.Model): name = models.CharField(max_length=60) ratings = models.CharField(max_length=5) taste = models.TextField() coffeeType = models.CharField(max_length=60) price = models.CharField(max_length=60) img = models.CharField(max_length=200) updated_at = models.DateTimeField(auto_now_add=True) shopName = models.CharField(max_length=60) coffeeShopID = models.CharField(max_length=200) location = models.CharField(max_length=200) user = models.ForeignKey(Account, on_delete=models.CASCADE, null=False, blank=False, related_name='user') def __str__(self): return self.name[0:50] class Meta: ordering = ['-updated_at'] Here is the serializer of that model: class CoffeeSerializers(serializers.ModelSerializer): class Meta: model = Coffee fields = '__all__' Here is views for post request: def addCoffee(request): data = request.data coffee = Coffee.objects.create( name=data['name'], ratings=data['ratings'], taste=data['taste'], coffeeType=data['coffeeType'], price=data['price'], img=data['img'], shopName=data['shopName'], coffeeShopID=data['coffeeShopID'], location=data['location'], user=data['user'] ) coffee.save() serializer = CoffeeSerializers(coffee) return Response(serializer.data) -
Email Verification on Django withou API
I'm trying to implement email verification using Django without an API. I included the following items in my settings.py file: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'stmp@gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'my_email@gmail.com' EMAIL_HOST_PASSWORD = 'my_password' DEFAULT_FROM_EMAIL = 'default from password' Below is my views.py file. I'm sending an email to the user who's registering here. from rest_framework.views import APIView from rest_framework.response import Response from .serializers import UserSerializer from django.contrib.auth.models import User from django.contrib.auth import authenticate from rest_framework.permissions import AllowAny from django.core.mail import send_mail class TestView(APIView): def get(self, request, format=None): print("API called") return Response("You did it!", status=200) class RegisterView(APIView): permission_classes = [AllowAny] def post(self, request, format=None): print("Registering User") user_data = request.data print(request.data) user_serializer = UserSerializer(data=user_data) if user_serializer.is_valid(raise_exception=False): user_serializer.save() send_mail( 'Verify Your All-in-one Account', 'Hi!', 'allinonehealthapp22@gmail.com', user_data['email'], fail_silently=False, ) return Response({'User': user_serializer.data}, status=200) return Response({'msg': "error: User not registered"}, status=400) class UserLoginView(APIView): permission_classes = [AllowAny] # convert user token to user data def get(self, request, format=None): if request.user.is_authenticated == False or request.user.is_active == False: return Response('Invalid credentials', status=403) user = UserSerializer(request.user) print(user.data) return Response("Testing", status=200) def post(self, request, format=None): print("Login class") # Looking for user's email or username user_obj = User.objects.filter(email=request.data['username']).first( ) or User.objects.filter(username=request.data['username']).first() # if user is valid, … -
Django ratelimit custom functions
How can I put a custom function for the method in django-ratelimit? I want it to be like this: I filled out a form. Then check if the length of the name is less than 5. If the length of the name is less than 5 then as many times as we fill the form it will never block the user. But if the length is bigger every time and he fills the form 5 times then the limiter will block the user from accessing the page. Something like flask-limiter cost function. Thanks. -
cannot underustand django custom authenticaton backend
I am trying to learn from book django 3 by example but i cannot understand few points in django custom authentication like why username and password is passed None and email=username and why we are using get_user Here is the code from django.contrib.auth.models import User class EmailAuthBackend(object): #Authenticate using an e-mail address def authenticate(self,request,username=None,password=None): try: user=User.objects.get(email=username) if user.check_password(password): return user return None except User.DoesNotExit: return None def get_user(self,user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExit: return None -
Django DetailView get one record from QuerySet
Please help me get one record from QuerySet object. views.py: from django.contrib.postgres.aggregates import ArrayAgg from django.http import JsonResponse, from django.views.generic.list import ListView from django.views.generic.detail import DetailView from movies.models import Book class BooksMixin(ListView): model = Book http_method_names = ['get'] def get_queryset(self): books = Book.objects.values().annotate(authors=ArrayAgg('authors__name',distinct=True) return books def render_to_response(self, context, **response_kwargs): return JsonResponse(context) class BooksDetail(BooksMixin, DetailView): def get_context_data(self, *, object_list=None, **kwargs): queryset = self.get_queryset() context = queryset.get(id=self.kwargs['pk']) return context urls.py: from django.urls import path from books import views urlpatterns = [ path('books/<uuid:pk>/', views.BooksDetail.as_view()), ] This works, but I want to get one record from the queryset inside the BooksDetail class more elegantly, without using the kwargs['pk'] filter. I tried to use construct like class BooksDetail(BooksMixin, DetailView): def get_context_data(self, *, object_list=None, **kwargs): queryset = self.get_queryset() context = super(BooksDetail, self).get_context_data(**kwargs) context['bla'] = queryset return context but got the error: 'BooksDetail' object has no attribute 'object' -
Access "upload_to" of a Model's FileFIeld in Django?
I have a Model with a FileField like that: class Video(MediaFile): """ Model to store Videos """ file = FileField(upload_to="videos/") [...] I'm populating the DB using a cron script. Is it possible to somehow access the "upload_to" value of the model? I could use a constant, but that seems messy. Is there any way to access it directly? -
Reduce database queries while render inclusion tag
I have model which represent tweets in my app and view which returns queryset with them. class Tweet(MPTTModel): text = models.CharField(max_length=140, db_index=True) pub_date = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, blank=True, related_name='liked_tweets', through='TweetLike') retweets = models.ManyToManyField(User, blank=True, related_name='retweeted_tweets', through='TweetRetweet') bookmarks = models.ManyToManyField(User, blank=True, related_name='bookmarked_tweets', through='TweetBookmark') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='tweets') parent = TreeForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, related_name='children') Each tweet renders with inclusion tag which includes another inclusion tag. This tag displays participants in the correspondence above the tweet text like in original twitter. @register.inclusion_tag('tweets/_reply_to_snippet.html') def reply_to(tweet, current_user): # Finds all ancestors for each tweet in queryset and then tweet owners. tweets_ancestors = tweet.get_ancestors().exclude(user=tweet.user) users_ancestors = CustomUser.objects.filter(tweets__in=tweets_ancestors). \ distinct() return { 'current_user': current_user, 'tweet_id': str(tweet.id), 'users': users_ancestors } And this tag hits database with new query for every tweet. I tried to play with prefetch_related in view, but seems it won't solve my problem. Now i have idea to add one more attr to view qs with users_ancestors or their ids, but didn't find right way to resolve this. -
Serializer data's "id" field returns null DRF
I've been running into an issue with a serializer I made for a particular model. This is the model: # Create your models here. class UserInfo(models.Model): id = models.IntegerField(primary_key=True, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=120, null=False) This is the serializer: class OnboardSerializer(serializers.ModelSerializer): class Meta: model = UserInfo fields = ('id', 'user', 'name', 'username') extra_kwargs = {'id': {'required': True}} This is the view: class OnboardAPI(generics.GenericAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = OnboardSerializer authentication_classes = (TokenAuthentication,) def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) When we try to run the OnboardAPI endpoint, we get the following error when we send this body { "id": 6, "user": 6, "name": "Muse" } django.db.utils.IntegrityError: null value in column "id" of relation "users_userinfo" violates not-null constraint DETAIL: Failing row contains (null, Muse, 6). It seems like the id column is not serialized, how do we fix this? Thank you!