Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I format a nested python dictionary and write it to a json file?
I am looking to run a calculation in my Django view and then write it to a json file. However I am struggling to get the formatting right. I need the output json file to look something like this: { "dates": { "year": { "total": 1586266, "upDown": 9.8, "data": { "labels": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], "income": [2000, 4000, 6000, 8000, 10000, 12000, 14000, 16000, 18000, 20000, 22000, 24000], "expenses": [6000, 12000, 18000, 24000, 30000, 36000, 42000, 48000, 54000, 60000, 66000, 72000] } } } } Here is what I have in my view: def generateGraph(): income = [{'income':['2000','2000','2000','2000','2000','2000','2000','2000','2000','2000','2000','2000']}] expenses = [{'expenses':['1000','1000','1000','1000','1000','1000','1000','1000','1000','1000','1000','1000']}] labels = [{'labels':['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']}] total = 1586266 upDown = 9.8 data = [labels, income, expenses] year = [total,upDown,data] dates = [year] with open( "static/graph.json") as f:json.dump(dates, f) return HttpResponse(open("static/graph.json", 'r'), content_type = 'application/json; charset=utf8') However, the output I currently get in my json file is: [[1586266, 9.8, [[{"labels": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]}], [{"income": ["2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000"]}], [{"expenses": ["1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000"]}]]]] Thanks! -
django html5 video plugin doesn't show in editor
i copied html5video in plugins folder and write 'html5video' in settings.py . video uploading icon doesn't show in editor, how can i fix this problem ? my configs ckeditor in settings.py : CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono', # 'skin': 'office2013', 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], 'toolbar_YourCustomToolbarConfig': [ {'name': 'document', 'items': ['Source', '-', 'Save', 'NewPage', 'Preview', 'Print', '-', 'Templates']}, {'name': 'clipboard', 'items': ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']}, {'name': 'editing', 'items': ['Find', 'Replace', '-', 'SelectAll']}, {'name': 'forms', 'items': ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField']}, '/', {'name': 'basicstyles', 'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']}, {'name': 'paragraph', 'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl', 'Language']}, {'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']}, {'name': 'insert', 'items': ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe']}, '/', {'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']}, {'name': 'colors', 'items': ['TextColor', 'BGColor']}, {'name': 'tools', 'items': ['Maximize', 'ShowBlocks']}, {'name': 'about', 'items': ['About']}, '/', # put this to force next toolbar on new line {'name': 'yourcustomtools', 'items': [ # put the name of your editor.ui.addButton here 'Preview', 'Maximize', ]}, ], 'toolbar': 'YourCustomToolbarConfig', # put selected toolbar config here # 'toolbarGroups': … -
Django Rest Framework: Delete multiple Cookies with same name but different domain?
I have an application running on different shards and each shard has a different domain. I am setting that domain as a domain for our cookies for respective environments. And the problem I am facing is that sometimes cookies from previous sessions (might be from different environments) are present in the browser. So When I try to perform certain actions then a cookie from the different session is used and validation failed. So now I want to delete those cookies with the same name. What I am doing is response.delete_cookie('profileActionId') But after this the cookies was something like this: profileActionID: 'cookie_value' :: domain: 'usa.example.com/' profileActionID: '' :: domain: 'example.com/' So this doesn't delete cookies with the same name which have a different domain and I don't have a way to access that different domain from the code and also can't hardcode it as It will change according to different environments. Also I can't change the domain for cookies for different environments. So Is there a way in Django by which we can delete all cookies with the same name irrespective of there domains or paths? -
Do I need to use a inline formset? Or am I over complicating my models?
I’m trying to create an app that stores golf round scores. This will have things like the course being played, which tees being used, etc. what’s causing me problems is this could have 1-4 players. I would like to use 1 model for this, but I don’t think it would be possible because I need one instance of the course criteria, while 1-4 instances for the players. Am I overthinking my models? Or does this sound correct. Based on the models.py below I would do a inline formset with Golf_Round and Round_player` from django.db import models from django import template from django.urls import reverse from Courses.models import Golf_Course from accounts.models import Golfer from django.utils.timezone import now class Golf_Round(models.Model): Tee= models.ForeignKey(Golf_Tee, on_delete=models.CASCADE) round_create_date = models.DateTimeField(default=now()) is_active_round = models.BooleanField(default=False) def _str_(self): return "{}.{}.{}".format(self.round_create_date, self.course,self.pk) class Round_Player(models.Model): player = models.ForeignKey(Golfer, on_delete=models.CASCADE, default='Please_Select',blank=False) round = models.ForeignKey(Golf_Round, on_delete=models.CASCADE) hole_1_score = models.IntegerField() hole_2_score = models.IntegerField() hole_3_score = models.IntegerField() hole_4_score = models.IntegerField() hole_5_score = models.IntegerField() hole_6_score = models.IntegerField() hole_7_score = models.IntegerField() hole_8_score = models.IntegerField() hole_9_score = models.IntegerField() hole_10_score = models.IntegerField() hole_11_score = models.IntegerField() hole_12_score = models.IntegerField() hole_13_score = models.IntegerField() hole_14_score = models.IntegerField() hole_15_score = models.IntegerField() hole_16_score = models.IntegerField() hole_17_score = models.IntegerField() hole_18_score = models.IntegerField() create_date = models.DateTimeField(default=now()) … -
How can I put the elements of a form horizontally?
This is the layout and I would like the form elements to be horizontal instead of vertical This is my view code def requerimientos(request): form_procesos = forms.procesos form_impuesto = forms.impuestos return render(request, 'requerimientos.html',{"proceso" : form_procesos,"impuesto" : form_impuesto,"value": 2}) This is my HTML code <div class="col-12 col-md-6 offset-md-3"> <div class="card"> <div class="card-body"> {% if value == 1 %} <h5 style="font-family: 'Ubuntu', sans-serif;">Proceso:</h5> <form action="{% url 'contacto' %}" method="POST"> {% csrf_token %} {% crispy proceso %} </form> {% else %} <h5 style="font-family: 'Ubuntu', sans-serif;">Proceso:</h5> <form action="{% url 'contacto' %}" method="POST"> {% csrf_token %} {% crispy proceso %} </form> <h5 style="font-family: 'Ubuntu', sans-serif;">Impuesto:</h5> <form action="{% url 'contacto' %}" method="POST"> {% csrf_token %} {% crispy impuesto %} </form> {% endif %} </div> </div> <!-- Boton de enviar --> <br> <div class="d-flex justify-content-end"> <button type="submit" class="btn btn-primary">Enviar</button> </div> </div> This is my form code from django.forms import ModelForm from django import forms from crispy_forms.helper import FormHelper, Layout class procesos(forms.Form): mora = forms.BooleanField(required=False) deuda_atrasada = forms.BooleanField(required=False) class impuestos(forms.Form): inmobiliario = forms.BooleanField(required=False) baldio = forms.BooleanField(required=False) rural = forms.BooleanField(required=False) edificado = forms.BooleanField(required=False) automotor = forms.BooleanField(required=False) embarcaciones = forms.BooleanField(required=False) complementario = forms.BooleanField(required=False) I have another question, I created two forms because I needed to describe what each element was, … -
html - Add bullet piont as place holder django forms
I am using django-forms to render out my signup page and i want to add a bullet point as placholder for password field by passing the &bull; character entity from the widgets in django-forms but it doesn't work. is how it is rendered out in browser. forms.py class Signup(forms.ModelForm): class Meta: model = User fields = ["username", "email", "password", "password2", "library_no", "first_name", "last_name",] help_texts = { "username":None, } labels = { } widgets = { "username": forms.TextInput(attrs={ "id":"input_46", "name":"q46_typeA46", "data-type":"input-textbox", "class":"form-textbox validate[required]", "size":"310", "data-component":"textbox", "aria-labelledby":"label_46", "placeholder":"180591001" }), "first_name":forms.TextInput(attrs={ "id":"first_4", "name":"q4_name[first]", "class":"form-textbox validate[required]", "autoComplete":"section-input_4 given-name", "data-component":"first", "aria-labelledby":"label_4 sublabel_4_first", "required":True, "placeholder":"Chinedu" }), "last_name":forms.TextInput(attrs={ "id":"last_4", "name":"q4_name[last]", "class":"form-textbox validate[required]", "autoComplete":"section-input_4 family-name", "data-component":"last", "aria-labelledby":"label_4 sublabel_4_last", "required":True, "placeholder":"Oladapo Dikko" }), "email":forms.EmailInput(attrs={ "id=":"input_10", "name":"q10_email10", "class":"form-textbox validate[required, Email]", "placeholder":"ex: myname@example.com", "data-component":"email", "aria-labelledby":"label_10 sublabel_input_10", "required":True }), "password": forms.PasswordInput(attrs={ "id":"first_50", "name":"q50_name50[first]", "class":"form-textbox", "autoComplete":"section-input_50 given-name", "data-component":"first", "aria-labelledby":"label_50 sublabel_50_first", "required":True, "placeholder":"&bull;&bull;" }), "password2": forms.PasswordInput(attrs={ "id":"last_50", "name":"q50_name50[last]", "class":"form-textbox", "autoComplete":"section-input_50 family-name", "data-component":"last", "aria-labelledby":"label_50 sublabel_50_last", "required": False }), "library_no": forms.TextInput(attrs={"required": False}), } signup.html <!DOCTYPE html> <html class="supernova"> <head> <title>SignUp</title> <style type="text/css">@media print{.form-section{display:inline!important}.form-pagebreak{display:none!important}.form-section-closed{height:auto!important}.page-section{position:initial!important}}</style> <link rel="stylesheet" href="/static/signup/css/style.css"> <link rel="stylesheet" href="/static/signup/css/main.css"> </head> <body> <form class="jotform-form" action="/signup/" method="post" name="form_230023299150548" id="230023299150548" accept-charset="utf-8" autocomplete="on"> {%csrf_token%} <div role="main" class="form-all"> <style> .form-all:before { background: none; } </style> <ul class="form-section page-section"> <li id="cid_28" class="form-input-wide" … -
Can I return multiple values from a SerializerMethodField? I am getting an error telling me I can't. How do I then get the values?
I have a post model that represents a normal post with images and possibly a video. I have a post reply model that represents comments or replies to a post. Here is the models.py file: class Category(models.Model): name = models.CharField(max_length=100, verbose_name="name") slug = AutoSlugField(populate_from=["name"]) description = models.TextField(max_length=300) parent = models.ForeignKey( "self", on_delete=models.CASCADE, blank=True, null=True, related_name="children" ) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "category" verbose_name_plural = "categories" ordering = ["name"] db_table = "post_categories" def __str__(self): return self.name def get_absolute_url(self): return self.slug def video_directory_path(instance, filename): return "{0}/posts/videos/{1}".format(instance.user.id, filename) def post_directory_path(instance, filename): return "posts/{0}/images/{1}".format(instance.post.id, filename) def reply_directory_path(instance, filename): return "replies/{0}/images/{1}".format(instance.reply.id, filename) def reply_videos_directory_path(instance, filename): return "{0}/posts/{1}/replies/{2}/videos/{3}".format(instance.user.id, instance.post.id, instance.reply.id, filename) class Post(models.Model): EV = "Everybody" FO = "Followers" FR = "Friends" AUDIENCE = [ (EV, "Everybody"), (FO, "Followers"), (FR, "Friends"), ] category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default=1) body = models.TextField("content", blank=True, null=True, max_length=5000) slug = AutoSlugField(populate_from=["category", "created_at"]) video = models.FileField(upload_to=video_directory_path, null=True, blank=True) can_view = models.CharField(max_length=10, choices=AUDIENCE, default=EV) can_comment = models.CharField(max_length=10, choices=AUDIENCE, default=EV) user = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name="user", related_name="user" ) published = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = "post" verbose_name_plural = "posts" db_table = "posts" ordering = ["created_at"] def __str__(self): return self.body[0:30] … -
SRC link changed when trying to integrate paypal button on django website
I'm trying to add the paypal button to my django shopping site. I have used the code from the SDK and replaced the id: My code: Client ID being: AWeSepzeHNW8BHE8rWPVm6CTuAGKz7SS1WzpbqEOZvQw-s_6qwFg6lxCO9MSXPpcVheUBWRgNuW6yKol However i am receiving a 400 error. Also viewing the page source shows the src has changed: If you follow this link you get the following message: throw new Error("SDK Validation error: 'Invalid query value for client-id: AabgYuFGxyzy3AbeWLPa-EtEGGreyL9bDDbWOxH4zFbPbgNc7y5yMpNO7B2NMRxCvT7-Ysou8ZXDNycT¤cy=USD'" ); /* Original Error: Invalid query value for client-id: AabgYuFGxyzy3AbeWLPa-EtEGGreyL9bDDbWOxH4zFbPbgNc7y5yMpNO7B2NMRxCvT7-Ysou8ZXDNycT¤cy=USD (debug id: f3776258140b9) */ Anyone know why the src has been changed from the source to when its rendered by django? I have followed the original src link from paypal and this, however when the page renders the link is altered. -
How to Get same Connection id in django for every file
Every time I run my Django webservice the connection (django and MySQL connector) is same for every python function that I call but Connection_id from MySQL workbench is different for every python function. My temporary table keeps dropping from the DB which was created from a python function A and has to be accessed by another independent python function B at a later point of time from a different webservice. I guess the temporary table is being dropped as a result of new instances(connection_id) getting generated in the MySQL DB everytime I run a webservice to call my python functions. Example outputs of connections: Mysql Connection ID: 18423 django connection: <django.utils.connection.ConnectionProxy object at 0x00000203C0C84340> mysql connection: <mysql.connector.connection_cext.CMySQLConnection object at 0x00000203C1B7C070> Mysql Connection ID: 18424 django connection: <django.utils.connection.ConnectionProxy object at 0x00000203C0C84340> mysql connection: <mysql.connector.connection_cext.CMySQLConnection object at 0x00000203C1B7C070> Expectation Example outputs of connections: Mysql Connection ID: 18423 django connection: <django.utils.connection.ConnectionProxy object at 0x00000203C0C84340> mysql connection: <mysql.connector.connection_cext.CMySQLConnection object at 0x00000203C1B7C070> same nexttime Mysql Connection ID: 18423 django connection: <django.utils.connection.ConnectionProxy object at 0x00000203C0C84340> mysql connection: <mysql.connector.connection_cext.CMySQLConnection object at 0x00000203C1B7C070> -
Vs code and py charm
Pls can I run my django on pycharm and run my HTML and CSS on vs code to build a web application if yes how do I link them together I tried installing the python extension on my vs code but it didnt work kept given me errors so I opted for pycharm to do my python -
Categories in blog
I need to put a categories in my blog website (python django)... I tried some ways but however I try, I either get error or blogs don't show in their categories Can someone help, what should I do? How to make this work -
Generate QR Code to URL with variable (page/pk_ID)
I am trying to generate a QR code that is unique to the page_id. The aim is to send a user that is not request.user to a specific page (loyalty_card/UserProfile_ID). As an example: site/loyaltycard/UserProfile_1 - would have qr code leading to site/pageID_1 site/loyaltycard/pageID_2 - would have qr code leading to site/pageID_2 here is where I am at. from io import BytesIO from qrcode.image.svg import SvgImage @login_required def venue_loyalty_card(request, userprofile_id): profile = UserProfile.objects.filter(user=userprofile_id) itemised_loyalty_cards = Itemised_Loyatly_Card.objects.filter(user=userprofile_id) factory = qrcode.image.svg.SvgImage stream = BytesIO() qrcode_url = "doopee-doo.herokuapp.com/account/" + str(userprofile_id) + "/" qrcode_img = qrcode.make(qrcode_url, image_factory=factory, box_size=10) qrcode_img.save(stream) return render(request,"main/account/venue_loyalty_card.html", {'itemised_loyalty_cards':itemised_loyalty_cards, 'profile':profile,'qrcode_url':qrcode_url,'qrcode_img':qrcode_img}) template {{qrcode_img|safe}} url path('loyalty_card/<userprofile_id>', views.venue_loyalty_card,name="venue-loyalty-card"), Current error message on console: ValueError: Field 'id' expected a number but got '<qrcode.image.svg.SvgImage'. -
unable to substract two timefeild in django
Hi Team i have models as below. And i am trying to substract out time and in time . class Attendance(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, default=1,related_name='Attendance') attendance_date = models.DateField(null=True) in_time = models.TimeField(null=True) out_time = models.TimeField(null=True ,blank=True) totaltime = models.TimeField(null=True ,blank=True) def __str__(self): return str(self.employee) + '-' + str(self.attendance_date) @property def totaltime(self): FMT = '%H:%M:%S' currentDate = date.today().strftime('%Y-%m-%d') sub = datetime.strptime('out_time', FMT) - datetime.strptime('in_time', FMT) return sub Still getting and error : ValueError: time data 'out_time' does not match format '%H:%M:%S' Please advise what should i do I am expecting how i will substract two timefeild -
how i can create input location in template django without create field for location
i want to determine location in template django without create field and model for location just show the box location and determine location and input lat & long in text {% elif field.field.field_type == 'location' %} <div class=""> <input type="text" name="{{ field.field.slug }}" maxlength="255" class="textinput textInput form-control" required="" id="{{ field.field.slug }}"> </div> -
auth_user table created alongside accounts_user table in postgres(Django)
Using: class User(AbstractBaseUser): pass #models here I added extra fields to my custom user model. This table is created successfully in postgres with absolutely no issues, however, whilst creating a superuser the credentials gets pushed to auth_user(default django user table) instead of account_user. auth_user shouldn't even be created alongside accounts_user?! Even worse: REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] which I set isn't required at all when creating superuser. It still uses default django configurations/fields. These are in order if you're wondering: AUTH_USER_MODELS = 'accounts.User' and installed 'accounts' in INSTALLED_APPS=[ ]. What is happening? Superuser credentials should be created in accounts_user table not auth_table in postgreSQL. REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] should be requested whilst creating superuser. -
DJANGO 'WSGIRequest' object has no attribute 'get'
I get this error 'WSGIRequest' object has no attribute 'get' in my code Below is my function in views.py def user_attendance(request): # Get the attendance records for the current user attendance_records = Attendance.objects.filter(user=request.user) # Create a form instance form = CompensationRequestForm() # Check if the form has been submitted if request.method == 'POST': # Bind the form with the POST data form = CompensationRequestForm(request.POST) # Check if the form is valid if form.is_valid(): # Save the form data form.save() # Redirect to the user_attendance view return redirect('user_attendance') context = {'attendance_records': attendance_records, 'form': form} # Render the template with the attendance records and form return render(request, 'user_attendance.html', context) and below is my form in forms.py class CompensationRequestForm(forms.Form): date = forms.DateField() reason = forms.CharField(widget=forms.Textarea) def save(self): # Save the form data to the database pass how to fix this? chatgpt didnt help, so i asked here -
Problem with categories on my blog website
I have added categories and everything but I can't see any posts in my categories. When I open for example http://localhost:8000/category/sport/ it is showing no posts... my urls.py : from django.urls import path #from . import views from .views import HomeView , ArticleDetailView, AddPostView, UpdatePostView, DeletePostView, CategoryView urlpatterns = [ #path('', views.home, name="homepage"), path('', HomeView.as_view(), name = 'home'), path('article/<int:pk>', ArticleDetailView.as_view(), name = 'article-details'), path('add_post/', AddPostView.as_view(), name = 'add_post'), path('article/edit/<int:pk>', UpdatePostView.as_view(), name = 'update_post'), path('article/<int:pk>/delete', DeletePostView.as_view(), name = 'delete_post'), path('category/<str:categories>/', CategoryView, name='category'), ] my models.py : from django.db import models from django.contrib.auth.models import User from django.urls import reverse from datetime import datetime, date class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name def get_absolute_url(self): #return reverse('article-details', args=(str(self.id))) return reverse('home') class Post(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255, default="YNTN") author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default="uncategorized") def __str__(self): return (self.title + " | " + str(self.author)) def get_absolute_url(self): return reverse("home") m y views.py : from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, Category from .forms import PostForm, EditForm from django.urls import reverse_lazy #def home(request): # return render(request, 'home.html', {}) class HomeView(ListView): model = Post template_name = 'home.html' … -
'import jwt' not working in Django views.py though I have PyJwt installed
I'm working with Django and trying to generate jwt tokens in views.py and displaying it in html page. import jwt is throwing No module found error in views.py even though I have PyJwt installed already inside the virtual environment and it is working fine outside the views.py (say, jwttoken.py file) views.py import jwt def generateJWT(portal): key = 'secret' payload = {'iat': time.time(), 'iss' : 'localhost', 'exp': int(time.time()) + (5*365*24 * 60), 'portal': portal} #return payload return jwt.encode(payload, key, algorithm="HS256") Does it mean that I can't make use of jwt module in django? Is there any other way to make it work in Django as it is working outside? -
Celery tasks running multiple times in Django application
For weeks now we have been having issues with tasks running multiple times (always twice actually). I have tried to reproduce this locally and did a lot of testing on our staging and production server, but I can not seem to reproduce it and find the issue. Right now I simply have no clue where to look. -We have recently upgraded from celery v4 to v5, but this was together with many other upgrades. -The issues are only with long running periodic tasks (celery beat) that takeabout 15 min. to complete. -We run celery in a managed kubernetes environment with separate deployments for beat and worker. Both deployments currently have a single pod. One example of a task running twice: @idempotent_notification_task(notification_tag='CREDITS_DIRECTDEBIT_PAYMENT') def create_directdebit_payments_for_credits(): plus_admin_ids = Order.objects.filter( subscription__type=Subscription.PLUS, credits_auto_top_up_amount__gt=0).values_list('administration_id', flat=True) admins = Administration.objects.filter(id__in=plus_admin_ids) for admin in admins: remaining_credits = admin.remaining_credits if remaining_credits < 0: po_exists = PurchaseOrder.objects.filter(administration=admin, created__date=today(), service=PurchaseOrder.SERVICE.CREDITS).exists() if po_exists: print(f"PurchaseOrder for client {admin.title} already exists!") return purchase_order = PurchaseOrder.objects.create( administration=admin, service=PurchaseOrder.SERVICE.CREDITS, credits_amount=admin.order.first().credits_auto_top_up_amount) payment = create_credits_mollie_payment_directdebit(purchase_order) Notification.create_credits_directdebit_payment(purchase_order) In an attempt to create a fix I created a wrapper function to make the task idempotent, but even this did not fix the issue. The wrapper function works as expected during local … -
I am using Django rest framework I want to use random in my views.py can someone help me
I am using Django rest framework I want to use random in my views.py can someone help me I want to make Questions in views.py to be random and here is my code views.py class QuizQuetionsList(generics.ListAPIView): serializer_class=QuizQuetionsSerializer def get_queryset(self): quiz_id=self.kwargs['quiz_id'] quiz=models.Quiz.objects.get(pk=quiz_id) return models.QuizQuetions.objects.filter(quiz=quiz) class QuizChapterQuetionsList(generics.ListAPIView): serializer_class=QuizQuetionsSerializer def get_queryset(self): quizChapter_id=self.kwargs['quizChapter_id'] quizChapter=models.QuizChapter.objects.get(pk=quizChapter_id) return models.QuizQuetions.objects.filter(quizChapter=quizChapter) I want to make both of them to be random to get solutions to my problem -
(Python) how to make change on mysql, can reflect to website too
Main problem: connect exsited mysql and website , that making change on mysql can reflect to website too (ps. the Django way will stock on no way to connect exsist websit and MySQL) tried method A : even though the Django way can connect MySQL and Django, but still not lead to change mysql reflect to website too Demo idea result : (refer to author DC con, his example Concretization my aim) if I update/change the context Nordic as Nike from mySQL, by success connect both, the website part the Nike can replace Nordic as new topic I read through all the relate question, they either not 100% same to mine issue, or that issue don't get solution, or I tried the solution, but not worked , thanks -
How to correctly import and run a trained pytorch model within django application
I have a django website up and running. I would need to import a pytorch trained model (of which I am by no means an expert) I was thinking to make a wheel out of if and importing it as a module within my application. The model is obviously trained outside of the app in its own special environment. Is my approach correct, or is there a better cleaner way to do it? -
How to deal with multipe user role's with only one username in django
I have a django project with 2 types of users (Parent, Child), and using phone number as username How should I define my user model (or project architecture) to able login both parent and child with only one phone number? Currently I think about seperating profile table's and identify user role from the login endpoint, Or microservice this project into 2 smaller project's (Microservice) to do this. -
How can import a serializer module from Django app with in the standalone script in the "scripts" package?
Here is my project setup. ProjectDirectorty AppDirectory model.py serializer.py scripts Directory init.py main.py manage.py I am trying to call external API and get JSON data. Later deserialize it and store in the DB created by App. When I am running main.py using python manage.py runscript main , I get error "Cannot import module 'scripts.main': No module named 'mix.mixapp'" project setup I understand diffrence between Script vs. Module and read Relative imports for the billionth time I got stuck in this part of article "perhaps you don't actually want to run moduleX, you just want to run some other script, say myfile.py, that uses functions inside moduleX. If that is the case, put myfile.py somewhere else – not inside the package directory – and run it. If inside myfile.py you do things like from package.moduleA import spam, it will work fine." It is similar to my case. I am running main.py which is in the "scripts" dir and using function from AppDirectory. It didn't help. Please guide me to solve this problem. -
Django Transaction Rollback on related objects
In django, while in a transaction if an object is deleted its related objects will be deleted(those having one to one and foreignkey with this object) so if the transaction rolls back the deleted object will get rolled back but not its deleted related object. Is there any way with which we can do so? I tried overriding the deleted method and putting everything in a transaction atomic block but this didn't work