Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How can I exclude user
I am creating a website where different users can upload a post and also tag other users to a post. I have list of post on news feed from different users and also users have been tagged on same posts.Example: user A and user B are friends, user A uploaded a post and user B uploaded a post, user A and user B tagged user C on a post. When user A blocked user C, user A will no longer find user C as tagged user to his post, but the problem here is that user A can still find user C in user B post. How can i exclude user C from other users post who are friends to user A, so that user A can no longer see any post associated to user C. I was able to remove user C from user A post when user A blocked user C, but how do i also make user A not to see user C when user A view tags of user B. I haave been trying to figure this out for awhile but no progress.I hope my explanation is understandable. Model: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) blocked_users = … -
How can I set up nginx for my django application on digitalocean?
Yes, I did research, but it confused me even more. I have an django app on digitalocean. Thanks to @jonas I figured out that I should use nginx to serve static files. I didn't knew that I had to use it, so I started without nginx. What steps must I take to serve my static files correctly with django? -
Django channels hosting
Any idea where can I host a Django app that uses channels? Its channel layer uses redis if that matters. I tried hosting it on pythonanywhere where I usually host my projects but after some research I found out that it does not support this type of app. I am thinking about trying to host it on heroku but I don't know if it will work on the free version. Any recommendation for a place where I can host my app (preferably for free)? -
Integrating Django REST Framework and Django OAuth Toolkit Authentication
I have followed through the documentation on how to integrate both the REST framework and OAuth Toolkit, but when I run a request with a token I receive: {"detail":"Authentication credentials were not provided."} Here is my REST settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'PAGE_SIZE': 20 } An example view: class GroupViewSet(viewsets.ReadOnlyModelViewSet): authentication_classes = [OAuth2Authentication] queryset = Group.objects.all() serializer_class = GroupSerializer permission_classes = [TokenHasScope] required_scopes = ['read', 'groups'] And I do have 'oauth2_provider' in my INSTALLED_APPS. I'm able to request and receive tokens without issue. It's only when I use them that I get the above error. -
Django. Price not saving when I call save() method
I have a model: class ProductSet(models.Model): """Set of some products""" price = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True) set_products = models.ManyToManyField(SetProduct, related_name='set', verbose_name='Товары набора') def save(self, *args, **kwargs): """If a total price for that product set isn't defined, save it as a sum of the set products total_price """ if not self.price: super().save(*args, **kwargs) self.price = sum([set_product.total_price for set_product in self.set_products.all()]) super().save(*args, **kwargs) The first save calling for saving "set_products" many-to-many relationship. The second save expression for saving a new self.price. But that's doesn't work, a price was saved only after I double-clicked to the django admin save button. What's the reason and how I can solve it? P.S SetProduct: class SetProduct(models.Model): """Product in ProductSet""" product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='Товар', related_name='product_sets') count = models.PositiveSmallIntegerField('Количество', default=1) actual_price = models.DecimalField('Актуальная цена', max_digits=7, decimal_places=2, blank=True, null=True) def save(self, *args, **kwargs): """If an actual price isn't defined, set it as the product.price_with_discount""" if not self.actual_price: self.actual_price = self.product.price_with_discount super().save(*args, **kwargs) @property def total_price(self): return self.actual_price * self.count -
Django admin history Custom view
I'm new to django & I'm trying to add a custom History view along with SimpleAdminHistory. The SimpleAdminHistory is working fine but the 2nd url that I'm adding is not working saying dragon with ID "1220/default_history" doesn't exist. Perhaps it was deleted? Without any errors. History Class In the following class I'm trying to add a class that extends SimpleHistoryAdmin (which extends model.AdminModel), and what I'm trying to do is add a new url which when accessed should hit default_history_view method. The problem is when I hit the url http://127.0.0.1:8000/admin/dragon/1220/default_history/ it's not hitting that method at all whereas http://127.0.0.1:8000/admin/dragon/1220/history/(SimpleAdminHistory method) works perfectly. class TestClass(SimpleHistoryAdmin): history_list_display = ['changed_fields'] # pylint: disable=no-self-use def changed_fields(self, obj): """Add changed fields to changed_fields column in History.""" if obj.prev_record: delta = obj.diff_against(obj.prev_record) return delta.changed_fields return None def get_urls(self): urls = super(GenericClass, self).get_urls() admin_site = self.admin_site opts = self.model._meta info = opts.app_label, opts.model_name history_urls = [ url( "^([^/]+)/default_history/$", admin_site.admin_view(self.default_history_view), name="%s_%s_history" % info, ), url( "^([^/]+)/history/([^/]+)/$", admin_site.admin_view(self.history_form_view), name="%s_%s_simple_history" % info, ) ] return urls + history_urls def default_history_view(self, request, object_id, extra_context=None): "The 'history' admin view for this model." # First check if the user can see this history. print(object_id) model = self.model obj = self.get_object(request, unquote(object_id)) if obj … -
making a foreignkey not required
I have these 2 models: # core/models.py Class Certificate: user = models.Foreignkey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='certificates') name = models.Charfield() . . # users/models.py Class User(AbstractBaseUser): . . and I want to send the certificates of a user along with its other pieces of information. this is my serializer: # users/serializers.py class CertificationSerializer(serializers.ModelSerializer): """Serializer for the certificate object""" class Meta: model = Certificate class UserSerializer(serializers.ModelSerializer): """Serializer for the user object""" # TODO # videos = serializers.PrimaryKeyRelatedField( # many=True, # queryset=Tag.objects.all() # ) certificates = CertificationSerializer(many=True) class Meta: model = get_user_model() # TODO add certificates and videos fields = ('id', 'email', 'password', 'first_name', 'last_name', 'phone_number', 'credit', 'points', 'certificates') extra_kwargs = {'password': {'write_only': True, 'label': 'گذرواژه', 'min_length': 5}} read_only_fields = ('id', 'certificates',) def create(self, validated_data): """Create a new user and return it""" return get_user_model().objects.create_user(**validated_data) def update(self, instance, validated_data): """Update a user and return it""" password = validated_data.pop('password', None) user = super().update(instance, validated_data) if password: user.set_password(password) user.save() return user now when I want to create a new user it tells me that field certificates can not be empty, how can I make the certificates field not required? -
Keep retrying Celery task and only move on if task succeeds or max retries reached
I have a Celery task that retries on failure with exponential backoff. This task POSTs messages received by a Django application (call it "transport") to a second Django application (call it "base") for processing. These messages have to be processed in order, and so the order in which the tasks are queued must be maintained. However, when a task fails (because transport cannot connect to base for whatever reason), it is relegated to the back of the queue, which is obviously an issue. Is it possible to "block" a Celery queue, ie. to keep retrying the same task until it either succeeds or reaches the max retries threshold, and only then move to the next task in the queue? In my case I need the task at the head of the queue to keep trying that POST until it can't anymore, and under no circumstances should the order of tasks in the queue be changed, though I'm not sure if this can be done with Celery (and if so, how). I've come across this previous question which seems to describe a very similar problem, but it's not fully relevant to my use case. -
Direct assignment to the forward side of a many-to-many set is prohibited. Use foods.set() instead in django
I have this view: @login_required def addmeal(request): if request.method == 'POST': form = addMeal(user=request.user, data=request.POST) if form.is_valid(): form.save(request) return redirect('food:index') else: form = addMeal(user=request.user) return render(request,'addmeal.html',{'form':form}) and this form: class addMeal(forms.Form): name = forms.CharField( max_length=40, widget=forms.TextInput(attrs={'class':'form-control','placeholder':'نام وعده'}) ) foods = forms.ModelMultipleChoiceField( queryset=Food.objects.none(), widget=forms.SelectMultiple(attrs={'class':'form-control'}) ) def save(self,request): data = self.cleaned_data meal = Meals(name=data['name'],user=request.user,foods=data['foods']) meal.save() def __init__(self, user=None,*args, **kwargs, ): super().__init__(*args, **kwargs) if user is not None: self.fields['foods'].queryset = Food.objects.filter(user=user) class Meta: model = Meals when i run server and fill out form and press submit django give me error(Direct assignment to the forward side of a many-to-many set is prohibited. Use foods.set() instead.). what should i do to fix it? -
insert selected multiple record in foreign-key
I have four models shop, product, customer, order. following are shop class Shop(models.Model): user = models.OneToOneField(User, null=True, related_name='shop', blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=70, null=True, default='shop', ) address = models.CharField(max_length=70, null=True) customer class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True, default='customer') Phone = models.PositiveIntegerField(blank=True, null=True) product class Product(models.Model): shop = models.ForeignKey(Shop, models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100, blank=True) Brand = models.CharField(max_length=200, blank=True) order class Order(models.Model): shop = models.ForeignKey(Shop, models.CASCADE, null=True) customer = models.ForeignKey(Customer, models.CASCADE, null=True) product = models.ForeignKey(Product, models.CASCADE, null=True) quantity = models.CharField(max_length=30) In order I want to insert the selected n.product but shop and customer is same that shown in the image how I can do this when user.customer login then on the home page shop will print when and they select shop after selecting the shop, product by the shop will be the print after submitting selected product with the remaining filed will print -
Update SetupProxy target dynamically
I am developing a tenant application with Django backend and React.js as a frontend framework. And using http-proxy-middleware to proxy the request to backend server. For different kind of tenants we need to update target value of createProxyMiddleware dynamically. Typically we can use const { createProxyMiddleware } = require('http-proxy-middleware'); module.exports = function(app) { app.use( '/api', createProxyMiddleware({ target: 'http://t1.demo.local:8000/', changeOrigin: true, secure: false }) ); }; Here i want to update target dynamically for different tenant client. How i can achieve that. Thanks a lot for reading -
RedirectView to external site. How to append parameters?
I would like to redirect from my page to external site. This external site address is defined and never changes... And I can implement it... The challenge comes from: I have a form, which posts Q into my view function, which gives final string of parameters to pass into the pattern of url supposedly attached to the main address of this external web site after the ? mark... I just cannot find the information how to pass and attach this string to a given url. Somehow it's difficult for me, please don't judge too harsh. Parameter is only one, it is a string, which formed in view function. I use RedirectView in urls.py: path('do_request/found/', RedirectView.as_view(url='https://docs.djangoproject.com/'), name='found_objects'), In views.py (there are probably some mistakes, but it's just for the purpose of the question): class UserFoundRequestView(TemplateView): model=ForQuery template_name='found_objects.html' def get_results(self, request): our_queries = ForQuery.objects.all() query=self.request.GET.get("q") if query: our_object=ForQuery.objects.filter(query_id__iexact=query) for x in our_queries: if x.query_id == our_object.query_id: name = x.dep_station #context = { # 'name' : name, #} return name def get_string(request): base_url = 'https://stackoverflow.com/' query_name = get_results() query_string = urlencode(query_name) url = '{}?{}'.format(base_url, query_string) return redirect(url) Thank you for the help! -
Self Signed Certificate Not Working - Invalid Certificate
I am following a Django book and trying to do social authentication. I've installed PythonSocial, Edited the hosts file and added 127.0.0.1 mysite.com. Also, I've installed django-extensions, werkzeug, pyOpenSSL adn added django-etensions to installed apps. When I tried to enter the site it is showing an insecure connection and I've added the certificate been shown first to the Trusted Root Certificates. When I click the certification and go to the certification path it is showing certification staus is ok but at the start when I click the red caution icon sort of it shows certificate is invalid. Please Help -
'attempt to write a readonly database' meanwhile everything is 777?
I've set my database and it's parent folders to 777 for diagnosing. within /: drwxr-xr-x. 21 root root 4096 Jun 21 15:36 var within /var: drwxr-xr-x. 5 apache apache 49 Jun 21 15:42 www within /var/www: drwxrwxrwx. 7 apache apache 131 Jun 21 18:18 project within /var/www/project: -rwxrwxrwx. 1 apache apache 143360 Jun 21 18:18 db.sqlite3 But I'm still getting errors when apache tries to write to the database. Any idea? I'm obviously going to remove 777 once I figure out what's going on but I'm out of ideas for now. -
How can i serve static files in django without apache or ngingx
I have a folder static: static -->css ----> main.css -->images ----> image.png Settings.py: STATICFILES_DIRS=[ os.path.join(BASE_DIR, "static"), ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static_cdn") I ran collectstatic Now I have in static_cdn: images, css and admin(never saw this last one before). When I run my server, it still doesn't use static files. How can I serve my static files to my server without using apache or nginx or that kind of stuff? Thx for your help and stay healthy! -
How to change file browser button to image button by useing forms design in Django
I can create the following form: I'm thinking when I click on the image like this: