Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django URLs MultipleObjectsReturned error
I am making a simple webapp with Django. A user can have a profile, and under that profile create a blog post. For example: "path('profile/<int:pk>/',profile, name='profile')" Returns the URL "http://127.0.0.1:8000/profile/1/" A user can then write blog posts which have the name in the URL Example: path('profile/<int:pk>/blog/<str:name>',Blogs, name='Blogs'), Returns the URL "http://127.0.0.1:8000/profile/1/blog/HelloWOrld" However, IF two different users both name their blogs the same exact name, i get a 'MultipleObjectsReturned' Error. I thought that by having the user PK earlier in the URL it would ensure that it would be unique, even if two blogs were called the exact same thing. IS there any way to work around this without using the PK of the blog as well? And if anyone could explain why my logic was wrong and it wasn't working in the first place. Thanks. -
Django rating star display
I am new to django and I have a problem. The rating of the film, for example, is 4, and in general there are 5 stars and I want to display 4 shaded stars and 1 not shaded star for example. Django <span class="rating"> {% for rating in movie.rating_set.all %} {% for k, v in star_form.fields.star.choices %} {% if rating.star > 0 %} <input id="rating{{ rating.star }}" type="radio" name="star" value="{{ k }}"> <label class="changed" for="rating{{ rating.star }}">{{ k }}</label> {% elif rating.star == 0 %} <input id="rating{{ v }}" type="radio" name="star" value="{{ k }}"> <label for="rating{{ v }}">{{ k }}</label> {% endif %} {% endfor %} </span> CSS .rating > label { position: relative; display: block; float: right; background: url('../images/star-off-big.png'); background-size: 30px 30px; } .rating > label:before { display: block; opacity: 0; content: ''; width: 30px; height: 30px; background: url('../images/star-on-big.png'); background-size: 30px 30px; transition: opacity 0.2s linear; } .changed{ position: relative; display: block; float: right; background: url('../images/star-on-big.png'); background-size: 30px 30px; } -
Prevent any CRUD functionality on a django model
Hello Im currently using a third party package called django-river to implement a sort of workflow system into my application. The reason for using this is because it allows the user to dynamically generate workflows and attatch functions on the fly . Im currently using this across some of my models that require this functionality. However , there is one model that i wish to restrict this freedom. I do not wish to allow the user to add any instances than the one i have added from the start , or edit them. Hence my question is: Is there a way to achieve this locking mechanism of the django models? -
Include a condition only if the value is not None in django ORM
I want to include a condition in django ORM's .objects.get method only if the value isn't None. Right now I'm using if/else and create two separate database query. Is it possible to combine these queries and do it at once? What I'm doing: if may_none_value: objects = MyModel.objects.get(field1=other_value, field2=may_none_value) else: objects = MyModel.objects.get(field1=other_value) -
Searching one-to-one-to-many relationship
I have three models, let's call them models A, B and C. A and B share one-to-one relationship, A can exists without B but B must always be linked to A. C has many-to-one relation with B. Or in other words: class ModelA(models.Model): #properties class ModelB(models.Model): a_link = models.OneToOneField(A, on_delete=models.CASCADE, related_name='a_link') #rest of the properties class ModelC(models.Model): set = models.ForeignKey(ModelB, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) Now, my question is, I find to find all A's that user has, by checking what Cs they have been tagged in. Can I just do searh ModelA.objects.filter(a_link__modelc__user=user) or do I need to first search for Cs in their own query, then select Bs from them and look for their relationship with A? -
How to convert datetime in python?
I am calling an user api from github here is my views.py: def user(req, username): username = str.lower(username) with urlopen(f'https://api.github.com/users/{username}') as response: source = response.read() data = json.loads(source) context = { 'username': username, 'data': data, } return render(req, 'user.html', context) and here is my template index.html: <div class="profile text-center"> <img src="{{data.avatar_url}}" class="border-primary" alt="profile-image"> <h1>{{data.name}}</h1> <a href=""> <p class="username text-primary">@{{data.login}}</p> </a> <p><i class="fal fa-map-marker-alt"></i> {{data.location}} <i class="far fa-calendar-alt"></i> {{data.created_at}} </p> </div> How can i convert a string datetime from github api to look like "March 22, 2016" -
how i can create a field for the post
I have model Order class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) 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, null=True, ) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS, default='Pending') note = models.CharField(max_length=1000, null=True) I create views.py for order def CreateOrder(request, shop_id, product_id): customer = request.user.customer shop = Shop.objects.get(id=shop_id) product = Product.objects.get(id=product_id) quantity = request.POST.get('quantity') note = request.POST.get('note') order = Order.objects.create(customer=customer, shop=shop, product=product, note=note, quantity=quantity) context = {'form': order} return render(request,'CreateOrder.html', context) I have created HTML page for the shop.products here I get the id of shop and product href="{% url 'CreateOrder' i.shop.id i.id %}" but when I click the button then the Order is created but the quantity and note is null how I can create a insert field for the quantity and note -
Getting Error when running Django Test on Heroku CI
I am using DRF and the tests are written for the APIs. I want to run those test on heroku and also use the CI in my pipeline for the development environment. When default SQLlite db is used in the config, the error that I am getting - Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead. My code and configs test_*.py class TestUser(APITestCase): def setUp(self): ... def test_user(self): ... base.py file db_config = dj_database_url.config(conn_max_age=600, ssl_require=False) DATABASES_AVAILABLE = { 'test': db_config, 'sqlite': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, } database = os.environ.get('DJANGO_DATABASE_TEST', 'sqlite') DATABASES = { 'default': DATABASES_AVAILABLE[database] } # Database Configuration Ends django_heroku.settings(locals(), databases=True) In Heroku CI Configs, I have DJANGO_DATABASE_TEST : test app.json { "buildpacks": [{ "url": "heroku/python" }], "environments": { "test": { "env": { "POSTGRESQL_VERSION": "10" }, "addons": ["heroku-postgresql:in-dyno"], "scripts": { "test": "./manage.py migrate && ./manage.py test" } } } } Error that I am getting in heroku ci django.db.utils.OperationalError: … -
Real time Chat: Message is going to wrong users. django-channels
I am adding chat facility in my project. I am showing a user list, when user click on specific user name, a chat box opens. This is working fine. Problem is when current user sends message, it going to all users. I know the reason of problem. I don't know the solution. <script> $(".user-name-container").click(function(){ var less_num = "variable" var big_num = "variable" var ws_scheme = window.location.protocol == "https:" ? "wss://" : "ws://"; window.chatCustomerSocket = new ReconnectingWebSocket( ws_scheme + window.location.host + '/ws/chat_to_customer/' + big_num +'/'+ less_num + '/'); <!------- Send message -------> $("#input-message-button").click(function(){ "-----logic------" chatCustomerSocket.send(JSON.stringify({ 'message': "msg", 'send_to': "sent_username", 'send_by': "self_username", })); }); <!------------ Recieve Message ------------> chatCustomerSocket.onmessage = function(e) { "Recieve Logic" }; }); </script> When user click on user name, websocket connection established but previous connection does not terminate. I think that's why message is going to all users which has been selected. This is consumers: class ChatToCustomerConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['first_user'] self.user_email = self.scope['url_route']['kwargs']['next_user'] self.room_group_name = 'chat_customer_%s' % self.room_name + self.user_email async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): first = self.scope['url_route']['kwargs']['first_user'] last = self.scope['url_route']['kwargs']['next_user'] chat_name = first + '-' + last text_data_json = json.loads(text_data) … -
Can I make a button in Django template to redirect a user to a specific Facebook Messenger account?
When the User clicks the button, Django must automatically send a message to a specific account in Facebook Messenger. Is that possible? Thanks in Advance! -
django rest framework problems with passing the header
I'm trying to pass the token to the backend but I'm having some issues. when I'm writing this in the cmd: curl -H "Authorization: Token 3c9c6079602737a04fcb6b2e737804142ef93930e4e705c0598b2fc597759f7f" http://127.0.0.1:8000/api/auth/user/ I get the user like I wanted. but when I'm sending the request from the postman / frontend, I get this error: { "detail": "Authentication credentials were not provided." } here is my service at the frontend const config = {headers: {Authorization: `Token ${token}`}} async function query() { try { return await axios.get(`http://127.0.0.1:8000/api/${types.TODO_API}/`, null, config); } catch (err) { throw err; }; }; when I'm sending the req, in the XHR - Networks I see it in query string params like this: headers: {"Authorization":"Token 50633f123efeb7b3f122e5e3ee4e9206463dfa5b413cacca475ab9ffd743da8f"} here is an image of postman here is my setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'todo', 'user', 'knox' ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'knox.auth.TokenAuthentication', ) } REST_KNOX = { 'TOKEN_TTL': timedelta(hours=10000), 'USER_SERIALIZER': 'knox.serializers.UserSerializer', } CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'access-control-allow-origin', ] CORS_ALLOW_CREDENTIALS = True here is the TodoViewSet, which also use the token, but not working unless i send the req + token from the cmd. class TodoViewSet(viewsets.ModelViewSet): permission_classes = (permissions.IsAuthenticated, ) serializer_class = … -
Create a Form from Model without foreign key Django
Can someone please help advise how to create a form with drop downs based on a table in the database. I do not have a primary key in the table to link it as a foreign key. However I would like to create form with a basic input text field with cascading drop downs from the table. Any expert who can advise how to do this? Thanks. -
Incrementing specific parameter in all objects in the QuerySet
I am trying to increment the same parameter in all objects in the query set. What I am doing right now: q = SomeModel.objects.all() for object in q: object.my_parameter += 1 object.save() I have wondered if it could be achieved in a simpler way, e.g. using update() function. To put it simply I would like to do something like this: SomeModel.objects.all().update(my_parameter += 1) I just can't believe that there is no shortcut for what I want to do. -
Is using a hidden input field in a template, to pass data to a django view not secure?
I'm sure there's better ways of doing this but I'm just curious if this is an insecure way of passing data to the view Template: {% for object in order.all %} ...other code <form method="POST"> {% csrf_token %} {{ form }} <input type="hidden" name="cart_id" value="{{ object.cart_id }}"> {% endfor %} -
how to update Django instance object with multiful fields
i want to update a instance by function update() in class CardSerializer(serializers.ModelSerializer) the following is class CardSerializer: class CardSerializer(serializers.ModelSerializer): image = serializers.CharField(read_only=True) class Meta: model = Card fields = ('id', 'template', 'data', 'MD5', 'image_md5', 'image', 'target_url', 'title', 'description', 'created', 'updated', 'createdBy') read_only_fields = ['MD5', 'image_md5', 'image', 'createdBy'] def update(self, instance, validated_data): # TODO Bug Fix new_ins = Card(**instance.data.update(validated_data)) md5 = new_ins.gen_md5() lookup = Card.objects.filter(MD5=md5).first() if lookup: return lookup return super(CardSerializer, self).update(instance, validated_data) currently i use patch in one Card Instance (id=206) http://127.0.0.1:8000/api/Card/206/ with body {"title": "asd"} , but would raise error {template: no this field}. then I degug, found function update(self, instance, validated_data) can't generate a new instance (new_ins) in line new_ins = Card(**instance.data.update(validated_data)) the arg validated_data in debug console is >validated_data {'title': 'asd'} 'title':'asd' __len__:1 instance is class object Card() : data:{'address': '123 Sydney St, Sydn... NSW 2000', 'avatar': 'https://cn.meetkol...._real.jpg', 'cover': 'https://cn.tdintell...Group.jpg', 'desc': 'vvvvbbbbbbxxxxxx jush oaighijjjoh', 'mail': 'zhujia@email.com', 'phone': '(61)0 410 888 888', 'qr': 'https://zhujia.com....ge/qr.png', 'title': 'new building', 'user': 'Martin' } MD5:'ae853b247d8510f06a9741e74b7851c3' description:'' pk:206 template:<CardTemplate: 7 | property_share_long | v1 long> template_id:7 title:'' updated:datetime.datetime(2020, 6, 30, 1, 35, 32, 871820, tzinfo=<UTC>) 'createdBy':<User: stevenqin> -
Django - Listening for sensor data
I am working on Django app that will take from the sensor and push to the HTML page. I have built the app for this project and I have a page set up however I am not sure how to go about the webserver part. I tried researching and there are lots of tutorials about API framework but I think my problem is a bit more specific. So my sensor is on my network and through its IP and sending the data to port 3080. I am trying to figure out which approach I need to use within Django to get the data on this sensor. I am not asking for you to solve this for me just to give me some guidance on how should I approach this. So I am assuming that in Django app I need to listen for incoming traffic that comes to this particular port. How do I go about that? -
django.db.utils.IntegrityError: NOT NULL constraint failed: in django
facing Error while python manage.py migrate and python manage.py migrate blog I also try a all the migrations file deleted and then again run command makemigrations and migrate but still not work class Post(models.Model): title = models.CharField(max_length=150) postImage = models.ImageField(default='img/hero.jpg') overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) category = models.ManyToManyField(Category, null=True) featured = models.BooleanField() author = models.ForeignKey(Author, on_delete=models.CASCADE,blank=True) ppost = models.ForeignKey('self',related_name='pre',on_delete=models.CASCADE, blank=True,null=True) npost = models.ForeignKey('self',related_name='next',on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.title + "-->" +self.overview class comment: content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) postby = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) def __str__(self): return self.content``` **when remove this 2 line Error was no Show:** ppost = models.ForeignKey('self',related_name='pre',on_delete=models.CASCADE, blank=True,null=True) npost = models.ForeignKey('self',related_name='next',on_delete=models.CASCADE, blank=True, null=True)``` why?? I a'm confuse ? thanks for try to solving -
Submitting a Comment form in Product Page not working
I am trying to add a comment section in products page, I am now trying to test the template to see if it directing correctly After I press the submit button nothing is happening it doesnt return any errors Here is the Models.py class Comment(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ItemComments") subject = models.CharField(max_length=50, blank=True) comment = models.CharField(max_length=250, blank=True) def __str__(self): return '{} by {}'.format(self.subject, str(self.user.username)) class CommentForm(ModelForm): class Meta: model = Comment fields = ['subject', 'comment'] here is the urls app_name = 'core' urlpatterns = [ path('', HomeView.as_view(), name='home'), path('<slug>/addcomment/', views.addcomment, name='addcomment'), Here is the views def addcomment(request): return HttpResponse("My product Page") Here is the template <form class="review-form" action={% url 'core:addcomment' item.slug %} method= "post"> {% csrf_token %} <div class="md-form md-outline"> <input name="subject" type="text" id="form75" class="form-control pr-6"> <label for="form75">Your Subject</label> </div> <div class="md-form md-outline"> <textarea name="comment" id="form76" class="md-textarea form-control pr-6" rows="4"></textarea> <label for="form76">Your review</label> </div> {% if request.user.is_authenticated %} <div class="text-right pb-2"> <button type="button" class="btn btn-primary waves-effect waves-light">Add a review</button> </div> {% else %} You must be Logged in to Comment {% endif %} </form> -
Can someone explain when/how to use Queryset modification vs Permissioning with Django Rest Framework?
I am struggling to understand how permissioning in DRF is meant to work. Particularly when/why should a permission be used versus when the queryset should be filtered and the difference between has_object_permission() & has_permission() and finally, where does the serializer come in. For example, with models: class Patient(models.Model): user = models.OneToOneField(User, related_name='patient') class Appointment(models.Model): patient = models.ForeignKey(Patient, related_name='appointment') To ensure that patients can only see/change their own appointments, you might check in a permission: class IsRelevantPatient(BasePermission): def has_object_permission(self, request, view, obj): if self.request.user.patient == obj.appointment.patient: return True else: return False But, modifying the queryset also makes sense: class AppointmentViewSet(ModelViewSet): ... def get_queryset(self): if self.request.user.is_authenticated: return Appointment.objects.filter(patient=self.request.user.patient) What's confusing me is, why have both? Filtering the queryset does the job - a GET (retrieve and list) only returns that patient's appointments and, a POST or PATCH (create or update) only works for that patient's appointments. Aside from this seemingly redundant permission - what is the difference between has_object_permission() & has_permission(), from my research, it sounds like has_permission() is for get:list and post:create whereas has_object_permission() is for get:retrieve and patch:update. But, I feel like that is probably an oversimplification. Lastly - where does validation in the serializer come in? For example, rather … -
How To Change A Third Party App's Models.py Due To Invalid Import
I'm trying to add django-messages to my app but I'm getting this error when I add it to my installed apps ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding' (C:\Users\Acer\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\encoding.py) Ive looked up this error and apparently it's caused by this line in Django-Messages models.py from django.utils.encoding import python_2_unicode_compatible To fix it I should change it to from django.utils.six import python_2_unicode_compatible As this is a third party app, how should I change this line? Should I copy the file structure into my own project (creating a django-messages folder among my apps then a models.py file inside it) and copy/paste the entire models.py into there then change the line? This seems wrong but I don't know how else to fix it. Or is the fact that it's using an outdated import signify that the app isn't maintained and shouldn't be used at all? Thank you. -
Changes made in admin page not reflecting in Django app
I have a model to store info about following a profile. But when i'm following a profile in admin section[Through "Follow" table], it's not reflecting in the application. But, when i'm following a profile in admin section[Through "Profile" table], it is displaying in application as expected(when I query through Profile table) but the changes were not updated in "Follow" table. models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) followed = models.ManyToManyField(User, default=None, blank=True, related_name = 'followed') bio = models.TextField(default='') image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' @property def num_follows(self): return self.followed.all().count() def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) FOLLOW_CHOICES = ( ('Follow', 'Follow'), ('Following', 'Following'), ) class Follow(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) follow_value = models.CharField(choices= FOLLOW_CHOICES,default='Follow', max_length=10) def __str__(self): return str(self.profile) admin.py: from django.contrib import admin from .models import Profile, Follow admin.site.register(Profile) admin.site.register(Follow) -
Getting an error 405 when submitting formview from detailview
I have the detailview, formview, and mail working. But it gives me a 405 error instead of redirecting back to the page. Please give me some eyes. I cannot see why it is not working. I have recently 3 switched # from .net mvc to python/django. Thank you for any help. class MessageSellerForm(forms.Form): contact_name = forms.CharField(max_length=100, required=True) contact_email = forms.EmailField(required=True) content = forms.CharField(required=True, widget=forms.Textarea) class PostDetailView(DetailView): model = Ad template_name = 'x_ads/ad_detail.html' def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context['form'] = MessageSellerForm return context class PostDetail(View): def get(self, request, *args, **kwargs): view = PostDetailView.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = PostDetailView.as_view() return view(request, *args, **kwargs) class PostMessageSeller(SingleObjectMixin, FormView): template_name = 'x_ads/ad_detail.html' form_class = MessageSellerForm success_url = '/' subject = 'User message about your ad' from_email = '********' to_email = '*********' message = '**********' send_mail(subject=subject, message=message, from_email=from_email, recipient_list=[to_email], fail_silently=False) model = Ad def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() return super().post(request, *args, **kwargs) <form method="POST"> {% csrf_token %} <fieldset class="form-group"> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-1 btn-sm" type="submit">Message Seller</button> </div> </form> -
Display calculated field in template (Django)
Referencing this question: Adding client side calculated fields to django admin I would like to do this exactly this such as : in admin.py: def Calc_result(self, obj): a = obj.field1 b = obj.field2 return a+b But then display the calculated value in a template as well. Any ideas on how to go about this? Thank you for any suggestions. -
How to ignore model field validators in the Django admin?
I have the following model: class Vote(models.Model): votes = models.IntegerField(default=1, validators=[MaxValueValidator(5, message="Hi")) ... snipped ... How can I ignore the validators if the votes field is being incremented in the admin section? Can I override the field to ignore validators? Or is there a way to not call full_clean() method to prevent the validators from running. -
Adding a Condition in Django Template Not Working
I have a model called Posts where users may have posts and may not have any posts, what I am trying to do is in the template to have condition that if the user has posts to have a button appearing to link to this page of posts otherwise to show nothing. There is no error showing it is simply not working as I want here is the posts model class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) here is the template <a href="{% url 'core:designer-posts' item.designer.username %}"> <button style="margin-top: 10px;text-transform: none;" button type="button" class="btn btn-primary btn-sm btn-block"> Check all my products </button> </a> {% if post.designer.id is not None %} <a href="{% url 'score:user-posts' item.designer.username %}"> <button style="margin-top: 10px;text-transform: none;" button type="button" class="btn btn-success btn-sm btn-block"> Check my posts </button> </a> {% else %} Show Nothing {% endif %} The template also has another model which is the item which is also the same user Here is the model class Item(models.Model): designer = models.ForeignKey( User, on_delete=models.CASCADE) title = models.CharField(max_length=100) Here is the views class HomeView(ListView): model = Item paginate_by = 12 template_name = "home.html" ordering = ['-timestamp'] def get_context_data(self, **kwargs): context['posts'] = Post return context