Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Edit specific user in Django using UserChangeForm
I'm trying to edit an specific User in Django, but I couldn't create my own form, since Django doesn't let you edit it after it's been created. So, I'm using 'UserChangeForm', but I can't get the information from the specific user, only the one that is logged in. How can I fix it? forms.py class EditarUsuarioForm(UserChangeForm): class Meta: model = User fields = ( 'first_name', 'last_name', 'email', ) first_name = forms.CharField(label='Nome', max_length=20, widget=forms.TextInput( attrs={ 'class': 'form-control', 'maxlength': '200', 'placeholder': "Ex.: José", 'name': 'nome' } )) last_name = forms.CharField(label='Sobrenome', max_length=150, widget=forms.TextInput( attrs={ 'class': 'form-control', 'maxlength': '200', 'placeholder': "Ex.: da Silva", 'name': 'sobrenome' } )) email = forms.EmailField(label='Email', max_length=200, widget=forms.EmailInput( attrs={ 'class': 'form-control', 'maxlength': '200', 'placeholder': "Ex.: jose@unemat.br", 'name': 'email' } )) views.py def editar(request, username): if request.method == 'GET': usuario = User(username=username) form = EditarUsuarioForm(instance=usuario) context = { 'form': form, 'user': usuario, } return render(request, 'usuarios/editar.html', context) if request.method == 'POST': usuario = User(username=username) form = EditarUsuarioForm(request.POST, instance=usuario) if form.is_valid(): form.save() return redirect('lista') else: print(form.errors) context = { 'form': form, } return render(request, 'usuarios/editar.html', context) edit.html <main role="main"> <div class="container mt-4"> <form action="" class="form-group" method="POST">{% csrf_token %} <div class="form-group"> {{form.first_name.label_tag}} {{form.first_name}} </div> <div class="form-group"> {{form.last_name.label_tag}} {{form.last_name}} </div> <div class="form-group"> {{ form.email.label_tag … -
NoReverseMatch at / Reverse for 'view_profile_with_pk' with keyword arguments
this error is killing me please help I sat on in like for 3 hours and I couldn't even know why is the error happening I will give all the information needed, btw I am new to Django so please explain if you can Thank You, Error: NoReverseMatch at / Reverse for 'view_profile_with_pk' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['account\/profile\/\(P(?P[^/]+)\\d\+\)\/$'] My URLs .py from django.urls import path, include from . import views from django.contrib.auth.views import (PasswordResetView , PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView) app_name= 'accounts' urlpatterns = [ path('signup/', views.register, name='signup'), path('login/', views.login, name='login'), path('logout', views.logout, name='logout'), path('profile/', views.view_profile, name='view_profile'), path('profile/(P<pk>\d+)/', views.view_profile, name='view_profile_with_pk'), path('profile/edit/', views.edit_profile, name='edit_profile'), path('change-password/', views.change_password, name='change_password'), path('password_reset/', PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/',PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] My views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib import auth from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm from django.contrib.auth import update_session_auth_hash from django.urls import reverse from accounts.forms import ( RegistrationForm, EditProfileForm, UserProfileForm ) from django.contrib.auth.models import User from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm from django.contrib.auth import update_session_auth_hash from django.contrib.auth.decorators import login_required def register(request): if request.method =='POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('accounts:home') else: form = RegistrationForm() args = {'form': form} … -
Django rest framework limit the number of image uploads
I would like to restrict the number of images a user can upload in Django Rest Framework when he creates a product. Let's say I want to restrict him to upload only 5 images per product. What is the best way to do this? models.py class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) image = models.ForeignKey(Image, on_delete=models.CASCADE) class Image(models.Model): image = models.ImageField(upload_to='product_images') serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = models.Product fields = ('__all__') -
AttributeError: 'postComments' object has no attribute 'model
I have made a new model postComments for my blogging website and now I am facing the above issue: models.py: from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now # Create your models here. class post(models.Model): SrNo = models.AutoField(primary_key=True) title = models.CharField(max_length=50) content = models.TextField() author = models.CharField(max_length=50) slug = models.SlugField(max_length=200) timeStamp = models.DateTimeField(blank=True) def __str__(self): return self.title + " by " + self.author class postComments(models.Model): sno = models.AutoField(primary_key=True) comment = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(post, on_delete=models.CASCADE) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True) timestamp = models.DateTimeField(default=now) after writing the above '''postComments``` model the log window is showing me this error: error log Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\contrib\admin\checks.py", line 54, in check_admin_app errors.extend(site.check(app_configs)) File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\contrib\admin\sites.py", line 84, in check if modeladmin.model._meta.app_config in app_configs: AttributeError: 'postComments' object has no attribute 'model' before adding this new model, … -
Removing collected static files
I ran collectstatic a few weeks back and I would like to remove most (99.5%) of the collected files so that I do not have to store them when deploying to production. I tried collectstatic --clear but this removed them and then placed the deleted files back afterwards (not sure what the practical point of the command is). Is there a way to erase the collected files? I've been using this page of the Django docs to try and find a solution but haven't had any luck. -
Django sum on an external attribut
I have an issue with database and sum in Django. I have 3 tables: customer, order and orderLine. For a report, I would like to calculate the sum of all line price for every order of a customer. class Customer(models.Model): firstName = models.CharField(max_length=200) lastName = models.CharField(max_length=200) mail = models.EmailField(max_length=100) etc... def get_count_of_orders(self): return self.orders.count() def get_sum_line_prince_of_all_orders(self): ??????????? return (sum_of_all_line_prince_all_orders) class Order(models.Model): orderNum = models.CharField(max_length=200) customer = models.ForeignKey(Customer, related_name="orders") globalAmount = models.DecimalField(max_digits=20, decimal_places=4) ... class OrderLine(models.Model): item = models.ForeignKey(Item, related_name="ordersLine") linePrice = models.DecimalField(max_digits=20, decimal_places=4) ... I don't know what to set in get_sum_of_orders to get the right result. I've trayed different things like annotate or aggregate. But without success at the moment. I didn't understand this process at the moment. Could you help me? -
Django Query month wise with last 6 month
I am trying to query and the group is the Order of the last 6 months. and this is my models: class Order(models.Model): created_on = models.DateTimeField(_("Created On"), auto_now_add=True) and this is my method to parse month: from django.db.models import Func class Month(Func): """ Method to extract month """ function = 'EXTRACT' template = '%(function)s(MONTH from %(expressions)s)' output_field = models.IntegerField() And this is my query: current_date = date.today() months_ago = 6 six_month_previous_date = current_date - timedelta(days=(months_ago * 365 / 12)) order = Order.objects.filter( created_on__gte=six_month_previous_date, ).annotate( month=Month('created_on') ).values( 'month' ).annotate( count=Count('id') ).values( 'month', 'count' ).order_by( 'month' ) In my database order table, there is only on entry: So it is returning [{'month': 10, 'count': 1}] But i dont want like this, i want like these of last 6 month, if in one month, there is no sales, it should return the count: 0 Like thise bellow: [ {'month': 10, 'count': 1}, {'month': 9, 'count': 0} {'month': 8, 'count': 0} {'month': 7, 'count': 0} {'month': 6, 'count': 0} {'month': 5, 'count': 0} ] -
I cannot create category and sub-categories list in home page,django
I can create a category page with sub-categories in a new template but i cannot list all my sub-categories in home page. All i need is a logic to work in home page. Here is my models.py class Category(MPTTModel): name = models.CharField(max_length=100,unique=True) parent = TreeForeignKey('self',null=True,blank=True,related_name='children',db_index=True,on_delete = models.CASCADE) slug = models.SlugField() class MPTTMeta: order_insertion_by = ['name'] def get_slug_list(self): try: ancestors = self.get_ancestors(include_self=True) except: ancestors = [] else: ancestors = [ i.slug for i in ancestors] slugs = [] for i in range(len(ancestors)): slugs.append('/'.join(ancestors[:i+1])) return slugs def __str__(self): return self.name def get_absolute_url(self): return reverse('product:product-category',args=[self.slug]) class Product(models.Model): category = TreeForeignKey(Category,null=True,blank=True,on_delete=models.CASCADE) name = models.CharField(max_length=200) slug = models.SlugField(max_length=200,unique=True) def get_absolute_url(self): return reverse('product:product-detail',kwargs={ 'slug':self.slug, }) here is my views.py def product_list(request,category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category,slug=category_slug) products = products.filter(category=category) return render( request,'product/home.html',{ 'category':category, 'categories':categories, 'products':products } ) def show_category(request,hierarchy= None): category_slug = hierarchy.split('/') parent = None root = Category.objects.all() for slug in category_slug[:-1]: parent = root.get(parent=parent, slug = slug) try: instance = Category.objects.get(parent=parent,slug=category_slug[-1]) except: instance = get_object_or_404(Product, slug = category_slug[-1]) return render(request, 'product/product.html', {'instance':instance}) else: return render(request, 'product/categories.html', {'instance':instance}) I used this logic in my template but it doesn't work. So any help to display the categories … -
Is there a way I could specify server timezone in Django database settings
Hello I would like to know if someone could help me. I have a problem with Django's TIMEZONE configuration in the settings.py file. The problem is the following. The timezone is set to TIME_ZONE = 'America/New_York' USE_TZ = True I have an online MySQL database set-up, which the details to are here database settings and when I try to run run the server, the following error appears django.db.utils.OperationalError: (2026, 'SSL connection error: unknown error number') Now, I have downloaded the plugin database browser AND MySQL Workbench after entering the details of the connection was able to get connected to the database in both cases. In the Data Sources and Drivers I could connect because it allowed me to edit serverTimezone as seen here: serverTimezone So now I'm having troubles and I don't know what to do. Sorry I just have no idea how to load this, I've also run the SELECT @@system_time_zone; inside the MySQL Workbench and the timezone I get is EDT. I have put TIME_ZONE parameter inside of the database settings in settings.py to TIME_ZONE = 'America/New_York', after which the front page can be loaded IF USE_TZ = False, but if I try to access any other sites, … -
Django parent creation with children collection
I'm having an issue passing several children OrderItem, a collection, when creating an Order parent instance. Although there a one to many relationship between Order and OrderItem models, I can't pass a list of children to the parent. What am I missing or doing wrong? Thanks for your responses! Here is an example of the request I try to make on this endpoint /api/orders/: { "bar_id": 2, "order_items":[ { "ref_id": 3 }, { "ref_id": 2 }, { "ref_id": 1 } ] } The error is as: { "order_items": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got list." ] } } Here is my parent OrderModel: from django.db import models from .model_bar import * class Order(models.Model): bar_id = models.ForeignKey(Bar, null=True, on_delete=models.CASCADE, related_name='orders') Here is my child OrderItemModel: from django.db import models from .model_order import * from .model_reference import * class OrderItem(models.Model): order_id = models.ForeignKey(Order, null=True, on_delete=models.CASCADE, related_name='order_items') ref_id = models.ForeignKey(Reference, null=True, on_delete=models.CASCADE, related_name='order_items') -
Django The API results do not link to the post
I'm a beginner and I'm trying to understand why when I receive the results of my API, that I add to my aliments field (linked by the ManyToManyField to the ListAliments model), are not directly linked to my post. The API works and the response too: data { concepts { name: "salad" ... } ... I use as agreed create and add if the result of the API is not already created in the ListAliments model. If one of the results is already created I just want to add it (link it to the post). The problem is that it doesn't work. My first step was to start with: self.aliments.create(name=concept.name) class ListAliments(models.Model): name = models.CharField(max_length=40, unique=True) slug = models.SlugField(editable=False) status = models.IntegerField(choices=STATUS, default=1) def save(self, *args,**kwargs): if not self.slug: self.slug = unique_slugify(self, slugify(self.name)) super(ListAliments, self).save(*args, **kwargs) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=190) url_image = models.URLField(max_length=200, default=None) aliments = models.ManyToManyField('ListAliments',blank=True, related_name='listaliments_post') ... def save(self, *args, **kwargs): if not self.slug: self.slug = unique_slugify(self, slugify(self.title)) ... if self.url_image: request = ... response = ... if response: names = [] for concept in response.outputs[0].data.concepts: current_aliments = ListAliments.objects.filter(name=concept.name) if current_aliments.count()<1: create_aliments = self.aliments.create(name=concept.name) self.aliments.add(create_aliments) else: existed_aliments = ListAliments.objects.get(name=concept.name) self.aliments.add(existed_aliments) super().save(*args, **kwargs) -
Two different on.change() events in JQuery and one ajax call
I have two built-in python dropdown and I am trying to link them together using Ajax calls. You can see the relevant code in the html: <script> $("#id_city").change(function () { // event on the city dropdown change. var cityId = $(this).val(); $.ajax({ // initialize an AJAX request url: '{% url "city_autocomplete" %}', // set the url of the request (= localhost:5000/app/ajax/city-autocomplete/) data: { 'cityId': cityId // add the city id to the GET parameters }, // dataType: 'json', success: function (data) { $('#preview').html(data); // replace the html response with the <div> content } }); event.preventDefault(); }); </script> <script> $("#id_tag").change(function () { var tagId = $(this).val(); $.ajax({ url: '{% url "city_autocomplete" %}', 'tag': tagId }, success: function (data) { $('#preview').html(data); } }); event.preventDefault(); }); </script> Once I select city, cityId takes the value but tagId returns none and vice-versa. I want to know what is the solution in jQuery, to listen to both dorpdown changes at the same time, or let's say how to merge two on.change() together? -
How to register a user with Email instead of username in Django Rest Framework
I've read tons of stack overflow posts about how to register a user with email instead of username but none of them seem to work, so I'm resetting to my defaults. I tried this and this but I still get 'username is required' back from the API when I try to register user. I think the problem might be that I couldn't find a post that's explicit to Django 3 and uses Django Rest Framework. Below are my models, serializers and views. # models class User(AbstractUser): ROLES = ( ('d', 'Doctor'), ('s', 'Secretary'), ('p', 'Patient'), ) role = models.CharField( max_length=1, choices=ROLES, blank=True, default='p', help_text='Role') class Doctor(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) clinic = models.ManyToManyField( Clinic, related_name="doctors", blank=True) appointment_duration = models.IntegerField(default=20, blank=True) # serializer User = get_user_model() class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'password', 'role', 'first_name', 'last_name', 'email', 'phone') extra_kwargs = {'password': {'write_only': True, 'required': True} # viewset class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (AllowAny,) So, how could I register with email instead of username? -
how can i access django with apache? apache showing default page on django
i am getting the default page of apache2 when i try to access the django on my lan ip address via apache server. i am also running django python manage.py runsever command and try to access with 192.168.10.11. but it still showing the default page of apache. how can i access django with apache? <VirtualHost *:80> ServerName localhost DocumentRoot /home/five/NewsDesk/server WSGIScriptAlias /NewsDesk /home/five/NewsDesk/server/server/wsgi.py # adjust the following line to match your Python path WSGIDaemonProcess 192.168.10.11 processes=2 threads=15 display-name=%{GROUP} python-home=/home/five/NewsDesk/env/lib/python3.8 WSGIProcessGroup 192.168.10.11 <directory /home/five/NewsDesk/server> <Files wsgi.py> Allow from all Require all granted </Files> AllowOverride all Require all granted Options FollowSymlinks </directory> Alias /static/ /home/five/NewsDesk/server/staticfiles/ <Directory /home/five/NewsDesk/server/staticfiles> Require all granted </Directory> </VirtualHost> apache2ctl -S $apache2ctl -S VirtualHost configuration: *:80 is a NameVirtualHost default server localhost (/etc/apache2/sites-enabled/000-default.conf:1) port 80 namevhost localhost (/etc/apache2/sites-enabled/000-default.conf:1) port 80 namevhost localhost (/etc/apache2/sites-enabled/newsdesk.conf:1) ServerRoot: "/etc/apache2" Main DocumentRoot: "/var/www/html" Main ErrorLog: "/var/log/apache2/error.log" Mutex default: dir="/var/run/apache2/" mechanism=default Mutex watchdog-callback: using_defaults PidFile: "/var/run/apache2/apache2.pid" Define: DUMP_VHOSTS Define: DUMP_RUN_CFG User: name="www-data" id=33 not_used Group: name="www-data" id=33 not_used -
django image not loading in many-to-many relationship
I have one model for the date and another model for images and a third many-to-many model that connects images to dates but in the template, I made a for loop but no image is showing up and in the developer console, I see <img class="img-fluid img-thumbnail" src="" alt=""> my models.py class MyDate(models.Model): english_date = models.DateField(auto_now=False) hebrew_date = models.CharField(max_length=20,unique=True) def get_absolute_url(self ): return reverse('date_detail',kwargs={'pk':self.pk}) def __str__(self): return self.hebrew_date # images class Images(models.Model): image = models.ImageField(unique=False,upload_to='images/') def get_absolute_url(self): return reverse("image_detail",kwargs={'pk':self.pk}) #connect days and images together class DayImage(models.Model): date = models.ForeignKey('luach.MyDate',related_name='day',on_delete=models.CASCADE) image = models.ManyToManyField('luach.images',related_name='images') def __str__(self): return self.pk my views.py def my_date_detail(request,pk): mydate = MyDate.objects.get(pk=pk) dayimage = DayImage.objects.filter(date=mydate) context = {'mydate':mydate,'dayimage':dayimage} return render(request, 'luach/mydate_detail.html',context) my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('date/<int:pk>',views.MyDateDetailView.as_view(),name='date_detail'), path('date/<int:pk>/add_image/',views.create_day_image_view,name='add_image') ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and I do have a media URL setup MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') my mydate_detail.html <div class="jumbotron"> <h2>Images</h2> {% for p in dayimage %} <div class="col-lg-3 col-md-4 col-6"> <div class="d-block mb-4 h-100"> <img class="img-fluid img-thumbnail" src="{{ p.image.url }}" alt="hi"> </div> </div> {% empty %} <h3>There is no images linked to this day</h3> {% endfor %} <a class="btn btn-outline-warning btn-sm" href="{% url 'add_image' pk=mydate.pk %}">add image</a> </div> -
How to speed up backend in electron framework?
I am creating a small project and I used electron for the front end and python for back end. The python is taking voice input and responding accordingly at back end but its too slow when integrated with electron. Is there any way to speed up the process by using Django or flask? -
How to store HStore field properly?
Here I have a HStoreField which will be taken from user Input. User gives the input in the format s:Small,l:Large But I think the HStoreField needs the data type like this{'s': 'Small','l':'Large'}. How can I covert the user data into this format so that I can store into the HStoreField. Or simply I need to store the data. How can I do it ? class MyModel(models.Model): properties = HStoreField() # view properties = request.POST.get('properties') print(properties) #properties has data in this format s:Small,l:Large, MyModel.objects.create(properties=properties) I get the error like this. django.db.utils.InternalError: Unexpected end of string LINE 1: ...antity_reserved") VALUES ('ttt', 11, 'ttt', '55', 'Small:rrr... -
Set null arraylist Django
How can I set null or empty value of my array list inorder to insert id autoincrement , I already tried 'None' but it returns error. Can anyone help me? error tuple indices must be integers or slices, not NoneType views.py def upload_excel_file(request): if request.method =='POST': person_resource = PersonResource() dataset = Dataset() new_person = request.FILES['myfile'] if not new_person.name.endswith('xlsx'): messages.info(request,'wrong format') return render (request,'dashboard.html') imported_data = dataset.load(new_person.read(),format="xlsx") for data in imported_data: value = Person( data[None], // It should Empty value data[1], data[2], data[3], data[4], data[5] ) value.save() return render(request,'dashboard.html') > model.py class Person(models.Model): person_id = models.AutoField(primary_key=True) covid_id = models.CharField(max_length=50) firstname = models.CharField(max_length=50) middle = models.CharField(max_length=50) lastname = models.CharField(max_length=50,blank=True) extension = models.CharField(max_length=50) -
Using MariaDB's 'DATE_FORMAT' within a Django Query Expression
Good afternoon, I'm trying to use the DATE_FORMAT (reference) function provided by MariaDB to convert a datetime field to str directly from the database; # Dummy Model class FooBar(models.Model): datetime = models.DateTimeField() # Query FooBar.objects.all().annotate(dt_field=Func('datetime', Value("'%W %M %Y'"), function='DATE_FORMAT')) If I check the resulting query the output is as expected. >>> print(FooBar.objects.annotate(str_date=Func('datetime', Value("'%Y-%m-%d %H:%M:%S'"), function='DATE_FORMAT')).query) SELECT DATE_FORMAT(`foobar`.`datetime`, '%Y-%m-%d %H:%M:%S') AS `str_date` FROM `foobar` However, the actual execution of the query fails: Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 252, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 258, in __len__ self._fetch_all() File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 74, in __iter__ for row in compiler.results_iter(results): File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1096, in apply_converters value = converter(value, expression, connection) File "/usr/local/lib/python3.8/site-packages/django/db/backends/mysql/operations.py", line 265, in convert_datetimefield_value value = timezone.make_aware(value, self.connection.timezone) File "/usr/local/lib/python3.8/site-packages/django/utils/timezone.py", line 270, in make_aware return timezone.localize(value, is_dst=is_dst) File "/usr/local/lib/python3.8/site-packages/pytz/__init__.py", line 237, in localize if dt.tzinfo is not None: AttributeError: 'str' object has no attribute 'tzinfo' I must be doing or assuming something incorrectly, any advice? -
How can i create Generated/Computed column Postgres/DJANGO?
How can I create Generated/Computed column Postgres/DJANGO? I tried in both ways: (1) By a Class: ERROR I GET: TypeError: init() got an unexpected keyword argument 'always_generated' class Product(models.Model): name = models.CharField(max_length=200, null=True) precio_costo = models.FloatField(null=True) cantidad = models.IntegerField(null=True) *****monto_stock = models.FloatField(always_generated='precio_costo * cantidad', stored=True)***** (2) Directly by POSTGRES Admin But I can't update or add a new field, Default value is required by Django. -
How to filter Django objects based on value returned by a method?
I have an Django object with a method get_volume_sum(self) that return a float, and I would like to query the top n objects with the highest value, how can I do that? For example I could do a loop like this but I would like a more elegant solution. vol = [] for m in Market.object.filter(**args): # 3000 objects sum = m.get_volume_sum() vol.append(sum) top = search_top_n(vol, n) From what I see here even with Python there isn't a single line solution. -
What is needed to successfully convert from referencing a model to sub classing it?
I am currently using two requests to create a User and a Doctor (or Patient). I would like to do it in a single request, so that it'll also be easier to determine the type of user later on. This is what I have for extending the User # models class User(AbstractUser): ROLES = ( ('d', 'Doctor'), ('s', 'Secretary'), ('p', 'Patient'), ) role = models.CharField( max_length=1, choices=ROLES, blank=True, default='p', help_text='Role') class Doctor(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) clinic = models.ManyToManyField( Clinic, related_name="doctors", blank=True) appointment_duration = models.IntegerField(default=20, blank=True) # serializer User = get_user_model() class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'password', 'role', 'first_name', 'last_name', 'email', 'phone') extra_kwargs = {'password': {'write_only': True, 'required': True} # viewset class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (AllowAny,) Here's what I tried: class User(AbstractUser): pass class Doctor(User): clinic = models.ManyToManyField( Clinic, related_name="doctors", blank=True) appointment_duration = models.IntegerField(default=20, blank=True) First, before deleting the user field from Doctor, there was this error in the terminal clinic.Doctor.user: (fields.E305) Reverse query name for 'Doctor.user' clashes with reverse query name for 'Doctor.user_ptr'. HINT: Add or change a related_name argument to the definition for 'Doctor.user' or 'Doctor.user_ptr'. I then deleted the user property of Doctor, the error … -
Connecting Django application to Oracle database
I am trying to connect a django application to an oracle database using this configuration ```DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': '<my SID>', 'USER': '<My user name>', 'PASSWORD': '<My password>', 'HOST': '<my host IP address>', 'PORT': '<My port>' } }``` I tested the connection, which was successful using this code import cx_Oracle # Set folder in which Instant Client is installed in system path os.environ['PATH'] = '<path_to_instant_client>\\instantclient_19_8' # Connect to user account in Oracle Database 12cExpress Edition con = cx_Oracle.connect("<Username>", "<Password>", "IP:PORT/SID") print("Connected!") con.close()``` While trying to run `python manage.py migrate` for the very first time, I get this error `raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc)` This table **django_migrations** did not exist in this database, when I run `python manage.py migrate`, it's created but from the error, the command want to create it again. Am not sure of what's happening here, kindly assist. -
estimating cloud provider price
I'm currently creating a startup and among the stuff I need to code/plan/etc I need to simulate my costs. I'm a student in AI and I have no experience using cloud providers. The project is a basic django rest application with a load balancer and a DBMS (I just started coding the MVP, some kind of private social network). My development server is my home htpc, a 12yo dual core celeron -T9400-and 2Gb of ram running with a bunch of docker apps, so absolutely not representative of a real use case All cloud providers estimators I've seen so far are using vCPUs, instances or bandwith to calculate their prices... But how does it translates in number of concurrent user? How can I use this estimation in pitches? -
Post method in django using ajax
I have a form that I am trying to implement with Ajax, after inputing some content on the textbox, when I click on the sumbit button using my mouse, everything works fine (page didnt refresh, data posted on database, and new data displayed on the page). But when I try to submit data by pressing enter, the page is displaying only the serialized data from my form (nothing more, html file do not work)and it says in the console: Resource interpreted as Document but transferred with MIME type application/json: "http://localhost:8000/try/". current page looks exactly like this after pressing enter button(nothing more): {"task": {"id": 52, "todo": "wws", "author": 1, "completed": false}} these are the data that came from my form. this is my views.py class TodoList(View): def get(self, request): todo_list = ToDo.objects.filter(author_id=request.user.id) form = AddTodo() context = { 'todo_list': todo_list, 'form': form, } return render(request, 'trylangto/try.html', context) def post(self, request): form = AddTodo(request.POST) if form.is_valid(): form.instance.author_id = request.user.id new_form = form.save() return JsonResponse({'task': model_to_dict(new_form)}, status=200) else: return redirect('trylang:todo-list') return redirect('trylang:todo-list') this is my main.js: $(document).ready(function(){ $("#createbutton").click(function(){ var formdata = $("#addtodoform").serialize(); $.ajax({ url: $("#addtodoform").data('url'), data: formdata, type: 'post', success: function(response){ $("#tasklist").append('<div class="card mb-1" ><div class="card-body">'+ response.task.todo +'<button type="button" class="close"><span aria-hidden="true">&times;</span></button></div></div>') } }); …