Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Getting column max value as Integer
I have this: maxAux = Auxi.objects.all().aggregate(Max('nroAux')) Then I need to add +1 to its value, but doing: maxAux = maxAux+1 will throw an error since "aggregate(max" returns a string value like "{'nroAux__max': 5}" and I only need this number 5. Please don't asnwer anything about id or django default autoincr column. I really need to make additions to my column "nroAux". Thanks!! -
Custom form Filed using cleaning/validation in field
I have a django custom form field: class RichTextFormField(forms.fields.CharField): def __init__(self, *args, **kwargs): """Create a new WYSIWYG form field. """ kwargs.update({ 'widget': CustomTextWidget() }) super().__init__(*args, **kwargs) I know I can do clean after in the form, but I want to do some cleaning (if is possible) directly on the field(because I will repeat this field multiple times. I want to do a min-length if the attribute is available, and also an html clean. I don't know what method to overwrite and how. -
How to use custom names in Options of Select tag?
schema_fld is a list of objects and how can I display the custom names in Select tag. I want to append values to the display string of the model. If the display string is 'Apple' then I want to display it as 'Fruit-Apple' in the UI. I cannot use the (str) method in models as it is being used in other part of the application. I created a method in model 'domval_display' but calling that from html is not working. <table class='no_error'> <thead> <tr> <th>Schema Fields</th> </tr> </thead> <tr> <td> {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {{ form.schema_fld.errors.as_ul }}{{ form.schema_fld }} </td> </tr> {% endfor %} </table> class SchemaFld(models.Model): schema_fld_id = models.AutoField(primary_key=True) fld_name = models.CharField(max_length=256) def domval_display(self): return 'Fruit-'+str(self.fld_name) def __str__(self): return str(str(self.fld_name)) -
Best approach for names input
I am making a little website with python/django for publication handling where an author can upload a paper. The website is only used by a small group of institute members (around 100 people). So there is a field for co-authors. Most of the time all the co-authors are the institute members, but sometimes they are also not from the institute (so they don't have a UserProfile in the system). I need to make co-author input field user friendly, so there should be some kind of autocomplete when you start typing the name of a person. And a person mentioned in the co-authors field should receive an automated message, saying a new publication was added for them. What would be the best approach to make such a field? If I make it just a text field and after parse a string to search for people names there is a always a chance for people named the same. -
DRF Serializer field for intermediate mode
I am making am app to control the presence of students. I have 4 models: class Student(models.Model): name = models.CharField(max_length=70) class Justification(models.Model): name = models.CharField(max_length=70) class Session(models.Model): date = models.DateTimeField() present = models.ManyToManyField(Student) absences = models.ManyToManyField(Student, related_name='absences_set', through='Absence') class Absence(models.Model): session = models.ForeignKey(Session, on_delete=models.CASCADE) atleta = models.ForeignKey(Student, on_delete=models.CASCADE) justification = models.ForeignKey(Justification, on_delete=models.CASCADE) The models have more fields and different names (I translated the names to English) but this is basically it. I am using DRF framework to make an API. I have setup the endpoints (and serializers) for Student, Justification and Absence but I can't figure out how to make the serializer for the Session model. I want it to work when someone makes the following POST (I only need an endpoint to create Sessions) request (I am using a ViewSet for the view): { "date": "2019-02-01T10:08:52-02:00" "present": [ 2 ], "absences": [ { "student": 1, "justification": 1 } ] } But the absences are not created. How can I make this nested relationship work? ps: I can only make one request that's why I don't want to make one request to create a Session and then many requests to create Absences and need it all together. If there is … -
How to use Django User Roles and Permissions on a React Frontend with Django Rest Framework
I am using Django Rest Framework with React on the Frontend. I am using Token Athentication and its all working fine. I now have a requirement of making sure different users can access different things depending on their rights. This is possible using Django admin but my users will be using the React frontend. I looked through Django Rest permissions but I didnt see how I can use this on my React Frontend. I also looked at Django guardian but I am not sure if its what I need for my requirement. I have looked through many tutorials and articles but I can't seem to find any straight forward way to achieve this. Here is the approach I have used sofar: Created a Serializer for the inbuilt User Model, then Created a ViewSet and I can now access the list of users on through the api. from django.contrib.auth.models import User class UserSerializer(SerializerExtensionsMixin,serializers.ModelSerializer): class Meta: model = User fields = '__all__' class UserViewSet(SerializerExtensionsAPIViewMixin, viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() router = DefaultRouter() router.register(r'user', UserViewSet, basename='user') Using this I am able to access a user with the groups and permissions as shown in the picture below. I am now going ahead … -
django-rest-auth google social auth by access token
I'm using django-rest-auth for social auth via API. I've configured Facebook and it works perfectly but I've got some issues with Google social auth. I've added to INSTALLED_APPS: allauth.socialaccount.providers.google', Created views: from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter from allauth.socialaccount.providers.oauth2.client import OAuth2Client class CustomGoogleOAuth2Adapter(GoogleOAuth2Adapter): basic_auth = False class GoogleLogin(SocialLoginView): adapter_class = CustomGoogleOAuth2Adapter client_class = OAuth2Client Created app by admin panel I've got access_token from https://developers.google.com/oauthplayground/ When I tried to log in by endpoint I got an error: Reverse for 'redirect' not found. 'redirect' is not a valid view function or pattern name. -
Using context as javascript array
Using django view i am returning a list of lists.I want to pass that in javascript code but i am getting Error:Not an array class SessionTemplateView(LoginRequiredMixin,TemplateView): template_name = "dashboard/map.html" def get_context_data(self, **kwargs): #Existing lines of code visitor_page_views = [['Page','Views'],['page1',5],['page2',4],['page3',1]] context['page_views'] = visitor_page_views return context Below is the javascript code where i want to pass this list of lists. map.html <div id="piechart"></div> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> // Load google charts google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); // Draw the chart and set the chart values function drawChart() { var data = google.visualization.arrayToDataTable({{ page_views}}); // Optional; add a title and set the width and height of the chart var options = {'title':'Page Views', 'width':950, 'height':700}; // Display the chart inside the <div> element with id="piechart" var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); } </script> I know that {{ page_views }} will produce string i.e var data = google.visualization.arrayToDataTable( "[['Page','Views'],['page1',5],['page2',4],['page3',1]]"); How can i pass this as an array of arrays i.e: var data = google.visualization.arrayToDataTable([['Page','Views'],['page1',5],['page2',4],['page3',1]]); -
Reusing view to render template inside a different view
I have many partial views that are being loaded with AJAX: class PartialView1(TemplateView): template_name = 'partialview1.html' Main page loading all these partials in place: $.get('{% url 'partialview1' %}', function(data) { $('#view1-block').html(data); }); I would like to be able to reuse views like PartialView1 to render their templates within other views and include it in the response: class MainView(TemplateView): def get_context_data(self, **kwargs): rendered_view1 = PartialView1.????? return super(MainView, self).get_context_data(rendered_view1=rendered_view1, **kwargs) That way in the main view I can do the following: {% if rendered_view1 %} $('#view1-block').html(data); {% else %} $.get('{% url 'partialview1' %}', function(data) { $('#view1-block').html(data); }); {% endif %} I know I could use render_to_string, but I would need to build context again. I would like to resuse the logic encapsulated in each CBV and render their templates as strings just as if we were performing a GET request. What are my options here? -
Django: Need help checking if the user group has the specific permission whilst looping through all permissions
First off I have a model named Account, which is connected to the default User model. As of now, I'm looping through all permissions associated with the Account model, but I also want to check if the Account profile page's user has the one or more of the specific permissions being looped through. This is just to create an overview. models.py class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) site = models.CharField(max_length=50, choices=(('all', 'all'), ('danielk', 'danielk'), ('flis', 'flis'), ('vmusic', 'vmusic')), blank=True) site_role = models.CharField(max_length=50, choices=(('Administrator', 'Administrator'), ('Moderator', 'Moderator'), ('Editor', 'Editor'))) phone_number = models.CharField(max_length=8) birth_date = models.DateField() street_adress = models.CharField(max_length=255) note = models.TextField(blank=True); zip_code = models.CharField(max_length=4) city = models.CharField(max_length=255) def formatedPhone(self, country=None): return phonenumbers.parse(Account.phone_number, "NO") """ def __str__(self): return "%s %s" % (self.User.first_name, self.user.last_name) """ def get_absolute_url(self): return reverse('account-detail', kwargs={'pk': self.pk}) class Meta: verbose_name = 'Account meta' verbose_name_plural = 'Accounts meta' permissions = ( ("has_user_hijack_permission", "Allows the user to log in as others"), ("has_user_management", "Allows a user to deactivate/delete other users"), ("has_user_site_edit", "Allows a user to edit site and role details"), ("has_user_takeout", "Can export user details"), ) views.py class cms_users_user_permissions(generic.DetailView): model = Account template_name = 'cms/users/cms-users-user-permissions.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["permissions"] = Permission.objects.filter(content_type=ContentType.objects.get_for_model(Account)) #context['permissions'] = Permission.objects.filter(content_type_id=7) return context table.html <table class="table … -
how can i reverence a url in django settings.py
I'm trying to reference a url in my settiings.py file. I currently have this in my urls.py file from django.urls import ( path, reverse_lazy, re_path ) my_app = 'accounts' re_path( r'^reset_password_confirm/(?P<uidb64>[0-9A-Za-z_-]+)-(?P<token>.+)/$', PasswordResetConfirmView.as_view( success_url = reverse_lazy('accounts:password_reset_complete') ), name = 'password_reset_confirm', ), and I have this in my settings.py file LOGIN_EXEMPT_URLS =( 'accounts/login/', 'accounts/register/', 'accounts/', 'accounts/reset_password/', 'accounts/reset_password_done/', r'^accounts/reset_password_confirm/(?P<uidb64>[0-9A-Za-z_-]+)-(?P<token>.+)/$', 'accounts/password_reset_complete/', ) I think my major problem is with the "r'^accounts/reset_password_confirm/(?p[0-9A-Za-z_-]+)-(?p.+)/$'". because the others seems to work -
Django in Visual Studio: "ImportError cannot import name '_remove_dead_weakref'"
I am beginning to work on a project in a Django Web with Visual Studio. As far as I try to create a superuser or try to run it without debugging I get the following error. Traceback (most recent call last): File "C:\Users\iandrada\Documents\ABRA_WEBSITE\ABRA_WEBSITE\ABRA_WEBSITE\manage.py", line 15, in from django.core.management import execute_from_command_line File "C:\Users\iandrada\Documents\ABRA_WEBSITE\ABRA_WEBSITE\ABRA_WEBSITE\env_ABRA\lib\site-packages\django__init__.py", line 3, in from django.utils.version import get_version File "C:\Users\iandrada\Documents\ABRA_WEBSITE\ABRA_WEBSITE\ABRA_WEBSITE\env_ABRA\lib\site-packages\django\utils\version.py", line 5, in import subprocess File "C:\Users\iandrada\AppData\Local\Programs\Python\Python36\Lib\subprocess.py", line 50, in import signal File "C:\Users\iandrada\AppData\Local\Programs\Python\Python36\Lib\signal.py", line 3, in from functools import wraps as _wraps File "C:\Users\iandrada\AppData\Local\Programs\Python\Python36\Lib\functools.py", line 23, in from weakref import WeakKeyDictionary File "C:\Users\iandrada\AppData\Local\Programs\Python\Python36\Lib\weakref.py", line 12, in from _weakref import ( ImportError: cannot import name '_remove_dead_weakref' Compilación del proyecto "ABRA_WEBSITE.pyproj" terminada -- ERROR. I have tried reinstalling VS, or updating Python to a more recent version, but still haven't found any solution. Thanks for all! -
How to have a form available for all Django Views
So I need to place a Contact Form (name, email, text), on the footer of the website. I already have the form created and a FormView that was being used to submitting it. But now I need basically to place that on the base.html of the website, but I am not sure how to handle the submit. I thought about using a templatetag to render the form, but can't think of a way to handle the form submission without touching ALL my views. Any idea? -
How to use django rest framework nested serializer
I have two models User and Address. The Address model is connected to User model as OneToOneField. In my case I trying to update the User model, in Initial case the address field of User model is null. So in first case When I update User model, I want to create an Address. In other cases only need to update address. How to achieve this? models.py class User(AbstractUser): first_name = models.CharField(max_length=100, blank=True, default=None, null=True) dp = models.ImageField(upload_to='profiles/', blank=True) gender = models.CharField(choices=GENDER_TYPE_CHOICES, max_length=10, default=None, blank=True, null=True) marital_status = models.BooleanField(default=False) dob = models.DateField(default=None, blank=True, null=True, ) email = models.EmailField(default=None, blank=True, null=True, unique=True) mobile = PhoneNumberField(blank=True, null=True, unique=True) fire_token = models.TextField(blank=True, default=None, null=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) def __str__(self): return str(self.first_name) class Address(models.Model): user = models.OneToOneField(User, default=None, null=True, blank=True, related_name="address_user", on_delete=models.CASCADE) raw = models.CharField(max_length=100, blank=True, default=None, null=True) street_number = models.CharField(max_length=100, blank=True, default=None, null=True) route = models.CharField(max_length=100, blank=True, default=None, null=True) locality = models.CharField(max_length=100, blank=True, default=None, null=True) postal_code = models.CharField(max_length=6, blank=True, default=None, null=True) state = models.CharField(max_length=100, blank=True, default=None, null=True) state_code = models.CharField(max_length=6, blank=True, default=None, null=True) country = models.CharField(max_length=100, blank=True, default=None, null=True) country_code = models.CharField(max_length=6, blank=True, default=None, null=True) def __str__(self): return str(self.raw) serializers.py class AddressSerializer(ModelSerializer): class Meta: model = Address fields = '__all__' class … -
Using Django with an html editor, econding and decoding the text
I'm receiving data in Django using the editor Quill, data formatted as HTML. It is possible to encode/clean the data when I push in the database, and when I retrieve to be back in html ? If yes how ? Also I use only paragraph,lists and (this is passed by editor), but I want to check if the user doesn't add anything else in code. -
django alternative for using getloadavg
I want do show the load average 1' 5' 15' in the dashboard in my django app. try: data = os.getloadavg() except Exception as err: data = str(err) throws an exception. But it works in a python console. Is there another way to get the information? -
How to create a running total input field in django form?
How to create a running total using javascript in django form. I tried this previously but was unsuccessful: <table class="table" id="calculate"> {{ contras.management_form }} <thead> <tr> <th class="col-md-6">Particulars<i class="material-icons" style="font-size:16px;color:red">*</i></th> <th class="col-md-6">Amount<i class="material-icons" style="font-size:16px;color:red">*</i></th> </tr> </thead> <tbody> {% for form in contras.forms %} <tr class='{% cycle "row1" "row2" %} formset_row'> <td class="col-md-6">{{ form.id }} {{ form.particular}}</td> <td class="col-md-6 amounts">{{ form.amount}}</td> </tr> {% endfor %} <tr> <td class="col-md-6"></td> <td class="col-md-6 totaled"><input type="text" name="total"></td> </tr> </tbody> </table> This is the javascript code I tried: <script type="text/javascript"> $(document).ready(function(e){ $('#calculate tbody').change(function(){ var totals = 0; $(".amounts").each(function(){ totals = totals + parseInt($(this).val()); }) $(".totaled").val(totals); }); }); </script> I am using inline formset in my template I want to display the running total of all the amount given in my inline form.. How is that possible to do it in django? any guess? Thank you -
How can I implement session expiry based on users inactivity in django framework?
I am using django request.session.set_expiry() to expire session for a logged in user. But it expires session even though user is active. if user is not None: login(request, user) request.session.set_expiry(60) -
Struggles unpacking a two-dimensional list in template
I'm passing a bunch of data into my template but am having a hard time breaking apart a zipped list of items. No matter what I try, I always get the following error. Need 2 values to unpack in for loop; got 0. Heres my code: views.py import requests from django.shortcuts import render from django.http import HttpResponse dictionary, words = [[], []], [] def home(request, username='johnny'): template_name = 'main/index.html' url = "https://www.duolingo.com/users/{}".format(username) getUserData(url) context = { 'username': username, 'dictionary': dictionary, 'words': words, } # print(context) return render(request, template_name, context) def getUserData(url): response = requests.get(url) userdata = response.json() wordlists, explanations = [], [] for language in userdata['language_data']: for index in userdata['language_data'][language]['skills']: if index.get('levels_finished') > 0: wordList = index.get("words") wordlists.append(wordList) explanations.append(index.get("explanation")) for wordItem in wordList: words.append(wordItem) dictionary = list(zip(wordlists, explanations)) relevant template {% block content %} {% for words, exp in dictionary %} {{ words }} {{ exp|safe }} {% endfor %} {% endblock %} I've tested this code, it works. Once I refactored to put wordLists in an array with explanations, things go to hell. If I print(dictionary) at the end of the method, the data shows in the console. Not sure what else I'm missing. -
last() and [] operator give different results
I have a model RSSFeed. To get the last element in my DB, I do: RSSFeed.objects.last() # Output: <RSSFeed: www.sooperarticles.com> I slice it to get the first 10 element in the query first_ten_feeds = RSSFeed.objects.all()[:10] Using first and the bracket operator is consistent: first_ten_feeds.first() # Output: <RSSFeed: pressetext News> first_ten_feeds[0] # Output: <RSSFeed: pressetext News> But using last and the bracket operator is not consistent: first_ten_feeds[9] # Output: <RSSFeed: FinanzNachrichten.de: Nachrichten zu IT-Dienstleistungen> first_ten_feeds.last() # Output: <RSSFeed: www.sooperarticles.com> Why? I expect to get the same result for this. RSSFeed.objects.last() and first_ten_feeds.last() seem to give the same result. -
How to configure remote debugging with Django docker app using VS code and ptvsd?
I see lots of articles describing how to setup remote debugging with VS code with flask docker apps e.g but don't find a any good resource which addresses remote debugging in the context of Django docker app with uWSGI. my uwsgi.ini looks like this: [uwsgi] appname = djapp env = DJANGO_SETTINGS_MODULE=djapp.settings_docker module = %(appname).wsgi:application socket = 0.0.0.0:9000 http = 0.0.0.0:8000 home = /app appdir = %(home) virtualenv = /venv/djapp_env master = 1 processes = 2 locks = 5 chdir = %(appdir) umask=000 mules = 1 I wonder how I would translate: python -m flask run -h 0.0.0.0 -p 8000 --no-debugger --reload --without-threads to uwsgi configs -
I am not getting all the record in elastic search using django
I am querying data between two timestamps and I am not geting the every record present in that index satisfying query. -
django models output ordering of banners
I have a Django site that i'm managing for a client of mine that is around 5 years old. It has a very simple carousel on one of the pages that is content managed. THe client wants these images to be randomly picked on page load as opposed to the order in which they are organised in the CMS. Here is the code for the models for this element from django.db import models class Banner(models.Model): created = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True, help_text='Display this banner on the website.') title = models.CharField(max_length=255) description = models.TextField() image = models.ImageField(upload_to='banners/') order = models.IntegerField(default=0) class Meta: ordering = ['order'] I was wondering if someone could help me by showing me how to do this or if its even possible? -
Django Absolute url
So I am new to django I have been working on PHP CodeIgniter in which to put absolute URL in href I used a function called base_url by calling URL helper <?php echo base_url().'xyz/abc';?> which gives output something like http://localhost/projectname/xyz/abc I want the same thing in Django but haven't got any answer or answer which I could understand. -
Override WSDL port, bound URL in spyne
I am using spyne with Django Application and the WSDL published returns the below information. I want to override/change the URL and port, since it displays the localhost info. Any ideas? <wsdl:service name="testService"> <wsdl:port name="testQueryServiceSoapBinding" binding="tns:testQueryServiceSoapBinding"> <wsdlsoap11:address location="http://192.168.1.1:8787/test/soap"/> </wsdl:port> </wsdl:service>