Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get a url from a django form
I have a Django form and a python function that counts words. So now when I input any text in the form, the program counts me the words. It is not necesary to know if my functions work because they do. My question is simple. My form is this one: <html> <form method="POST" action="" id = "loginForm"> {% csrf_token %} <input type="text" name="text" value= '{% if submitbutton == "Submit" %} {{ firstname }} {% endif %}'/> <input type="reset" name="Reset" value="Reset" /> <input type="Submit" name="Submit" value="Submit" /> {% if submitbutton == "Submit" %} <h1 name = "resultado1"> texto introducido: {{ text }}</h1> <h1 name="resultado2"> tipo: {{ type }}</h1> {% endif %} </form> </html> And my python class is this one: from django.shortcuts import render import urllib from bs4 import BeautifulSoup from sample import text_examples def vistaFormulario(request): text = request.POST.get('text') submitbutton = request.POST.get('Submit') m=str(text) #descarga el contenido del html with urllib.request.urlopen('https://politica.elpais.com/politica/2018/06/04/actualidad/1528126438_458260.html') as response: page = response.read() soup = BeautifulSoup(page, 'html.parser') salida_articulo_box = soup.find('div',attrs={'class' : 'articulo-cuerpo'}) articulo = salida_articulo_box.text.strip() n = text_examples.TextExamples.quitarSigno(articulo) k = text_examples.TextExamples.contar(n) context = {'text': text, 'submitbutton': submitbutton, 'type':k} return render(request, 'form/form.html', context) So what I want is to introduce in the form the url, save it in a variable, … -
Djando apps . Craeted my first app and run the server but it won't run
I have created my first app in django . But when I run the server the app won't show up . it looks like this -
Implement a facebook type simpler 'like' feature in backend
I am working on a website made in Django and i want to implement a facebook type (or any social media type) like button. I have a user table, and a post table, and i want users to be able to like the posts. I am confused about some particular things : I am thinking of creating a new field in post table, say post_likes, which have list of users who currently like the post. Then, before rendering the 'post' template, i have to loop over all the users (in field post_likes) to check if the request.user likes the post or not (in my view), and send that data to template (to change the ui of like button to liked), but this approach seems very naive to me, also slow. What could be the better approaches? -
google cloud sdk install error
I am getting the following error while installing google cloud SDK, Output folder: C:\Users\Admin\AppData\Local\Google\Cloud SDK Downloading Google Cloud SDK core. Extracting Google Cloud SDK core. Create Google Cloud SDK bat file: C:\Users\Admin\AppData\Local\Google\Cloud SDK\cloud_env.bat Installing components. Welcome to the Google Cloud SDK! This will install all the core command line tools necessary for working with the Google Cloud Platform. Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\bootstrapping\install.py", line 218, in main() File "C:\Users\Admin\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\bootstrapping\install.py", line 196, in main Install(pargs.override_components, pargs.additional_components) File "C:\Users\Admin\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\bootstrapping\install.py", line 137, in Install InstallOrUpdateComponents(to_install, update=update) File "C:\Users\Admin\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\bootstrapping\install.py", line 180, in InstallOrUpdateComponents ['--quiet', 'components', verb, '--allow-no-backup'] + component_ids) File "C:\Users\Admin\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\cli.py", line 870, in Execute self._HandleAllErrors(exc, command_path_string, specified_arg_names) File "C:\Users\Admin\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\cli.py", line 908, in _HandleAllErrors exceptions.HandleError(exc, command_path_string, self.known_error_handler) File "C:\Users\Admin\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\exceptions.py", line 526, in HandleError core_exceptions.reraise(exc) File "C:\Users\Admin\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\core\exceptions.py", line 137, in reraise six.reraise(type(exc_value), exc_value, tb) File "C:\Users\Admin\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\cli.py", line 844, in Execute resources = calliope_command.Run(cli=self, args=args) File "C:\Users\Admin\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\backend.py", line 756, in Run resources = command_instance.Run(args) File "C:\Users\Admin\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\surface\components\update.py", line 109, in Run version=args.version) File "C:\Users\Admin\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\core\updater\update_manager.py", line 890, in Update command_path='components.update') File "C:\Users\Admin\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\core\updater\update_manager.py", line 600, in _GetStateAndDiff command_path=command_path) File "C:\Users\Admin\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\core\updater\update_manager.py", line 583, in _GetLatestSnapshot *effective_url.split(','), command_path=command_path) File "C:\Users\Admin\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\core\updater\snapshots.py", line 178, in FromURLs … -
Django 1.11 Natural Sort QuerySet
I am looking for a way to naturally sort Django's QuerySets. I found a similar question, but it did not focus on QuerySets. Instead they are doing it directly in Python. So here is my problem. Let's say I have this model: class Item(models.Model): signature = models.CharField('Signatur', max_length=50) In the Django Admin Interface, I want to use a filter, which sorts them alphanumeric. Currently, they are sorted this way: What I'd expect is a list of ["BA 1", "BA 2", ...]. I found admin.SimpleListFilter in the official documentation, which sounds quite suitable. But what I get in the queryset() function is a QuerySet, which can not be sorted in a natural way, because it does not contain the elements, but only the query to the database. The order_by method on QuerySet gives the same ordering as it can be seen in the image. Is there a way to manipulate the QuerySet to get it naturally sorted? My code so far: class AlphanumericSignatureFilter(admin.SimpleListFilter): title = 'Signature (alphanumeric)' parameter_name = 'signature_alphanumeric' def lookups(self, request, model_admin): return ( ('signature', 'Signature (alphanumeric)'), ) def queryset(self, request, queryset: QuerySet): return queryset.order_by('signature') How can I transform the QuerySet to get my desired output? Or is there … -
Calling REST endpoints in views?
I am using the Django REST framework package. I have several endpoints that I've already built to return data. I am calling these endpoints within Ajax to retrieve data. However, if a user does not have JavaScript enabled and presses let's say a subscribe button or a follow button for example, the action would be handled in the views.py file for that specific POST request. Would it be better to handle the request manually by doing a simple query in the views.py or is it better to just hand it off to the endpoint for that specific request inside the views.py? -
Appended items to FormData lost after POST Request in Safari 11
I'm not sure why, but when attaching new formdata content in safari 11.1, it gets lost in the POST data received by the python endpoint. The rest of the key/val of the formdata shows up in the querydict but not the appended ones. However in the request data it shows up like so: ------WebKitFormBoundaryY7mJ4NPCCGy7YWjY Content-Disposition: form-data; name="model_name" story It works fine in chrome and had worked in safari 10. Any clues? var formdata = new FormData($("form")[0]); formdata.append("model_name", "cows"); $.ajax({ url: url, type: "POST", data: formdata, processData: false, contentType: false }) -
Django get foreign key objects
I am coming from .NET Core and I am curious if Django has anything similar to .NET Core's projections. For instance, I can describe a relationship in a .NET Core model and then later query for it. So, if Articles can have an Author I can do something like: var articles = dbContext.Where(article.ID == id).Inclue(a => a.author); What I would get back are articles that have their author attached. Is there anything similar to this in Django? How can I load related data in Django that's described in the model? -
Debian Nginx listening but not working
I have had a lot of trouble setting up Nginx for Django on Debian. I tried probably every nginx django conf file I could find on the internet but none of them worked, I assume I cant see the forrest for the trees... So I am running Django 2.0.4 and daphne 2.1.1. For Daphne I am using this command: daphne -b 0.0.0.0 -e ssl:8080:privateKey=privkey.pem:certKey=fullchain.pem share_game.asgi:application -v2 And this is my Nginx Conf file, I have added a redirect to google so I can actually see that it is running: upstream tsg-backend { server 127.0.0.1:8080; } server { listen 159.69.13.156:80; server_name thesharegame.com www.thesharegame.com; if ($host ~* ^thesharegame\.com$) { rewrite ^(.*)$ https://www.thesharegame.com$1 permanent; } } server{ listen 159.69.13.156:443 ssl http2; server_name thesharegame.com www.thesharegame.com; access_log /var/log/nginx/tsg.log; error_log /var/log/nginx/tsg.log; return 301 https://google.com$request_uri; ssl on; ssl_certificate /home/tsg/fullchain.pem; # managed by Certbot ssl_certificate_key /home/tsg/privkey.pem; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot client_max_body_size 20M; if ($host ~* ^thesharegame\.com$) { rewrite ^(.*)$ https://www.thesharegame.com$1 permanent; } location / { ## If you use HTTPS make sure you disable gzip compression ## to be safe against BREACH attack. proxy_read_timeout 3600; proxy_connect_timeout 300; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Host $http_host; proxy_set_header X-Real-IP … -
Django ORM subquery with window function
I'm trying to do this query with Django's ORM: SELECT id, pn, revision, description FROM (SELECT id, pn, revision, MAX(revision) OVER ( PARTITION BY pn ) max_rev, description FROM table) maxarts WHERE revision = max_rev The result needs to be a queryset, i have tried every combination of Window/OuterRef/Subquery i know with no success. Do i have to use a raw query? Thanks in advance Marco -
Creating Reports with Django-Rest-Framework
I'm creating an API that will return pay-period and charge reports. I have a work-orders model that stores all the necessary information, and I've created a reports app within the project, that uses SerializerMethodField to return the calculations I need. My issue is that if I make a post request with data in the fields for an object that exists, it creates a new object. I am using the ListCreateAPIView, and from what I can tell, it's supposed to retrieve the object if it already exists. What am I missing? Thanks for reading! models.py class PayPeriodReport(models.Model): tech = models.ForeignKey(Employee, null=True, on_delete=models.CASCADE, related_name='employee') start_date = models.DateField() end_date = models.DateField() urls.py urlpatterns = [ path('payperiodreport/<employee>/<start_date>/<end_date>', views.PayPeriodReportView.as_view(), name='payperiod-report') ] views.py class PayPeriodReportView(generics.ListCreateAPIView): serializer_class = PayPeriodReportSerializer serializers.py class PayPeriodReportSerializer(serializers.ModelSerializer): break_down = serializers.SerializerMethodField() class Meta: model = PayPeriodReport fields = '__all__' # Get all work orders associated with report def get_all_workorders(self, obj): return WorkOrder.objects.filter(tech=obj.tech, start_date__range=(obj.start_date, obj.end_date)) # Get days as a list of strings to be used as keys in dictinoary. def get_list_of_days(self, obj): days = obj.end_date - obj.start_date return [obj.start_date + timedelta(days=time) for time in range(days.days +1)] # returns a list of the week numbers to be used in weekly breakdown dictinoary. def get_payperiod_weeks(self, … -
Django: populate form field with javascript array
I have a template where I plot some images and comments associated to the image. I want to allow users to add comments to one image displayed directly in the template. Then, when the user fill its comment, I would like that all the other fields except the text are automatically filled. Question: How to define the value of a form field with Javascript ? Idiot example: {{ form.field1.value }} = jsArray[0] Many thanks for your help :) -
Finding neighbors of a home to the left and right
im trying to write two function, one that gives me 3 homes to the right and 3 homes to the left, both using a home's polygon, centerpoint, rears and fronts... so i have these queries def three_neighbors_left(self): first_home = Home.objects.get( front_left__distance_lte=(self.home.front_left, Distance(m=20)), rear_left__distance_lte=(self.home.rear_left, Distance(m=20)), polygon__touches=self.home.polygon ) second_home = Home.objects.filter( front_left__distance_lte=(first_home.front_left, Distance(m=20)), rear_left__distance_lte=(first_home.rear_left, Distance(m=20)), polygon__touches=first_home.polygon ).exclude(id=first_home.id).first() third_home = Home.objects.filter( front_left__distance_lte=(second_home.front_left, Distance(m=20)), rear_left__distance_lte=(second_home.rear_left, Distance(m=20)), polygon__touches=second_home.polygon ).exclude(id=second_home.id).first() ids = [first_home.id, second_home.id, third_home.id] return Home.objects.filter(id__in=ids) def three_neighbors_right(self): first_home = Home.objects.get( front_right__distance_lte=(self.home.front_right, Distance(m=20)), rear_right__distance_lte=(self.home.rear_right, Distance(m=20)), polygon__touches=self.home.polygon ) second_home = Home.objects.filter( front_right__distance_lte=(first_home.front_right, Distance(m=20)), rear_right__distance_lte=(first_home.rear_right, Distance(m=20)), polygon__touches=first_home.polygon ).exclude(id=first_home.id).first() third_home = Home.objects.filter( front_right__distance_lte=(second_home.front_right, Distance(m=20)), rear_right__distance_lte=(second_home.rear_right, Distance(m=20)), polygon__touches=second_home.polygon ).exclude(id=second_home.id).first() ids = [first_home.id, second_home.id, third_home.id] return Home.objects.filter(id__in=ids) that is not giving me the results i want, i have also tried Home.objects.filter(polygon__left=self.home.polygon) but that gives me a lot of results most of which aren't really neighbors anymore -
Django AbstractUser display new fields in admin
I have replaced Django user with the following custom AbstractUser model: from django.db import models from django.contrib.auth.models import AbstractUser class Profile(AbstractUser): bio = models.TextField(blank=True) After replacing user in settings I wanted to check new fields in admin. In admin.py code looks like this: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Profile class PersonAdmin(UserAdmin): list_filter = ('bio',) admin.site.register(Profile, PersonAdmin) However, new field didn't appear in django admin. Could you advise what is the best way to display new field in admin? -
Missing 1 required positional argument - issue
May be it's stupid question, but I'm begginer in django. I have a problem with error: "PartyNumView() missing 1 required positional argument: 'pk'" views.py: from description.models import Part from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.shortcuts import render_to_response, get_object_or_404 def PartyNumView(request, pk, page_number = 1): all_parties = Part.objects.all() current_page = Paginator(all_parties, 10) try: context = current_page.page(page_number) except PageNotAnInteger: context = current_page.page(1) except EmptyPage: context = current_page.page(current_page.num_pages) onePart = get_object_or_404(Part, pk = pk) return render_to_response('part_list.html', {'PartyNum': context, 'onePart': onePart}) urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^parties/(\d+)/$', PartyNumView), url(r'^parties', PartyNumView), url(r'parties/(?P<pk>[\d]+)$', PartyNumView, name='onePart'), url(r'^main/', TemplateView.as_view(template_name='main.html')), #static html url(r'^measures/', TemplateView.as_view(template_name='IcDesc.html')), #static html ] And a little bit of part_list.html: {% for object in PartyNum %} <tr> <td>{{ forloop.counter }}</td> <td><a href="{% url 'onePart' pk = object.pk %}"> {{ object.Party_number }}</a></td> <td>{{ object.Film }}</td> <td>{{ object.Thick }}</td> <td>{{ object.Critical_temperature }}</td> <td>{{ object.R_s }}</td> {% endfor %} In Models.py I have a class Part(models.Model) Help me please find a mistake. -
Django project with a table prefix
I have to run 2 different Django projects which have to share the same database. They have to share the same database as I need to use Django Models relationships between the 2 projects (Django does not allow relationships across diferente DBs) Is there a way to have a global prefix variable so that Django uses that automatically to generate all tables? In example: project1_auth_user project1_django_migrations ... project2_auth_user project2_django_migrations ... -
Change mysql save chars encoding in django
sorry for my bad english, i have the next question with django and mysql. How i can config django to save text from 'buen día' to 'buen dÃa' i need this because i have a legacy db with data encoded. Thanks. -
Django local variable 'allowance_tax' referenced before assignment
here inside my createview .... salary = 1000 allowance = allowance_tax tax = (((((salary + allowance) *12) - 5000)*15/100)+250 )/ 12 allowance_tax = tax .... on realife salary tax calculation like above. I can do easily calculate it with Ms. Excel. but on my django app how to do it?... since theres no initial value on allowance_tax i got error local variable 'allowance_tax' referenced before assignment but if i set allowance_tax with value, tax calculation will be wrong. i need allowance = allowance_tax but allowance_tax is from the calculation. seems complicated but that the right calculation. -
Cannot add temporarily data to instance without saving on database Django
I have the following problem: I have a set of Consequences and this consequences has a likes ManyToManyField attribute that stores all the users that have like the consequence. What i want to archive is to add to the consequences an extra temporal attribute call isLiked So later on the template I can add a data-attribute to the html indicating that the user of the request has liked already X consequences. I am trying to do it with this approach: views.py def list_consequences(request, proponsal_id): try: consequences: [Consequence] = Consequence.objects.filter(of_proponsal=proponsal_id) user_likes =request.user.likes_consequences.get_queryset() union = consequences | user_likes for consequence in union: aux =consequences.get(pk=consequence.pk) aux.isLiked=True pros: Consequence = consequences.filter(efecto=Consecuencia.PRO) against: Consequence = consequences.filter(efecto=Consecuencia.AGAINST) template = loader.get_template('participation/consequences.html') context = { 'pros': pros, 'against': against, 'is_user_authenticated': str(request.user.is_authenticated).lower(), } return HttpResponse(template.render(context, request)) except Consequence.DoesNotExist: raise Http404("The consequence with id doesn't exist") So later on the template i can do this: consequences.html ... {% for pro in pros %} <button data-is-liked={{pro.isLiked}}> icon</button> {% endfor %} ... Someone know how I could do this? Thanks in advance Django version : 2.0 Python : 3.6.5 -
Django Restful framework post to create foreign key if not already exists
class ModelA(models.Model): name = models.CharField(max_length=100) code = models.CharField(max_length=100, default='') class ModelB(models.Model): name = models.CharField(max_length=100) code = models.CharField(max_length=100, default='') class ModelC(models.Model): name = models.CharField(max_length=100) modelA = models.ForeignKey(ModelA, on_delete=models.CASCADE) modelB = models.ForeignKey(ModelB, on_delete=models.CASCADE) These are the models. class ModelASerializer(serializers.ModelSerializer): class Meta: model = ModelA fields = "__all__" class ModelBSerializer(serializers.ModelSerializer): class Meta: model = ModelB fields = "__all__" class ModelC(serializers.ModelSerializer): modelA = ModelASerializer() modelB = ModelBSerializer() class Meta: model = ModelC fields = "__all__" These are my serializers. Right now I have no problem with a GET request. What I want to achieve is that when I do a post request for ModelC and if ModelA and ModelB do not already exist then create them. Right now I am able to do post with existing modelA and modelB by removing the nested serializer. Thanks for everyone's help. -
Variables inside clear() method aren't saved in Django
In models.py I have a model with custom clear() method. However, any variables I save in it aren't stored. If I try to save the variable outside of the clear() method, everything works well. class MenuItem(SortableMixin): item_internal = models.ForeignKey(Page, on_delete=models.CASCADE, blank=True, null=True) item_external = models.CharField(max_length=500000, blank=True, null=True) def clean(self): if self.item_external is not None and self.item_internal is not None: raise ValidationError('Error') elif self.item_external is None and self.item_internal is None: raise ValidationError('Error) else: if self.item_external is not None: self.item_link = self.item_external elif self.item_internal is not None: self.item_link = '/' + self.item_internal.title_text.replace(' ', '%20') Anything inside item_link is not saved. Why? How to fix it? -
add a unique "intermediary" model to all my Django ManyToManyField() fields
Hello Awesome People! Such a question that I have made a lot of searches for it. I am done building a website 2 months ago, but today The team decides to track every time an instance has been added to another in ManyToManyField() fields. I was thinking using the through argument to point to the model that will act as an intermediary may work but not at all in my case (70%). Just Because I want to have a unique intermediary model that will record for all ManyToManyField() class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateTimeField(auto_now_add=True) Ah! Something is required. I need to explicitly specify foreign keys to the models that are involved in the many-to-many relationship. Django ContentType may anticipate for all my models, but it's not working, I wonder why? it also contains ForeignKey (the one required by an intermediary model). Do I really need to edit all my ManyToManyField and create Model as much as ManytoManyField? is there a way to record date_joined without creating a model intermediary model for each? -
Refresh django sitemap
I recently switched my urls for a django app from displaying ids to displaying slugs as below: urlpatterns = [ url(r'^(?P<slug>\S+)/$', views.PostDetailView.as_view(), name="post_detail"), ] However I notice that in my sitemap, the urls are still displaying with the ids. How can I update the sitemap to show the new urls? I tried deleting and adding them back but nothing changed. My sitemap is defined as below: class PostSitemap(Sitemap): changefreq = "monthly" priority = 0.5 def items(self): return Post.objects.all() -
Django redirect to same page with same parameters
In Django after making Post request to any page I want to redirect back to same page but with the same url parameters. -
Django: Can the value of a DOM Element be passed to a TemplateTag?
Being new to the framework, I am faced with the problem of creating a view (index.html) which allows the user to select a certain value from an input element and show it. This value needs to be processed and the output of this process will be shown in the template. I am trying to use a TemplateTag with the following structure: def foo(value): ret = doOperations(value) return ret; However, I am not sure if TemplateTags can receive the value of a dom element since the examples in django's documentation only show TemplateTags used with variables passed from the view. The ideal scenario would be somehow passing the value (a text element) directly to the template: {{ valueOfDomElement|foo }} I would like to know if my approach to this problem is viable or how I should proceed in order to communicate correctly between templatetag (if needed) and view.