Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to test models with foreign keys in Django v3
I have already tested the Destinations models and it pass the test with the approach: def test_destinations_model(self): destination = Destinations.objects.create( tour_title = 'test1', booking_start_date='2021-05-30', booking_end_date= '2022-05-30', price=2000, description='test1', author='test1', image='image.png' ) destination.save() self.assertEquals(destination.tour_title, 'test1') self.assertEquals(destination.booking_start_date, '2021-05-30') self.assertEquals(destination.booking_end_date, '2022-05-30') self.assertEquals(destination.price, 2000) self.assertEquals(destination.description, 'test1') self.assertEquals(destination.author, 'test1') self.assertEquals(destination.image, 'image.png') However, I don't know how to test the Comment model since it is related to the Destinations one. I have done the following approach but the test is failing with the following message: #message of failing test for test_comment_mode self.assertEquals(destination, comment) AssertionError: <Destinations: test1> != <Comment: Comment test1 by John> #Failling test: def test_comment_model(self): #post not needed to test as foreignKey destination = Destinations( tour_title = 'test1', booking_start_date='2021-05-30', booking_end_date= '2022-05-30', price=2000, description='test1', author='test1', image='image.png' ) destination.save() comment = Comment( post=destination, name = 'John', email = 'any@email.com', comment = 'test1', created_on = timezone.now(), active = False, ) comment.save() self.assertEquals(destination, comment) class Destinations(models.Model): author = models.CharField(max_length=200, unique=False) tour_title = models.CharField(max_length=250) description = RichTextUploadingField() image = models.ImageField(upload_to='tour_images', blank=True) location = models.CharField(max_length=250) booking_start_date = models.DateField() booking_end_date = models.DateField() price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return self.tour_title class Comment(models.Model): post = models.ForeignKey(Destinations,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() comment = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: … -
Many To Many field and request.user not working
I am trying to do a very simple request : My model class LogBook(models.Model): name = models.CharField( max_length=50, verbose_name="Nom du registre de maintenance" ) members = models.ManyToManyField(User, verbose_name="Utilisateurs", related_name = 'member') Now if I tried in my view : if request.user == log.members To check whether or not the user belongs to the LogBook it does not deny access, any idea ? -
Should I put my modal in my django views or through the html?
I am trying to figure out wether it would be easier to implement a modal/alert system from my views.py or through the html. Currently, I have a matching system where users like or dislike each other, and if they like each other, I send them to another html and it says they matched and can message each other. I'd like to do that through a modal or alert. I am thinking it would be easier to implement that through the views.py, but I don't know how to do it, I only know how to do it through html. But through html, I'm not sure how to compare the vote values between each user like I do in my views. What should I do? I currently have mingle.html which is where users like and dislike each other, and then if they both like each other, it sends them to match.html. views.py/CreateVote @login_required def create_vote(request, profile_id, vote): profile = get_object_or_404(Profile, pk=profile_id) UserVote.objects.create( user=profile, voter=request.user, vote=vote ) other = UserVote.objects.filter( voter=profile, user=request.user, vote=True ) if vote and other.exists(): profile.matches.add(request.user) request.user.matches.add(profile) return render(request, 'dating_app/match.html', dict( match=profile, )) return redirect('dating_app:mingle') mingle.html <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.bundle.min.js"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/> {% if profile %} <section> <div class="col-md-3 … -
Django Admin Honeypot Undefined Template Variables
https://github.com/dmpayton/django-admin-honeypot/issues/62 Can someone advise what needs to be done for this pull request to be completed? Such as what files need to change and what the code needs to be for it? -
How to access Postgres through a SOCKS proxy in Django
I'd like to proxy database connections from Django through a SOCKS proxy. How can this be configured in Django? -
How to delete an object in django without rendering an html page to get the confirmation
I have created a Blog website and I want to add the functionality to delete a post object while clicking on the Delete button without rendering a separate HTML page rather using the confirm method in JavaScript. And I have no idea to complete that. -
Unable to send emails with django in production although having no problem in development
I have a django app deployed on a Google Cloud instance. It used to send emails through gmail without problems until I changed the settings structure (I passed from one single settings file to a production/development split one). I'm not really sure this change was the trigger of these errors, but it's the most probable. At the beginning I thought it was a gmail thing with security, and after reading every single question on SOF I gave up and got a new institutional email account from my university to work with. To my surprise I have the same behaviour: emailing works fine in development but it doesn't work in production. These are the setting files: # base.py (production) EMAIL_HOST = os.getenv('EMAIL_HOST') EMAIL_HOST_IMAP = os.getenv('EMAIL_HOST_IMAP') EMAIL_PORT = os.getenv('EMAIL_PORT') EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD') EMAIL_HOST_USER_MED = os.getenv('EMAIL_HOST_USER_MED') EMAIL_HOST_PSSWD_MED = os.getenv('EMAIL_HOST_PSSWD_MED') EMAIL_USE_TLS = True # dev.py (development) from inventario.settings.base import * DEBUG = True SECRET_KEY = 'xxx' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.abc.de' EMAIL_PORT = '587' EMAIL_HOST_USER = 'xxx' EMAIL_HOST_PASSWORD = 'xxx' EMAIL_HOST_USER_MED = 'xxx' EMAIL_HOST_PSSWD_MED = 'xxx' EMAIL_HOST_IMAP = 'imap.abc.de' EMAIL_PORT_IMAP = '587' I've run the django shell with production settings and checked that the variables are being acquired properly from … -
how to create a subscriber form in django .?
I have a subscriber form field in index template. When someone interest to join our newsletter How to get it in django admin ?. need a detailed answers from experienced persons -
Filter in DJANGO using Multiple Select Form
I have a single form input (see below) where a user can filter Workshop objects based on multiple properties like name, what equipment it has, if it has equipment with certain capabilities and material functionality, etc. Form: Form Template: <form method="get" action="."> <fieldset> <legend>WHAT ARE YOU LOOKING FOR?</legend> <div class="suggestion-wrap"> <span>Workshop</span> <span>Equipment</span> <span>Materials</span> <span>Capabilities</span> </div> <div class="inner-form"> <div class="input-field"> <select multiple placeholder="Type to search..." name="name_contains" id="choices-text-preset-values" class="form-control"> {% for Material in material_list %} <option>{{ Material.material }}</option> {% endfor %} {% for MachineType in machinetype_list %} <option>{{ MachineType.machineType }}</option> {% endfor %} {% for Capabilities in capabilities_list %} <option>{{ Capabilities.capabilities }}</option> {% endfor %} {% for Workshop in workshop_list %} <option>{{ Workshop.workshop_name }}</option> {% endfor %} {% for Equipment in equipment_list %} <option>{{ Equipment.equipment_name }}</option> {% endfor %} </select> <div class="select-dropdown"></div> <button class="btn-search" type="submit"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"> <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path> </svg> </button> </div> </div> </fieldset> <!-- <button class="btn-submit" type="submit">search</button> --> </form> As you can see this … -
How to keep 2 fields using django forms
As django forms run a loop for the fields {% for field in form %} <div class="col-6"> {{ field.errors }} {{ field.label_tag }} {{ field }} </div> {% endfor %} I actually want to have 2 fields, I found a cheap solution to this issue using Bootstrap4 I created the columns by using col-6 by which I get 2 fields in the row. But what if I want to make custom designs of forms in django ? -
Is there an advantage to using aws s3 to serve media files instead of nginx
If I am already serving django static files with nginx, would there be any advantage to serving media files with aws s3? -
Django taggit app not working.Tag names for filtering not being rendered
i am trying to create a blog which shows posts according to selected tags.I've got half of it working as the tags are being displayed on the posts.But the option to filter posts will not appear. my views.py:- def post_list(request,tag_slug=None): object_list=UserPost.published.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) object_list = object_list.filter(tags__in=[tag]) #paginationstart paginator = Paginator(object_list, 3) # Show 25 contacts per page. page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts = paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results posts = paginator.page(paginator.num_pages) return render(request,'post/list.html',{'posts':posts,'page':page,'tag':tag}) my urls.py: urlpatterns = [ path('', views.post_list, name='post_list'), path('tag/<slug:tag_slug>/',views.post_list, name='post_list_by_tag'), path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.post_detail, name='post_detail'), path('<int:post_id>/share/', views.post_share, name='post_share'), My template: {% if tag %} <h2>Posts tagged with "{{ tag.name }}"</h2> {% endif %} <p class="tags"> Tags: {% for tag in post.tags.all %} <a href="{% url "/blog/post_list_by_tag" tag.slug %}"> {{ tag.name }} </a> {% if not forloop.last %}, {% endif %} {% endfor %} </p> i have added TaggableManager to models.The 'tags' element in the 'p' tags are being rendered after the title.But the tag names from the for loop are not being rendered. -
Return client credentials and refresh token using access token - Django Rest Oauth2
I need to return refresh token and client id client secret, after verifying validity of given token. My api : class VerifyTokenAPI(APIView): permission_classes = (permissions.IsAuthenticated,) def get(self, request): try: token = AccessToken.objects.get(token=request.META.get('HTTP_AUTHORIZATION')[7:]) except get_access_token_model().DoesNotExist: return Response({"error": "This token doesn't exist"}, status=status.HTTP_404_NOT_FOUND) if token.expires > timezone.now(): # I wish I could return something like this info = {'refresh_token': token.application.refresh_token, 'client_id': token.application.client_id,'client_secret': token.aplication.client_secret} return Response(info, status=status.HTTP_200_OK) else: return Response({'token': 'invalid'}, status=status.HTTP_400_BAD_REQUEST) -
Use alert popup to delete object in django
I am using django generic DeleteView() for deleting object from my database. The deleteview is working fine. But I want a alert message before deleting the object. I have a ListView for showing the objects list in a table. In that table i have a trash icon, when user presses the trash icon it redirects to delete url and deletes the object. But i dont want to go a different page for my deletion instead I want to stay on that list page and want a popup alert message if i want to delete the object. if i click the yes button it deletes the object staying on that page and refreshes the list table. I have tried several codes for this. <button action="{% url 'employee:employee-delete' employee.id %}" type="button" name="button" class="btn btn-dnager" onclick="document.getElementById('deleteEmployee').style.display='block'"> <span data-feather="trash"></span> </button> <div id="deleteEmployee" class="modal"> <span onclick="document.getElementById('deleteEmployee').style.display='none'" class="close" title="Close Modal">×</span> <div class="modal-content"> <h1>Delete Account</h1> <p>Are you sure you want to delete your account?</p> </div> {% block footer%} {% include 'employee/employee_delete.html' %} {% endblock footer %} </div> currently I have above code for popup message and trash icon. when the icon is clicked a modal opens. employee_delete.html: <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> … -
Why the img will be invisible after click the color change js function?
I have a django project including the change color function with js, but the img will be invisible after I use those function. Btw this img has been uploaded to cloudinary. something I need to re-config? Below is my js function for the changing color, I have already set the img.crossOrigin = ' ' to prevent from the Error of 'getImageData' : var mug = document.getElementById("mug"); var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); var originalPixels = null; var currentPixels = null; function getPixels(img) { img.crossOrigin = ''; canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0, img.width, img.height); originalPixels = ctx.getImageData(0, 0, img.width, img.height); currentPixels = ctx.getImageData(0, 0, img.width, img.height); img.onload = null; } function hexToRGB(hex) { var long = parseInt(hex.replace(/^#/, ""), 16); return { R: (long >>> 16) & 0xff, G: (long >>> 8) & 0xff, B: long & 0xff }; } function changeColor() { var mug = document.getElementById("mug"); if(!originalPixels) return; // Check if image has loaded var newColor = hexToRGB(document.getElementById("color").value); for(var I = 0, L = originalPixels.data.length; I < L; I += 4) { if(currentPixels.data[I + 3] > 0) // If it's not a transparent pixel { currentPixels.data[I] = originalPixels.data[I] / 255 * … -
DRF Serializer boolean field not saving model default
I'm using Django 2.2 I have a model with a boolean field class MyModel(models.Model): is_active = models.BooleanField(default=True, blank=True) and serializer class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = [ 'is_active' ] def validate(self, attrs): print('attrs: {}'.format(attrs)) return super().validate(attrs) def create(self, validated_data): print('validated_data: {}'.format(validated_data)) return super().create(validated_data) Even though the model is_active field is default set to True, the attrs in the validate() method and validated_data inside the create() method contains is_active as False if is_active is not explicitly sent with the request. To set the default to True, I need to add explicitly serializer field to the serializer class is_active = serializers.BooleanField(default=True, required=False) Why doesn't it set the default value of the model field? -
Custom button only functioning at first element in the HTML list
I am creating a Django HTML template that contains a list and each list is supposed to have a custom button, as many list elements that exist there must be a custom button for it. This button is supposed to toggle between active and inactive. After creating this toggle using JavaScript, it only works for the first element of the list. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Dashboard</title> {% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}"> <script src="{% static 'js/dashboard.js' %}"> </script> </head> <body> {% for all_users in users %} <li>{{all_users}} <button onclick="handleToggle()" id="switchName" type="submit"> Switch To Active State </button> </li> {% endfor %} <p> this is all {{users}}</p> <p>there are {{usersCount}} users in the admin and its presently {{now}}</p> <form method="get"> {{filterUsers.form.as_p}} <button type="submit">Search</button> </form> <ul> {% for user in filterUsers.qs %} <li>{{user}}</li> {% endfor %} </ul> </body> </html> My corresponding JavaScript looks like function handleToggle() { var elem = document.getElementById("switchName"); if (elem.innerHTML=="Switch To Active State") elem.innerHTML = "Switch To Inactive State"; else elem.innerHTML = "Switch To Active State"; } PLease any suggestions and corrections are veery much welcom -
Get serialized data in a particular format in django
I am inserting data in Serializer and trying to get response in a particular format but it seems like I'm doing something wrong. My model: class Game(models.Model): id = models.AutoField(primary_key=True) lane_number = models.IntegerField() class Player(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) games = models.ManyToManyField(Game, related_name='players') My serializer: class PlayerSerializer(serializers.ModelSerializer): class Meta: model = Player fields = ['id', 'name'] class GameCreateSerializer(serializers.ModelSerializer): players = PlayerSerializer(many=True) class Meta: model = Game fields = ['lane_number', 'players'] def create(self, validated_data): players_details = validated_data.pop('players') game = Game.objects.create(**validated_data) g_id = game.id for player_data in players_details: a = Player.objects.create(**player_data) a.games.add(g_id) return game class GameListSerializer(serializers.ModelSerializer): players = PlayerSerializer(many=True, read_only=True) class Meta: model = Game fields = ('id', 'lane_number', 'players') My view: class GameAPIView(APIView): def post(self, request, *args, **kwargs): data = json.loads(request.body.decode("utf-8")) serializers = GameCreateSerializer(data=data) if serializers.is_valid(): serializer = serializers.save() data = Game.objects.all() serializers = GameListSerializer(data, many=True) return Response(serializers.data) return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST) Request: { "lane_number": 3, "players": [{ "name": "A" }, { "name": "B" }] } Expected Output: { "game": { "id": 1, "lane_number": 3 }, "player_details": [ { "player": { "id": 1, "name": "A" } }, { "player": { "id": 2, "name": "B" } } ] } After saving my data I have used another serializer to get data … -
Waypoints infinite scrolling not working on mobile devices
This is the code that is in my template. It works fine in desktop but does'nt work in mobile at all. var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], handler: function(direction) { }, offset: 'bottom-in-view', onBeforePageLoad: function () { $('.spinner-border').show(); }, onAfterPageLoad: function () { $('.spinner-border').hide(); } }); -
Django-rest-framework fetch foreign key field
serializers.py class EmployeeSerializer(serializers.ModelSerializer): password = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Employee fields = "__all__" models.py class Employee(CreateUpdateModel): emp_id = models.CharField(max_length=200, validators =[validate_min_5]) first_name = models.CharField(max_length=200, validators =[validate_min_3]) last_name = models.CharField(max_length=200, validators =[validate_min_2]) class Password(models.Model): emp_id = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name="employee_password") password = models.CharField(max_length=200, validators =[validate_min_5]) When i am visiting /employee/ i am not getting password field i want all fields of employee along with password also. Please have a look. -
Django admin - creating image admin models
I have looked through the posts but didn't find what I'm looking for, this is why I'm asking. The goal is to be able to create image galleries in the admin, then to upload images and to choose in which (already created) gallery to be uploaded and after that, when creating a post (for example) to have a field which to access the gallery model and to choose images to be used in a carousel gallery in the said post. For example, I'm creating a post in a travel blog and would like to add few images from the trip I had to use in a carousel. I hope I have explained the goal understandable and someone to be able to show me a way or to point in the right direction If there are any first party solutions, I'd be very happy Please, since I'm new in django link a more detailed answer or tutorial or explain for a newbie -
Selecting all fields and grouping by by one
I want to write a query like SELECT * FROM users GROUP BY some_attribute. How can I do that using Django ORM? User.objects.all().values('some_attribute').annotate(count=Count('*')) doesn't work, because it just selects some_attribute, instead of * - all. I need it using the ORM, I don't want to write raw statement. -
Django Background Tasks not working with Apache + mod_wsgi
I use django-background-tasks to run some heavy tasks in the background in my Django application. On my local machine everything works fine. However, if I deploy my application in production with Apache and mod_wsgi, the scheduled tasks are not executed. Instead, if I run the command python manage.py process_tasks in some terminal, the message 'Failed to retrieve tasks. Database unreachable.' is printed every 5 sec or so. What am I doing wrong? Where/how am I supposed to run "python manage.py process_tasks"? -
How to manually set the template of Django forms?
In a Django project, I have the following form: class MyForm(forms.Form): field_1 = forms.BooleanField(initial=True, required=False) field_2 = forms.ChoiceField( initial='choice_1', choices=( ('choice_1', 'Choice 1'), ('choice_2', 'Choice 2'), ('choice_3', 'Choice 3') ) ) In the template, I am simply calling the form using {{ form }}. The form gets rendered using browser default. However, I do have a very exact HTML markup in mind for the form. Its something like this: <form action="/" method="POST"> <div class="form-field"> <div class="my-checkbox"> <input type="checkbox" id="field-1" value=""> <label for="field-1">Field 1 (Recommended)</label> </div> </div> <div class="form-field"> <label for="field-2" class="required">Field 2</label> <select class="my-select" id="field-2" required="required"> <option value="choice_1" selected="selected">Choice 1</option> <option value="choice_2">Choice 2</option> <option value="choice_3">Choice 3</option> </select> </div> </form> What I am struggling with is adding the wrapping containers for the fields, and also how to set the default value for field 1 (which should be checked by default). How can I do this using Django? Thanks for any help. -
Sql command in subquery ORM Django
How i can do this commmand sql in django orm: SELECT SUM(total) as result FROM ( SELECT SUM(p.pr_preco) AS total FROM clientes_produto p JOIN clientes_itens i ON (p.id = i.prod_id) JOIN clientes_pedido ped ON (ped.id = i.pedi_id) WHERE i.pedi_id = 21 GROUP BY p.id ) as inner_query ??? My itens has two foreign key: one to produto and other to pedido. Tks.