Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django project - OPEN MODAL FROM BOOTSTRAP CARD
I'm working on a django project in which i have several bootstrap cards that display some datas that i get from the database. More precisely each cards represents a project, so it has its title, its description, its deadline and so on. At the end of the card i put a button to open a modal to show more details of the project that aren't displayed in the card. My problem is that I don't know how to take the right information of the cards for each modal, for example even if i click on the button of the third card to open the modali to view the detail of the third projects, the modal still shows me the data of the first project (so it takes them from the first card). Can anyone help me please? -
ReactJS - URL Paramaters to filter a search query
firstly, apologies for the horrible question title (edit suggestions welcome!) I'm very new to React and programming as a whole. As a side task, I've been asked to research how to include some date filters into a demo project my company has (I don't work in tech but want to learn). The idea is go filter some incoming messages so only messages between 2 certain dates are displayed. Basically I've been told that the filters are up and ready (Django back-end) to be used with the React front-end. However after fixing a few bugs here and there I can't figure out how to make the date filters actually filter the results. Django query filters: class ViewMessages(APIView): authentication_classes = (TokenAuthentication, SessionAuthentication) permission_classes = (permissions.MessagePermissions,) def limit_by_parameter(self, data): """ Include only those results which match all parameters (except search) """ query_set = DataMessage.objects.all() # Start with all email objects try: if data.get('id'): query_set = query_set.filter(pk=data.get('id')) if data.get('exhibit'): query_set = query_set.filter(exhibit_id=data.get('exhibit')) # Filter by foreign key if data.get('case'): query_set = query_set.filter(exhibit_id__case_id=data.get('case')) # Filter by foreign key (once removed) if data.get('source'): query_set = query_set.filter(data_source__iexact=data.get('source')) if data.get('datetime'): query_set = query_set.filter(datetime__gte=data.get('datetime')) if data.get('datetime_lower'): query_set = query_set.filter(datetime__gte=data.get('datetime_lower')) if data.get('datetime_upper'): query_set = query_set.filter(datetime__lte=data.get('datetime_upper')) if data.get('message_type'): query_set = query_set.filter(data_type__iexact=data.get('message_type')) … -
How can one serializer display information from another serializer?
After defining image model and like model, I will create a serializer corresponding to each and show it to PostSerializer. By the way, I put ImageSerializer and LikeSerializer in the PostSerializer field, but JSON does not display any information about these serializers. How can I display this information? Here is my code. models.py class Post (models.Model) : author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='author', null=True) title = models.CharField(max_length=40, null=True) text = models.TextField(max_length=300, null=True) tag = models.CharField(max_length=511, null=True) view = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) def __str__ (self) : return self.title @property def comment_count (self) : return Comment.objects.filter(post=self.pk).count() @property def like_count (self) : return Like.objects.filter(post=self.pk).count() class Image (models.Model) : post = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True) class Like (models.Model) : liker = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True) serializers.py class AuthorSerializer(serializers.ModelSerializer): profile = serializers.ImageField(use_url=True) class Meta: model = User fields = ('username', 'email', 'profile') class ImageSerializer (serializers.ModelSerializer) : image = serializers.ImageField(use_url=True) class Meta : model = Image fields = ('image') class LikerSerializer (serializers.ModelSerializer) : id = serializers.CharField(source='liker.pk') class Meta : model = Like fields = ('id') class PostSerializer (serializers.ModelSerializer) : author = AuthorSerializer(read_only=True) image = ImageSerializer(read_only=True, many=True) like_count = serializers.ReadOnlyField() liker = LikerSerializer(read_only=True, many=True) comment_count = serializers.ReadOnlyField() class Meta : model … -
how do i show individual questions in Django template like in online exam using next and previous buttons?
All questions are in Questions table. I am able to display one question but i need to display next questions one by one by clicking and next button like in online exam. Please answer my question. should i use java script for next and previous buttons. please post script also if need. Thank you views.py: def render_questions(request): questions = Questions.objects.all() ques_list = [] for question in questions: ques = {} ques['question'] = question.questions ques['option_a'] = question.option_a ques['option_b'] = question.option_b ques['option_c'] = question.option_c ques['option_d'] = question.option_d ques['answer'] = question.answers ques['ques_no'] = str(question.qs_no) ques_list.append(ques) print(f'{ques_list}', flush=True) return render(request, 'report.html', {'ques': ques_list}) template.html: <form action="answer" method="POST"> {% csrf_token %} {% for question in ques %} {% if forloop.first %} <table cellspacing="15"> <tr> <td><input type="hidden" name="ques_id" value="{{question.ques_no}}">{{ question.ques_no }}</td> <td>{{ question.question }}</td> </tr> <tr> <td><input type="radio" name="answer" value="{{question.option_a}}"></td><td style="padding-bottom:8px;padding-right:5px;"> {{ question.option_a }}</td> </tr> <tr> <td><input type="radio" name="answer" value="{{question.option_b}}"></td><td style="padding-bottom:8px;padding-right:5px;">{{ question.option_b }}</td> </tr> <tr> <td><input type="radio" name="answer" value="{{question.option_c}}"></td><td style="padding-bottom:8px;padding-right:5px;">{{ question.option_c }}</td> </tr> <tr> <td><input type="radio" name="answer" value="{{question.option_d}}"></td><td style="padding-bottom:8px;padding-right:5px;">{{ question.option_d }}</td> </tr> </table> <a href='answer'> <input type="submit" value="submit"></a><br> <input type="button" value="next">Next <input type="button" value="previous">Previous {% endif %} {% endfor %} -
Move data from one model to another model on a button click
I have two models, Draft and Post. On "Draft" detail page, I need a publish button that moves data from draft to model Post -
in django i have made models but on commenting in blog i found error
class BlogComment(models.Model): sno=models.AutoField(primary_key=True) comment=models.TextField() user=models.ForeignKey(User, on_delete=models.CASCADE) post=models.ForeignKey(Post, on_delete=models.CASCADE) parent=models.ForeignKey('self',on_delete=models.CASCADE,null=True, blank=True) timeStamp=models.DateTimeField(default=now) Why this error is showing while commenting IntegrityError at /blog/postComment NOT NULL constraint failed: blog_blogcomment.comment -
Django responsive template not working on mobile - static files copied exactly and code including viewpoint checked line by line
The raw template I downloaded shows responsive in browser but when I implemented the same code on my pythonanywhere app it is not showing correctly on mobile. I copied all the static files exactly and checked template code line by line and cannot find any difference to cause this. The viewpoint tag is also included. The problem is that it is not using device width as the width. I attached two pictures to compare. In the original template it is using the device width 414 and in my app it is using width 980 despite the device width 414. Not sure where it is getting the 980 width from. {% load static %} <!DOCTYPE html> <html class="no-js" lang="zxx"> <head> <meta charset="uft-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>{% block title %}title{% endblock title %}</title> <meta name="description" content=""> <meta name="viewpoint" content="width=device-width, initial-scale=1"> <link rel="manifest" href="site.webmanifest"> <link rel="shortcut icon" type="image/x-icon" href="{% static 'assets/img/favicon.ico' %}"> <!-- CSS here --> <link rel="stylesheet" href="{% static 'assets/css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/owl.carousel.min.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/flaticon.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/slicknav.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/animate.min.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/magnific-popup.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/fontawesome-all.min.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/themify-icons.css' … -
Sending JSON object to Django server (Client-side submission)
After submitting a form, the field values are wrapped inside a JSON object but nothing happens when I submit the form. I want a new Email object to be created and display the messages accordingly as defined in views.py. Does anyone know what is going wrong? It is supposed to send a JSON response after the submit button on form is clicked. Views.py @csrf_exempt @login_required def compose(request): # Composing a new email must be via POST if request.method != "POST": return JsonResponse({"error": "POST request required."}, status=400) # Check recipient emails data = json.loads(request.body) return HttpResponse(request.body) emails = [email.strip() for email in data.get("recipients").split(",")] if emails == [""]: return JsonResponse({ "error": "At least one recipient required." }, status=400) # Convert email addresses to users recipients = [] for email in emails: try: user = User.objects.get(email=email) recipients.append(user) except User.DoesNotExist: return JsonResponse({ "error": f"User with email {email} does not exist." }, status=400) # Get contents of email subject = data.get("subject", "") body = data.get("body", "") # Create one email for each recipient, plus sender users = set() users.add(request.user) users.update(recipients) for user in users: email = Email( user=user, sender=request.user, subject=subject, body=body, read=user == request.user ) email.save() for recipient in recipients: email.recipients.add(recipient) email.save() return JsonResponse({"message": "Email … -
If statement on a Model.field
hopefully this is clear. I am trying to put together a view that takes care of what happens when a user places a bid on an active listing on the auction site I am trying to build. I'm doing an if statement to tackle what happens if a user tries to bid on a closed listing but pylint keeps throwing a syntax error on the line that reads: if auction.status is not 'active': I have tried: if auction.status is closed: if auction.status.closed: Is it a keyword that I'm missing or parentheses? models.py class Listing(models.Model): class NewManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='active') options = ( ('active', 'Active'), ('closed', 'Closed'), ) title = models.CharField(max_length=64) description = models.TextField(max_length=64) price = models.DecimalField(max_digits=9, decimal_places=2, validators=[MinValueValidator(0.99)]) image = models.URLField(max_length=200, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="listings") lister = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None, null=True, blank=True) status = models.CharField(max_length=10, choices=options, default="active") favourites = models.ManyToManyField(User, related_name="favourite", default=None, blank=True) objects = models.Manager() listingmanager = NewManager() def __str__(self): return f"Product: {self.title} \nDescription: {self.description} \nCurrent Price: £{self.price}\nImage: {self.image} \nCategory: {self.category} \nListed by: {self.lister}" class Bid(models.Model): bidder = models.ForeignKey(User, on_delete=models.CASCADE, related_name="bidders") item = models.ManyToManyField(Listing, related_name="bid_item", default=None, blank=True) price = models.DecimalField time = models.TimeField() views.py def bidding(request, listing_id): bid_item = get_object_or_404(Listing, pk=listing_id) bid_item.resolve() bidding = Bid.objects.filter(bidder=request.user.filter(listing=listing).first() if … -
celery: migrating from AMQP to rabbitmq queue system
I am updating an old Django app. Can anyone please direct me to a guide that explain how to migrate celery from the AMQP queue system (deprecated) to rabbitmq. Thank you very much for your help -
Django: Use query result in future queries instead of repeating it
I have a custom user profile model. This model has can_edit property that uses ContentType and Permission objects to determine if the user has permission or not. I'm using this property within serializer and it works fine, but is terribly inefficient, as per each user the ContentType and Permission are queried again. It seems like prefetch_related could fit here, but I don't know how to apply it, as these objects are not referenced directly through some properties, but kinda queried separately. Is it possible to fetch the ContentType and Permission beforehand and just use the results in further queries? Here's my model: class CustomProfile(models.Model): user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) @property def can_edit(self): content_type = ContentType.objects.get_for_model(Article) permission, _ = Permission.objects.get_or_create( codename="edit", name="Can edit", content_type=content_type ) return self.user.has_perm(self._permission_name(permission)) def _permission_name(self, permission): return f"{permission.content_type.app_label}.{permission.codename}" My current query: User.objects.order_by("username").select_related("profile") My serializer: class UserSerializer(serializers.ModelSerializer): can_edit = serializers.ReadOnlyField(source="profile.can_edit") class Meta: model = User fields = ( "id", "username", "first_name", "last_name", "is_active", "is_staff", "can_edit", ) In fact, I have more than one property with similar content to can_edit, so each user instance adds around 6 unnecessary queries for ContentType and Permission. How can I optimize it? -
Data is not saving to the database but shows on terminal in Django
So i have been trying to add Tags using django-taggit, but for some reason tags are not saving to the database when i try to upload a post using website but it works perfectly with django admin(Tags are saving to the database). Also when i go to my Post_edit view and try to update empty tags field then it works. In other words, tags are only saving to the database when i try to edit it using Postedit view or upload it using admin. I want it to save to the database using PostUpload view only(like i have to use PostEdit view for every post to display tags). Also i can see request.POST data is returning the list of Tags on the terminal and form returns no errors. Everything else is saving to the database except Tags. here's my code Views.py Uploading Posts( views.py ) @login_required(login_url="/login/") def post_upload(request): index1 = Blog.objects.all().order_by('-time')[0] content = request.POST.get('content') title = request.POST.get('title') image = request.FILES.get('image') if request.method == 'POST': post_form = PostUpload(request.POST, request.FILES, instance=request.user) if post_form.is_valid(): tags = post_form.cleaned_data['tags'] context = post_form.cleaned_data['context'] excerpt_type = post_form.cleaned_data['excerpt_type'] ins = Blog.objects.create(user=request.user, content=content, title=title, image=image, context=context, tags=tags, excerpt_type=excerpt_type) ins.save() messages.success(request, 'Your Post has been successfully posted') print(request.POST) print(tags) return … -
Django ajax post modal boostrap form
i want to use ajax in boottsrap modal popup form, i found a few doc but it was not clearly. I wan to use ajax form with popup window, for post some models with this window, have can i do it the best way? thansk. -
Cannot create container for service web: status code not OK but 500 ..Encountered errors while bringing up the project
Please watch the screenshot of Dockerfile and docker-compose.yml along with directory structure Dockerfile docker-compose.yml I used that following command in the gitbash terminal Windows 10 after creating django project successfully to now run into docker desktop. $ docker-compose up -d --build After that this is the error which Im facing , error is messy so I m posting a Screenshot please go throught that and help me to fix that. Thank You Error Screenshot -
How to do you pass a variable that contains a 2D array from a python file into the django views file as a context for a specific view?
The time table displayed below will be stored in a 2D array in a variable called dayPlan: "return dayPlan" Now I need to access this variable within this the views file: the path for this file is: django_project-->blog-->views.py This is my import statement in my views file: from django_project.Outer_Code.TimeTable import timeTable This is where I am trying to access the timetable variable: variable accessing This is the structure of my files: Main directories Where the views file exists: Views file Where the variable I am trying to access exists: Variable location I have tried many different import statements in order to access the class which contains the variable 'dayPlan' so that I can use it in the website, but I keep getting this error: from django_project.Outer_Code.TimeTable import timeTable ModuleNotFoudError: No module named 'django.project.Outer_Code' Any help in fixing this error will be useful. -
Django debug toolbar not appearing when using with nginx server
I am using django debug toolbar in server. When i use virtualenv it shows the debug toolbar. But when using gunicorn and nginx, it doesn't show the debug toolbar. Is it because of reverse proxy? INTERNAL_IP=[my device ip address] and Debug=True. It works with virtualenv but not with nginx. -
Running Django server without IDE
I want to run my django server without running PyCharm or any other IDE. I've tried to run this using command 'python manage.py runserver' in projekt folder cmd which generated errors. Do I have to configure something to run server without IDE? -
How to create new log file for each new order in django?
I am developing a new eCommerce website using Django. I want to create a new log file for each new order so that I can track any error till payment confirmation. Is it possible to create a new log file for each new order?How can we do that? Please help me, guys. -
Unable to access Django development server from windows host machine
Im currently running Centos 8 on my virtual machine and I created a django application on this virtual machine. I am only able to access the Django application within the virtual machine by typing 127.0.0.1:8000 in the firefox search bar but this does not work on my windows host computer. -
Asynchronous tasks or Multiprocessing in Django
I have a function that accepts a request from a client. Based on the request, it makes a request to another API. Once the response is received, it finally returns a response to the client. class View(APIView): #receives request def post(self, request, pk, *args, **kwargs): makeRequest() #make request to other API #Do something after request ... #return response to client after response from API has been received return Response(status=status.HTTP_HTTP_200_OK) This approach has several issues as response time is made longer and any unpredictable activity from the API being consumed could further affect the response time. The solution in mind is receiving the request and having the function making the request run separately as a response is returned to the client. class View(APIView): #receives request def post(self, request, pk, *args, **kwargs): makeRequest() #make request to other API separately and do something with response later return Response(status=status.HTTP_202_ACCEPTED) #return accepted response to client How can this be achieved? -
Python Crash Course Learning Log Public tag
can anyone help me with this issue, i have already finish all the project and lm only fixing some modification from the book Python Crash Course 2nd edition , lm currently working the last part of the project which is adding the public status for the post, can anyone give me some pointers , logic or recommendation on how to fix this problem. any topic that’s public is visible to unauthenticated users as well. well. please see the pictures i attach. thank you. VIEWS def new_topic(request): """Add new Topic""" if request.method != "POST": form = TopicForms() else: """process the submitted data""" form = TopicForms(data=request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.owner = request.user if request.POST["public"]: new_topic.public = True new_topic.save() return redirect("learning_logs:topics") #display blank or invalid form context = {'form': form } return render(request, "learning_logs/new_topic.html", context) forms class TopicForms(forms.ModelForm): class Meta: model = Topic fields = ['text', 'public'] labels = {'text': '', 'public': 'Public'} model class Topic(models.Model): """A topic user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) public = models.BooleanField(default=False) def __str__(self): """Return a string representation of the model.""" return self.text strong texttemplate {% extends "learning_logs/base.html" %} {% block page_header %} <h1>Topics</h1> {% endblock page_header %} … -
how to exclude choices field values in django models?
form Depending from the user group of the logged in user, some story_status values should be remove if logged in user is not belong from certain group.i have a producer group, if logged in user is not belong form producer group then i want to remove the choices field value footage ready from the story_status. my code is not excluding the values models.py class Article(models.Model): STORY_STATUS = { ('story not done', 'story not done'), ('story finish', 'story finish'), ('Copy Editor Done', 'Copy Editor Done'), ('footage ready', 'footage ready') } title = models.CharField(max_length=255, help_text="Short title") story_status = models.CharField(choices=STORY_STATUS) output.html class ArticleForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(ArticleForm, self).__init__(*args, **kwargs) if not self.user.groups.filter(name__iexact='producer').exists(): self.queryset = Article.objects.exclude(story_status='footage ready') class Meta: model = Article fields = [ 'title', 'story_status' ] -
It posibble to have Django admin interface of mongodb?
In my project, I have two database (mariadb and mongodb). I want to create new admin interface to basic CRUD mongo's data . It possible to have two django admin interface into the same project? and what library I should work with mongodb? -
failed to create process while creating new project in django
I have installed a fresh python 3.7 and django 3.1.2 but when i tried to create a new project it showed me this error i tried doing everything but nothing solved this so far. C:\Users\Ahmed>django-admin startproject theapp failed to create process. -
sql server login with django/python/django Rest framework
I have an sql server database with already SQL LOGIN users , is there any way i can connect Django user model to those SQL LOGINS (i dont want to create any user model database as i already have it in my sql server) or any idea so i can login to sql server with django login?