Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Django xml parser?
I've got a Django endpoint to which I want to send a quite complicated/nested XML. For this I'm trying to use the django-rest-framework-xml package. I created the following viewset: class RecordViewSet(viewsets.ModelViewSet): queryset = Publication.objects.all() serializer_class = PublicationSerializer serializer_detail_class = PublicationSerializer parser_classes = (XMLParser,) renderer_classes = (XMLRenderer,) def create(self, request, *args, **kwargs): print(type(request.data)) print(request.data) return Response("", status=status.HTTP_201_CREATED) In the create() method it first prints out "str" and then the raw xml I'm receiving. It hasn't been converted to a dict or anything else. I'm a missing something here? Shouldn't it have at least been parsed to something else than a raw string? Also; since the XML has quite a complex structure I need to reshuffle some fields in order to shape it into my models. What would be the place to do such a thing? All tips are welcome! -
I cannot display the list of products on the home page? python django
I have a website written in python django, in the products menu I want to list my products on the homepage using api serzializer, what should I do? thank you -
django-markdownx with cloudinary
I am trying to make a django application using django-markdownx and dj3-cloudinary-storage together. Here are the necessary codes. Pipfile [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] [packages] django = "*" pillow = "*" autopep8 = "*" dj3-cloudinary-storage = "*" django-markdownx = "*" [requires] python_version = "3.8" settings.py(necessary parts) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.forms', # for django-markdownx # third party 'cloudinary_storage', 'cloudinary', 'markdownx', # local 'pages.apps.PagesConfig', ] # media MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # cloudinary configs CLOUDINARY_STORAGE = { 'CLOUD_NAME': <user_name>, 'API_KEY': <public_key>, 'API_SECRET': <secret_key>, } DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('markdownx/', include('markdownx.urls')), path('', include('pages.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In my pages app these are the code. models.py from django.db import models from django.urls import reverse from markdownx.models import MarkdownxField class Page(models.Model): title = models.CharField(max_length=255) description = MarkdownxField() cover = models.ImageField(upload_to='covers/', blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("pages:detail", kwargs={"pk": self.pk}) views.py from django.views.generic import CreateView, DetailView from .models import Page class PageDetailView(DetailView): model = Page template_name = 'detail.html' class PageCreateView(CreateView): model = Page template_name = 'new.html' … -
Footer Django PDFTemplateView
I need to put a footer in a document that I am doing, but I must do it from the template.html since they are different combined pdfs and I calculate separately their numbering, the part of combining them is already listed, I simply cannot put the footer in the bottom right. cmd_options = { 'footer-right': '[page] / [topage]' } cmd options allow me to automatically put the footer but in this case or at least the way I am using them do not work for me, this is how I have the html (without the 'footer-rigth' property of cmd options). <div style="font-size: 13px; position: absolute; bottom:0px;"> {{page_id}} - {{forloop.counter}}/{{all_pages|length}} </div> -
'str' object is not callable in django
I'm newbie in Django. I get the TypeError 'str' object is not callable in my Django Project when I go browsable api in url "localhost:8000/api/questions/".I'm using Django 3.I don't know how to debug this error so here I write. I think I'm doing something wrong with urls main urls.py path('accounts/', include('django.contrib.auth.urls') ), path('accounts/', include('django_registration.backends.one_step.urls') ), path('api/', include('users.api.urls') ), path('api/', include('questions.api.urls') ) urls.py in app from rest_framework.routers import DefaultRouter from questions.api.views import QuestionViewSet router = DefaultRouter() router.register(r'questions', QuestionViewSet) urlpatterns = [ path('', include(router.urls)) ] views.py in app from rest_framework.permissions import IsAuthenticated from questions.api.permissions import IsAuthorOrReadOnly from questions.api.serializers import QuestionSerializer, AnswerSerializer from questions.models import Question class QuestionViewSet(viewsets.ModelViewSet): queryset = Question.objects.all() lookup_field = 'slug' serializer_class = QuestionSerializer permission_classes = ['IsAuthenticated','IsAuthorOrReadOnly'] def perform_create(self, serializer): serializer.save(author=self.request.user) serializers.py in app from rest_framework import serializers from questions.models import Answer, Question class QuestionSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField(read_only=True) created_at = serializers.SerializerMethodField() slug = serializers.SlugField(read_only=True) answer_count = serializers.SerializerMethodField() user_has_answered = serializers.SerializerMethodField() class Meta: model = Question exclude = ['updated_at'] def get_created_at(self, instance): return instance.created_at.strftime('%B %d, %Y') def get_answer_count(self, instance): return instance.answers.count() def get_user_has_answered(self, instance): request = self.context.get('request') return instance.answers.filter(author=request.user.pk).exists() structure of my project /project /questions /api serializers.py views.py urls.py -
Unable to receive RSS updates to my webhook setup using Django. Replay option sends empty POST and GET data
I am trying to setup webhooks for Django and use Superfeedr.com to receive webhooks. I am using the RSS feed link they provide for testing: http://push-pub.appspot.com/. You can update the website in realtime to test your webhook. When I update the website I don't receive anything from my webhook. From the main subscriptions page on Superfeedr, when I click on replay for that rss feed, I receive empty POST and GET request to the webhook. How can I configure my webhook correctly so that I receive the updated RSS feed? Here is my views: @csrf_exempt @require_http_methods(["GET", "POST", ]) def daily_mtg_hook(request): print(request.GET) print(request.POST) challenge = request.GET.get("hub.challenge") topic = request.GET.get("hub.topic") return HttpResponse(challenge) and I used the following options to subscribe: def create_feed(topic): data = { 'hub.mode': 'subscribe', 'hub.topic': topic, 'lang': 'en', 'hub.callback': 'MY_CALLBACK_LINK', 'hub.secret': 'SECRET', 'hub.verify': 'sync', 'format': 'json' } response = requests.post('https://push.superfeedr.com/', data=data, auth=('USERNAME', 'KEY')) print(response) create_feed("http://push-pub.appspot.com/") -
Why static files are served on Heroku without activating WhiteNoise?
I followed a tutorial on deploying Django app on Heroku server and I stumble across this: I have installed WhiteNoise package for serving statics Added inside settings.py: MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', ] But omitted to activate it inside wsgi.py file: from whitenoise import WhiteNoise from my_project import MyWSGIApp application = MyWSGIApp() application = WhiteNoise(application, root='/path/to/static/files') application.add_files('/path/to/more/static/files', prefix='more-files/') Why the static files are served on the production site ? Should not the above code be responsible for this ? -
Django - added images to list display in django admin panel not working
I was trying to display images in my django admin list of Paintings, yet they won't work. I tried to work with different urls of images and nothing works. Here is part of my model.py class Painting(models.Model): artist = models.ForeignKey(Artist, null=True, on_delete=models.SET_NULL) image = models.FileField(upload_to=path_and_rename('static/rsc/paintings/'), blank=True, null=True) description = models.TextField(null=True) def image_tag(self): if self.image: return mark_safe('<img src="%s" style="width: 120; height:120;" />' % self.image.url) else: return 'No Image Found' image_tag.short_description = 'Image' def __str__(self): return self.artist.name + " " + self.artist.surname + " | " + self.description And here is my admin.py: admin.site.register(Article) admin.site.register(Artist) admin.site.register(Offer) class PaintingAdmin(admin.ModelAdmin): list_display = ('image_tag', 'artist') readonly_fields = ['image_tag'] admin.site.register(Painting, PaintingAdmin) This does seem to work in some way, since blank images are appearing as shown in the photo: Photo of admin panel Is this problem with url or something? I'm hopeless now. -
Is it possible to connect local django project to MySql running on AWS EC2?
What I tried: Installed the MySql server on the EC2 instance. In the security group of the instance added an inbound rule to allow all the traffic Created a database and user Given that user all permissions using GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION; Created a Django project using django-admin startproject mysite and installed mysqlclient in project settings, I changed the default database from SQLite to { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dbtest', 'USER': 'root', 'HOST': '{IPv4 Public IP of the Instance}', 'PASSWORD': 'password', } Now when I run python manage.py runserver it gives me the error django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'XX.XX.XX.XX' (using password: YES)") Then I granted all privileges to this specific IP as well using: GRANT ALL PRIVILEGES ON *.* TO 'root'@'XX.XX.XX.XX' WITH GRANT OPTION; -
Why did bytes() solve my newlines problem?
I was working on a wiki app in Django, and had a textarea where the user submits markdown text. The string content would be passed to django.core.files.base.ContentFile(content), and then this would be saved via django.core.files.storage.default_storage.save(filename, ContentFile(content)). However, the saved markdown file (it was the same with .txt files) would have double the number of newlines as what the user entered. I have Windows and the program must have tried to convert the Windows-formatted data to Windows again, thinking that it was in Unix. CR LF was being converted to CR CR LF. I fixed this by using bytes(content, 'utf8') before passing it to the save function. My question is, why did this work? What did bytes() do to the data and its newline characters so that the program no longer thought it was in unix? -
Django JSONField filtering is not worked
I'm using jsonfield(https://github.com/rpkilby/jsonfield). # models.py from djongo import models from jsonfield import JSONField class Card(models.Model): name = models.CharField(max_length=50, primary_key=True) keyword = JSONField() # views.py from rest_framework.views import APIView class CardView(APIView): def get(self, request, obj): card = Card.objects.all().filter(subject=obj).filter(keyword__contains={"balanced": "TRUE"}) # <QuerySet []> I definitely having {"balanced": "TRUE"} document. But filtering is not worked correctly, why is this happening? -
Why would POST requests in Django work sometimes and not the other times? (It's almost random)
I have a Django CRUD web app that is basically used to add values to the database, which are visible on the frontend when the page is refreshed and there is a button to edit that entry. It works perfectly fine 90% of the time. But there will be a random instance where someone adds something using the UI and it is added to the database but when refreshed, the entry disappears from the database! It's the most absurd thing I've ever seen. If something was wrong with the code wouldn't it never add it correctly. I'm just confused why it adds values fine 90% of the time but there's that few instances of disappearing entries. def index(request, user, created_by): if request.POST: print(request.POST) selected_user = request.POST.get('name_user') selected_project = request.POST.get('name_project') print(selected_user) week_starting = request.POST.get('date') hours = request.POST.get('hours') activity = request.POST.get('activity') selected_tag = request.POST.get('tag') # check if record already exists for the same user and same week_starting and selected_project # if not then insert to DB # else don't insert, say record already exists if selected_tag == '': check_if_exists = TABLENAME.objects.filter(username=selected_user, week_starting=week_starting, project_id=selected_project, tag_id__isnull=True) else: check_if_exists = TABLENAME.objects.filter(username=selected_user, week_starting=week_starting, project_id=selected_project, tag_id=selected_tag) count = check_if_exists.count() print("at insert") print("how many same records already exist: … -
Having problem in displaying product details on different pages using django postgresql
I am working on a website and am facing a problem.I have a page category.html which is working fine.Below is its code(used for loop) <div class="product-caption"> <h4><a href="#" id="{{product.productid}}">{{product.name}}</a></h4> <div class="price"> <ul> <li>RS {{product.currentprice}}</li> <li class="discount">RS {{product.originalprice}}</li> <div> <a href="/category/singleproduct/" class="btn header-btn btn-outline-info">View</a> <a href="#" class="btn header-btn btn-outline-info">Add to Cart</a> </div> </ul> </div> </div> and in this when i click on view it transfers me to /category/singleproduct. Below is some part of the code for singleproduct.html: <div class="single_product_img"> <img src="{{product.disimage.url}}" alt="#" class="img-fluid"> </div> </div> </div> <div class="col-lg-8"> <div class="single_product_text text-center"> <h3>{{product.name}} <br>rebound pillows</h3> But this is giving me nothing.I want this to display the image and name of the product that was selected(using view in category.html) Here is my views.py: def category(request): types = Category.objects.all() prods= Product.objects.all() return render(request,"category.html",{'types':types,'prods':prods}) def singleproduct(request): types = Category.objects.all() prods= Product.objects.all() return render(request,"singleproduct.html",{'types':types,'prods':prods}) (Dont mind the indentation.Its correct in original code) -
Why is the follower count not working on django
I have been trying to implement a follow/unfollow system on django in which a user can follow other users and the user can also be followed, in the user's profile there is a following count which displays how many people the user is following and a follower count which is supposed to display how many followers the user has just like in instagram. Everything is working good except for the follower count which doesn't counting the followers. for doing this follower count, I used signals but it doesnt work. How can I fix this problem? models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='profile_pics', null=True, blank=True, default='default.png') bio = models.CharField(max_length=400, default=1, null=True) connection = models.CharField(max_length = 100, blank=True) follower = models.IntegerField(default=0) following = models.IntegerField(default=0) def __str__(self): return f'{self.user.username} Profile' class Following(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) followed = models.ManyToManyField(User, related_name="followed") follower = models.ManyToManyField(User, related_name="follower") @classmethod def follow(cls, user, another_account): obj, create = cls.objects.get_or_create(user = user) obj.followed.add(another_account) print("followed") @classmethod def unfollow(cls, user, another_account): obj, create = cls.objects.get_or_create(user = user) obj.followed.remove(another_account) print("unfollowed") def __str__(self): return f'{self.user.username} Profile' views.py def profile(request, username=None): profile, created = Profile.objects.get_or_create(user=request.user) if username: post_owner = get_object_or_404(User, username=username) profile_bio = Profile.objects.filter(user_id=post_owner) user_posts = Post.objects.filter(user_id=post_owner) user = User.objects.get(username=username) is_following = … -
Use annotate to sum only the entries with a distinct field (field not used in values and sum functions)
Model I have a model in Django, which has several fields, but, for the purpose of this question, it can be summarized with the following fields: from django.core.validators import MaxValueValidator, MinValueValidator class FailureTable(models.Model): DETECTION_CHOICES = ( ('P', 'PBIT'), ('C', 'CBIT'), ) failure_id = models.CharField(max_length=50, blank=False, null=False, default='Failure ID', verbose_name='Failure ID') end_effect = models.CharField(max_length=200, blank=False, null=False, default='No safety Effect', verbose_name='End Effect') detection = models.CharField(max_length=1, choices=DETECTION_CHOICES, blank=True, null=True, verbose_name='Detection') failure_rate = models.FloatField(blank=True, null=True, validators=[MinValueValidator(0), MaxValueValidator(1)], verbose_name='Failure Rate') Data example A typical kind of table would something like this: failure_id | end_effect | detection | failure_rate ========================================================== FM_01 | loss of function | P | 1e-6 FM_01 | erroneous function | P | 1e-6 FM_02 | loss of function | P | 1e-6 FM_03 | loss of function | C | 2e-6 Current solution Currently, I have been able to obtain a dictionary that sums all the failure rates according to the detection type with the following annotate expression: from django.db.models import Sum dict_fr={item["detection"]: '%.2E' % item["sum_fr"] for item in FailureTable.objects.filter.values("detection").annotate(sum_fr=Sum('failure_rate'))} Problem The problem is that this sums the failure_rate regardless of the "failure_id" field. I would like not to sum the failure_rate when we have already considered a failure_id. In the example … -
How to log more detail of 400 responses in Django Rest Framework?
I've got an endpoint built with Django Rest Framework, to which someone is posting data. Since this morning he's getting a lot of 400 responses. In my Kibana logging I can only confirm that he indeed receives a lot of 400 responses. I need to debug this, but I don't have a lot of info. So I want to log more detail about the 400 responses. So I thought of doing the following in my viewset def create(self, request, *args, **kwargs): try: response = super().create(request, *args, **kwargs) return response except exceptions.ValidationError as e: logger.error(f"{e} in message: {request.data}") return Response(e, status=status.HTTP_400_BAD_REQUEST) This seems to work, but it doesn't really feel like the most logical way of doing it. Does anybody know of a more pythonic way of logging 400 responses? -
How can we deploy a django application on aws if we are using wkhtmltopdf for pdfkit?
I am using pdfkit on windows to convert HTML URL to a pdf file and send it as a response. I installed wkhtmltopdf on my system, as it was a dependency to use pdfkit. I am adding the path for wkhtmtopdf stored in my drive, to the configuration value of pdfkit. Everything is working properly, but my concern is, the path is hardcoded in my app, now what happens if I want to dockerize my application and deploy it on amazon. Here is the code that I am using: path_wkthmltopdf = 'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf) pdf = pdfkit.from_url(order["invoice_url"], False, configuration=config) response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_" + order["order_id"] + "_" + datetime.today().strftime('%d-%m-%Y') + ".pdf" content = "attachment; filename=" + filename response['Content-Disposition'] = content return response Is there a better way to handle this HTML URL to PDF conversion? -
Django model.save seems to cover old instances
I have a player table which uses the user id from auth_user table as the foreign key, and I have a view function checking whether the player already exists: def index(request): try: player = models.Player.objects.get(player_user_id=request.user) logger.debug('found player') except: logger.debug('player doesn\'t exist!') player = models.Player(player_user_id=request.user, player_isconsented=True, player_isactive=True, player_deactivated_ts=None) player.save() but every time a new player is created it seems to cover the old player row. And there is only one row existing in the player table although there are multiple users. Any thoughts? much appreciated. -
How to test if exception was caught while running a django test
Suppose this is my code: def fun(): try: raise Exception("An exception") except Exception as e: logger.debug(f'{e}') Now how can I write a test case which checks if that particular exception was caught? I could have tested by reading sys.stderr, but I'm using logger.debug. -
what am i doing wrong? CSS files don't work in Django project
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Japan</title> <link rel="stylesheet" href="css/reset.css"> <link rel="stylesheet" href="css/style.css"> </head> what must i do to work css files in django project? -
How to add annotate in subquery
I have 3 models. Item(): id = IntegerField() ..... Attachment(): id = IntegerField() item = ForeignKey(Item) url = TextField() ..... AttachmentTypes(): id = IntegerField() name = models.CharField(max_length=255) extensions = ArrayField(models.CharField(max_length=255)) About last one it just contain name like "Picture" an extension list ["png", "jpg"] The logic is next: When we get item we also get attachment list but we need annotate what type of this attachment. So I have a queryset: Item.objects.prefetch_related(Prefetch('attachments', queryset=Attachment.objects .annotate(ext=Func(F('url'), Value('([^.]+$)'),function='substring')) .annotate(atype=AttachmentsType.objects.filter( extensions__contains[OuterRef('aext')]).values('name')[:1]))) So, as you can see queryset is easy. I use prefetch_related to 'attachments' but add queryset which contain 2 annotate (first just do the sub-string on 'url' to get extension from it and store it in 'ext' column - its working fine. Second annotate should find type and store it in new column 'atype'. But problem there that I dont know how to get access to 'aext' in this second annotate. By the way, maybe it helps, This SQL is working for attachmets as I expect SELECT *, ( SELECT U0."name" FROM "items_attachmentstype" U0 WHERE U0."extensions" @> ARRAY[foo.aext]::varchar(255)[] LIMIT 1 ) AS "atype" FROM ( SELECT * substring("items_attachment"."url", '([^.]+$)') AS "aext" FROM "items_attachment" WHERE "items_attachment"."item_id" IN ('f34b7a7a-2fa6-4a90-a62b-c9b60f4773b2'::uuid, '1a9219c5-66e1-43ab-9906-6e47269e5d85'::uuid, .... ) AS foo -
How to save data to PostGis database from uploaded GPX file in Django?
I have the following problem: my goal is to make an archive of gps tracks that can be displayed on a map. (using Python, Django, PostgreSQL, PostGIS) I found a tutorial: https://web.archive.org/web/20160425053015/http://ipasic.com/article/uploading-parsing-and-saving-gpx-data-postgis-geodjango the file upload works fine, but I can't figure out how to save data from a file to the database and use them as models. My code: forms.py from django import forms from .models import gpxFile class UploadGpxForm(forms.ModelForm): title = forms.CharField(max_length=100) gpx_file = forms.FileField(required='FALSE') class Meta: model = gpxFile fields = ['title', 'gpx_file'] models.py from django.contrib.gis.db import models from django.contrib import admin from django.contrib.gis import admin as geoadmin from django.db.models.manager import Manager def GPX_Folder(instance, filename): return "uploaded_gpx_files/%s" % (filename) class gpxFile(models.Model): title = models.CharField("Title", max_length=100) gpx_file = models.FileField(upload_to=GPX_Folder, blank=True) def __unicode__(self): return self.title class GPXPoint(models.Model): name = models.CharField("Name", max_length=50, blank=True) description = models.CharField("Description", max_length=250, blank=True) gpx_file = models.ForeignKey(gpxFile, on_delete=models.CASCADE) point = models.PointField() objects = models.Manager() def __unicode__(self): return unicode(self.name) class GPXTrack(models.Model): track = models.MultiLineStringField() gpx_file = models.ForeignKey(gpxFile, on_delete=models.CASCADE) objects = models.Manager() views.py from django.shortcuts import render from .forms import UploadGpxForm, Up from .models import GPXPoint, GPXTrack, gpxFile from django.http import HttpResponseRedirect from django.contrib.gis.geos import Point, LineString, MultiLineString from django.conf import settings import gpxpy import gpxpy.gpx def home(request): #context … -
Password Encryption/ Decryption algorithms in MySQL and Django
I am using MySQL for database and Django for backend. I have already stored the password in the database using SQL workbench directly: INSERT INTO erebordb.email values('AKKI', aes_encrypt('1234','KEY')); Have made use of AES algorithm. The table looks like: Output I want to retrieve this password in Django, and decrypt it. How can I do that? Or is there a better algorithm for the same? -
How to write general django views, where one ListView or DetailView can be used for many models
How can I write urls and views that can be used with many models? Example for Bike, Scooty, Mobile i want to use same model. -
Getting data from django to React in Real Time
I created one API which downloads artifacts from jenkins using python requests library. The API is triggered by the react front end. I want to show the download progress in the react frontend. download_folder = "location" bytes_read = 0 url = 'https://jenkinsServer/job/'+ ID + '/' + Build_no + '/artifact/*zip*/archive.zip' response = requests.get(url, auth=(username, APIPin), stream=True, allow_redirects=True, verify = False) with open(download_folder, 'wb') as f: itrcount=1 for chunk in response.iter_content(chunk_size=1024): itrcount=itrcount+1 f.write(chunk) bytes_read += len(chunk) print(bytes_read) response.close() Above is the view inside Django. I want to get the bytes_read value to the frontend react to use it for the progress bar. In react I just used fetch var url = "DJANGO API URL FOR THE ABOVE CODE; fetch(url) .then(res => res.json()) .then() .catch((error) =>{ console.log('Error'); }) I found about some channels that can be used in Django to send real time data, but couldnt understand it much. I am a pretty beginner in Django and React thus please don't mind the code/ any error. I just need the download progress from the python requests to be shown in the frontend. Or if there is any other method that I can use ?