Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I integrate React Template Folder with Django Project
I bought a template for my news & magazine website and website maked With django. So I want to integrate react folder and app in my django project. How can I do it? This is template Folder Structure -
Generate Django Model Fields
I want to add the field according to the type chosen. Suppose if I choose Charfield I want to have option name as Char and if DateFied is chosen I want to have a Date field in my model. Is is possible to do it in Django? class Options(models.Model): TYPE= ( ('Charfield','Charfield'), ('Integerfield','Integerfield'), ('Datefield','Datefield'), ) optiontype = models.CharField(max_length=20, choices=TYPE) optionname= models.CharField(max_length=50) -
How to automate Django - React app deployment
I have Django as backend and React as frontend, my current deployment process is I use WinSCP to transfer react build to django backend and then with Putty I use python manage.py collectstatic. Then I update git repo at aws, do migrations (if any) manually. I want to automate this in way that There is no need to build and copy react to backend also not to pull current repo changes or use WinSCP or Putty etc. I just want simple script or any standard way by which, whenever I update code in my production branch at backend and frontend, deployment will be done automatically. Pls suggest me the way. TIA -
meta tags shows in <body> While Should be placed in the <head>
I have a website based on the django framework. I want to add meta tags to the website With conditions : """Definition of models.""" from django.db import models class Pages_Meta(models.Model): Page_name = models.TextField(null=False) Page_meta = models.TextField(null=False) page_title = models.TextField(null=False) And html page is: <html> <head> <title> {{ title }} - Farhad Dorod </title> {{ meta }} </head> </html> <body> ... </body> And urls.py is: path('index/', LoginView.as_view( template_name='app/index.html', extra_context= { 'title': Pages_Meta.objects.get(id = 1).page_title, 'meta' : Pages_Meta.objects.get(id = 1).Page_meta, }), name='index') result: all meta tags shows in body While Should be placed in the head enter image description here -
Django does not redirect after receiving POST request
After taking google credentials through POST request, I want Django to log the user in and redirect to home page from google.auth import jwt def google_login(request): if request.method == "POST": credential = request.body profile_info = jwt.decode(credential, verify = False) email = profile_info["email"] user = User.objects.filter(email = email) if user: login(request, user.first()) print("---------------login success") return HttpResponseRedirect(reverse("index")) else: return render(request, "network/login.html", { "message": "Invalid username and/or password." }) else: return render(request, "network/login.html") login success is printed but the page is not redirected nor refresh. The terminal doesn't show much ---------------login success [22/Sep/2021 16:05:59] "POST /google_login HTTP/1.1" 302 0 [22/Sep/2021 16:05:59] "GET / HTTP/1.1" 200 13957 [22/Sep/2021 16:06:03] "GET /static/network/styles.css.map HTTP/1.1" 404 1825 [22/Sep/2021 16:06:10] "GET /account/login HTTP/1.1" 200 4342 [22/Sep/2021 16:06:10] "GET /static/network/styles.css.map HTTP/1.1" 404 1825 [22/Sep/2021 16:06:10] "GET /account/login HTTP/1.1" 200 4342 My code in the front end is liked this const csrftoken = Cookies.get('csrftoken'); function handleCredentialResponse(response) { fetch(`/google_login`, { method: 'POST', headers: { 'X-CSRFToken': csrftoken }, body: response.credential }) } -
getting button to perform function in django
I am wanting webpage where the user clicks a button to produce a word document. Currently, however, when the user clicks the button, the page simply reloads and appends '?get_doc=get_doc#' to the url. Instead I would like a prompt for the user to download the generated document urls.py app_name = "patient" urlpatterns = [ path('add/', views.PatientAddView.as_view(), name="patient_add"), path( route='<patient_id>/', view=views.TreatmentTemplateView.as_view(), name='treatment_detail'), ] views.py class TreatmentTemplateView(TemplateView): template_name = "../templates/patient/treatment_detail.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["patient_id"] = self.kwargs["patient_id"] result = find_treatment(context["patient_id"]) context = result[0] context["patient"] = result[1] return context def get_doc(request): print('running9') # if(request.GET.get('get_doc')): if 'get_doc' in request.GET: print('running') document = Document() docx_title="TEST_DOCUMENT.docx" # ---- Cover Letter ---- document.add_paragraph() document.add_paragraph("%s" % date.today().strftime('%B %d, %Y')) document.add_paragraph('Dear Sir or Madam:') document.add_paragraph('We are pleased to help you with your widgets.') document.add_paragraph('Please feel free to contact me') document.add_paragraph('I look forward to assisting you in this project.') document.add_paragraph('Best regards,') document.add_paragraph('Acme Specialist 1]') document.add_page_break() # Prepare document for download # ----------------------------- f = BytesIO() document.save(f) length = f.tell() f.seek(0) response = HttpResponse( f.getvalue(), content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document' ) response['Content-Disposition'] = 'attachment; filename=' + docx_title response['Content-Length'] = length return response html {% extends "base.html" %} <!-- {% block title %}Patient: {{ patient.name }}{% endblock %} --> {% block content … -
Django: Dependency on swappable model (lazy reference)
Disclaimer, I have read the following posts, and they did not provide a helpful answer for my case: lazy reference: doesn't provide model user? django custom user model gives me lazy reference error django-swappable-models I have written a reusable app that handels authentication methods and user management. In its core, it overrides the AUTH_USER_MODEL (lets call the model CustomUser and provides a swappable model Person, which has O2O field to a CustomUser: class CustomUser(AbstractUser): def save(self, *args, **kwargs): if not self.pk or hasattr(self, 'person') is False: super().save(*args, **kwargs) get_person_model().objects.create(birthdate=None, user=self) else: super().save(*args, **kwargs) class AbstractPerson(models.Model): user = models.OneToOneField(settings.MY_APP_PERSON_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name='person') birthdate = DateField(null=True, default=None) class Meta: abstract = True class Person(AbstractPerson): class Meta(AbstractPerson.Meta): swappable = 'REUSABLE_APP_PERSON_MODEL' To create the migrations in my reusable app, I have setup a "dummy" django project which includes this app, and sets REUSABLE_APP_PERSON_MODEL to reusable_app.Person. This works flawlessly, in my real django project, I can set REUSABLE_APP_PERSON_MODEL to a model that inherits from reusable_app.AbstractPerson. The problem arises, when my reusable app has another model that holds a foreign key to REUSABLE_APP_PERSON_MODEL: class Invite(models.Model): email = models.EmailField() person = models.OneToOneField(settings.REUSABLE_APP_PERSON_MODEL, on_delete=models.CASCADE, null=False, related_name='+') code = models.CharField(max_length=5) Again, I created a migration for this model … -
ValueError at / The view leads.views.home_page didn't return an HttpResponse object. It returned None instead python django template error how to fix
ValueError at / The view leads.views.home_page didn't return an HttpResponse object. It returned None instead. this is my code: views.py: from django.shortcuts import render from django.http import HttpResponse def home_page(request): # return HttpResponse('Hello world') render(request, 'leads/home_page.html') and here's the urls.py: from django.contrib import admin from django.urls import path from leads.views import home_page urlpatterns = [ path('admin/', admin.site.urls), path('', home_page), ] and here's the template: -
How to handle multiple Django forms in a request.POST
Let's say I have a form that contains the following values after I submit the form: print(request.POST): <QueryDict: {'csrfmiddlewaretoken': ['3oveeCkYroBwKNSLw8wOr8dtURYGcO9AtOKYfPoNbf8q3L5Az7aEAnJaQldYmnaG'], 'user': ['1'], 'reset': ['false'], 'project': ['100001'], 'contents': ['test'], 'amount': ['3'], 'currency': ['JPY'], 'expense_date': ['09/22/2021'], 'store_company_client_name': ['test'], 'expense_category': ['Staffing payments'], 'note': ['fdv']}> What if I have multiple inputs and I get a request.POST like this: <QueryDict: {'csrfmiddlewaretoken': ['xbdRWXh4LdKTTJoCMJa7O53lApbY03byXBsBXalTv4hNcHBrPIOXXkz2wTqgaCcE'], 'user': ['1','1','1'], 'expense_date': ['09/22/2021', '09/21/2021', '09/20/2021'], 'project': ['100001', '100002', '100002'], 'expense_category': ['Staffing payments', 'Staffing payments', 'Staffing payments'], 'expense_type': ['Salaries', 'Salaries', 'Salaries'], 'contents': ['test', 'test', 'test'], 'currency': ['1', '1', '1'], 'amount': ['12', '1', '4'], 'store_company_client_name': ['customer1', 'customer2', 'customer3'], 'note': ['lorem ipsum', 'lorem ipsum', 'lorem ipsum']}> How can I process it in the back-end? Right now for a simple form I have this view: def new_expense(request): data = { 'title': "New Expense", } data['projects'] = Project.objects.filter(is_visible=True).values('id') data['expense_category'] = dict((y, x) for x, y in EXPENSE_CATEGORY) data['expense_type'] = dict((y, x) for x, y in EXPENSE_TYPE) form = ExpenseForm() if request.method == "POST": print(request.POST) reset = request.POST['reset'] form = ExpenseForm(request.POST) if form.is_valid(): form.save() if reset == 'true': form = ExpenseForm() data['form'] = form return render(request, "expense/new_expense.html", data) And I want to create a new view capable of doing exactly the same thing as new_expense but just for … -
How to display data in model formset for foreign key to manytomanyfield as readonly text with prefilled data that passes validation?
I have a problem displaying data in a form as readonly text. My model: class SalesPlan(models.Model): customer = models.ForeignKey(Customer, on_delete=models.RESTRICT) date = models.DateField(null=True, blank=True) product = models.ForeignKey(Product, on_delete=models.RESTRICT) quantity = models.FloatField(default=0) My form: class SalesPlanForm(forms.ModelForm): # product = forms.CharField(widget=forms.TextInput(attrs={'readonly':'readonly'})) class Meta: model = SalesPlan fields = '__all__' widgets = { 'customer': forms.HiddenInput(), 'date': forms.HiddenInput(), } The form in prefilled with initial data and this works fine for input and save of the formset. Problem is, users can change product, since it is a dropdown of their portfolio and I want to change that behavior. Customer class: class Customer(models.Model): code = models.CharField(max_length=6, primary_key=True, unique=True) name = models.CharField(max_length=100) belongs_to_sales_channel = models.ForeignKey(SalesChannel, on_delete=models.RESTRICT) portfolio = models.ManyToManyField(Product) date_created = models.DateTimeField(auto_now_add=True, null=True) If I uncomment the product in SalesPlanForm, I display correct data, but the form does not save with error: ValueError at /sales/create/100022/2028/1/1/ Cannot assign "'product_1'": "SalesPlan.product" must be a "Product" instance. Notice the DOUBLE quotes and SINGLE quotes for variable. If I insted assign widget for 'product' in the dict in Meta, I can save the form, but data displayed in rendered form is just 1, 2, 3, 4 for every form in formset instead of product object name. Is there a way … -
Conflicting 'news' models in application 'articles': <class 'articles.models.news.News'> and <class 'apps.articles.models.news.News'
I have my django apps inside apps folder. Due to multiple article types I decided to split my models.py for the articles app and put it inside the models folder where each modelname.py file points to a model. Problem: configuring syndication framework (as described in https://docs.djangoproject.com/en/3.2/ref/contrib/syndication/) causes a runtime error Conflicting 'news' models in application 'articles': <class 'articles.models.news.News'> and <class 'apps.articles.models.news.News'>. Note: Before adding syndication framework functionality everything works just fine. I tried: Adding app_label to the News model. apps folder structure: ├── articles │ ├── admin.py │ ├── apps.py │ ├── feeds.py │ ├── __init__.py │ ├── models │ │ ├── __init__.py │ │ ├── articles.py │ │ ├── categories.py │ │ ├── news.py │ │ ├── reviews.py │ │ └── tags.py │ ├── tests.py │ ├── urls.py │ └── views │ ├── __init__.py │ ├── news.py ├── conftest.py ├── education ├── __init__.py ├── users /apps/articles/models/news.py: from django.db import models class News(models.Model): // // Model Fields // class Meta: ... app_label = 'articles' ... def __str__(self): return self.title def get_absolute_url(self): return reverse("articles:news_detail", kwargs={"slug": self.slug}) /apps/articles/feeds.py: from django.contrib.syndication.views import Feed from django.utils.translation import gettext_lazy as _ from .models.news import News class NewsEntriesFeed(Feed): title = _("News") link = "/news/" description = … -
Invalid Django formset
I have a django formset, when I enter just one row of data it works. If I try to enter two or more rows of data, when I submit the form I get the error: ManagementForm data is missing or has been tampered with. Missing fields: form-TOTAL_FORMS, form-INITIAL_FORMS. Reading similar questions it seems missing the management_form but in my code is present..any ideas? This is my code: models.py and forms.py #models.py from django.db import models class Station(models.Model): id_station = models.IntegerField(blank=False) station_name = models.CharField(max_length=30, blank=False) unity_name = models.CharField(blank=False, max_length=10) id_sensor = models.IntegerField(blank=False) sensor_name = models.CharField(max_length=50, blank=False) class Meta: db_table = 'station' def __str__(self): return self.name # forms.py from django import forms from .models import Station from django.forms import formset_factory class StationForm(forms.Form): id_station = forms.IntegerField(label='id della stazione') #, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Book Name here'})) station_name = forms.CharField(label='nome stazione', max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'nome stazione'})) unity_name = forms.CharField(label='nome unita', max_length=10, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'nome unita'})) id_sensor = forms.IntegerField(label='id sensore') sensor_name = forms.CharField(label='nome sensore', max_length=50, widget=forms.TextInput(attrs={'placeholder': 'nome sensore'})) StationFormset = formset_factory(StationForm, extra=1) views.py from django.template import RequestContext from django.shortcuts import render, redirect from .forms import StationFormset from .models import Station def new_station(request): context = RequestContext(request) template_name = 'station.html' heading_message = 'Add a new … -
'function' object has no attribute 'lastname' [duplicate]
I Couldnot Resolve this problem please help me. Whenever I try to fetch data it always show this message views.py `from django.http import request from django.shortcuts import render from .models import * # Create your views here. def Profile(request): mydata = PersonalDetail.objects.all mycskill = CoddingSkills.objects.all wskill = AdditionalSkill.objects.all print(mydata.lastname) return render(request,'index.html', {'mydata':mydata,'mycskill':mycskill,'wskill':wskill})` admin.py from Efolio.settings import DATABASES from django.db.models.base import Model from django.db.models.fields import CharField from django.db import models # Create your models here. class PersonalDetail(models.Model): fistname = CharField(max_length=100) lastname = models.CharField(max_length=100) age = models.CharField(max_length=3) designaton = models.CharField(max_length=300) aboutme = models.CharField(max_length=100) addressfrom = models.CharField(max_length=300) addressnow= models.CharField(max_length=300) gender = models.CharField(max_length=20)` *Plz I AM STUCK HER HELP ME * -
django manytomany through with constraint
I tried to use ManytoManyfield with through into my models to help user to associate their Basket with mulitples % of items. Each items have a value and each user have a budget. So i am not able to limit items association even i used a field percentage. Do you have any idea how to add this constraint ? meaning user cannot add more than 100% of the items to one or more Basket below my models so far : class Basket(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) items = models.ManyToManyField(items,through='Percentage') details = models.CharField(max_length=200) date = models.DateField(blank=True, null=True) budget = models.IntegerField(default=0) class Percentage(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) basket = models.ForeignKey(Basket, on_delete=models.SET_NULL, blank=True) item = models.ForeignKey(Item, on_delete=models.SET_NULL, blank=True, null=True) percentage = models.IntegerField(default=0) class Item(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=20) description = models.CharField(max_length=250) value = models.CharField(max_length=20) -
Please enter the correct Email and password for a staff account. Note that both fields may be case-sensitive
I complete makemigrations and migrate then create a superuser. After this http://127.0.0.1:8000/admin i try to log in then show this error Please enter the correct Email and password for a staff account. Note that both fields may be case-sensitive seetings.py AUTH_USER_MODEL = 'user.CustomUser' **models.py** from django.db import models from django.contrib.auth.models import AbstractUser,BaseUserManager class CustomUserManager(BaseUserManager): """ Creates and saves a User with the given email, date of birth and password. """ def create_user(self, email, password=None): if not email: raise ValueError('User must have an email id') user=self.model( email=self.normalize_email(email) ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None): user=self.create_user( email, password=password ) user.is_admin = True user.save(using=self._db) return user class CustomUser(AbstractUser): #only add email field for login email = models.EmailField( verbose_name='Email', max_length=50, unique=True ) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email ***admin.py*** from django.contrib import admin from django.contrib.auth import get_user_model user=get_user_model() admin.site.register(user) -
how to deploy and upload python app to CPanel?
Dears, I'm trying to deploy a python web application on Cpanel hosting provider but I cannot determine the: Application startup file. Application Entry point. Check attached screenshots (Cpanel required fields + app files), please need help and advice Cpanel required fields Applications files -
Unique values of field per user
I have a model where users can have duplicate values but each user can only have unique values. for example - User A can have value1, value2, value3, all unique values. User B can have value1, value3, value4, again all unique values. So both users can have value1 but neither User A or User B can have multiple value1(duplicate values) So I cant do something like this in the model (setting unique = true) class ABC(models.Model): field1 = models.EmailField(unique=True) What is the best way to validate such a case? For now, I'm checking values in the database against the value which I pass during the create method of my views.py. And looking for any better approach to use in build Validators from the rest framework. class abc_viewset(viewsets.ModelViewSet): queryset = abc.objects.all() serializer_class = abc_serializer def create(self, request, format=None): data = request.data serializer = self.get_serializer(data=request.data) self.field1=data['field1'] self.prevValues=abc.objects.filter(field1=self.field1,user=request.user) .values_list('field1',flat=True) if self.prevValues: return Response({"Failure":"Dublicate value"}) if serializer.is_valid(): serializer.save() -
Getting a word document from a django generated view
I have a class based django view that presents some tables and text to the user dependent on their inputs. I would like to have a button on this page that allows the user to download this data as a word document. What would be the best way to accomplish this? urls.py app_name = "patient" urlpatterns = [ path('add/', views.PatientAddView.as_view(), name="patient_add"), path( route='<patient_id>/', view=views.TreatmentTemplateView.as_view(), name='treatment_detail'), ] views.py class TreatmentTemplateView(TemplateView): template_name = "../templates/patient/treatment_detail.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["patient_id"] = self.kwargs["patient_id"] result = find_treatment(context["patient_id"]) context = result[0] context["patient"] = result[1] return context hmtl {% extends "base.html" %} <!-- {% block title %}Patient: {{ patient.name }}{% endblock %} --> {% block content %} <h3>Patient Summary</h3> <p> {{pt_letter|linebreaks}} </p> <br> <br> <h3>Current Medication</h3> <p> {{current_med_letter|safe}} </p> <br> <br> <h3>Past Medication</h3> <p> {{past_med_letter|safe}} </p> <br> <br> <h3>Plan </h3> <br> <h5>Treatment Recommendation</h5> <p> {{newmed_letter|safe}} {{existingmed_letter|safe}} </p> <br> <h5>Physical Health Monitoring</h5> <p> {{monitor_letter|safe}} </p> <br> <h5>Potential Drug Interactions</h5> <p> {{interaction_letter|safe}} </p> {% endblock content %} -
Viewing a Word doc in Django
Fairly new to Django and I have an app that records certain details from the user, it then adds these details to certain fields in a template to create a brand new 'report'. This all works fine, however I am finding it difficult to now upload that report to a page so that the user may view it.\ views.py form.save(commit=False) new_record = form.save(commit=False) new_record.save() tpl = DocxTemplate('record/retail_report_temp.docx') context = { 'date_time': form['date_time'].value(), 'name': form['name'].value(), 'd_o_b': form['d_o_b'].value(), 'department': form['department'].value(), } tpl.render(context) tpl.save(f"{form['name'].value()}_retail_report.docx") return render(request, 'home.html',) HTML {% if record.retail_pack %} <a class="nav-link" href="{{ record.retail_pack }}">Report</a> {% endif %} I can view the report from the file and that part works, but I would like the user to have a link or something so they could view/print the report. Thank you in advance for your time, it is much appreciated. -
How do I display image in my view page django
I have created a page when the staff click on the view button, it should redirect them to the view page and display it out accordingly, like when the user click on the view button for id 1 it should display the id 1 image out, but it is not displaying. This is how it my viewreception page looks like. when the staff click on the view button, the url did manage to get the id but image not displaying out. models.py class Photo(models.Model): class Meta: verbose_name = 'Photo' verbose_name_plural = 'Photos' datetime = models.DateTimeField() image = models.ImageField(null=False, blank=False) descriptionbox = models.TextField() serialno = models.TextField() partno = models.TextField() reception = models.TextField() customername = models.TextField() nonc = models.TextField() # nonc stand for non conformity TypeOfNonConformity = models.TextField() def __str__(self): return self.descriptionbox urls.py urlpatterns = [ path('register/', views.register, name='register'), path('adminpage/', views.admin, name='adminpage'), path('customer/', views.customer, name='customer'), path('logistic/', views.logistic, name='logistic'), path('forget/', views.forget, name='forget'), path('changepassword/', views.changepassword, name='changepassword'), path('newblock/', views.newblock, name='newblock'), path('quote/', views.quote, name='quote'), path('profile/', views.profile, name='profile'), path('adminprofile/', views.adminprofile, name='adminprofile'), path('', views.login_user, name='login'), path('home/', views.home, name='home'), path('allstaff/', views.allstaff, name='allstaff'), path('updatestaff', views.updatestaff, name='updatestaff'), path('delete/<int:id>/', views.delete, name='delete'), path('deletephoto/<int:id>/', views.deletephoto, name='deletephoto'), path('update/<int:id>/', views.update, name='update'), path('logout/', views.logout_view, name='logout'), path('register/', views.register_view, name='register'), path('edit-register/', views.edit_register_view, name='edit_register'), path('edit_profile/', views.edit_profile, name='edit_profile'), path('ReceptionUnserviceable/', views.ReceptionUnserviceable, name='ReceptionUnserviceable'), … -
While proceeding for payment, a pop-up box pops up saying, Invalid amount
When i try to proceed for payment, after clicking the button, a pop-up shows saying Oops! Something went wrong. Invalid amount (should be passed in integer paise. Minimum value is 100 paise, i.e. ₹ 1) The order_amount is being correctly fetched, then why is the amount is not been processed? views.py: #Payment Integration - Razorpay @login_required def payment(request): add = Address.objects.filter(default=True) order = Order.objects.filter(user=request.user).first() print(order) client = razorpay.Client(auth=("XXX", "YYY")) if order.razorpay_order_id is None: order_id = order.order_id print(order_id) x = order.get_total() print(x) order_amount = int(x) * 100 print(order_amount) order_currency = 'INR' order_receipt = 'Rcpt' #data = {"amount": order_amount, "currency": order_currency, "receipt": order_receipt, "payment_capture": '1'} razorpay_order = client.order.create(dict(amount=order_amount, currency=order_currency, receipt=order_receipt, payment_capture=1)) # Razorpay order inserted into database order order.razorpay_order_id = razorpay_order["id"] order.save() else: razorpay_order = client.order.fetch(order.razorpay_order_id) return render(request, 'payment.html', {'razorpay_order': razorpay_order, 'add': add}) -
Is it possible to let Postgres automatically retry transactions?
I'm developing a Django application in which I want to have strong guarantees about the correctness of the data. For this reason, I have SERIALIZABLE as the transaction isolation level. However, during load testing I see some related error messages: could not serialize access due to read/write dependencies among transactions DETAIL: Reason code: Canceled on identification as a pivot, during write. HINT: The transaction might succeed if retried. and could not serialize access due to read/write dependencies among transactions DETAIL: Reason code: Canceled on conflict out to pivot 23933812, during read. HINT: The transaction might succeed if retried. and current transaction is aborted, commands ignored until end of transaction block I do automatically retry the transaction via Django, but I'm uncertain if this solution is actually good. I wondered: Is it possible to let Postgres automatically retry transactions that failed for those reasons? Is there maybe something directly in Django allowing me to configure that? (It would not have to be for all transactions; I know the candidates that are failing more often / that are more important) -
Unable to understand self-referencing many-to-many and filter in django?
I am trying to learn Self-referencing many-to-many and stuck on code segment Let assume two models,Person and relation ship,as below:- class Person(models.Model): name = models.CharField(max_length=100) relationships = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to') def __unicode__(self): return self.name RELATIONSHIP_FOLLOWING = 1 RELATIONSHIP_BLOCKED = 2 RELATIONSHIP_STATUSES = ( (RELATIONSHIP_FOLLOWING, 'Following'), (RELATIONSHIP_BLOCKED, 'Blocked'), ) class Relationship(models.Model): from_person = models.ForeignKey(Person, related_name='from_people') to_person = models.ForeignKey(Person, related_name='to_people') status = models.IntegerField(choices=RELATIONSHIP_STATUSES) and person model contains following methods:- def get_relationships(self, status): return self.relationships.filter( to_people__status=status, to_people__from_person=self) def get_related_to(self, status): return self.related_to.filter( from_people__status=status, from_people__to_person=self) I am unable to understand how these two methods are working and what they are returning. I am unable to understand how filter and reverse-lookup are working together. Please anyone help me to understand real intuition behind this. Thanks in advance. Hope to here from you soon. -
how to get python screen sharing seperate application window to show on django web server?
Im fairly new to python and django and im trying to share the desktop video of a windows virtual machine to show onto a linux django web server. When i run the python scripts the screen sharing would show as a seperate application window. How do i get the python seperate window to show onto the django web server instead? receiver.py (running on linux machine) from vidstream import StreamingServer import threading receiver = StreamingServer('ipaddr', 8080) t = threading.Thread(target=receiver.start_server) t.start() while input("") != 'STOP': continue receiver.stop_server() sender.py (running on windows virtual machine) from vidstream import ScreenShareClient import threading sender = ScreenShareClient('ipaddr', 8080) t = threading.Thread(target=sender.start_stream) t.start() while input("") != 'STOP': continue sender.stop_stream() -
ImportError: cannot import name 'DEFAULT_CURRENCY' from 'moneyed' on Ubuntu
I've been using Django for just over a year for the development of an automation software and am currently just running the project locally on my windows machine. I hadn't run into any issues with it, until I tried running cron tasks, which ofc windows doesn't support. Scheduled tasks don't work the same way imo, so I installed a Ubuntu VM to work with the project. Set everything up correctly(I think?), installed Django and all. Currently installing all the libraries the project uses, one of which is django-money. I have installed it, as well as py-moneyed, yet on trying to make migrations, or run the server, I run into this error enter image description here Can't find anything about this online. The project still works perfectly with the windows command prompt, as well as PowerShell but having this issue on the ubuntu VM. Installed apps on my settings.py look like: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap5', 'sass_processor', 'djmoney', 'background_task', 'django_crontab', 'companies', 'google_cal', 'dashboard', ] Any help on this, or good alternative for corn tasks-need some to run every 2 hours and update the db and others to run once a day at a specific time. Celery …