Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Parse python multiline traceback to one line with fluentbit
My python application writing logs to STDOUT and I am collecting the logs with fluentbit agent. My logs sample Checking for future activity Activity Time: 1636487814 Current Time: 1636490831 Not the future activity request for athlete: 505 [2021-11-09 20:47:11,781] ERROR in app: Exception on /api/v1/lala/activity-request [POST] Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request rv = self.dispatch_request() File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/usr/local/lib/python3.7/site-packages/newrelic/hooks/framework_flask.py", line 64, in _nr_wrapper_handler_ return wrapped(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/flask_restful/__init__.py", line 467, in wrapper resp = resource(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/flask/views.py", line 89, in view return self.dispatch_request(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/flask_restful/__init__.py", line 582, in dispatch_request resp = meth(*args, **kwargs) File "./test-app/api/resources/lala/v1/resources.py", line 111, in post lalaService.send_activity_request_to_broker(athlete, activity_request) File "./test-app/api/resources/lala/services.py", line 94, in send_activity_request_to_broker ThirdPartyService.produce_activity(activity_data) File "./test-app/api/resources/common/services.py", line 91, in produce_activity get_or_create_eventloop().run_until_complete(produce_activity(activity_data)) File "/usr/local/lib/python3.7/asyncio/base_events.py", line 587, in run_until_complete return future.result() File "./test-app/producer.py", line 12, in produce_activity await result RuntimeError: Task <Task pending coro=<produce_activity() running at ./test-app/producer.py:12> cb=[remove_from_cache() at /usr/local/lib/python3.7/site-packages/newrelic/hooks/coroutines_asyncio.py:20, _run_until_complete_cb() at /usr/local/lib/python3.7/asyncio/base_events.py:157]> got Future <Future pending cb=[Topic._on_published(message=<FutureMessage pending>, state={}, producer=<Producer: running >)()]> attached to a different loop [pid: 10|app: 0|req: 15952/63804] 10.0.225.22 () {60 vars in 2181 bytes} [Tue Nov 9 20:47:11 2021] POST /api/v1/lala/activity-request => generated 37 bytes in 506 msecs (HTTP/1.1 500) … -
Implement Odoo Connector for external application?
The exact question is about roadmap of implementation. It is Django application that I'm mentioning as external application. Actually I want to speak (sending changed data to Django) with Django when data created, deleted or updated on Odoo. Also how can I get the mutated data from Django app? In other word I want to learn how can I build synchronization structure (bidirectional synchronization) between Odoo and Django app? is there any information can help? -
How to improve multiple query for multiple chart in 1 page
I would like to increase speed for loading page for my website I have to write code with difference group by eg. data that group by period type data that group by country data that group by daterange Question:how can i improve my coding for increse speed on query?. View.py def get_queryset(self): dateRange = self.request.query_params.get('dateRange') if dateRange is not None: datestart = datetime.datetime.strptime(dateRange.split('-')[0], "%Y%m%d").strftime("%Y-%m-%d") dateend = datetime.datetime.strptime(dateRange.split('-')[1], "%Y%m%d").strftime("%Y-%m-%d") else: year_today = str((datetime.datetime.now().date() - datetime.timedelta(days=1)).year) week_today = str((datetime.datetime.now().date() - datetime.timedelta(days=1)).isocalendar()[1] - 1) datestart = datetime.datetime.strptime(year_today + '-W' + week_today + '-1', "%Y-W%W-%w") dateend = datetime.datetime.strptime(year_today + '-W' + week_today + '-0', "%Y-W%W-%w") queryset = ranking_page_data.objects.filter(Date_start__range=(datestart, dateend), Period_Type="daily", Order_Type="Gross Order").values('Country').annotate( Sales_Euro=Sum('Sales_Euro'), Orders=Sum('Orders'), Unit=Sum('Unit'), buyers=Sum('buyers'), Visitors=Sum('Visitors'), Pageview=Sum('Pageview'), Conversion_Rate=Avg('Conversion_Rate')).order_by('-Sales_Euro') queryset1 = ranking_page_data.objects.filter(Date_start__range=(datestart, dateend), Period_Type="daily", Order_Type="Gross Order").values('Platform').annotate( Sales_Euro=Sum('Sales_Euro'), Orders=Sum('Orders'), Unit=Sum('Unit'), buyers=Sum('buyers'), Visitors=Sum('Visitors'), Pageview=Sum('Pageview'), Conversion_Rate=Avg('Conversion_Rate')).order_by('-Sales_Euro') queryset2 = ranking_page_data.objects.filter(Date_start__range=(datestart, dateend), Period_Type="daily", Order_Type="Gross Order").values('Country','Platform').annotate( Sales_Euro=Sum('Sales_Euro'), Orders=Sum('Orders'), Unit=Sum('Unit'), buyers=Sum('buyers'), Visitors=Sum('Visitors'), Pageview=Sum('Pageview'), Conversion_Rate=Avg('Conversion_Rate')).order_by('-Sales_Euro') return queryset,queryset1,queryset2 and model.py class ranking_page_data(models.Model): ID = models.IntegerField() Specific_Identity = models.TextField() Country = models.TextField() Platform = models.TextField() Brand = models.TextField() Period_Type = models.TextField() Date_start = models.DateField() Date_end = models.DateField() Order_Type = models.TextField() Date = models.TextField() Time = models.TextField() Conversion_Rate = models.FloatField() Orders = models.IntegerField() buyers = models.IntegerField() Pageview = models.IntegerField() Unit = models.IntegerField() Visitors = models.IntegerField() … -
Audio recording in modal Bootstrap and Django
I need to insert in a boostrap modal the possibility to record a microphone audio and pass the file to the django view. For the text I did it like this but I don't know how to do it for the audio, ideas? HTML: <div class="modal fade" id="textModal"> <div class="modal-dialog"> <div class="modal-content"> <form action="results_text_analysis" method="POST"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Input text</h4> <button type="button" class="btn-close" data-bs-dismiss="modal"></button> </div> <!-- Modal body --> <div class="modal-body"> {% csrf_token %} <textarea type="text" class="form-control input-lg" name="text"></textarea> </div> <!-- Modal footer --> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Calculate</button> </div> </form> </div> </div> VIEW: @api_view(['POST']) def results_text_analysis(request): input_text = request.POST['text'] ..... -
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance
I am using Django Rest and my request parameter contains: [ { "job_role": 2, "technology": 1 }, { "job_role": 1, "technology": 1 }, { "job_role": 2, "technology": 1 } ] My models are: class Technology(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class JobRole(models.Model): role_name = models.CharField(max_length=100) def __str__(self): return self.role_name class ExpertPricing(models.Model): role_name = models.OneToOneField(JobRole, related_name="role", on_delete=models.SET_NULL, null=True) experience_in_years = models.PositiveBigIntegerField() technology = models.OneToOneField(Technology, related_name="technology", on_delete=models.SET_NULL, null=True) salary_per_month = models.PositiveBigIntegerField() My view looks like this: class PricingView(APIView): def post(self, request): datas = request.data data_list = [] for data in datas: job_role_id = data["job_role"] technology_id = data["technology"] job_role = JobRole.objects.get(pk=job_role_id) technology = Technology.objects.get(pk=technology_id) expert_pricing = ExpertPricing.objects.filter(role_name=job_role, technology=technology) if expert_pricing: data_list.append(expert_pricing) serializer = ExpertPricingSerializer(data_list, many=True) return Response(serializer.data, status=status.HTTP_200_OK) serializers.py class TechnologySerializer(serializers.ModelSerializer): class Meta: model = Technology fields = ("id", "name") class JobRoleSerializer(serializers.ModelSerializer): class Meta: model = JobRole fields = ("id","role_name") class ExpertPricingSerializer(serializers.ModelSerializer): role = JobRoleSerializer(many=False, read_only=True) technology = TechnologySerializer(many=False, read_only=True) class Meta: model = ExpertPricing fields = "__all__" I am unable to understand why data_list is not being serialized. the error says: AttributeError: Got AttributeError when attempting to get a value for field `experience_in_years` on serializer `ExpertPricingSerializer`. The serializer field might be named incorrectly and not match any attribute or key … -
AttributeError: 'QuerySet' object has no attribute 'save'
This is the page that I'm trying to work out. If the update is clicked, the filled-in details should be updated in a MySql database called TL. But while clicking update, it's throwing the following error: AttributeError at /add/ 'QuerySet' object has no attribute 'save' The following is Views.py file in Django where I had put code for add: def add(request): ad = TL.objects.all() if request.method == 'POST': TL_Name = request.POST.get('TL_Name') Proj_name = request.POST.get('Proj_name') Deadline = request.POST.get('Deadline') ad.TL_Name = TL_Name ad.Proj_name = Proj_name ad.Deadline = Deadline ad.save() return redirect("/operations") return render(request, 'operations.html', {"name": ad, 'b': ad}) The following is the urls.py file: from . import views urlpatterns = [ path('', views.home), path('adminlogin/', views.adminlogin), path('operations/', views.operations), path('approve/<int:pk>', views.approval), path('decline/<int:pk>/', views.delete), path('edit/<int:pk>/', views.edit), path('add/', views.add), path('tlist/', views.approved_tlist) ] The following is the operations.html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Team Leaders</title> </head> <body> <h1>List of Team Leaders</h1> <table id="table"> <tr> <th>TL_Name</th> <th>Proj_name</th> <th>Proj_Status</th> <th>Deadline</th> <th>Action</th> </tr> {% for i in name %} <tr> <td>{{i.TL_Name}}</td> <td>{{i.Proj_name}}</td> <td>{{i.Proj_Status}}</td> <td>{{i.Deadline}}</td> <td> <a href="/approve/{{i.id}}">Approve</a> <a href="/decline/{{i.pk}}">Decline</a> <a href="/edit/{{i.pk}}">Edit</a> </td> </tr> {% endfor %} </table> <br> <br> {% if a %} <form method="post"> {% csrf_token %} <table> <tr> <td> <label>TL_Name</label> </td> <td> <input type="text" name="TL_Name" … -
Unable to display the firebase push notification/message on background mode
Im working on firebase messaging service to send push notification via django web application to Andriod,IOS and website as well, i refer to this link, i managed to get token but not able to display the message on background mode, please find the js code in html index page and firebase-messaging-sw for your reference (Note: i don't get any error, but at the same time I don't receive any notification nor message!!) html: <!-- Getting the tocken --> <script type="module"> // Import the functions you need from the SDKs you need import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js'; // Your web app's Firebase configuration // For Firebase JS SDK v7.20.0 and later, measurementId is optional const firebaseConfig = { apiKey: "xxxxxxxxxxxxxx", authDomain: "xxxxxxxxxxxxxx", projectId: "xxxxxxxxxxxx", storageBucket: "xxxxxxxxxxxxxxxx", messagingSenderId: "xxxxxxxxxxxxxxxxx", appId: "xxxxxxxxxxxxxxxxxxxxx", measurementId: "xxxxxxxxxxxxxxxxxxx" }; // Initialize Firebase const app = initializeApp(firebaseConfig); import { getMessaging, getToken } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging.js'; // Get registration token. Initially this makes a network call, once retrieved // subsequent calls to getToken will return from cache. const messaging = getMessaging(); getToken(messaging, { vapidKey: 'BJRrwDBTJkgQ0j0buwcfLsSxfr5tOxPrOzI5XM7J38n-k9Tzeq8qrY8SPeHyb3LRF49eFEj7lv6BiDFhEVJZn0A' }).then((currentToken) => { if (currentToken) { console.log(currentToken); // Send the token to your server and update the UI if necessary // ... } else … -
infinite scroll working but not populating all data because of javascript call
in my web site i want to show the user ratings for that i used the infinite scroll but i am facing one problem. when it first loads the data before calling the <a class="infinite-more-link" href="?page={{ ratings.next_page_number }}"></a> it is showing the star with the count of vote,but when after calling the <a class="infinite-more-link" href="?page={{ ratings.next_page_number }}"></a> it is not showing the star. my views.py @login_required def ratings_user(request,pk): ratings = VoteUser.objects.filter(the_user_id=pk).order_by('-pk') paginator = Paginator(ratings, 1) page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request,request.session['is_mobile']+'profile/ratings.html',{'ratings':posts}) html {% extends 'mobile/profile/base.html' %} {% block title %} Ratings {% endblock %} {% block leftcontent %} <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css" rel="stylesheet"> {% endblock %} {% block middlecontent %} <div class="infinite-container"> {% for i in ratings %} <div class="infinite-item"> <div class="w3-container w3-card w3-white w3-round w3-margin"> <img src="{{ i.the_user.profile.avatar.url }}" alt="Avatar" class="w3-left w3-circle w3-margin-right" style="width:40px;height:40px;border-radius:50%;"> <a href ="{% url 'profile' i.the_user_id %}" style="color:black;">{% with user=i.the_user.profile %}{{ user.prenom|title|truncatewords:2 }} {{ user.nom|title|truncatewords:1 }}{% endwith %}</a> <br> <span class="stars" data-rating="{{ i.vote.vote }}" data-num-stars="5" ></span> <hr class="w3-clear"> <p> {{ i.commentaire|linebreaksbr }} </p> <span class="glyphicon glyphicon-user"></span> <a href ="{% url 'profile' i.the_sender_id %}">{% with user=i.the_sender.profile %}{{ user.prenom|title|truncatewords:2 }} {{ user.nom|title|truncatewords:1 }}{% endwith %}</a> </div> … -
How to retrieve Django list as array in Javascript
I'm sending django list from view.py to my javascript. But when I receive the list in javscript, it only return me as string. I tried to print the type of the variable but it show me false which mean its not array list. So how can I retrieve the list as array in Javascript? View.py mergedCompare = [item_listAssigned[f'subject{i}'] + ': ' + item_listAssigned[f'serial{i}'] for i in range(1, len(item_listAssigned) // 2 + 1)] global context context = { 'mergedCompare': mergedCompare } mergedCompare = ['EMP004: BPCE-RNHC-25G8', 'EMP003: 8FIW-9JRB-NY4J', 'EMP005: 7QF2-6HI9-XKZZ', 'EMP002: SG8P-YQKG-ZV3C', 'EMP001: PBF7-WZHT-WPZR'] JavaScript: var assignedDevices = "{{mergedCompare|safe}}" const list = assignedDevices; console.log(Array.isArray(list)) //false , not array -
Is there a way to add more than one field on a dropdown?
So I am calling fields from a persons class to a shareholders class so I us a Many2One field to call the field to call the firstnames as drop form the persons class. I now want to show the firstname, lastname and email on the dropdown. class shareholder(models.Model): person_id = fields.Many2one('person', string='First Name', required=True) last_name = fields.Char(string='Last Name', related= 'person_id.last_name') email = fields.Char(string='Email Address', related= 'person_id.email') -
Django models datetime with timezone UTC+1 saved as UTC+0
In my django project i have a model where i store data (in my read_date field) with a DateTime field for storing date (with timezone): class Results(models.Model): id = models.AutoField(primary_key=True) device = models.ForeignKey(Device, null=True, on_delete=models.SET_NULL) proj_code = models.CharField(max_length=400) res_key = models.SlugField(max_length=80, verbose_name="Message unique key", unique=True) read_date = models.DateTimeField(verbose_name="Datetime of vals readings") unit = models.ForeignKey(ModbusDevice, null=True, on_delete=models.SET_NULL) i setted in settings.py file using timezone: TIME_ZONE = 'UTC+1' USE_TZ = True So, the problem is, when i pass a corrected formatted ditetime with UTC+1 timezone as: 2021-11-12 10:39:59.495396+01:00 in my db i get: 2021-11-12 9:39:59.495396+00 Why my stored value is UTC+0 instead using timezone passed? So many thanks in advance -
I am having some trouble designing API endpoint for my Django App (DRF)
I am designing an API for an E-learning project. The platform enables students to take online tests. The tests contain questions and questions can have multiple options. Below is the schema for my app: Test: id: Primary Key duration: Integer created: Timestamp Question: id: Primary Key serial: Integer test: Foreign Key (Test) body: Char Field Option: id: Primary Key question: Foreign Key (Question) body: Char Field correct: Boolean Field StudentSelectedOption: id: Primary Key question: Foreign Key (Question) student: Foreign Key (User) option: Foreign Key (Option) Now, the problem is that I want to create an endpoint for returning student selected options based on the requesting user /test/<int:test_id>/student-answers/ But I am not able to filter selected options related to the test id and user. Can someone help me out? -
More efficient way to update multiple model objects each with unique values
I am looking for a more efficient way to update a bunch of model objects. Every night I have background jobs creating 'NCAABGame' objects from an API once the scores are final. In the morning I have to update all the fields in the model with the stats that the API did not provide. As of right now I get the stats formatted from an excel file and I copy and paste each update and run it like this: NCAABGame.objects.filter( name__name='San Francisco', updated=False).update( field_goals=38, field_goal_attempts=55, three_points=11, three_point_attempts=24, ... ) The other day there were 183 games, most days between 20-30 so it can be very timely doing it this way. I've looked into bulk_update and a few other things but I can't really find a solution. I'm sure there is something simple that I'm just not seeing. I appreciate any ideas or solutions you can offer. -
Problem installing fixtures - duplicate key value violates unique constraint "profiles_userprofile_user_id_key" : Key (user_id)=(2) already exists
I have set up a Django project with data on mysql. I have carried out a data dump to move my project to postgres and Heroku/AWS but when i run python3 manage.py loaddata db.json to load my data to postgres, i am getting the following error django.db.utils.IntegrityError: Problem installing fixture '/workspace/press_records/db.json': Could not load profiles.UserProfile(pk=1): duplicate key value violates unique constraint "profiles_userprofile_user_id_key" DETAIL: Key (user_id)=(2) already exists. My Model: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django_countries.fields import CountryField class UserProfile(models.Model): """ A user profile model for maintaining default delivery information and order history """ user = models.OneToOneField(User, on_delete=models.CASCADE) default_phone_number = models.CharField(max_length=20, null=True, blank=True) default_street_address1 = models.CharField(max_length=80, null=True, blank=True) default_street_address2 = models.CharField(max_length=80, null=True, blank=True) default_town_or_city = models.CharField(max_length=40, null=True, blank=True) default_county = models.CharField(max_length=80, null=True, blank=True) default_country = CountryField(blank_label='Country', null=True, blank=True) default_postcode = models.CharField(max_length=20, null=True, blank=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): """ Create or update the user profile """ if created: UserProfile.objects.create(user=instance) # Existing users: just save the profile instance.userprofile.save() My Form from django import forms from .models import UserProfile class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile exclude = ('user',) def __init__(self, *args, **kwargs): """ Add … -
"Object has no attribute" when executing RunPython in django migration
I'm trying to run this operation: def apply_func(apps, schema_editor): User = apps.get_model("accounts", "User") for user in User.objects.all(): if user.is_two_fa_enabled: user.is_verified = True user.save() class Migration(migrations.Migration): operations = [ migrations.AddField( model_name='user', name='is_verified', field=models.BooleanField(default=False), ), migrations.RunPython(apply_func) ] but I've no idea why am I getting such an error AttributeError: 'User' object has no attribute 'is_two_fa_enabled' when I want to migrate. class User(AbstractBaseUser, PermissionsMixin): is_verified = models.BooleanField(default=False) two_fa_type = models.CharField(choices=TwoFaTypes.choices, default=TwoFaTypes.SMS.value, max_length=32, null=True) @property def is_two_fa_enabled(self): return bool(self.two_fa_type) Could you please explain me what am I doing wrong? -
How to connect react with django channels?
I want to add chat to my react app and I am using DRF to build my apis want to know how is it possible to connect django channels to my react app -
How do I filter items by name and timestamp range in django?
I want to filter transactions by external id that fit in start and end date range. When I add dates within the range they don't show up. Here is my current code filtered_transactions = Transaction.objects.filter( organisation_id_from_partner=organisation_id, timestamp__range=[latest_transaction.timestamp, start_date] ) -
Django: Issue displaying updates for a MultipleChoiceField, template keeps displaying initial values
First post, apologies in advance for errors. My problem: I initialize my model fields from a proprietary db. These fields are displayed correctly in my template (I can see the html reflects the values in my proprietary db). I then change the initial selection options (for the MultiSelectField) in my template, and save these changed options to the Django db (verified its saved via the admin function) via post overloading in my views. My success_url is setup in urls.py to redisplay the same view. I have overloaded get_context_data in views to load the form data from the Django database, and to update context data with this loaded data, the idea being that when the templates redisplays, my form should now displays the from data loaded from the Django db (not the initial values). What's happening, though, is that the initial values seems to be displayed, as opposed to the changed values I have loaded from the Django db. I would really appreciate help wrt understanding why the template displays values other than what I have loaded from the Django db. my models.py: class LiquidAssetModel(models.Model): #Get my initial values from an external db unq_assets = Jnance_base_data_main.get_unq_assets() init_values = Jnance_base_data_main.get_liq_indexes() liq_dates = … -
How to filter queryset with custom function
I have the following models and I am trying to apply some filtering. Basically I have this player model that can have multiple Experiences, and I want to send on my query params xp that will receive a value in years, and my queryset should only retrieve the players with at least that amount of years of experience in total. The calc_player_experience method reads throw the players experience and calculates de amount of experience the player has and returns true or false if it meets the xp received on the query params. How do I apply a function to model.filter()? is that a thing? models.py class Player(BaseModel): name = models.CharField(_("name"), max_length=255, blank=True) class Experience(BaseModel): player = models.ForeignKey( "players.Player", on_delete=models.CASCADE ) team = models.CharField(_("team"), max_length=255) start_date = models.DateField(_("start_date"), null=True, blank=True) end_date = models.DateField(_("end_date"), null=True, blank=True) views.py class PlayersViewSet(viewsets.ModelViewSet): serializer_class = PlayerSerializer queryset = Player.objects.all() def get_queryset(self): """Filters the players to retrieve only those not archived and approved""" queryset = Player.objects.filter(is_approved=True, is_active=True) return apply_filters(self, queryset) def apply_filters(obj, queryset): """Apply filters to given queryset""" xp = dict(obj.request.GET).get("xp", []) if xp: queryset = queryset.filter(lambda player: obj.calc_player_experience(player,xp[0])) -
Docker-compose up with conda not working properly
Good afternoon. First of all, I'm very beginner in Docker and I have a ongoing project with Django+PostgreSQL. I have issue with running docker-compose up. First of all I was facing a error code 137. I went through the steps. I give docker more ram (was 2GB, I give it 4GB firstly and then expand to 8GB). Here is SO thread for this error Error was solved, but now I'm facing infinity loading on this steps. ' => [3/5] RUN conda install -y --file /conda_files/requirements.txt -c conda-forge -c anaconda ' It can be going for 2000secs+ Here is my Dockerfile FROM conda/miniconda3 COPY requirements.txt /conda_files/requirements.txt RUN conda install -y --file /conda_files/requirements.txt -c conda- forge -c anaconda RUN pip install requests-html==0.10.0 COPY . /app/ref_wallet ENV PYTHONPATH "${PYTHONPATH}:/app/ref_wallet" Here is my docker-compose.yml version: '3.7' services: web: build: . command: python /app/current/manage.py runserver 0.0.0.0:80 volumes: - .:/app/current/ ports: - 8082:80 The most strange thing. That my colleague can run this code on his Windows PC. And I'm on my MacBook can not. Any ideas of why it's happening and how I can solve it? Cause currently I don't receive any errors. It's just infinity loading for me now. -
How can I show a HTML but not in string?
I'm working with Django. I save text and images with a HTML editor to show it in another HTML file with format, but it shows only text. I write all description with: <div class="col-sm-6"> <div class="form-group"> <label for="{{mails_form.subject.label}}">{{mails_form.subject.label}}</label> {{mails_form.subject}} </div> </div> Then I save the content with description = send_mails.description in the view. And in another HTML file I show: <tr> <td class="content-block"> <strong>{{description}}</strong> </td> </tr> But it just shows this: https://i.stack.imgur.com/zmU2E.png (I wrote a little text and included an image) I don't want to show only the text, I want to show it in HTML format, not write the tags, but use them. -
django-rest-framework override get_queryset and pass additional data to serializer along queryset
This is a toy example of the problem that I am facing. For some reason, I am unable to pass the expected data to my serializer and that is raising the following error. AttributeError at /my-end-point/ Got AttributeError when attempting to get a value for field main_data on serializer ParentSerializer. The serializer field might be named incorrectly and not match any attribute or key on the str instance. Original exception text was: 'str' object has no attribute 'main_data'. class MainModelSerializer(serializers.ModelSerializer): class Meta: model = MainModel class ParentSerializer(serializers.Serializer): main_data = MainModelSerializer(many=True) extra_data = serializers.FloatField() class View(ListCreateAPIView): serializer = ParentSerializer def get_queryset(self): # extra_data would have some calculated value which would be a float extra_data = some_calculated_value() queryset = MainModel.objects.filter(some filters) return { 'main_data': queryset, 'extra_data': extra_data } # expected data that is passed to the ParentSerializer # { # 'main_data': queryset, # 'extra_data': extra_data # } -
Redirecting a user to checkout page in Django
I want to redirect a user to checkout page that is automatically generated by the payment gateway. Anytime a user submits a request, the payment gateway returns a response in the format below. What i want to do is redirect the user to the checkout page to make payment. "status": true, "message": "Authorization URL created", "data": { "authorization_url": "https://checkout.paystack.com/eddno1f6rf411p0", "access_code": "eddno1f6rf411p0", "reference": "bpozkels2v" def paystack(request): url = 'https://api.paystack.co/transaction/initialize' transaction_id = random.randint(100000000000, 999999999999) data = { "key": "PUBLIC_KEY", "ref": transaction_id, "amount": "000000000100", "callback": f"http://127.0.0.1:8000", "email": "email@me.com", } headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer SECRET_KEY', 'Cache-Control': 'no-cache' } res = requests.post(url, data=json.dumps(data), headers=headers) response_data = res.json() print(response_data["authorization_url"]) redirect(response_data["authorization_url"]) The error i get is KeyError at /paystack 'authorization_url' -
SSL certificates and https for AWS hosted django site
I have a django site hosted on elastic beanstalk. I have obtained a AWS SSL certificate and this has been associated with the load balancer 443 HTTPS port. In my config file I have: MIDDLEWARE = [ ... "django.middleware.csrf.CsrfViewMiddleware", ] CSRF_COOKIE_HTTPONLY = False SESSION_COOKIE_HTTPONLY = True With this setup I am able to login to the site but the browser displays 'not secure' in the address bar, and if I prepend 'https://' to the urls I get a page stating the connection is not private. If I add SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True Then it becomes impossible to login (the login page just reloads) or if I got to a incognito browser I get a 'CSRF verification failed. Request aborted.' message. It may be related but I am also receiving emails stating 'Invalid HTTP_HOST header: ’52.XX.X.XXX’. You may need to add ’52.XX.X.XXX’ to ALLOWED_HOSTS. The ip address relates to one of the ec2 instances running the site but my understanding was that only the address for the elastic beanstalk environment and my domain name needed to be added here. Apologies for the log question, I've just tried to include ay detail that may be relevant -
How do I get the an object by name and highest timestamp
I want to fetch the transaction belonging to external_id=1 and has the highest timestamp. I have tried this max_rating = Transaction.objects.aggregate(organisation_id_from_partner=organisation_id, highest_timestamp=Max('timestamp')) But I get TypeError: QuerySet.aggregate() received non-expression(s): 1.