Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Retrieving multiple rows from seperate model in django relationships
I've been struggling with this puzzled for a few hours. Here's a schema of what I'm trying to do. I have a user model and a profile model, it's a one-to-one relationship, but I'd like to be able to query a user and retrieve all the email addresses (from the User model) for users that share the same company (from the Profile Model). To be fair, my understanding of django is limited, but I went through the serializer relations guide and tried my hands at most approach described there, to no avail. At this point, I'm not even sure I'm on the right path. So, my understanding of it is From the user, I need to fetch the profile (a source='profile' approach may work) From that profile, I need to retrieve the company From that company, I need to retrieve all the user_id that belongs to that company From those user_ids, I need to lookup the email fields of all those users I need to also filter out the email address of the user making the request Does this make any sense? At this point, I'm trying to accomplish all of that from the serializer, but was unsuccessful. Here are … -
How to render markdown file to HTML using django?
I am trying to render a page that written in markdown to HTML when clicking a link using Django. but every time I click on the link the markdown page does not render will here's my views.py: from django.shortcuts import render from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def search(request, name): return render(request, f"{ name }.md") and here's the urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<str:name>", views.search, name="search") ] -
How to export arabic characters to pdf in xhtml2pdf?
I want to export arabic characters to pdf using xhtml2pdf, cause I'm using it in my django app. I know that they made an update saying that they fixed it, but it didn't work with me, I used a custom font but still not working. So please anyone knows the right encryption for this or anyway around it, help me. invoice.html : {% load static %} <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <head> <title>{{title}}</title> <style type="text/css"> @font-face { font-family: Amiri, "Amiri Font"; src: url("{% static 'font/Amiri-Italic.ttf'%}"); } body { font-weight: 200; font-size: 14px; } </style> </head> <body><pdf:language name="arabic"/> <div class='wrapper'> <div class='header'> <p class='title'>Invoice # {{ invoice_ID }} </p> </div> <div> <div class='details'> <pdf:language name="arabic"/> <p> تجربة</p> customername : {{customer_name}} <br><hr> <hr class='hrItem' /> </div> </div> </body> </html> utils.py : from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None views.py : from django.shortcuts import render, redirect, HttpResponse import pandas as pd from .models import SaleInvoice, TransferWays, User, InstallingCities from siteManagment.models import MarketersManagment, … -
DRF - Create a Viewset Mixin/Baseclass to inherit a viewset-action
I have a website that is essentially a wiki for a DnD campaign that I am participating in. As such it has articles of Creatures, Characters, Locations and more. I wanted to use Viewsets to access them easily and wanted to use a Viewset action (together with a custom router) to be able to look for individual records not through pk, but through various query-parameters. I already have something that works for this, now I would like to apply some inheritance to it to not repeat myself. What I'd like to do is something like this: class WikiBaseViewset (viewsets.ModelViewSet): detail_with_params_url_pattern_suffix: str @action(detail=True, url_name="detail-params", url_path=detail_with_params_url_pattern_suffix) def detail_through_params(self, request, **kwargs): if self.detail_with_params_url_pattern_suffix == "": raise InvalidViewsetURLException("URL of view 'detail_through_params' of WikiBaseViewset is not defined!") model = self.serializer_class.Meta.model instance = get_object_or_404(model, **kwargs) serializer = self.get_serializer(instance) return Response(serializer.data) class CharacterSerializer (serializers.HyperlinkedModelSerializer): class Meta: model = wiki_models.Character fields = '__all__' class CharacterViewSet(WikiBaseViewset): """Called with URLs: character, character/<str: name>""" serializer_class = CharacterSerializer queryset = wiki_models.Character.objects.all() detail_with_params_url_pattern_suffix = "(?P<name__iexact>.+)" However, I'm struggling over the fact that the decorator absolutely requires the URL parameter in the base class. Otherwise the code just doesn't compile. If you were to set detail_with_params_url_pattern_suffix="" in the base-class in order to not get … -
Django-allauth confirm email message redirect to different URL
I am trying to set up django-allauth to verify user emails. Currently, I have set it up to send an email, however, after signup, it redirects to the login page and I do not know how to configure it to should a custom HTML message that users need to verify email address. Currently my signup view is: from allauth.account.utils import * def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() send_email_confirmation(request, user, True) return redirect('main:user_login') else: form = SignUpForm() return render(request, 'main/signup.html', {'form': form}) How can I configure it so it shows a message: Confirmation email sent to someone@example.com On my custom HTML template. I cannot find this on the docs I only have managed to change the custom email template which I have set in my project directory in: project --app1 --app2 --templates ----account -------email ---------emain_confirmation_message.txt How can I redirect users after signup to a message page that they need to verify their email address? And they can resend if it is incorrect? -
Django Rest Framework - How to return all info from a model in a Response when getting Object of type model is not JSON serializable?
I am trying to return an object with more information after a user logs in. class CustomAuthToken(ObtainAuthToken): def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) player = Player.objects.get(id=user.pk) return Response({ 'token': token.key, 'user_id': user.pk, 'email': user.email, 'full_user_info': player, # Object of type Player is not JSON serializable }) I've tried dict(player) but then the error reads TypeError: 'Player' object is not iterable -
AttributeError: 'QuerySet' object has no attribute '_require_cacheprofile'
I have an error when trying to use @cached_as(OmittedLeadEmail) @cached_as(OmittedLeadEmail) File "/pyenv/versions/3.7.8/lib/python3.7/site-packages/cacheops/query.py", line 92, in cached_as querysets = lmap(_get_queryset, samples) File "/pyenv/versions/3.7.8/lib/python3.7/site-packages/funcy/seqs.py", line 114, in lmap return _lmap(make_func(f, builtin=PY2), *seqs) File "/pyenv/versions/3.7.8/lib/python3.7/site-packages/funcy/compat.py", line 8, in lmap return list(map(f, *seqs)) File "/pyenv/versions/3.7.8/lib/python3.7/site-packages/cacheops/query.py", line 88, in _get_queryset queryset._require_cacheprofile() AttributeError: 'QuerySet' object has no attribute '_require_cacheprofile' -
How To Make Files Downloadable But Not shareable
I am developing a music distribution platform like that of Itunes model, I want to be able to allow music artist upload their tracks and sell it, but I want to make it in such a way that they are downloadable after being paid for but when they get to any third party device they can no longer be shared via Bluetooth, social media apps or any file sharing software. I want one music to be unique to a single device. any suggestions ?? -
Django on Heroku: relation "app_label" does not exist
I'm trying to deploy my Django app on Heroku. The build is successful, but the deployment fails with django.db.utils.ProgrammingError: relation "app_label" does not exist. I'm deploying directly from GitHub; the repo is public. I already looked for advice online and added try-except around the urlpatterns as suggested here, but it didn't help. I also have all the migrations committed. Now I'm not sure what might have caused the problem or how to fix it. I have successfully deployed another Django and proceeded the same way now, which is why I'm surprised it doesn't work. I'm trying to connect to the same PostgreSQL DB on Heroku that I use for the other Django app. Is that a problem? Do I need to reconfigure something here? Or do I ever need to run python manage.py migrate manually on Heroku? I think this should be taken care of by my Procfile. Any ideas or tips? I'm using Python 3.8 and Django 3.1. -
Django conditional field display on form
I am trying to make a simple form, that conditionally shows the website input field based on the value of another database field (that is not on the form) status. For the sake of this process the status field is not editable by the user, just by the admin. Both fields are in the same table: profile. After working at this for a while I copped-out and just did the conditional hiding and showing on the template. But, I realise this is the unsophisticated method, and would like to improve it. What I tried so far in forms.py: class WebsiteForm(forms.ModelForm): class Meta: model = Profile fields = ( 'e-mail', 'website', ) if Profile.status == 'personal' : exclude = ('website',) This method in forms.py works effectively, in that I can conditionally show and hide the field if I use test comparitors in the if statement like: if 1 == 1: or if 1 != 1: But, I cannot get an effective test using the field Profile.status, the value in the field seems to be unavailable at the point the if test in forms.py is performed. If I use print(Profile.status) I get the following output in the terminal: user__profile__status__isnull, so I think … -
static files doesnt want to work as they are shown on website
From this link i copied all to create my index.html https://codepen.io/jeffglenn/pen/KNYoKa I copied and pasted all css into new created main.css file in statics and rest of HTML i pasted into my index.html body section, typed on the top {% load static %} created new lane in head <link rel="stylesheet" type="text/css" href="{% static 'wwwapp/main.css' %}"> and when Im restarting localserver, then i can see .css images but they are not moving as they are on demo + they are all the time grey... If you can explain me how can i amend this lane <div class="tl-bg" style="background-image: url(https://placeimg.com/802/802/nature)"></div>to get my .jpg instead of rendered photo from www. my path to downloaded images is wwwapp/static/wwwapp/images/11.jpg and 22.jpg and so one... Can someone help ?:) -
Djang multiple levels of template extension while keeping the elements of the upper levels
I have 3 templates as following: base.html (the top level template, as usual). <body> <div id="header"> ... </div> <div id="content"> {% block content %} {% endblock %} </div> </body> category.html : {% extends "base.html" %} {% block content %} ....display some elements here... <div class="item_row"> {% block level_2_content %} {% endblock %} </div> </div> {% endblock %} and item.htlm {% extends "category/category.html" %} {% block level_2_content %} <div id="test_div"> {% for item in menu_items %} <p>{{item.name}}</p> {% endfor %} </div> {% endblock %} When item.html is rendered, all the elements that were rendered by category.html are gone. Only the elements of the base.html are retained. How do I retain all elements in all parent templates instead of just base.html? A general method to do this for more than 3 levels of extension like in my case? -
Django Rest Framework object has no attribute pk
I am working in Django / DjangoRestFramework trying to use extra actions to build out a foreignkey that is routable. I am getting the following error, I believe it has something to do with the create method on the FinancialsSerializer, or lack thereof, but I am not sure web_1 | AttributeError: 'dict' object has no attribute 'pk' stocks.viewset 19 class StockViewSet(viewsets.ModelViewSet): 20 queryset = Stock.objects.all() 21 serializer_class = StockSerializer 22 lookup_url_kwarg = "ticker" 23 lookup_field = "ticker__iexact" 24 25 @action(detail=True, methods=["POST", "GET"]) 26 def financials(self, request, ticker=None): 27 if request.method == "GET": 28 stock = self.get_object() 29 financials = stock.get_financials() 30 financials = FinancialsSerializer(financials) 31 return Response(financials.data) 32 if request.method == "POST": 33 serializer = FinancialsSerializer(request.data) 34 financials = Financials.objects.create(serializer.data) 35 financials.save() FinancialsSerializer 9 class FinancialsSerializer(WritableNestedModelSerializer): 10 balance_sheet = BalanceSheetSerializer() 11 income_statement = IncomeStatementSerializer() 12 cashflows_statement = CashflowsStatementSerializer() 13 14 class Meta: 15 model = Financials 16 fields = ["balance_sheet", "income_statement", "cashflows_statement"] -
django simple history field indexing
How can I tell DSH to index particular field? Some queries that I do to historical models take too much time I've base abstract model and all my models inherit from that model. The history field is also defined in this base model: class BaseModel(models.Model): class PublishingStatus(models.TextChoices): DRAFT = 'draft', _('Draft') ACCEPTED = 'accepted', _('Accepted'), REJECTED = 'rejected', _('Rejected'), MODIFIED = 'modified', _('Modified') publishing_status = models.CharField( max_length=9, choices=PublishingStatus.choices, default=PublishingStatus.DRAFT, help_text=_("Publishing status represents the state of the object. By default it is 'draft'") ) history = HistoricalRecords(inherit=True) And I've also added indexes in this base model class Meta: abstract = True indexes = [models.Index(fields=[ 'publishing_status', ])] It would be nice if Django Simple History could check which fields are indexed and create the same indexes in the historical models Maybe there is a way to tell django simple history explicitly which field must be indexed additionally? -
ValueError at /profiles/user-profile/ Field 'id' expected a number but got 'testuser'
I am creating follow system in my project but got an error. Can anybody tell me how i can fix it? models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follower = models.ManyToManyField(User, related_name ='is_following',blank=True) avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True) create_date = models.DateField(auto_now_add=True,null=True) def __str__(self): return f'{self.user.username}' views.py class UserProfileFollowToggle(View): def post(self, request, *args, **kwargs): print(request.POST) user_to_toggle = request.POST.get('username') print(user_to_toggle) profile_ = UserProfile.objects.get(user__username__iexact=user_to_toggle) profile_1 = request.user.userprofile user = request.user print(user,'p') if user_to_toggle in profile_.follower.all(): profile_.follower.remove(user_to_toggle) else: profile_.follower.add(user_to_toggle) return redirect(f'/profiles/{profile_.pk}') If more code or detail is require than tell me in comments i will share that by updating my question with that detail. -
In Django My form is resubmitting every time I refresh, I know I can solve this by redirecting it but i also want to pass pass data to my template
This is my code in views def pay(request): if request.method == 'POST': name=request.POST.get('name') email=request.POST.get('email') phone=request.POST.get('phone') course_name=request.POST.get('course_name') amount=int(request.POST.get('amount')) client = razorpay.Client(auth=('rzp_test_W8wCwbUqAGeqku','uETWabWBUeK53r70Qnz0Sg2Vknb')) payment = client.order.create({'amount':amount*100, 'currency':'INR', 'payment_capture':'1'}) order = Order(course_name=course_name, name=name, email=email, phone=phone, amount=amount, payment_id=payment['id']) order.save() return render(request, 'pay.html',{'payment':payment}) `I know I can solve this by redirecting it like this return redirect('womenlab:pay') but I also want to pass payment variable` return render(request, 'pay.html') I do not want every time I refresh the page it get resumbitted, please help -
Djnago Template - Url with multiple parameter
I am using Django template. I want to add multiple parameter in URL currently I am passing only one parameter my reset_password.html Click on this link to reset your password {% if htmlVersion %} <div> <a href="{{domain}}{% url 'pweuser:user_password_sms_reset' token %}"> {{domain}}{% url 'pweuser:user_password_sms_reset' token %} </a> </div> {% else %} {{domain}}{% url 'pweuser:user_password_sms_reset' token %} {% endif %} This link will expire in 15 minutes my urls.py url(r"^resetPasswordSms/(?P<token>[-\w_=]{28})/$", PasswordResetSmsView.as_view(), name="user_password_sms_reset",), my views.py t = loader.get_template("reset_password.html") c = {"htmlVersion": True, "domain": settings.SITE_DOMAIN, "token": token.token} htmlVersion = t.render(c) c = {"htmlVersion": False, "domain": settings.SITE_DOMAIN, "token": token.token} textVersion = t.render(c) Here its is working good in this I want to add more than 1 parameter. means here token is the 1st parameter and I need to add userId as 2nd parameter and need to pass in template.. how can i add multiple parameter in URL and template URL -
Trying to return a variable mid script to my template
I am wanting to display a dynamic count on my home.html. While my for loop is running I would like my Template to display the current count of the loop. Is this possible, and if so what is this process called so I can read up on it. home.html <!DOCTYPE html> <html> <body> {% block content %} {% if output >= 1 %} <p>Current count is {output}</p> {%endif%} {% endblock content %} </body> </html> views.py def page_objects(request): output = 0 for row in c: output = output + 1 return output return render(request, 'home.html') urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name = 'home'), path('views', views.page_objects, name = 'page_objects') ] -
How to get data form MySQL by dates in django?
I have an app that I'm building using Django and I want to filter the data by dates. Basicaly, I used the raw sql query for this one. Is there any one that can help me? Here's what I've one so far : views.py def getConnection(): host = config['oof_ord']['host'] port = config['oof_ord']['port'] database = config['oof_ord']['database'] password = config['oof_ord']['password'] user = config['oof_ord']['user'] try: connection = MySQLdb.connect(host=host, user=user, password=password, database=database) cursor = connection.cursor() print("Connection to" + f'{connection}' + "successfully") return cursor except: return False def getDate(request): weight_date = None if request.GET.get('weight_date') != None and request.GET.get('weight_date') != "": weight_date = request.GET.get('weight_date') else: weight_date = request.session.get('weight_date') return weight_date def filler_weight(request): template_name = 'oof_ord/fill_weight.html' cursor = getConnection() date = getDate(request) try: query = "SELECT * FROM fill_weight where weight_date = '{rundate}' ".format(rundate = getDate(request)) cursor.execute(query) rows = cursor.fetchall() print(rows[1][5]) for row in rows: print(row) finally: cursor.close() return render(request, template_name, {"rows" : rows}) My code is working if I am going to show all the data in my MySQL but what if I want to filter data by it's specific dates and show it in my template ? BTW, I get an error running this: mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (1525, "Incorrect DATE value: 'None'") -
how to combine image and videoembed in listview django
I have two class model image and videoembed. the question is how to put two class in single listview.. when there's no image, video embed show up it's my code. views.py def news_list(request): """news list category""" category = Category.objects.get(id=1) a_list = Article.objects.filter(category=1) g_list = Gallery.objects.filter(category=1) v_list = Videoembed.objects.filter(category=1) object_list = sorted( chain(a_list, g_list, v_list), key=attrgetter("publish"), reverse=True ) paginator = Paginator(object_list, 4) # 3 posts in each page page = request.GET.get("page") try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts = paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results posts = paginator.page(paginator.num_pages) return render( request, "blog/post/news.html", {"category": category, "page": page, "posts": posts}, ) and in news.html <div class="row"> {% for post in posts %} <div class="col-lg-4 col-md-6 col-sm-12 pb-4"> {% if forloop.counter0|divisibleby:3 and not forloop.first %}<div class="w-100"></div>{% endif %} {% video post.video %} <img src="{{ post.images.url }}" width="300px"> <P> <h2><a href="{{ post.get_absolute_url }}"> {{ post.title }} </a> </h2> </p> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body|safe|truncatewords:30|linebreaks }} </div> {% endfor %} thanks for any help -
Saving/Updating nested data from 3rd party API Django Rest
serializers.py class MajorUnitLaborSerializer(serializers.ModelSerializer): class Meta: model = MajorUnitLabor fields = '__all__' depth = 1 class MajorUnitPartsSerializer(serializers.ModelSerializer): class Meta: model = MajorUnitParts fields = ['DealerId', 'Description', 'SetupInstall', 'Qty', 'Cost', 'Price'] depth = 1 class MajorUnitSerializer(serializers.ModelSerializer): Parts = MajorUnitPartsSerializer(many=True) Labor = MajorUnitLaborSerializer(many=True) class Meta: model = MajorUnit fields = '__all__' def create(self, validated_data): parts_data = validated_data.pop('Parts') labor_data = validated_data.pop('Labor') majorunit = MajorUnit.objects.create(**validated_data) for part_data in parts_data: MajorUnitParts.objects.create(Unit=majorunit, **part_data) for labor in labor_data: MajorUnitLabor.objects.create(MajorUnitHeaderId=majorunit, **labor) return majorunit def update(self, instance, validated_data): instance.Parts = validated_data.get('Parts', instance.Parts) [setattr(instance, k, v) for k, v in validated_data.items()] instance.save() instance.Labor = validated_data.get('Labor', instance.Labor) [setattr(instance, k, v) for k, v in validated_data.items()] instance.save() return instance views.py @api_view(['GET','POST']) def majorunitapilist(request): query = '76179602' api_majorunit_list = get_majorunit(query) for unit in api_majorunit_list: pk = unit.get('MajorUnitHeaderId') try: obj = MajorUnit.objects.get(MajorUnitHeaderId=pk) serializer = MajorUnitSerializer(instance=obj, data=unit) if serializer.is_valid(): serializer.save() except: serializer = MajorUnitSerializer(data=unit) if serializer.is_valid(): serializer.save() else: print(serializer.errors) return Response(serializer.data) I have so many questions I don't know where to begin. Here is the basic rundown of what I'm trying to do.. Make call to 3rd party API Create/Update records in my database (data-dump) The api_majorunit_list var is a complete list of the data queried. My thought is to grab the value I'm using as … -
Can't pass dictionary in Django
So I was trying something new and I decided to try Django... And I was building a self motivated project of a hotel eCommerce site.. I was playing around with different template tags and I found moyself in a bit of a pickle... :/ Below is the attached code, if you have time to check it... Thank You... Also I have another question: Does include tag automatically inherits the contexts from the index html or should I have to pass the context from the index page with a 'with' keyword? Although I tried both "with" and without "with" with no luck. Thanks again, I am stuck in this for quite some time now... My views.py def home_view(request, *args, **kwargs): ob1 = Room.objects.all() return render(request, 'index.html', {'Rooms': ob1}) My included html snippet: {% if not Rooms %} <script type="text/javascript">console.log("No!!")</script> {% endif %} {% if Rooms %} {% for room in rooms %} <h1>{{ room.Room_Types }}</h1> <script type="text/javascript">console.log("Yes!!")</script> {% endfor %} {% endif %} Sadly, The console log was always no!!! ;( -
Encrypted model fields for sensitive data in Django
Hi I am currently developing a website with a react frontend and django backend. I need to store a gitlab access token for each user in my db so that it can be used to interact with the gitlab api (using python gitlab api https://python-gitlab.readthedocs.io/en/stable/), so that the user can create or modify a git repository using this access token. I want to store the GitLab access token in a model with the users email so that when they for example want to create a repository the view will take the users input such as repository name etc and then use the access token to create the repository but I am wary about storing the access token as I know this could be a security risk. This is for a personal project for self-education purposes so if I do make a mistake the repurcussions will be low as no actual users will be using this program just me. I still want to do this the "right way" however and I am wondering, is there any way in django to create an encrypted field for the access token field in the model, that can then be obtained and decrypted when it … -
Django setvar custom template variable availability issue
I created an custom_template_tag.py as this: from django import template register = template.Library() @register.simple_tag def setvar(val=None): return val now in my template I am looping through db and getting the correct data, but when I am trying to use my set variable outside of for loop I get nothing {% for personLiked in Post.likes.filter %} {% if request.user.id == personLiked.id %} {% setvar "True" as is_liked %} {{is_liked}} <--------GETTING VALUE HERE {% endif %} {% endfor %} {{is_liked}} <--------NOT GETTING VALUE HERE Not sure what I am missing since I believe this should be available to the rest of the page. I am aware that this is happening because I am inside of for loop. but Any suggestions how to solve this? -
Postgres manipulating sequence for bulkinsert on multiple tables
I am writing a migration script to migrate a data from old db schema to new db schema. I am doing bulk insert two tables lets assume Table A and Table B, Table B have a fk relation with Table A. The reason i am doing bulkinsert because the old tables have millions of data, so i am using postgres copy method. To achive this i am manipulating Table A sequence to allocate from N number to N number and using that allocated number to generate the data from old database to a csv and table 2 relation id. In this method everything working fine, but when i insert something through the API which is written in Django. For insertion the Django still taking the id's from the allocated sequence. Because of this even if the migration run smooth after migration the insertion is failing. I have chekced the sequence manipulation part, the count increments are working fine and also the nextval is also fetching the right one when i do it in the console. any idea what i am missing here?