Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Installing gettext via pip
I tried to use Django's internationalization instead of creating an own one. For this I need gettext. But since the internationalization in Django isn't documented well, I had to take a look at some guides. Main problem: After running django-admin makemessages -l en I got the error: CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed.. According to some guides I run pip install python-gettext. But the problem still exists. Trying to run pip install gettext I get the following error: ERROR: Could not find a version that satisfies the requirement gettext (from versions: none) ERROR: No matching distribution found for gettext So how can I install get-text via pip install? Django Version: 3.1.2 -
ValueError: Field 'id' expected a number but got 'DEFAULT VALUE'
When I try to execute python manage.py migrate I get this error: ValueError: Field 'id' expected a number but got 'DEFAULT VALUE'.What could be wrong with my code.Any help pleaseThanks in advance. File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1772, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'DEFAULT VALUE' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 233, in handle fake_initial=fake_initial, File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 112, in database_forwards field, File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 328, in add_field self._remake_table(model, create_field=field) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 189, in _remake_table self.effective_default(create_field) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 303, … -
how to add custom user model to users section of admin panel - django 3.1.1
I have added a custom user model in my django project which was explained here. I defined extra fields in models.py like this: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.CharField(max_length=25, blank=True) address = models.TextField(max_length=500, blank=True) zipcode = models.CharField(max_length=15, blank=True) city = models.CharField(max_length=25, blank=True) country = models.CharField(max_length=25, blank=True) phone = models.CharField(max_length=15) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() in my views.py, the registration goes like this: from django.shortcuts import render, redirect from django.contrib.auth.models import User def update_profile(request, user_id, company, address, zipcode, city, country, phonenumber): user = User.objects.get(pk=user_id) user.profile.company = company user.profile.address = address user.profile.zipcode = zipcode user.profile.city = city user.profile.country = country user.profile.phoneNumber = phonenumber user.save() def register(request): if request.method == 'POST': # Get form values first_name = request.POST['firstname'] last_name = request.POST['lastname'] company = request.POST['company'] address = request.POST['address'] zipcode = request.POST['zipcode'] city = request.POST['city'] country = request.POST['country'] phoneNumber = request.POST['phoneNumber'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] # Check if password match if password == password2: # Check username if User.objects.filter(username=username).exists(): return redirect('register') else: if User.objects.filter(email=email).exists(): return redirect('register') … -
how can i set foreign key set automatically to the user in my person field
this is my views.py @login_required(login_url='/login') def user_edit(request, user_id): if request.method == 'POST': user = User.objects.get(id=user_id) form = ProfileForm(request.POST or None, instance=user) if form.is_valid(): i = form.save(commit=False) i.user = request.user i.save() return redirect('list') else: form = ProfileForm() return render(request, "home/intro.html", {'form': form}) else: return render(request, "home/intro.html") this is my forms.py from django import forms from django.forms import ModelForm from .models import Profile class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = '__all__' this is my models.py from django.contrib.auth.models import User from django.db import models class Profile(models.Model): img = models.ImageField(upload_to='imgs/') about = models.TextField(max_length=255, null=False) phnum = models.IntegerField() uname = models.CharField(max_length=255, null=False) person = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def __str__(self): return self.about how can i set person to that user id that is currently logged in...??? i wanted to save user id to that foreign key so that if i delete user then profile of that user will also be deleted -
Unable to run the new Django site as whenever I tried to do so by running the local host ip:127.0.0.1:8000 it's accessing the old Django Project site [closed]
I am newbie to Django. I had created a simple Django site and ran it I had some issues with it hence abandoned it and now I created a second Django project however when I ran the link 'python manage.py runserver' and trying to access second project via link:'127.0.0.1:8000' it's taking me to the old Django project. Please help me. -
Best way to export multiple PDF files with django as backend and React as frontend
I am currently working on a web application which has django backend (using DRF) and React as frontend. I want to create an API which can export multiple PDF files(of 4-5 pages each). Ofcourse, it will take a long time and doing it in normal HTTP request/response cycle will timeout. What is the best way/architecture to incorporate this in the backend? PS: I already have celery working for several other apis(time consuming background tasks) but in this case, I want response (i.e pdf files) from the celery to reach frontend. I am not sure how to do that. Any other method which is ideal for such scenario is appreciated. Thanks in advance!! -
how to increase disk size of RabbitMQ with celery in Django
I am using RabbitMQ as broker with Celery in my django project. But problem is that Celery task get stuck. I am getting OCR of pdf file in that task and normally it works fine but if I upload file more than 1 MB celery task takes alot of time as it seems like it gets stuck. I read online and found that its happening because disk size of RabbitMQ is less. So my question is how I can assign RabbitMQ more disk space I have read official docs and more solutions related to that but still I am unable to understand. Because there isn't any default setting file of RabbitMQ. If you know please explain briefly how I can set it up and increase its size -
AttributeError: 'HttpResponseSeeOther' object has no attribute 'url'
I'm looking to test for a 303 See Other status code when a User attempts to login. Django does not have a built in class to handle this status code, so I constructed a sub class of HttpResponse. from http import HTTPStatus from django.http import HttpResponse class HttpResponseSeeOther(HttpResponse): '''Represents a 303 status code''' status_code = HTTPStatus.SEE_OTHER Next, I constructed a TestCase to test a View's response when it is passed valid form data. However, the test raises this error: AttributeError: 'HttpResponseSeeOther' object has no attribute 'url' . Going over the Django docs, I cannot see any reference to a Response object having an URL attribute. How can I go about addressing this error so that a server returns a 200 OK response after a successful 303 See Other redirect? test_views.py class TestUserLoginPage(TestCase): @classmethod def setUpTestData(cls): User.objects.create_user(username="User", password="password") cls.login_creds = { 'username': 'User', 'password': 'password' } def test_successful_login_redirect(self): response = self.client.post( reverse("login"), data=self.login_creds, follow=True ) self.assertRedirects(response, reverse("photos:main_gallery"), status_code=303) self.assertTemplateUsed(response, "photos/main_gallery.html") views.py class LoginPage(View): def get(self, request): form = UserAuthenticationForm() return render(request, 'login.html', context={'form': form}) def post(self, request): import pdb; pdb.set_trace() form = UserAuthenticationForm(request, request.POST) if form.is_valid(): messages.success(request, f"Welcome {request.user}!") return HttpResponseSeeOther(reverse("photos:main_gallery")) messages.info(request, "Login Failed. Username not registered.") form = UserAuthenticationForm() return … -
How to show OrderItem in Order in Django Admin.py
I am trying to show the orderitemsadmin in the orderadmin using TabularInline but I keep getting the following error. AttributeError: 'OrderItemAdmin' object has no attribute 'urls' This is a Django e-commerce project and I am trying to facilitating the admin viewing the orders and their items. Here is the admin.py class OrderItemAdmin(admin.TabularInline): list_display = ['item', 'quantity', 'ordered'] model = OrderItem raw_id_fields = ['item'] class OrderAdmin(admin.ModelAdmin): list_display = ['user', 'ordered', 'ordered_date', 'coupon', 'payment', 'shipping_address', 'status', 'refund_requested', 'refund_granted', 'ref_code'] list_display_links = [ 'user', 'shipping_address', 'payment', 'coupon' ] list_editable = ['status'] list_filter = ['ordered', 'ordered_date', 'refund_requested', 'refund_granted', 'status'] search_fields = [ 'user__username', 'ref_code' ] actions = [make_refund_accepted] inlines = [ OrderItemAdmin, ] Here is the models.py class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, ------------------------------------------------------ status = models.CharField(max_length=50, choices=[('pending', 'Pending'), ('ofd', 'Out For Delivery'), ('recieved', 'Recieved')], default='pending') def __str__(self): return self.user.username -
Django - can I add a form on changelist_view?
I have a model admin with a simple custom change view page, can I add a form on it? class MyModelAdmin(admin.ModelAdmin): change_list_template = 'custom_template.html' def changelist_view(self, request, extra_content=None): # How do I link the form to this view ? # logic of handling data from the form return super(MyModelAdmin, self).changelist_view(request, extra_context=None) -
Django WebSocket Multiple Send
i try realize multiple send in websockets. In synchronous and only 1 to 1 work but if i try send message 1 to many or asynchronous 1 to 1 i don't see notification. Can you help please with code or rewrite this code. I'm not an expert in websockets, but I'm trying to write something. consumers.py class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): if self.scope["user"].is_anonymous: await self.close() else: self.group_name = "user_id_" + str(self.scope["user"].id) for group in self.group_name: self.channel_layer.group_add( group, self.channel_name) await self.accept() async def disconnect(self, close_code): await self.close() async def notify(self, event): await self.send(text_data=json.dumps(event["text"])) notify.py def send_notification(data, user, req_user, email): channel_layer = get_channel_layer() group_name = 'user_id_{0}'.format(user.id) async_to_sync(channel_layer.group_send)(group_name, { "type": "notify", "text": data, }, ) if email: send_mail(subject='Message', message=f"{data}", from_email=req_user.email, recipient_list=[user.email]) notify = Notification.objects.create(sender=req_user, message=data) notify.receivers.add(user) notify.save() Execute function send_notification('notify_text', user=[User.objects.get(username='applicant1'), applicant1 = User.objects.get(username='applicant0')], req_user=user_id,email=False) template <script> var loc = window.location var wsStart = "ws://" if (loc.protocol === "https:"){ wsStart = "wss://" } var webSocketEndpoint = wsStart + loc.host + '/notifications/' // ws : wss // Websocket URL, Same on as mentioned in the routing.py var socket = new WebSocket(webSocketEndpoint) // Creating a new Web Socket Connection // Socket On receive message Functionality socket.onmessage = function(e){ console.log('message', e) $("body").append("<h3>"+e.data+"</h3>") // Can write any … -
Django Filtering Foreign Key Item
I have problem using fk in django. I want to make a fk field that the parent's queryset has been filtered. I have app called user that has costumized User model in model.py class User(AbstractUser): username = models.CharField(max_length=50, unique=True) email = models.EmailField(_('email address'), unique=True) phone = models.IntegerField(_('phone number'), unique=True, blank=True, null=True) this User has ManyToMany Relationship with Group queryset: maker, checker, signer >>> print(Group.objects.all()) <QuerySet [<Group: maker>, <Group: checker>, <Group: signer>]> In other app called cleaning I have cln_daily model that has foreignkey relationship with that User model based on their group. class cln_daily(models.Model): . . user_maker = models.ForeignKey(User,verbose_name="Maker's Signature",on_delete=models.CASCADE, related_name="makerSignature", blank=True, null=True,) user_checker = models.ForeignKey(User, verbose_name="Checker's Signature",on_delete=models.CASCADE, related_name="checkerSignature", blank=True, null=True) user_signer = models.ForeignKey(User, verbose_name="Signer's Signature",on_delete=models.CASCADE, related_name="signerSignature", blank=True, null=True) So what I mean is user_maker queryset has users that only belong to group maker. user_checker has users that only belong to group checker and user_signer queryset has users that only belong to group signer. How to express filtered User model in that model.py? -
Use regroup with datetimefield
I want to regroup a queryset in my template : {% regroup events by date as events_group %} {% for event in events_group %} <div class="time-label"> <span class="bg-danger"> {{ event.grouper }} It's works but the "date" is a datetimefield. I want to group my results per day. Today the results are displayed like : 10 Oct 2020 16:59 event1 10 Oct 2020 16:55 event2 10 Oct 2020 16:54 event3 09 Oct 2020 12:59 event4 09 Oct 2020 11:59 event5 I want : 10 Oct 2020 event1 event2 event3 09 Oct 2020 event4 event5 How to do this ? -
convert Django raw sql return into object
my sql Django raw query returns : [ (datetime.date(1998, 10, 8), 'swe', 'tam', 'images/3.jpg', 190, 'female', 1), (datetime.date(2020, 10, 8), 'Sal', 'ws', '1_qvQ9V4k.jpg', 122, 'male', 4) ] I want to convert the below format .how to do that. <QuerySet [<player: Sal>, <player: lee>, <player: swe>, <player: pol>, <player: Pak>, <player: Ask>, <player: sal>]> becuase i want to use it for my custom filter function : myFilter = RankFilter(request.GET, queryset=player_features.objects.all().order_by('-ranking_points')) -
Django Python DetailView not working as expected. I get an issue when I try and view a specific note
Advice required. would someone point me in the right direction? Using Django 3.1.1 with Pycharm Community 2020.2 I'm working with ListView to show all To-Do notes on one page allTasks.html {% extends "app/base.html" %} {% load static %} {% block content %} <body> <div class="section"> <div class="container" id="heading"> <h3>List of all Tasks to-date</h3> </div> <div class="container"> <ul id="taskcontainer"> {% for i in obj %} <li> <div class="row"> <div class="col-md-12"> <div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-inblock"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-primary">{{ i.name }}</strong> <h6 class="mb-0">{{ i.date }}</h6> <div class="mb-1 text-muted">Team {{ i.team_project }}</div> <p class="card-text mb-auto">{{ i.notes }}</p> <p class="card-text mb-auto">Priority: {{ i.urgency }}</p> <strong class="d-inline-block mb-2 text-danger">Completed? {{ i.completed }}</strong> <span> <a href="{% url 'task-detail' task.id %}" class="link">View</a> <a href="#" class="link">Edit</a> </span> </div> </div> </div> </div> </li> {% endfor %} </ul> </div> </div> </body> From here I go into DetailView to each individual note task_detail.html {% extends "app/base.html" %} {% load static %} {% block content %} <br> <div class="row"> <div class="col-md-12"> <div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-inblock"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-primary">{{ object.name }}</strong> <h6 class="mb-0">{{ object.date }}</h6> <div … -
Object of type QuerySet is not JSON serializable Django with AngularJS
I have a Django project where am using AngularJs as frontend. I have a very simple search where user will search a code and if the code matches from the db table it will show it. Am pretty new with angularjs what i tried is fetching objects as an array. ** my view ** @csrf_exempt def hscodesearch(request): chaptercode = '' hs4code = '' chapter_description = '' chapter_description1 = '' if (request.method == 'POST'): data = json.loads(request.body) s_t = data.get('hs_search') hs_content = { "chaptercode": chaptercode, "chapter_description": chapter_description, "chapter_description1": chapter_description1, "search_test": s_t, "hs4code": hs4code, } result = [hs_content] return HttpResponse(json.dumps({"status": 1, "data": result}), content_type='application/json') my controller.js mainApp.controller('hsController', function($scope, $http, $compile, $timeout, $location) { $scope.data = {}; $scope.init = function() { console.log("angular loaded!") } $scope.data.form = { hs_search: "", result: "", }; $scope.data.formStyle = { hs_search: "" }; $scope.submitForm = function() { //console.log($scope.data.form) var error = 0; if(!$scope.data.form.hs_search) { $scope.data.formStyle.hs_search = "is_invalid"; error++; } else { $scope.data.formStyle.hs_search = ""; } if(error==0) { var jsonCall = $http({ method: 'POST', url:'/theapp/hs-code-search', data: $scope.data.form, headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'} }); jsonCall.success(function(data, status, headers, config) { if(data.status==1) { $scope.data.form.result = data.data console.log($scope.data.form.result) } }); jsonCall.error(function(data, status, headers, config) { if(data.status==0) { $.growl.error({ message: data.error}); } }); console.log($scope.data.form) } … -
Django rest framework, DELETE request responds with "Method \"GET\" not allowed." to every valid request
Here is my code for DELETE method for a "comment" model (views.py): class CommentDelete(DestroyAPIView): queryset = Comment.objects.all() serializer_class = CommentSerializer in urlpatterns it looks like this (urls.py): ... path('delete/', views.CommentDelete.as_view()), ... For some reason when I make a direct DELETE request, the result is "Method \"GET\" not allowed." I'm also using swagger, and it gets even more weird there. There is a DELETE option but it doesn't provide any parameter field even after I've specified it in views.py (lookup_field = 'id'). When I run it, it gives me an expected error: Expected view CommentDelete to be called with a URL keyword argument named "id". -
Nested foreign key serializer with customized response in Django not working
Part of models.py class Supporting_organizationSerializer(serializers.ModelSerializer): name = serializers.CharField(required=True) image_name = serializers.CharField(required=False) class Challenge(models.Model): title = models.CharField(max_length= 1000, blank=False) supporting_organization = models.ForeignKey(Supporting_organization, related_name="supporting_organizationId",on_delete=models.CASCADE,blank=True) class Challenge_progressLog_detail (models.Model): challenge = models.ForeignKey(Challenge, related_name="challengeCreationId",on_delete=models.CASCADE) latitude = models.DecimalField(max_digits=9, decimal_places=6,default=0.0) longitude = models.DecimalField(max_digits=9, decimal_places=6,default=0.0) location_address = models.TextField(default='') photo_description = models.TextField(default='') part of serializers.py: class Supporting_organizationSerializer(serializers.ModelSerializer): name = serializers.CharField(required=True) class Meta: model = Supporting_organization fields = '__all__' class ChallengeSerializer(serializers.ModelSerializer): supporting_organization = serializers.RelatedField(source='supporting_organizationId', read_only=True) class Meta: model = Challenge fields = '__all__' class Challenge_progressLog_detail_Serializer(serializers.ModelSerializer): challenge = serializers.RelatedField(source='challengeCreationId', read_only=True) class Meta: model = Challenge_progressLog_detail fields = '__all__' I want the Challenge_progressLog_detail_Serializer to return a nested object detail which will havechallenge detail with respective supporting organization. The categorization is straightforward, having a list of challenge progress log detail in the first level, challenge types in the second, and supporting organization items in the third level. Problem is that Challenge_progressLog_detail_Serializer only returns the first and second level only i.e. only the challenge detail is shown. But I want the full nested list of Challenge_progressLog_detail with Challenge Detail, And supporting organization detail items. I used below serializer class in in challenge_progresslog_detail ==> serializer.py file for get customized response in list. Apart from I used rest_framework serializer. class challengeListSerializer(serializers.ModelSerializer): challenge_id = serializers.SerializerMethodField() challenge_title = … -
Git db.sqlite and wsgi.py file keep reverting on pull
I have a python/django/wagtail project that I built locally using db.sqlite3. I did an initial push with everything to github, and then pulled it to my server. I made a change to the wsgi file and did some work in the cms which updated the database. I made some changes locally. I changed my .gitignore to exclude db.sqlite3 and wsgi.py. git add ., git commit, git push origin master. then, on the server, sudo git pull origin master. db.sqlite3 reverts back to before I made the cms changes and the wsgi.py reverts back to pointing to my dev settings. I made the changes back to the cms but now I need to do another update when I have made even more cms changes and I do not want to overwrite the database again. wsgi.py is a small fix but still. My .gitignore # Created by https://www.toptal.com/developers/gitignore/api/django # Edit at https://www.toptal.com/developers/gitignore?templates=django ### Django ### *.log *.pot *.pyc __pycache__/ local_settings.py db.sqlite3 db.sqlite3-journal media wsgi.py # If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ # in your Git repository. Update and uncomment the following line accordingly. # <django-project-name>/staticfiles/ ### Django.Python Stack ### # Byte-compiled … -
Crispy form does not work with specific form field and button
I am trying to use crispy-forms but ran into the following two problems. This is the form.py from django import forms from menu.models import Item class TableCheckInForm(forms.Form): guest_count = forms.IntegerField(min_value =0) # item = forms.ModelChoiceField(queryset=Item.objects.all()) item = forms.IntegerField(min_value =0) and the template: {% extends "base.html" %} {% load crispy_forms_tags %} {% block title %}Table{% endblock %} {% block content %} <div class="table_order_form"> <h1>Order</h1> <form action="{% url 'table_order_view' %}" method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" class = "button table_order">PLACE ORDER</button> </form> </div> {% endblock %} And of course in the settings.py, I have declared: crispy_forms and CRISPY_TEMPLATE_PACK = 'bootstrap4' Problem 1: in forms.py, if the field item is a ModelChoiceField (the commented line), the form is out of whack, not "crispy" at all. But if I replace it with a usual form field such as IntegerField, the form is nicely formatted. Problem 2: in the template, I place a button right below the form, but when rendered, the button appears in parallel with the form, to its top right, and out of whack. Looking for some advice. Thanks. -
How to increment inside session in Django?
I try to create a counter inside session but I fail. the session is print out the result I added once and it doesn't increment the process when I want to add a new comment again. the comment will be added but counter is still equal to one so, how can I do increment into session: def post(self, request, user_slug, *args, **kwargs): my_question = UserAsking.objects.get(ask_slug=user_slug) userprof = UserProfile.objects.get(userasking__ask_slug=user_slug) comment_form = CommentForm(request.POST, instance=request.user) name = "%s %s" % (self.request.user.first_name, self.request.user.last_name) username = self.request.user.username logo = self.request.user.userprofile.logo.url if comment_form.is_valid(): comment_request = self.request.POST.get('comment', None) comment_form = Comment.objects.create(comment=comment_request, userasking_id=my_question.id, userprofile_id=userprof.id, name=name, username=username, logo=logo, comment_slug=my_question.ask_slug ) q = UserAsking.objects.get(ask_slug=my_question.ask_slug) c = comment_form u = comment_form.userprofile if 'notify_counts' in request.session: counter = request.session.get('notify_counts', 0) request.session['notify_counts'] = counter + 1 request.session.save() print('%s is commented your post: %s and comment is (%s) notify = %i' %(u, q, c, counter)) return redirect('community:question_view', user_slug) # return redirect('community:question_view', comment_form.userasking.ask_slug) return render(request, 'community/question_view.html', {'comment_form': comment_form}) -
Django - Business users to fill a form that is to be sent as an email
Here is the problem I got. I need non-developers to send occasional marketing emails via the Django admin. Nothing too crazy or customized to justify paying for mailchimp and/or similar services, but more than just plain old text (which is currently working). Markdown formatting will do. I am aware of render_to_strings and using html files. But, that would require either manipulation of those html files by non-developers or doing a lot of them to fit the marketing needs. Currently it's a simple TextField that gets sent as is to the customers. Here is the code. Models from django.db import models from django.conf import settings from django.core.mail import EmailMessage class Subscriber(models.Model): email = models.EmailField(unique=True) def __str__(self): return self.email class Email_update(models.Model): subject = models.CharField(max_length=150) content = models.TextField() -- *Change to Markdownx or something similar?* created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.subject + " " + self.created_at.strftime("%B %d, %Y") def send(self, request): subscribers = Subscriber.objects.all() email_list = [] for sub in subscribers: email_list.append(sub.email) email = EmailMessage( self.subject, self.content, "email@company", ["email@company.com"], email_list, ) email.send() Admin.py from django.contrib import admin from .models import Subscriber, Email_update # Register your models here. def send_email_update(modeladmin, request, queryset): for email_update in queryset: email_update.send(request) send_email_update.short_description = "Send selected Newsletters to … -
How can solve errors on cookiecutter django?
I tried running django using cookiecutter but while running it there were some errors error message: [2020-10-12 01:18:22,782 basehttp] ERROR: "GET /en/ HTTP/1.1" 500 23209 [2020-10-12 01:18:23,900 basehttp] INFO: "GET /favicon.ico HTTP/1.1" 302 0 [2020-10-12 01:18:23,928 log] WARNING: Not Found: /en/favicon.ico/ [2020-10-12 01:18:23,928 basehttp] WARNING: "GET /en/favicon.ico/ HTTP/1.1" 404 1335 -
DRF, read/write permission for own profile
There is a write problem about own profile. I arrange some permissions and now super user can read and write all profiles. No problem at this part. But when it comes to normal user, I give a permission that user can only read it's own profile and write it also... Read part is working, but not write part. Here is part of my code. permissons.py from rest_framework import permissions class IsSuperUser(permissions.BasePermission): def has_permission(self, request, view): return request.user and request.user.is_superuser class IsOwner(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: if request.user.is_superuser: return True else: return obj == request.user else: return False views.py class ProfileViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = ProfileSerializer def get_permissions(self): # not very sure how to handle get permissions function. # if I try [IsSuperUser, IsOwner] it's not quite working. self.permission_classes = [IsSuperUser] # # I pass the IsOwner in condition, but ofcourse then it can't write # it's own profile only read if self.action == 'retrieve': self.permission_classes = [IsOwner] return super(self.__class__, self).get_permissions() How to arrange that user can read/write it's own profile? -
How to control the format of a duration field in django
I am making a simple clock in app. You push a button to punch in, and push it to punch out. I am trying to display the hours/mins between the out-punch and the in-punch. The code works, but I would like to change the output of the code. The output I am getting is something like this: I am pretty new to django and python in general, and would like to know how I can make this output something better, maybe like x:hours y:minutes or something like that. I definitely do not need the milliseconds. For clarity, the code is as follows: The model for the process is: class Punch(models.Model): employee = models.ForeignKey("timekeeper.User", on_delete=models.CASCADE, related_name="employee_punch") punchDate = models.DateField(default='2020-01-01') punchInTime = models.TimeField(default='01:01:01') punchOutTime = models.TimeField(null=True) worked = models.DurationField(null=True) def __str__(self): return f"Emp: {self.employee}, Timestamp: {self.punchDate}, IN: {self.punchInTime}, OUT:{self.punchOutTime} -- Worked: {self.worked}" The view code is: # Create your views here. def index(request): # The punch button was pushed if request.method == 'POST': r = request.POST.get('punch_button') # Record the punch on the Punch table if r == "PUNCH IN": Punch.objects.create( employee=request.user, punchInTime=datetime.now().time(), punchDate=datetime.now().date() ) elif r == "PUNCH OUT": now = datetime.now() p = Punch.objects.filter(employee=request.user, punchDate=now.date()).last() p.punchOutTime=now.time() # Converting punch times to …