Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
takes 1 positional argument but 2 were given error for dict
how to add two dict in cs list I want to add two dictionaries to the cs list in the addcoursess function, but it gives an error Text error: takes 1 positional argument but 2 were given mainlist: cs = [ { "title": "Python", "teacher": "Amiri", }, { "title": "HTML", "teacher": "Dehyami", }, { "title": "PHP", "teacher": "Enayati" } ] class User: def __init__(self, fisrtname, lastname): self.fname = fisrtname self.lname = lastname def fullname(self): print(f"my fullname is {self.fname} {self.lname}") class Student(User): def __init__(self, fisrtname, lastname, email): super().__init__(fisrtname, lastname) self.email = email self.coursess = [] def fullname(self): print("i am an student") super().fullname() def printcoursess(self): if self.coursess: for course in self.coursess: print("Coursess : " + course["title"]) else: print("There is no course") Here is the class in which it is error class Teacher(User): def __init__(self, fisrtname, lastname, code): super().__init__(fisrtname, lastname) self.code = code def addcoursess(item): dict = {} dict.update(item) cs.append(dict) print(dict) def fullname(self): print("i am an teacher") super().fullname() t1 = Teacher("abolfazl", "zaker", 3223) addcoursess function here t1.addcoursess({"title": "Java", "teacher": "ganjeali"}) print(cs) -
django left join sql to django orm
i only write sql, django orm is so-so,how to sql convert to django orm? sql SELECT ct.id, ct.nid, ct.`status`, ct.create_time, bp.id as program_id FROM `ct_task` as ct JOIN program as bp on ct.hash_code=bp.hash_code ORDER BY ct.id DESC LIMIT 0,10 orm class CTask(models.Model): hash_code = models.CharField(max_length=50, null=True, db_index=True) class Program (models.Model): hash_code = models.CharField(max_length=50, null=True, db_index=True) -
How to filter is_active product by Backward relationship in Django templates?
{% for category in categories %} {% for product in categories.product_set.all %} <h1> {{ product.name }} </h1> {% endfor %} {% endfor %} I want to show filter products(Those are is_active) that belong to a category in Django template. -
Django ORM filter then join on same column
Fairly new to Django, a bit lost... My objective : I these models : class IndicatorValue(models.Model): my_obj = models.ForeignKey("MyObject", on_delete=models.CASCADE) type = models.IntegerField() value = models.FloatField( null=True, blank=True, db_index=True) class MyObject(models.Model): date = models.DateTimeField("start_date", db_index=True) I want to get a list of IndicatorValue (value and type) for a MyObject that: has date > X has one indicator value of type Y that is above Z What I would do in SQL: In SQL, I would do something like : SELECT iv2.type, iv2.value FROM MyObject m JOIN IndicatorValue iv1 on m.pk = iv1.object_pk and iv1.type = Y and iv1.value > Z JOIN IndicatorValue iv2 on iv1.object_pk = iv2.object_pk WHERE m.date > X What i do I managed to do it with a loop as such: values_ok = IndicatorValue.objects.filter(type=Y).filter(value__gt=Z) for val in values_ok: print(val.my_obj.indicator_set.all()) but this is extremely slow as I suppose the each val.my_obj.indicator_set.all() fetches from the db. How would I fetch all the data I want in one go AND how do I access it ? (I have seen sometimes logging the sql queries that it does the double join but it creates an alias for the table - T5 for instance - and I don't know how to get … -
Unable to serialize custom boolean fields from models AbstractUser in django rest framework
I am unable to serialize custom model booleanfields is_subuser, is_student in django rest framework, even if i try to post using postman still i am unable, but i am able to see this two fields in django admin backend. models.py class User(AbstractUser): is_school = models.BooleanField('school status',default=False) is_student = models.BooleanField('student status',default=False) is_subuser = models.BooleanField('subuser status',default=False) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = "__all__" -
How to create a notification about adding a record to a database table in django?
A parser with a separate database is connected to django. How to make sure that you receive a notification about adding a record to the database in the admin panel? DB = Sqlite my models.py from django.db import models class WyrestormItem(models.Model): article = models.TextField(blank=True, null=True) name = models.TextField(blank=True, null=True) description_min = models.TextField(blank=True, null=True) description_max = models.TextField(blank=True, null=True) features = models.TextField(blank=True, null=True) specifications = models.TextField(blank=True, null=True) image_count = models.IntegerField(blank=True, null=True) image_links = models.TextField(blank=True, null=True) class Meta: managed = True db_table = 'wyrestorm_items' def __str__(self): return self.name -
How can I return image address to Django template from a function of the file views.py?
I need to display an image using Django templates but don't know how the "image address" will be returned from the function of the file views.py The image address will be stored according to the "id" of the project (a project has an image associated with it). Here is the function of the views.py file that I am writing:- def file_path(request, awp_id): Component_Progress_Update_inst = get_object_or_404( Component_Progress_Update, pk=awp_id) filepath = Component_Progress_Update_inst.Supporting_documents.name filepath = "/media/"+filepath print(filepath) # Returning the file path return HttpResponse(filepath) Following is the image tag, I am writing in HTML file:- <img src="{% url 'component_progress:file_path' awp.id %}" alt="Supporting image" width="200" height="200"> But the image is not getting displayed, instead of the image this "alt text" is getting printed. While I have tried displaying the image directly -> By directly writing that address in image "src". -
DRF and TensorFlow in Production WSGI. How to load models only once for all requests
I've created an API using the Django Rest Framework. The API uses a model for object classification using TensorFlow. The initial load of TensorFlow (import tensorflow as tf) can take time to instantiate (around 30 seconds), thankfully I only need them once and then the rest of my application can make use of accessing the pre-loaded model. Locally, I solved this issue by importing TensorFlow and my models just once during Django's start-up in settings.py, for example: import tensorflow as tf MODEL = tf.keras.models.load_model(BASE_DIR /'saved_model/') This allows me to call and reuse the model in my views/serializers without having to re-import or load them on every request again, for example: In serializers.py: # Get Model model = settings.MODEL model.predict(SOMEPADDEDVALUE) Everything works well in my local development (using runserver). However, I would like to move my Django API to production and I'm worried about the above approach! I will be using a WSGI server which I believe will use Multi-Threading (or multiprocess I get these confused) and the initial loading of my models will be duplicated on every request (I think) meaning the API will be unusable. I'm sure I'm not the first to come across this issue using TensorFlow saved … -
Visual Studio Code suggestions are gone
{ "editor.formatOnSave": true, "python.formatting.provider": "black", "python.linting.pylintEnabled": true, "python.linting.enabled": true, "python.linting.lintOnSave": true, "[python]": { "editor.defaultFormatter": "ms-python.python" }, "tabnine.experimentalAutoImports": true, "vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue", "python.pythonPath": "", "files.associations": { "*.html": "html", "**/templates/**/*.html": "django-html", "**/templates/**/*": "django-txt", "**/requirements{/**,*}.{txt,in}": "pip-requirements" }, "editor.quickSuggestions": true, "html.suggest.html5": true, "html.autoClosingTags": true, "emmet.includeLanguages": {"django-html": "html"}, "emmet.showAbbreviationSuggestions": true, "editor.suggestSelection": "first", } this is inside of my vsc settings.py i am working with django and launguage mode is Django-Templates if i type div or for i dont het any suggestion or autocomplete also in .py i dont see any suggestions would anybody please give me help? -
What is the use case for Django's on_commit?
Reading this documentation https://docs.djangoproject.com/en/4.0/topics/db/transactions/#django.db.transaction.on_commit This is the use case for on_commit with transaction.atomic(): # Outer atomic, start a new transaction transaction.on_commit(foo) # Do things... with transaction.atomic(): # Inner atomic block, create a savepoint transaction.on_commit(bar) # Do more things... # foo() and then bar() will be called when leaving the outermost block But why not just write the code like normal without on_commit hooks? Like this: with transaction.atomic(): # Outer atomic, start a new transaction # Do things... with transaction.atomic(): # Inner atomic block, create a savepoint # Do more things... foo() bar() # foo() and then bar() will be called when leaving the outermost block It's easier to read since it doesn't require more knowledge of the Django APIs and the statements are put in the order of when they are executed. It's easier to test since you don't have to use any special test classes for Django. So what is the use-case for the on_commit hook? -
How do i display information created by my powershell script onto my website
im a 14 y/o coder trying to create a website which can display some information . Link for code https://github.com/Aadishshele/Questionable/tree/main/Question In the powershell script, it gets the pc information and displays it onto a html website (X.html). Along with this i have a login script which takes user input and displays it onto a screen(Login.html). I want to display the pc information onto the same page as the display of the user input. Can anyone guide me on how to be able to do it? -
Web Framework Structure
There are plenty of Web Application Frameworks available over the internet. Each of them has its own rich documentation and tutorials. However, there is a lack of information about the structure of these Web Frameworks. By structure, I mean simple description and graphical representation of relationships and communications between "Web-Server" & "Web-API/ Web-Framework" regardless of programming languages employed to implement them. The most ambiguous part for me is relationships and communications between the "Web-API / Web-Framework" and the "Web-Server". I've done surfing the Net but I have not found any proper reliable info. -
Django Login error TypeError: Object of type User is not JSON serializable
I have an issue with use login on my Django app. I created a custom user model and it works fine with the database . Some how the login page is not working , it is expecting Json data. I have no idea why it is doing it to. I have the following model class AdminAccounts(BaseUserManager): def create_user(self, user, password=None): """ Creates and saves a User with the given email and password. """ if not user: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(user), ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, user, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( user, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, user, password): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( user, password=password, ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): id = models.BigAutoField(primary_key=True) user = models.CharField(max_length=50,unique=True,verbose_name='User name') name = models.CharField(max_length=50,verbose_name='User name',default=None,blank=True, null=True) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser objects= AdminAccounts() # notice the absence … -
Images from the database not displaying in react when using DRF
The tutorial was going smoothly until I got to Lecture 18 (Serializing Data). When the data from the database is being serialized, the images stop displaying in react but {product.image} shows the path of the image. Please I want to know why the image isn't displaying in react but is working perfectly in django. Whenever I click on the image link in the admin page the product gets displayed. The images displayed in react when fetching the products as python array from django, but when I turn to drf it stops displaying. I'm using Django 4.0, I have no Idea whether this has any effect on the issue. When using DRF, EVERY OTHER PROPERTY OF THE PRODUCT IS BEING DISPLAYED IN REACT EXCEPT THE IMAGE Here's the part of the React component where the image is referenced <Link to={`/product/${product._id}`}. <Card.Img src={product.image} /> </Link> urlpatterns = [ path('admin/', admin.site.urls), path('', include('base.urls')) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) STATIC_URL = 'static/' MEDIA_URL = '/images/' STATICFILES_DIR = [ BASE_DIR / 'static' ] MEDIA_ROOT = 'static/images -
Django QuerySet Filter() Not Returning Anything, But When I Use Mongo Compass To Search, It Does Exist
I tried to change the id to string and into integer to test if its due to the type, but both did not work, any help is appreciated thanks! All other code using filter() works except this particular one. Views.py: baseQuery = messageData.objects.using('telegram').filter(from_id = {'user_id':1029783740}) print(baseQuery) Terminal Output: <QuerySet []> MongoDb Compass Search Results: -
This was likely an oversight when migrating to django.urls.path()
I am getting a warning when I run server in django3.2.9. WARNINGS: ?: (2_0.W001) Your URL pattern 'activate/(?P<uid>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$' [name='activate'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). Here is my code: path('activate/(?P<uid>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', activate, name='activate') I know I need to use the re_path. How should I rewrite above line using re_path? -
IntegrityError at order/order/add/ null value in column "total_incl_tax" violates not-null constraint DETAIL: Failing row contains
When I try to add price to django oscar I get this error and this field is not editable in the model or writable I need help to get this done IntegrityError at order/order/add/ null value in column "total_incl_tax" violates not-null constraint DETAIL: Failing row contains class AbstractOrder(models.Model): """ The main order model """ number = models.CharField( _("Order number"), max_length=128, db_index=True, unique=True) # We track the site that each order is placed within site = models.ForeignKey( 'sites.Site', verbose_name=_("Site"), null=True, on_delete=models.SET_NULL) basket = models.ForeignKey( 'basket.Basket', verbose_name=_("Basket"), null=True, blank=True, on_delete=models.SET_NULL) # Orders can be placed without the user authenticating so we don't always # have a customer ID. user = models.ForeignKey( AUTH_USER_MODEL, related_name='orders', null=True, blank=True, verbose_name=_("User"), on_delete=models.SET_NULL) # Billing address is not always required (eg paying by gift card) billing_address = models.ForeignKey( 'order.BillingAddress', null=True, blank=True, verbose_name=_("Billing Address"), on_delete=models.SET_NULL) # Total price looks like it could be calculated by adding up the # prices of the associated lines, but in some circumstances extra # order-level charges are added and so we need to store it separately currency = models.CharField( _("Currency"), max_length=12, default=get_default_currency) total_incl_tax = models.DecimalField( _("Order total (inc. tax)"), decimal_places=2, max_digits=12) total_excl_tax = models.DecimalField( _("Order total (excl. tax)"), decimal_places=2, max_digits=12) # Shipping charges … -
TypeError: Direct assignment to the reverse side of a related set is prohibited. Use roompicture.set() instead
I am a beginner in Django and I am stuck with podting nested images, in my project I want to post images of a hotel and images of the room inside the hotel. but I am getting the following error: TypeError: Direct assignment to the reverse side of a related set is prohibited. Use roompicture.set() instead. This is the code with the problem: room = Room.objects.create(hotel=hotel, **room_data) Hier is my serializers.py: class RoomPictureSerializer(serializers.ModelSerializer): location = Base64ImageField(max_length=None, use_url=True) class Meta: model = RoomPicture fields = ['id', 'room', 'location'] class RoomSerializer(serializers.ModelSerializer): roompicture = RoomPictureSerializer(many=True) class Meta: model = Room fields = ['id', 'roompicture'] class HotelPictureSerializer(serializers.ModelSerializer): location = Base64ImageField(max_length=None, use_url=True) class Meta: model = HotelPicture fields = ['id', 'hotel', 'location'] class HotelSerializer(serializers.ModelSerializer): hotelpicture = HotelPictureSerializer(many=True) rooms = RoomSerializer(many=True) class Meta: model = Hotel fields = ['id', 'hotelpicture', 'rooms'] def create(self, validated_data): hotelpictures_data = validated_data.pop('hotelpicture') rooms_data = validated_data.pop('rooms') hotel = Complex.objects.create(**validated_data) for hotelpicture in hotelpictures_data: HotelPicture.objects.create(hotel=hotel, **hotelpicture) for room_data in rooms_data: room = Room.objects.create(hotel=hotel, **room_data) room_pictures_data = room_data.pop('roompicture') for room_picture_data in room_pictures_data: RoomPicture.objects.create(room=room, **room_picture_data) return hotel Hier is the views.py: class PictureViewSet(mixins.CreateModelMixin, RetrieveModelMixin, ListModelMixin, GenericViewSet, UpdateModelMixin): queryset = Hotel.objects.all() serializer_class = HotelSerializer Hier is my model.py: class Hotel(models.Model): country = models.CharField() hotel_name = models.CharField(max_length=20) … -
How to dynamically update the modified fields of a Model
Let's say I have the model Project. The model Project has > 100 fields. I can create new Projects from the front-End using forms. When I want to edit/update some field of a Project in the back-end I've been doing something like this (truncated): def edit_project(request): if request.method == 'POST': project_to_edit = Project.objects.get(pk=request.POST['project_id']) project_to_edit.description = request.POST['description'] project_to_edit.name = request.POST['name'] #repeat the same process for each field...(>50) project_to_edit.save() return redirect('project_page/') return redirect('index') The problem is that new fields are constantly being added to the Projects model. Is there a dynamic/ pythonic way to update each field in the model without having to do it 'manually' for each field and save lines of code? -
Django admin site callable attrs seems not working with python regex
I'm adding an additional column to the Django.admin site, according to the document, it oughts to work, but once I introduced re package to this function, things went wrong. here's code sample: class InfoAddrAdmin(ModelAdmin): list_display = ('id', 'machineId', 'uptime', 'repath') list_filter = ('machineId',) def repath(self, obj): res = re.search(r"10\.1\d+\.\d+\.\d+", obj.ipaddr) return res.group()<-Exception comes from here and the related Model is defined as: class RemoteAddress(models.Model): id = models.AutoField(primary_key=True) machineId = models.CharField(max_length=32) uptime = models.DateTimeField(default=now) ipaddr = models.TextField() a piece of text with lots of IP addresses(i.e. the result of command ipconfig) is stored in the ipaddr attr, and that regex searchs for an IP with prefix like '10.1xx.xxx.xxx', which proved working fine. and the main error is: AttributeError: 'NoneType' object has no attribute 'group' You may find some information from https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display -
Method Not Allowed (POST): /
I'm trying to make a simple one-paged shop. I made a ListView of the items and it renders no problem. The shopping cart will be in a modal. I made the buy button, but whenever I press it, it says: Method Not Allowed (POST): / Method Not Allowed: / [22/Dec/2021 11:40:04] "POST / HTTP/1.1" 405 0 Here are my views: from django.shortcuts import render from django.views.generic import ListView from .models import Item from .forms import AddCartForm class ItemsListView(ListView): model = Item template_name = 'main_page.html' def aBuy(request): form = AddCartForm if request.method == 'POST': print('BUY BUY') return render(request, 'main_page.html', {'form':form}) This is the form: class AddCartForm(ModelForm): class Meta: model = Item fields = ['price', 'quantity'] The form in html: <div class="col" style="text-align:left"> <form name="buy" method="POST"> {% csrf_token %} {{ form }} <input type="submit" class="btn btn-info butt" value="Buy"> </form> </div> I cannot continue making the logic for adding it to the future cart because of it. print('BUY BUY') is just for testing. In the url file it's only the main page with ItemListView.as_view. I tried putting the aBuy function in it and out, same problem remains. -
How to Get Authentication from Oauth2 on Angular that using Django REST-Framework as Back-end
I want to build Authentication server for my user and easily to access other my new application without singing up again on the new apps using Oauth2 my current project are below: 1st Project: Authentication Provider (Django implemented Django Oauth Toolkits) 2nd Project: Client Angular using Django REST Frameworks as back-end. So I don't want user sign up on Client app. Just want them on singup on Authentication provider and request access to Client app without signup on it. I have successful implement on Client back-end is working with Authentication Provider but I don't know how to implement on Angular for this case. But Angular is not yet. I don't know how to implement for Angular and Back-end working properly to get authentication from Authentication Provider. Please help to share me the tutorials for practice projects. Thank in advance. -
from django.core.management import execute_from_command_line not working
I am working on a bug project. Which is on Python 2.7, we are migrating to Python 3.9. I am getting import errors in manage.py during importfrom django.core.management import execute_from_command_line. For python 2.7 it is fine but for python 3 it is not working. I've created separate virtual environment for Python 3. manage.py #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "best_buy_mall.settings") try: from django.core.management import execute_from_command_line except ImportError: try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv) dir tree: my_app/django_site/manage.py my_app/venv (for python2) my_app/v_env (for python3) -
Mandrill API to send email with recipients(cc), but It also send mail to recipients(cc) as 'TO' using Django==1.11.10
Code: def send_mandrill_subscribe_wac(link,user_email, from_user, from_email='examplecc@abc.com'): mandrill_client = mandrill.Mandrill(MANDRILL_API_KEY) #template_name = "Invited-user-email-for-someone-without-an-account" template_name = "invited-user-email-for-someone-without-an-account" template_content = [{'content': 'example content', 'name': 'example name'}] message = { 'from_email': 'examplecc@abc.com', 'to': [ { 'email': user_email, 'type': 'to' }, { 'email': from_email, 'type': 'cc' }, { 'email': 'examplecc2@abc.com', 'type': 'cc' } ], 'global_merge_vars': [ {'content': user_email}, {'name': "redirect_link", 'content': link}, {'name': 'from_user', 'content': from_user} ], } return mandrill_client.messages.send_template(template_name=template_name, template_content=template_content, message=message) In official Documentation they mentioned preserve_recipients set to True to send recipients, But don't know where to add this parameter. Need help please -
return single instance of message django
i'm trying to create a p2p messaging system in my chat app (not using channels) so in my view.py i list out all messages, but i don't want it to list out multiple messages from a single user, just the most recent, sad to say it does the exact opposite, if brings out all messages between 2 people instead of only the most recent, i tried creating a different models so i can filter by that and add the distinct function, but still didn't work, i really wanna get this done by christmas, so i appreciate any help views.py def pmpage(request): user = recceiver.objects.get(id=request.user.id) all_message = pm.objects.filter(recepient=user).distinct() unread = pm.objects.filter(recepient=user, unread=True).order_by('sender').distinct() sent = pm.objects.filter(sender=request.user) context = { 'all_message' : all_message, 'unread' : unread, 'sent' : sent, } return render(request, 'message.html', context) models.py class recceiver(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.name) class pm(models.Model): sender = models.ForeignKey(User, related_name='sender', on_delete=models.CASCADE) recepient = models.ForeignKey(recceiver, related_name='recceiver', on_delete=models.CASCADE, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) body = models.TextField() unread = models.BooleanField(default=False) def __str__(self): return f'{self.body}' thanks again