Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django QuerySet filter field in JSONField list
I've got two models. On that is not relevant except the fact that it has id and the other has a JSONField with a serialized list of first model's id's. I want to get a QuerySet of first model's objects that id's are in a JSONField's list of second model object. What I've managed to do is: @property def variant_id_list(self): return json.loads(self.variant_ids or "[]") @property def variants(self): return Variant.objects.filter(id__in=self.variant_id_list) But aboves aproach forces Django and Postgres to get variant_ids from DB then convert it to python list and then again request DB to check if an id is in a list, whereas (I think) DB could handle whole operation itself. Is there a way to do this simplier? I can't change JSONField to ArrayField or any other, it has to be JSONField. -
How to print current details of a logged in user django
I have used oneToOneField to connect username to the sellerdetails model. In the dashboard, I print the username with {{ request.user }} and now I want to print the name of the user, which is stored in the SellerDetail model in models.py, linked to the current user. I have tried using {{ request.name }} But it does not return any value. name here is a field defined in my model SellerDetails. How can I print the deatils of the currently logged in user? -
What is shallow key transformation
I was reading about CVE-2019-14234 Detail.There it is mentioned about shallow key transformation.Can you please tell me what is shallow key transformation.It would be better if someone can explain about this CVE also.Please ignore this if this question is at wrong place. -
TimeRotated logging in Python/Django not working as expected
i have the following handler configuration: "handlers": { 'system_file': { 'level': 'DEBUG', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': os.path.join(LOG_FOLDER, "all.log"), 'formatter': 'verbose', 'when': 'midnight', 'backupCount': '30', } } Now based on this configuration my logs should get rotated every midnight. In the all.log file, everything gets logged properly with correct timestamp, but when the rotation happens, I see a strange content in the backup log files. For example: Let's say today is 2019-10-29, the all.log file starts storing all the logs from 2019-10-29 00:00:00 to 2019-10-29 23:59:59. The next day i.e. on 2019-10-30 (when rotation would have happened), when I go and check all.log.2019-10-29, it contains log from 2019-10-30 00:00:00 till 2019-10-30 01:00:00, instead of the log of 2019-10-29 and the all.log file starts storing logs of 2019-10-30 from 00:00:00 onwards. So basically all my backup files only contain log of the next day from 00:00:00-01:00:00. all.log as on 2019-10-30 [DEBUG 2019-10-30 00:00:07,463 cron.py:44] ..... [DEBUG 2019-10-30 00:00:11,692 cron.py:44] .... [DEBUG 2019-10-30 00:00:13,679 cron.py:44] .... . . . . *Till current time* all.log.2019-10-29 as on 2019-10-30 [DEBUG 2019-10-30 00:00:07,463 cron.py:44] ..... [DEBUG 2019-10-30 00:00:11,692 cron.py:44] .... [DEBUG 2019-10-30 00:00:13,679 cron.py:44] .... . . . [DEBUG 2019-10-30 00:00:52,463 cron.py:44] ..... [DEBUG 2019-10-30 00:00:55,692 cron.py:44] … -
Enabling logging for OpenLDAP client?
I'm trying to do some authentication inside a Django application using django-auth-ldap via the OpenLDAP client. It's not working so how do I enable some logging? I CAN make LDAP queries using ldapsearch so fundamentally my config is correct and I tried enabling logging for django-auth-ldap but it just reports an Error(0) which is completely unhelpful. So how do I enable logging for the OpenLDAP client part of the equation? Ideally I would like to see what queries it is making and using which config is being passed down from django-auth-ldap. I did find ldap.conf but the syntax man page implies there is no logging or debug option. -
for loop is not working in one template and different request ( just first loop shown )
I have model and passed content base on each dashboard slug but item of dashboard for first one just create and other item not shown , what is my problem code? View: def dashboards(request,slug): domain_list = Domain.objects.all() category_list = Dashboard.objects.all() widget_list = Widget.objects.filter(dashboard_list__Dashboard_name__contains=slug) return render(request, "Dashboards.html", {'domain_list': domain_list, 'category_list': category_list, 'widget_list': widget_list }) class DashboardList(generic.ListView): queryset = Widget.objects.filter(status=1).order_by('-created_on') template_name = 'Dashboards.html' class DashboardDetail(generic.DetailView): model = Widget template_name = 'Dashboards.html' url : urlpatterns = [ path('dashboards/<slug:slug>/',dashboards, name='dashboard_list'), ] Dashboard.html: {% for Post in widget_list.all %} {{ Post.title }} {% endfor %} I have menu and slug call from them: {% for Category in domain.categorys.all %} <ul class="treeview-menu"> <li><a href="http://127.0.0.1:8000/dashboards/{{ Category.slug }}#"><i class="fa fa-adjust"></i> {{ Category.Dashboard_name }}</a></li> </ul> {% endfor %} Model : class Widget(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) dashboard_list = models.ForeignKey(Dashboard, on_delete=models.CASCADE, related_name='Widget_category') def __str__(self): return self.title class Dashboard(models.Model): Dashboard_name = models.CharField(max_length=20) slug = models.SlugField() Domain=models.ForeignKey(Domain,related_name='categorys',on_delete=models.CASCADE) -
Delete user image from S3 and update his profile with default one also stored on S3
I'm creating user profile page in Django and I want to give users ability to delete previously uploaded avatar and replace it with default one. What I have done is that after pressing delete button the image on AWS S3 is deleted, but I don't know how to update user.image in database. If it was a string or int type, there would be no problem. But the question is how do I get the image from AWS, transform it to whatever object type is needed and update database? models.py: class Patient(models.Model): image = models.ImageField(default='default.jpg', upload_to=get_file_path) I have also implemented an ability to update an old image with new one, so I've create an UpdateForm for that. On a page with that form is also a button that calls delete_image from views.py forms.py class PatientUpdateForm(forms.ModelForm): image = forms.ImageField(required=False) class Meta: model = Patient fields = ['image'] views.py @login_required def delete_image(request): old_image_name = request.user.patient.image.name # refers to the specific user # don't know what's next Patient.objects.filter(pk=request.user.patient.pk).update(??) storage.delete(old_image_name) return redirect('profile') -
How to: Django Parler CRUD Forms
I am using Parler for localizing my models. Django Admin works fine, but now I want to recreate the admin forms in the frontend. So far, I can create a new model but it is always created in the default language. The question now is, how can I set the language? Best case scenario would be, that I can select the language via <select> in the form, but the default value would be set by a get param language=iso_code or if it is way easier using the language tabs like in Django Admin. Model class Category(MPTTModel, TranslatableModel): title = TranslatedField(any_language=True) description = TranslatedField() slug = TranslatedField() parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children', db_index=True) objects = CategoryManager() def save(self, *args, **kwargs): super(Category, self).save(*args, **kwargs) class CategoryTranslation(TranslatedFieldsModel): title = models.CharField(max_length=200) description = models.TextField(null=True) slug = models.SlugField() master = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='translations') class Meta: unique_together = ( ('language_code', 'slug'), ) View @method_decorator(login_required, name='dispatch') class CategoriesCreateView(TranslatableCreateView): model = Category context_object_name = 'categories' template_name = 'categories/update.html' form_class = CategoryForm object = Category() def get(self, request, *args, **kwargs): request.DEFAULT_LANGUAGE = LANGUAGE_CODE request.meta_title = _('Create Category') return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): request.DEFAULT_LANGUAGE = LANGUAGE_CODE request.meta_title = _('Create Category') return super().post(request, *args, **kwargs) … -
how to redirect after logging in django admin page to home page if user is staff
Give me any links or idea about how to redirect from Django admin login page to other pages. -
Select raw data from multi table
I would like to select raw data from multiple tables. eg. query = tempmodel.objects.raw('select empid as id,employee.empid,ccmaster.cscid from employee left join ccmaster on employee.cscid = ccmaster.cscid' Am I need to create a new model for tempmodel that includes all required fields? I already tried with cursor.execute but this only returns result value, not with the field. How can I select raw for multi-table? I already check that one=> raw sql with multiple table but honestly, I don't understand the answer. -
Is there a way to change what icon set for tempus dominus datetimepicker?
I've just started using tempusdominus for Bootstrap 4.0. I've got it working all well and integrates nicely with my backend. However, my site is already using an icon set (material-icons) and I want to see if I can use the icons in this font already. I changed this <div class="input-group-text"><i class="fa fa-calendar"></i></div> To use my icon from material-icons. However, I can't seem to figure out how to change the icon of the clock. I've located it in the Javascript and also looked at the docs and it only seems possible to me to change which Font Awesome icon you use. -
Django reverse function isn't properly working in management commands
I'm trying to send emails via a management command, but I'm having a hard time adding an unsubscribe link. As I stated in the title, Django reverse function from django.core.urlresolvers isn't working as expected. Honestly, I've no idea where to look. I've tried to use FORCE_SCRIPT_NAME and SCRIPT_NAME settings but these didn't get me anywhere. I'm using Django 1.8 and Python 2.7. for subscriber in active_subscribers: news_template_params['unsubscribe_link'] = reverse('news:news_unsubscribe_from_subscription', args=(subscriber.code,)) send_mail( subject=subject, message=message, html_message=render_to_string('news/email-news.html', news_template_params), from_email=from_email, recipient_list=[subscriber.email], fail_silently=True ) When I use print to see the result of reverse function, I see: print news_template_params['unsubscribe_link'] # ==> /None/news/subscription/unsubscribe/e4559105-dfb3-4c42-8019-d1ac1sasd23 The same goes for get_absoulte_url method of news objects in email template. Why is there /None/? How does it appear? -
Why can't I find elements on the page using behave-django?
I am simply trying to create my first behavioural test to locate a link on a page so that I can click on it. I have tried this with both the Chrome and Firefox drivers, but I keep getting the following error when I try to : selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: Cookie Policy I've been following several guides, but they all seem to be pretty consistent, and have found no significant discrepancy between my implementation and their instruction. The driver setup looks like this in environment.py: def before_scenario(context, feature): context.browser = webdriver.Firefox() context.browser.implicitly_wait(10) The failing step is: @when('I click on "{link_text}"') def i_click_on(context, link_text): link = context.browser.find_element_by_link_text(link_text) link.click() The scenario looks like this: Scenario: Navigate to cookie policy Given I am on the homepage When I click on "Cookie Policy" The relevant part of the html being searched is: <a href="/terms">Terms and Conditions</a>, <a href="/privacy">Privacy Policy</a>, <a href="/research-policy">Research Policy and Consent</a>, and <a href="/cookie-statement">Cookie Policy</a> The resulting error is: /Users/olorton/.local/share/virtualenvs/ogg-django-7ceMMn7K/bin/python /Applications/PyCharm.app/Contents/helpers/pycharm/behave_runner.py -t wip --stop --no-skipped --format progress manage.py behave -fcom.jetbrains.pycharm.formatter /Users/olorton/Code/ogg-django/features -t wip --stop --no-skipped --format progress -n Creating test database for alias 'default'... features/basic_user_flow.feature Traceback (most recent call last): File "/Users/olorton/.local/share/virtualenvs/ogg-django-7ceMMn7K/lib/python3.7/site-packages/behave/model.py", line 1329, in run match.run(runner.context) File … -
Why does Django ORM add a not specified field in the GROUP BY clause
I want to perform this query with the ORM : SELECT ARRAY_AGG("wcm_workflows_transition"."name") AS "names" FROM "wcm_workflows_transition" GROUP BY "wcm_workflows_transition"."workflow_id" ORDER BY "wcm_workflows_transition"."name" ASC; To do this I use Transition.objects.values("workflow__id").annotate(names=ArrayAgg("name")).values("names") But for some unknown reasons, Django adds "wcm_workflows_transition"."name" to the GROUP BY clause. So the query performed by the previous Django ORM expression is : SELECT ARRAY_AGG("wcm_workflows_transition"."name") AS "names" FROM "wcm_workflows_transition" GROUP BY "wcm_workflows_transition"."workflow_id", "wcm_workflows_transition"."name" ORDER BY "wcm_workflows_transition"."name" ASC; I cannot use aggregate because I want to use the queryset in a subquery. Here are the models (simplified) class Workflow: name = models.CharField(_(u'Name'), max_length=100, unique=True, db_index=True) class Transition(models.Model): name = models.CharField(_(u'Name'), max_length=100, db_index=True) workflow = models.ForeignKey(Workflow, verbose_name=_(u'Workflow'), related_name='transitions', db_index=True, on_delete=models.PROTECT) class Meta: ordering = ('name', ) Now I have two questions : Why Django ORM adds this fields to the GROUP BY clause ? How to perform the expected query using the ORM What I have tried : I thought that Django added in the GROUP BY all the fields that are used in the annotation, so I changed the field aggregated but it didn't change the grouped by fields. Then I asked myself if the name field had any constraint. In fact it has the db_index=True constraint. So I changed … -
Why duplicate data(notification) is saved(for same event) and web-socket connection is killed forcefully in Django-Channels?
I have created a real time notifier using web-socket, implemented using Django-Channels. It sends the "Post Author" a real time notification whenever any user likes the author's post. The problem is, for single like button click, multiple notifications are being saved in database until the web-socket is disconnected. In the following lines I will provide detail of what is actually happening(to the best of my understanding) behind the scene. 1. Like button is clicked. <a class="like-btn" id="like-btn-{{ post.pk }}" data-likes="{{ post.likes.count }}" href="{% url 'like_toggle' post.slug %}"> Like </a> JavaScript prevents the default action and generates an AJAX call to a URL. $('.like-btn').click(function (event) { event.preventDefault(); var this_ = $(this); var url = this_.attr('href'); var likesCount = parseInt(this_.attr('data-likes')) || 0; $.ajax({ url: url, method: "GET", data: {}, success: function (json) { // DOM is manipulated accordingly. }, error: function (json) { // Error. } }); }); The URL is mapped to a function defined in views.py. (Note: Code for Post Model is at the last if required for reference.) # In urls.py urlpatterns = [ path('<slug:slug>/like/', views.post_like_toggle, name="like_toggle"), ] # In views.py @login_required def post_like_toggle(request, slug): """ Function to like/unlike posts using AJAX. """ post = Post.objects.get(slug=slug) user = request.user … -
Is it possible to use vue.js with wagtail stream-fields without using DRF?
is it possible to use vue.js with wagtail stream-fields without using DRF? I would like to use wagtail and vue.js without going the headless route. So is it possible to use vue.js as part of wagtail's stream-field? -
Python Ajax Request to get searches data
At first here you go: https://www.ahpra.gov.au/Registration/Registers-of-Practitioners.aspx If you search like smith, you will get some data and if you search whatever name you want, you will get data. so now I am tyring to get data with python request. import requests url = 'https://www.ahpra.gov.au/Registration/Registers-of-Practitioners.aspx' resposne = requests.get(url, params={'key': 'smith'}) print(resposne.text) then I dont see the data the searched. I want the data with what keyword i search with python. I want to get this data to visualize on my Django website but i don't to save the data in the database. I just want when user search data from the frontend, then they will see the data on the page. Can anyone help me how to get it done? How to search data with python request? I heard of selenium but I knew it works with a browser but I am confused will it work with Django following my requirement? -
AttributeError After processing the view
After Submitting the like button data is successfuly updating with the database but after this step it won't redirecting to the successful url. instead of that it is throwing attribute error. If I use HttpResponseRedirect('/album/') instaed of successful url this error is not comming. models.py Codes in models.py class VoteManager(models.Manager): def get_vote_or_unsaved_blank_vote(self,song,user): try: return Vote.objects.get(song=song,user=user) except ObjectDoesNotExist: return Vote.objects.create(song=song,user=user) class Vote(models.Model): UP = 1 DOWN = -1 VALUE_CHOICE = ((UP, "👍️"),(DOWN, "👎️"),) like = models.SmallIntegerField(null=True, blank=True, choices=VALUE_CHOICE) user = models.ForeignKey(User,on_delete=models.CASCADE) song = models.ForeignKey(Song, on_delete=models.CASCADE) voted_on = models.DateTimeField(auto_now=True) objects = VoteManager() class Meta: unique_together = ('user', 'song') views.py codes in views.py class SongDetailView(DetailView): model = Song template_name = 'song/song_detail.html' def get_context_data(self,**kwargs): ctx = super().get_context_data(**kwargs) if self.request.user.is_authenticated: vote = Vote.objects.get_vote_or_unsaved_blank_vote(song=self.object, user = self.request.user) vote_url = reverse('music:song_vote_create', kwargs={'song_id':vote.song.id}) vote_form = SongVoteForm(instance=vote) ctx['vote_form'] = vote_form ctx['vote_url'] = vote_url return ctx class SongVoteCreateView(View): form_class = SongVoteForm context = {} def get_success_url(self,**kwargs): song_id = self.kwargs.get('song_id') return reverse('music:song_detail', kwargs={'pk':song_id}) def post(self,request,pk=None,song_id=None): user = self.request.user song_obj = Song.objects.get(pk=song_id) vote_obj,created = Vote.objects.get_or_create(song = song_obj,user = user) vote_form = SongVoteForm(request.POST, instance=vote_obj) if vote_form.is_valid(): new_vote = vote_form.save(commit=False) new_vote.user = self.request.user new_vote.save() return new_vote Error code Please refer this link for the traceback 'Vote' object has no attribute 'get' -
Token authentication in django (rest_framework) not working
the title pretty much says it all. I'm trying to authenticate with a token. I am getting information from the django database to my flutter app. I've successfully retrieved my token from the rest_framework and added it to the headers of the rest request. I printed these headers in django which results in { 'Content-Length': '0', 'Content-Type': 'text/plain', 'User-Agent': 'Dart/2.5 (dart:io)', 'Accept-Encoding': 'gzip', 'Authorization': 'Token 10cf58e1402b8e48c1a455aaff7f7bcf53e24231', 'Host': '192.168.0.110:8000' } The result however, is the webpage with a login form and not the rest data that I've requested. What am I missing? settings.py ... REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } ... -
How to add a registered user to the User model (within Authentication and authorization section) in Django?
A newbie here. This is a Django related question. How can I save a newly registered user to the User Model (auth.model)? Currently, the only account which is seen inside the admin panel -- under Users (Authentication and Authorization section) is the superuser (aka me). I am using DRF (Rest framework) in order to register a user and not an HTML form. models.py: class Register(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) username = models.CharField(max_length = 100) email = models.EmailField(max_length = 100) password = models.CharField(max_length = 100) def __str__(self): return self.name views.py: class RegisterView(APIView): def post(self, request, format=None): serializer = RegisterSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response("Thank you for registering", status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py: from rest_framework import serializers from .models import Register class RegisterSerializer(serializers.ModelSerializer): class Meta: model = Register fields = ['username', 'email', 'password'] When registering a new user via POSTMAN, the data is saved within the Register model (which is fine) but my issue is that it's not seen within the Users model. Any feedback is highly appreciated. Thank you. -
How can I annotate?
How can I annotate all copies_sold of books for each Author from django.db import models from django.db.models import Count class AuthorQuerySet(models.QuerySet): def annotate_with_copies_sold(self): return Author.objects.annotate(num_copies=Count('books__copies_sold')) class AuthorManager(models.Manager): def get_queryset(self): return AuthorQuerySet(self.model, using=self._db) def annotate_with_copies_sold(self): return self.get_queryset().annotate_with_copies_sold() class Author(models.Model): objects = AuthorManager() first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class Book(models.Model): title = models.CharField(max_length=30) copies_sold = models.PositiveIntegerField() author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books') -
SMTPSender Issue with Django and EmailMultiAlternatives
I'm working on a little Django project for my corporation and I need to send emails through my web application. The issue encountered is: SMTPSenderRefused (530, b'5.7.1 Client was not authenticated', 'valentin.j*****@*****.com') I configured the mail settings correctly: EMAIL_HOST = 'ptx.send.corp.****' EMAIL_HOST_USER = 'valentin.j*****@*****.com' EMAIL_PORT = 587 EMAIL_USER = '' EMAIL_PASSWORD = '' And this is my code in my views.py file: class TemplateGenerator(TemplateView): form_class = CommunicationForm template_name = 'form.html' success_url = '/HTML_Result/' def get(self, request): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('HTML_Result') args = {'form': form} return render(request, self.template_name, args) class HTMLResult(TemplateView): template_name = 'template_1.html' def get(self, request): data = Communication.objects.values().latest('id') get_template_email(data) return render(request, self.template_name, {'data': data}) def get_template_email(data): subject = "Communication E2E" context = {'data': data} from_email, to = settings.EMAIL_HOST_USER, settings.EMAIL_HOST_USER html_content = render_to_string('template_1.html', context) text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() I have a form page with some fields, once the form is validated, I overcome to an HTML page completed by form values. And this page, this template should be send by email (up to now, there is no button to send email, just when I come to … -
save() missing 1 required positional argument: 'self'
I need help with figuring out this error. Does anybody know what I did wrong here? This is the model.py database that gives out the error -
Passing multiple arguments in django view
I have tree different users and I want to use one view function and three different forms. So I need to pass two arguments to user_signup view: the request object and the form Class. In urls.py I have the following code path('signup/admin/', views.user_signup(request, AdminSignupForm), name='admin_signup') in views.py I defined user_signup function def user_signup(request, form, template_name='users/signup_staff.html'): if request.method == 'POST': form = form(request.POST) if form.is_valid(): user = form.save() # save function is redefined in AdminSignupForm else: form = form() return render(request, template_name, {'form': form}) How can I pass a request object to user_signup? -
Requested resource '{spyne.examples.django}' not found
I'm trying to develop a soap service in Django using Spyne.i clone spyne for app 'Hello_world' in django application, but i get error.i need help. My codes is similar with the below.. app = Application([HelloWorldService], 'spyne.examples.hello.http', in_protocol=HttpRpc(), out_protocol=Soap11(), ) but i get bellow error. <faultcode>soap11env:Client.ResourceNotFound</faultcode> <faultstring>Requested resource '{spyne.examples.django}' not found</faultstring> <faultactor/>